diff --git a/include/Makefile.am b/include/Makefile.am index 54d68f9441..ca94448984 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -1,19 +1,20 @@ # # Copyright 2003-2019 the Pacemaker project contributors # # The version control history for this file may have further details. # # This source code is licensed under the GNU General Public License version 2 # or later (GPLv2+) WITHOUT ANY WARRANTY. # MAINTAINERCLEANFILES = Makefile.in config.h.in noinst_HEADERS = config.h \ crm_internal.h \ doxygen.h \ + pacemaker.h \ pacemaker-internal.h \ portability.h pkginclude_HEADERS = crm_config.h SUBDIRS = crm pcmki diff --git a/include/crm/common/cmdline_internal.h b/include/crm/common/cmdline_internal.h index 77f4acbaef..77f1ec6d9a 100644 --- a/include/crm/common/cmdline_internal.h +++ b/include/crm/common/cmdline_internal.h @@ -1,168 +1,167 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef CMDLINE_INTERNAL__H #define CMDLINE_INTERNAL__H #ifdef __cplusplus extern "C" { #endif #include typedef struct { char *summary; char *output_as_descr; gboolean version; gboolean quiet; unsigned int verbosity; char *output_ty; char *output_dest; } pcmk__common_args_t; /*! * \internal * \brief Allocate a new common args object * * \param[in] summary Summary description of tool for man page * * \return Newly allocated common args object * \note This function will immediately exit the program if memory allocation * fails, since the intent is to call it at the very beginning of a * program, before logging has been set up. */ pcmk__common_args_t * pcmk__new_common_args(const char *summary); /*! * \internal * \brief Create and return a GOptionContext containing the command line options * supported by all tools. * * \note Formatted output options will be added unless fmts is NULL. This allows * for using this function in tools that have not yet been converted to * formatted output. It should not be NULL in any tool that calls * pcmk__register_formats() as that function adds its own command line * options. * * \param[in,out] common_args A ::pcmk__common_args_t structure where the * results of handling command options will be written. * \param[in] fmts The help string for which formats are supported. * \param[in,out] output_group A ::GOptionGroup that formatted output related * command line arguments should be added to. */ GOptionContext * pcmk__build_arg_context(pcmk__common_args_t *common_args, const char *fmts, GOptionGroup **output_group); /*! * \internal * \brief Clean up after pcmk__build_arg_context(). This should be called * instead of ::g_option_context_free at program termination. * * \param[in,out] context Argument context to free */ void pcmk__free_arg_context(GOptionContext *context); /*! * \internal * \brief Add options to the main application options * * \param[in,out] context Argument context to add options to * \param[in] entries Option entries to add * * \note This is simply a convenience wrapper to reduce duplication */ void pcmk__add_main_args(GOptionContext *context, GOptionEntry entries[]); /*! * \internal * \brief Add an option group to an argument context * * \param[in,out] context Argument context to add group to * \param[in] name Option group name (to be used in --help-NAME) * \param[in] header Header for --help-NAME output * \param[in] desc Short description for --help-NAME option * \param[in] entries Array of options in group * * \note This is simply a convenience wrapper to reduce duplication */ void pcmk__add_arg_group(GOptionContext *context, const char *name, const char *header, const char *desc, GOptionEntry entries[]); /*! * \internal * \brief Pre-process command line arguments to preserve compatibility with * getopt behavior. * * getopt and glib have slightly different behavior when it comes to processing * single command line arguments. getopt allows this: -x, while glib will * try to handle like it is additional single letter arguments. glib * prefers -x instead. * * This function scans argv, looking for any single letter command line options * (indicated by the 'special' parameter). When one is found, everything after * that argument to the next whitespace is converted into its own value. Single * letter command line options can come in a group after a single dash, but * this function will expand each group into many arguments. * * Long options and anything after "--" is preserved. The result of this function * can then be passed to ::g_option_context_parse_strv for actual processing. * * In pseudocode, this: * * pcmk__cmdline_preproc(4, ["-XbA", "--blah=foo", "-aF", "-Fval", "--", "--extra", "-args"], "aF") * * Would be turned into this: * * ["-X", "-b", "-A", "--blah=foo", "-a", "F", "-F", "val", "--", "--extra", "-args"] * * This function does not modify argv, and the return value is built of copies * of all the command line arguments. It is up to the caller to free this memory * after use. * - * \param[in] argc The length of argv. * \param[in] argv The command line arguments. * \param[in] special Single-letter command line arguments that take a value. * These letters will all have pre-processing applied. */ -char ** -pcmk__cmdline_preproc(int argc, char **argv, const char *special); +gchar ** +pcmk__cmdline_preproc(char **argv, const char *special); /*! * \internal * \brief Process extra arguments as if they were provided by the user on the * command line. * * \param[in,out] context The command line option processing context. * \param[out] error A place for errors to be collected. * \param[in] format The command line to be processed, potentially with * format specifiers. * \param[in] ... Arguments to be formatted. * * \note The first item in the list of arguments must be the name of the * program, exactly as if the format string were coming from the * command line. Otherwise, the first argument will be ignored. * * \return TRUE if processing succeeded, or FALSE otherwise. If FALSE, error * should be checked and displayed to the user. */ G_GNUC_PRINTF(3, 4) gboolean pcmk__force_args(GOptionContext *context, GError **error, const char *format, ...); #ifdef __cplusplus } #endif #endif diff --git a/include/crm/common/output.h b/include/crm/common/output.h index d2e6514183..56faabf755 100644 --- a/include/crm/common/output.h +++ b/include/crm/common/output.h @@ -1,713 +1,713 @@ /* * Copyright 2019-2020 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef CRM_OUTPUT__H # define CRM_OUTPUT__H #ifdef __cplusplus extern "C" { #endif /** * \file * \brief Formatted output for pacemaker tools */ # include # include # include # include # include # include # define PCMK__API_VERSION "2.0" typedef struct pcmk__output_s pcmk__output_t; /*! * \internal * \brief The type of a function that creates a ::pcmk__output_t. * * Instances of this type are passed to pcmk__register_format(), stored in an * internal data structure, and later accessed by pcmk__output_new(). For * examples, see pcmk__mk_xml_output() and pcmk__mk_text_output(). * * \param[in] argv The list of command line arguments. */ typedef pcmk__output_t * (*pcmk__output_factory_t)(char **argv); /*! * \internal * \brief The type of a custom message formatting function. * * These functions are defined by various libraries to support formatting of * types aside from the basic types provided by a ::pcmk__output_t. * * The meaning of the return value will be different for each message. * In general, however, 0 should be returned on success and a positive value * on error. * * \note These functions must not call va_start or va_end - that is done * automatically before the custom formatting function is called. */ typedef int (*pcmk__message_fn_t)(pcmk__output_t *out, va_list args); /*! * \internal * \brief Internal type for tracking custom messages. * * Each library can register functions that format custom message types. These * are commonly used to handle some library-specific type. Registration is * done by first defining a table of ::pcmk__message_entry_t structures and * then passing that table to pcmk__register_messages(). Separate handlers * can be defined for the same message, but for different formats (xml vs. * text). Unknown formats will be ignored. */ typedef struct pcmk__message_entry_s { /*! * \brief The message to be handled. * * This must be the same ID that is passed to the message function of * a ::pcmk__output_t. Unknown message IDs will be ignored. */ const char *message_id; /*! * \brief The format type this handler is for. * * This name must match the fmt_name of the currently active formatter in * order for the registered function to be called. It is valid to have * multiple entries for the same message_id but with different fmt_name * values. */ const char *fmt_name; /*! * \brief The function to be called for message_id given a match on * fmt_name. See comments on ::pcmk__message_fn_t. */ pcmk__message_fn_t fn; } pcmk__message_entry_t; /*! * \internal * \brief This structure contains everything needed to add support for a * single output formatter to a command line program. */ typedef struct pcmk__supported_format_s { /*! * \brief The name of this output formatter, which should match the * fmt_name parameter in some ::pcmk__output_t structure. */ const char *name; /*! * \brief A function that creates a ::pcmk__output_t. */ pcmk__output_factory_t create; /*! * \brief Format-specific command line options. This can be NULL if * no command line options should be supported. */ GOptionEntry *options; } pcmk__supported_format_t; /* The following three blocks need to be updated each time a new base formatter * is added. */ extern GOptionEntry pcmk__html_output_entries[]; extern GOptionEntry pcmk__log_output_entries[]; extern GOptionEntry pcmk__none_output_entries[]; extern GOptionEntry pcmk__text_output_entries[]; extern GOptionEntry pcmk__xml_output_entries[]; pcmk__output_t *pcmk__mk_html_output(char **argv); pcmk__output_t *pcmk__mk_log_output(char **argv); pcmk__output_t *pcmk__mk_none_output(char **argv); pcmk__output_t *pcmk__mk_text_output(char **argv); pcmk__output_t *pcmk__mk_xml_output(char **argv); #define PCMK__SUPPORTED_FORMAT_HTML { "html", pcmk__mk_html_output, pcmk__html_output_entries } #define PCMK__SUPPORTED_FORMAT_LOG { "log", pcmk__mk_log_output, pcmk__log_output_entries } #define PCMK__SUPPORTED_FORMAT_NONE { "none", pcmk__mk_none_output, pcmk__none_output_entries } #define PCMK__SUPPORTED_FORMAT_TEXT { "text", pcmk__mk_text_output, pcmk__text_output_entries } #define PCMK__SUPPORTED_FORMAT_XML { "xml", pcmk__mk_xml_output, pcmk__xml_output_entries } /*! * \brief This structure contains everything that makes up a single output * formatter. * * Instances of this structure may be created by calling pcmk__output_new() * with the name of the desired formatter. They should later be freed with * pcmk__output_free(). */ struct pcmk__output_s { /*! * \brief The name of this output formatter. */ const char *fmt_name; /*! * \brief A copy of the request that generated this output. * * In the case of command line usage, this would be the command line * arguments. For other use cases, it could be different. */ - char *request; + gchar *request; /*! * \brief Does this formatter support a special quiet mode? * * In this mode, most output can be supressed but some information is still * displayed to an interactive user. In general, machine-readable output * formats will not support this while user-oriented formats will. */ bool supports_quiet; /*! * \brief Where output should be written. * * This could be a file handle, or stdout or stderr. This is really only * useful internally. */ FILE *dest; /*! * \brief Custom messages that are currently registered on this formatter. * * Keys are the string message IDs, values are ::pcmk__message_fn_t function * pointers. */ GHashTable *messages; /*! * \brief Implementation-specific private data. * * Each individual formatter may have some private data useful in its * implementation. This points to that data. Callers should not rely on * its contents or structure. */ void *priv; /*! * \internal * \brief Take whatever actions are necessary to prepare out for use. This is * called by pcmk__output_new(). End users should not need to call this. * * \note For formatted output implementers - This function should be written in * such a way that it can be called repeatedly on an already initialized * object without causing problems, or on a previously finished object * without crashing. * * \param[in,out] out The output functions structure. * * \return true on success, false on error. */ bool (*init) (pcmk__output_t *out); /*! * \internal * \brief Free the private formatter-specific data. * * This is called from pcmk__output_free() and does not typically need to be * called directly. * * \param[in,out] out The output functions structure. */ void (*free_priv)(pcmk__output_t *out); /*! * \internal * \brief Take whatever actions are necessary to end formatted output. * * This could include flushing output to a file, but does not include freeing * anything. The finish method can potentially be fairly complicated, adding * additional information to the internal data structures or doing whatever * else. It is therefore suggested that finish only be called once. * * \note The print parameter will only affect those formatters that do all * their output at the end. Console-oriented formatters typically print * a line at a time as they go, so this parameter will not affect them. * Structured formatters will honor it, however. * * \note The copy_dest parameter does not apply to all formatters. Console- * oriented formatters do not build up a structure as they go, and thus * do not have anything to return. Structured formatters will honor it, * however. Note that each type of formatter will return a different * type of value in this parameter. To use this parameter, call this * function like so: * * \code * xmlNode *dest = NULL; * out->finish(out, exit_code, false, (void **) &dest); * \endcode * * \param[in,out] out The output functions structure. * \param[in] exit_status The exit value of the whole program. * \param[in] print Whether this function should write any output. * \param[out] copy_dest A destination to store a copy of the internal * data structure for this output, or NULL if no * copy is required. The caller should free this * memory when done with it. */ void (*finish) (pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest); /*! * \internal * \brief Finalize output and then immediately set back up to start a new set * of output. * * This is conceptually the same as calling finish and then init, though in * practice more be happening behind the scenes. * * \note This function differs from finish in that no exit_status is added. * The idea is that the program is not shutting down, so there is not * yet a final exit code. Call finish on the last time through if this * is needed. * * \param[in,out] out The output functions structure. */ void (*reset) (pcmk__output_t *out); /*! * \internal * \brief Register a custom message. * * \param[in,out] out The output functions structure. * \param[in] message_id The name of the message to register. This name * will be used as the message_id parameter to the * message function in order to call the custom * format function. * \param[in] fn The custom format function to call for message_id. */ void (*register_message) (pcmk__output_t *out, const char *message_id, pcmk__message_fn_t fn); /*! * \internal * \brief Call a previously registered custom message. * * \param[in,out] out The output functions structure. * \param[in] message_id The name of the message to call. This name must * be the same as the message_id parameter of some * previous call to register_message. * \param[in] ... Arguments to be passed to the registered function. * * \return 0 if a function was registered for the message, that function was * called, and returned successfully. A negative value is returned if * no function was registered. A positive value is returned if the * function was called but encountered an error. */ int (*message) (pcmk__output_t *out, const char *message_id, ...); /*! * \internal * \brief Format the output of a completed subprocess. * * \param[in,out] out The output functions structure. * \param[in] exit_status The exit value of the subprocess. * \param[in] proc_stdout stdout from the completed subprocess. * \param[in] proc_stderr stderr from the completed subprocess. */ void (*subprocess_output) (pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr); /*! * \internal * \brief Format version information. This is useful for the --version * argument of command line tools. * * \param[in,out] out The output functions structure. * \param[in] extended Add additional version information. */ void (*version) (pcmk__output_t *out, bool extended); /*! * \internal * \brief Format an informational message that should be shown to * to an interactive user. Not all formatters will do this. * * \note A newline will automatically be added to the end of the format * string, so callers should not include a newline. * * \param[in,out] out The output functions structure. * \param[in] buf The message to be printed. * \param[in] ... Arguments to be formatted. */ void (*info) (pcmk__output_t *out, const char *format, ...) G_GNUC_PRINTF(2, 3); /*! * \internal * \brief Format an error message that should be shown to an interactive * user. Not all formatters will do this. * * \note A newline will automatically be added to the end of the format * string, so callers should not include a newline. * * \param[in,out] out The output functions structure. * \param[in] buf The message to be printed. * \param[in] ... Arguments to be formatted. */ void (*err) (pcmk__output_t *out, const char *format, ...) G_GNUC_PRINTF(2, 3); /*! * \internal * \brief Format already formatted XML. * * \param[in,out] out The output functions structure. * \param[in] name A name to associate with the XML. * \param[in] buf The XML in a string. */ void (*output_xml) (pcmk__output_t *out, const char *name, const char *buf); /*! * \internal * \brief Start a new list of items. * * \note For text output, this corresponds to another level of indentation. For * XML output, this corresponds to wrapping any following output in another * layer of tags. * * \note If singular_noun and plural_noun are non-NULL, calling end_list will * result in a summary being added. * * \param[in,out] out The output functions structure. * \param[in] singular_noun When outputting the summary for a list with * one item, the noun to use. * \param[in] plural_noun When outputting the summary for a list with * more than one item, the noun to use. * \param[in] format The format string. * \param[in] ... Arguments to be formatted. */ void (*begin_list) (pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) G_GNUC_PRINTF(4, 5); /*! * \internal * \brief Format a single item in a list. * * \param[in,out] out The output functions structure. * \param[in] name A name to associate with this item. * \param[in] format The format string. * \param[in] ... Arguments to be formatted. */ void (*list_item) (pcmk__output_t *out, const char *name, const char *format, ...) G_GNUC_PRINTF(3, 4); /*! * \internal * \brief Increment the internal counter of the current list's length. * * Typically, this counter is maintained behind the scenes as a side effect * of calling list_item(). However, custom functions that maintain lists * some other way will need to manage this counter manually. This is * useful for implementing custom message functions and should not be * needed otherwise. * * \param[in,out] out The output functions structure. */ void (*increment_list) (pcmk__output_t *out); /*! * \internal * \brief Conclude a list. * * \note If begin_list was called with non-NULL for both the singular_noun * and plural_noun arguments, this function will output a summary. * Otherwise, no summary will be added. * * \param[in,out] out The output functions structure. */ void (*end_list) (pcmk__output_t *out); }; /*! * \internal * \brief Call a formatting function for a previously registered message. * * \note This function is for implementing custom formatters. It should not * be called directly. Instead, call out->message. * * \param[in,out] out The output functions structure. * \param[in] message_id The message to be handled. Unknown messages * will be ignored. * \param[in] ... Arguments to be passed to the registered function. */ int pcmk__call_message(pcmk__output_t *out, const char *message_id, ...); /*! * \internal * \brief Free a ::pcmk__output_t structure that was previously created by * pcmk__output_new(). * * \note While the create and finish functions are designed in such a way that * they can be called repeatedly, this function will completely free the * memory of the object. Once this function has been called, producing * more output requires starting over from pcmk__output_new(). * * \param[in,out] out The output structure. */ void pcmk__output_free(pcmk__output_t *out); /*! * \internal * \brief Create a new ::pcmk__output_t structure. * * \param[in,out] out The destination of the new ::pcmk__output_t. * \param[in] fmt_name How should output be formatted? * \param[in] filename Where should formatted output be written to? This * can be a filename (which will be overwritten if it * already exists), or NULL or "-" for stdout. For no * output, pass a filename of "/dev/null". * \param[in] argv The list of command line arguments. * * \return Standard Pacemaker return code */ int pcmk__output_new(pcmk__output_t **out, const char *fmt_name, const char *filename, char **argv); /*! * \internal * \brief Register a new output formatter, making it available for use * the same as a base formatter. * * \param[in,out] group A ::GOptionGroup that formatted output related command * line arguments should be added to. This can be NULL * for use outside of command line programs. * \param[in] name The name of the format. This will be used to select a * format from command line options and for displaying help. * \param[in] create A function that creates a ::pcmk__output_t. * \param[in] options Format-specific command line options. These will be * added to the context. This argument can also be NULL. * * \return 0 on success or an error code on error. */ int pcmk__register_format(GOptionGroup *group, const char *name, pcmk__output_factory_t create, GOptionEntry *options); /*! * \internal * \brief Register an entire table of output formatters at once. * * \param[in,out] group A ::GOptionGroup that formatted output related command * line arguments should be added to. This can be NULL * for use outside of command line programs. * \param[in] table An array of ::pcmk__supported_format_t which should * all be registered. This array must be NULL-terminated. * */ void pcmk__register_formats(GOptionGroup *group, pcmk__supported_format_t *table); /*! * \internal * \brief Register a function to handle a custom message. * * \note This function is for implementing custom formatters. It should not * be called directly. Instead, call out->register_message. * * \param[in,out] out The output functions structure. * \param[in] message_id The message to be handled. * \param[in] fn The custom format function to call for message_id. */ void pcmk__register_message(pcmk__output_t *out, const char *message_id, pcmk__message_fn_t fn); /*! * \internal * \brief Register an entire table of custom formatting functions at once. * * This table can contain multiple formatting functions for the same message ID * if they are for different format types. * * \param[in,out] out The output functions structure. * \param[in] table An array of ::pcmk__message_entry_t values which should * all be registered. This array must be NULL-terminated. */ void pcmk__register_messages(pcmk__output_t *out, pcmk__message_entry_t *table); /* Functions that are useful for implementing custom message formatters */ /*! * \internal * \brief A printf-like function. * * This function writes to out->dest and indents the text to the current level * of the text formatter's nesting. This should be used when implementing * custom message functions instead of printf. * * \param[in,out] out The output functions structure. */ void pcmk__indented_printf(pcmk__output_t *out, const char *format, ...) G_GNUC_PRINTF(2, 3); /*! * \internal * \brief A vprintf-like function. * * This function is like pcmk__indented_printf(), except it takes a va_list instead * of a list of arguments. This should be used when implementing custom message * functions instead of vprintf. * * \param[in,out] out The output functions structure. * \param[in] format The format string. * \param[in] args A list of arguments to apply to the format string. */ void pcmk__indented_vprintf(pcmk__output_t *out, const char *format, va_list args) G_GNUC_PRINTF(2, 0); /*! * \internal * \brief Create and return a new XML node with the given name, as a child of the * current list parent. The new node is then added as the new list parent, * meaning all subsequent nodes will be its children. This is used when * implementing custom functions. * * \param[in,out] out The output functions structure. * \param[in] name The name of the node to be created. */ xmlNodePtr pcmk__output_xml_create_parent(pcmk__output_t *out, const char *name); /*! * \internal * \brief Add the given node as a child of the current list parent. This is * used when implementing custom message functions. * * \param[in,out] out The output functions structure. * \param[in] node An XML node to be added as a child. */ void pcmk__output_xml_add_node(pcmk__output_t *out, xmlNodePtr node); /*! * \internal * \brief Create and return a new XML node with the given name, as a child of the * current list parent. This is used when implementing custom functions. * * \param[in,out] out The output functions structure. * \param[in] name The name of the node to be created. */ xmlNodePtr pcmk__output_create_xml_node(pcmk__output_t *out, const char *name); /*! * \internal * \brief Like pcmk__output_create_xml_node(), but add the given text content to the * new node. * * \param[in,out] out The output functions structure. * \param[in] name The name of the node to be created. * \param[in] content The text content of the node. */ xmlNodePtr pcmk__output_create_xml_text_node(pcmk__output_t *out, const char *name, const char *content); /*! * \internal * \brief Push a parent XML node onto the stack. This is used when implementing * custom message functions. * * The XML output formatter maintains an internal stack to keep track of which nodes * are parents in order to build up the tree structure. This function can be used * to temporarily push a new node onto the stack. After calling this function, any * other formatting functions will have their nodes added as children of this new * parent. * * \param[in,out] out The output functions structure. * \param[in] node The node to be added/ */ void pcmk__output_xml_push_parent(pcmk__output_t *out, xmlNodePtr node); /*! * \internal * \brief Pop a parent XML node onto the stack. This is used when implementing * custom message functions. * * This function removes a parent node from the stack. See pcmk__xml_push_parent() * for more details. * * \note Little checking is done with this function. Be sure you only pop parents * that were previously pushed. In general, it is best to keep the code between * push and pop simple. * * \param[in,out] out The output functions structure. */ void pcmk__output_xml_pop_parent(pcmk__output_t *out); /*! * \internal * \brief Peek a parent XML node onto the stack. This is used when implementing * custom message functions. * * This function peeks a parent node on stack. See pcmk__xml_push_parent() * for more details. It has no side-effect and can be called for an empty stack. * * \note Little checking is done with this function. * * \param[in,out] out The output functions structure. * * \return NULL if stack is empty, otherwise the parent of the stack. */ xmlNodePtr pcmk__output_xml_peek_parent(pcmk__output_t *out); /*! * \internal * \brief Create a new XML node consisting of the provided text inside an HTML * element node of the given name. * * \param[in,out] out The output functions structure. * \param[in] element_name The name of the new HTML element. * \param[in] id The CSS ID selector to apply to this element. * If NULL, no ID is added. * \param[in] class_name The CSS class selector to apply to this element. * If NULL, no class is added. * \param[in] text The text content of the node. */ xmlNodePtr pcmk__output_create_html_node(pcmk__output_t *out, const char *element_name, const char *id, const char *class_name, const char *text); /*! * \internal * \brief Add an HTML tag to the section. * * The arguments after name are a NULL-terminated list of keys and values, * all of which will be added as attributes to the given tag. For instance, * the following code would generate the tag "": * * \code * pcmk__html_add_header(parent, "meta", "http-equiv", "refresh", "content", "19", NULL); * \endcode * * \param[in,out] parent The node that will be the parent of the new node. * \param[in] name The HTML tag for the new node. * \param[in] ... A NULL-terminated key/value list of attributes. */ void pcmk__html_add_header(xmlNodePtr parent, const char *name, ...) G_GNUC_NULL_TERMINATED; #ifdef __cplusplus } #endif #endif diff --git a/include/doxygen.h b/include/doxygen.h index 5d465a7ff6..7fa258cd60 100644 --- a/include/doxygen.h +++ b/include/doxygen.h @@ -1,50 +1,52 @@ /* * Copyright 2006-2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef DOXYGEN__H # define DOXYGEN__H /** * \file * \brief Fake header file that contains doxygen documentation. * \author Andrew Beekhof * * The purpose of this file is to provide a file that can be used to create * doxygen pages. It should contain _only_ comment blocks. * * * \defgroup core Core API * \defgroup date ISO-8601 Date/Time API * \defgroup cib Configuration API * \defgroup lrmd Executor API * \defgroup pengine Scheduler API * \defgroup fencing Fencing API + * \defgroup pacemaker Pacemaker High Level API */ /** * \mainpage * Welcome to the developer documentation for The Pacemaker Project! For more * information about Pacemaker, please visit the * project web site. * * Here are some pointers on where to go from here. * * Using Pacemaker APIs: * - \ref core * - \ref date * - \ref cib * - \ref lrmd * - \ref pengine * - \ref fencing + * - \ref pacemaker * * Contributing to the Pacemaker Project: * - Pacemaker Development */ #endif /* DOXYGEN__H */ diff --git a/include/pacemaker-internal.h b/include/pacemaker-internal.h index 51d722550b..37399e73a8 100644 --- a/include/pacemaker-internal.h +++ b/include/pacemaker-internal.h @@ -1,20 +1,22 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef PACEMAKER_INTERNAL__H # define PACEMAKER_INTERNAL__H # include +# include +# include # include # include # include # include # include #endif diff --git a/include/pacemaker.h b/include/pacemaker.h new file mode 100644 index 0000000000..43a4a6c1a8 --- /dev/null +++ b/include/pacemaker.h @@ -0,0 +1,202 @@ +/* + * Copyright 2019 the Pacemaker project contributors + * + * The version control history for this file may have further details. + * + * This source code is licensed under the GNU Lesser General Public License + * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. + */ + +#ifndef PACEMAKER__H +# define PACEMAKER__H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef BUILD_PUBLIC_LIBPACEMAKER + +/** + * \file + * \brief High Level API + * \ingroup pacemaker + */ + +# include +# include + +/*! + * \brief Perform a STONITH action. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The node receiving the action. + * \param[in] action The action to perform. + * \param[in] name Who requested the fence action? + * \param[in] timeout How long to wait for the operation to complete (in ms). + * \param[in] tolerance If a successful action for \p target happened within + * this many ms, return 0 without performing the action + * again. + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_action(stonith_t *st, const char *target, const char *action, + const char *name, unsigned int timeout, unsigned int tolerance); + +/*! + * \brief List the fencing operations that have occurred for a specific node. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] target The node to get history for. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * \param[in] quiet Suppress most output. + * \param[in] verbose Include additional output. + * \param[in] broadcast Gather fencing history from all nodes. + * \param[in] cleanup Clean up fencing history after listing. + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_history(xmlNodePtr *xml, stonith_t *st, char *target, + unsigned int timeout, bool quiet, int verbose, + bool broadcast, bool cleanup); + +/*! + * \brief List all installed STONITH agents. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_installed(xmlNodePtr *xml, stonith_t *st, unsigned int timeout); + +/*! + * \brief When was a device last fenced? + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] target The node that was fenced. + * \param[in] as_nodeid + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_last(xmlNodePtr *xml, const char *target, bool as_nodeid); + +/*! + * \brief List nodes that can be fenced. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The agent that can do the fencing. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_list_targets(xmlNodePtr *xml, stonith_t *st, char *agent, + unsigned int timeout); + +/*! + * \brief Get metadata for a resource. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The fence agent to get metadata for. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_metadata(xmlNodePtr *xml, stonith_t *st, char *agent, + unsigned int timeout); + +/*! + * \brief List registered fence devices. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] target If not NULL, only return devices that can fence + * this node. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_registered(xmlNodePtr *xml, stonith_t *st, char *target, + unsigned int timeout); + +/*! + * \brief Register a fencing level for a specific node, node regex, or attribute. + * + * \p target can take three different forms: + * - name=value, in which case \p target is an attribute. + * - @pattern, in which case \p target is a node regex. + * - Otherwise, \p target is a node name. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The object to register a fencing level for. + * \param[in] fence_level Index number of level to add. + * \param[in] devices Devices to use in level. + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_register_level(stonith_t *st, char *target, int fence_level, + stonith_key_value_t *devices); + +/*! + * \brief Unregister a fencing level for a specific node, node regex, or attribute. + * + * \p target can take three different forms: + * - name=value, in which case \p target is an attribute. + * - @pattern, in which case \p target is a node regex. + * - Otherwise, \p target is a node name. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The object to unregister a fencing level for. + * \param[in] fence_level Index number of level to remove. + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_unregister_level(stonith_t *st, char *target, int fence_level); + +/*! + * \brief Validate a STONITH device configuration. + * + * \note If \p xml is not NULL, it will be freed first and the previous + * contents lost. + * + * \param[in,out] xml The destination for the result, as an XML tree. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The agent to validate (for example, "fence_xvm"). + * \param[in] id STONITH device ID (may be NULL). + * \param[in] params STONITH device configuration parameters. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk_fence_validate(xmlNodePtr *xml, stonith_t *st, const char *agent, + const char *id, stonith_key_value_t *params, + unsigned int timeout); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/pcmki/Makefile.am b/include/pcmki/Makefile.am index 4cf1cf23ab..647f2dca6c 100644 --- a/include/pcmki/Makefile.am +++ b/include/pcmki/Makefile.am @@ -1,19 +1,21 @@ # # Copyright 2019 the Pacemaker project contributors # # The version control history for this file may have further details. # # This source code is licensed under the GNU General Public License version 2 # or later (GPLv2+) WITHOUT ANY WARRANTY. # MAINTAINERCLEANFILES = Makefile.in noinst_HEADERS = pcmki_error.h \ + pcmki_fence.h \ + pcmki_output.h \ pcmki_sched_allocate.h \ pcmki_sched_notif.h \ pcmki_sched_utils.h \ pcmki_scheduler.h \ pcmki_transition.h .PHONY: $(ARCHIVE_VERSION) diff --git a/include/pcmki/pcmki_fence.h b/include/pcmki/pcmki_fence.h new file mode 100644 index 0000000000..6f699e27ec --- /dev/null +++ b/include/pcmki/pcmki_fence.h @@ -0,0 +1,220 @@ +/* + * Copyright 2019 the Pacemaker project contributors + * + * The version control history for this file may have further details. + * + * This source code is licensed under the GNU Lesser General Public License + * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. + */ +#ifndef PCMKI_STONITH_H +# define PCMKI_STONITH_H + +# include +# include + +/*! + * \brief Perform a STONITH action. + * + * \note This is the internal version of pcmk_fence_action(). External users + * of the pacemaker API should use that function instead. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The node receiving the action. + * \param[in] action The action to perform. + * \param[in] name Who requested the fence action? + * \param[in] timeout How long to wait for the operation to complete (in ms). + * \param[in] tolerance If a successful action for \p target happened within + * this many ms, return 0 without performing the action + * again. + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_action(stonith_t *st, const char *target, const char *action, + const char *name, unsigned int timeout, unsigned int tolerance); + +/*! + * \brief List the fencing operations that have occurred for a specific node. + * + * \note This is the internal version of pcmk_fence_history(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] target The node to get history for. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * \param[in] quiet Suppress most output. + * \param[in] verbose Include additional output. + * \param[in] broadcast Gather fencing history from all nodes. + * \param[in] cleanup Clean up fencing history after listing. + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_history(pcmk__output_t *out, stonith_t *st, char *target, + unsigned int timeout, bool quiet, int verbose, + bool broadcast, bool cleanup); + +/** + * \brief List all installed STONITH agents. + * + * \note This is the internal version of pcmk_fence_installed(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_installed(pcmk__output_t *out, stonith_t *st, unsigned int timeout); + +/*! + * \brief When was a device last fenced? + * + * \note This is the internal version of pcmk_fence_last(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] target The node that was fenced. + * \param[in] as_nodeid + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_last(pcmk__output_t *out, const char *target, bool as_nodeid); + +/*! + * \brief List nodes that can be fenced. + * + * \note This is the internal version of pcmk_fence_list_targets(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The agent that can do the fencing. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_list_targets(pcmk__output_t *out, stonith_t *st, char *agent, + unsigned int timeout); + +/*! + * \brief Get metadata for a resource. + * + * \note This is the internal version of pcmk_fence_metadata(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The fence agent to get metadata for. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_metadata(pcmk__output_t *out, stonith_t *st, char *agent, + unsigned int timeout); + +/*! + * \brief List registered fence devices. + * + * \note This is the internal version of pcmk_fence_metadata(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] target If not NULL, only return devices that can fence + * this node. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_registered(pcmk__output_t *out, stonith_t *st, char *target, + unsigned int timeout); + +/*! + * \brief Register a fencing level for a specific node, node regex, or attribute. + * + * \note This is the internal version of pcmk_fence_register_level(). External users + * of the pacemaker API should use that function instead. + * + * \p target can take three different forms: + * - name=value, in which case \p target is an attribute. + * - @pattern, in which case \p target is a node regex. + * - Otherwise, \p target is a node name. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The object to register a fencing level for. + * \param[in] fence_level Index number of level to add. + * \param[in] devices Devices to use in level. + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_register_level(stonith_t *st, char *target, int fence_level, + stonith_key_value_t *devices); + +/*! + * \brief Unregister a fencing level for a specific node, node regex, or attribute. + * + * \note This is the internal version of pcmk_fence_unregister_level(). External users + * of the pacemaker API should use that function instead. + * + * \p target can take three different forms: + * - name=value, in which case \p target is an attribute. + * - @pattern, in which case \p target is a node regex. + * - Otherwise, \p target is a node name. + * + * \param[in] st A connection to the STONITH API. + * \param[in] target The object to unregister a fencing level for. + * \param[in] fence_level Index number of level to remove. + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_unregister_level(stonith_t *st, char *target, int fence_level); + +/** + * \brief Validate a STONITH device configuration. + * + * \note This is the internal version of pcmk_stonith_validate(). External users + * of the pacemaker API should use that function instead. + * + * \note \p out should be initialized with pcmk__output_new() before calling this + * function and destroyed with out->finish and pcmk__output_free() before + * reusing it with any other functions in this library. + * + * \param[in,out] out The output functions structure. + * \param[in] st A connection to the STONITH API. + * \param[in] agent The agent to validate (for example, "fence_xvm"). + * \param[in] id STONITH device ID (may be NULL). + * \param[in] params STONITH device configuration parameters. + * \param[in] timeout How long to wait for the operation to complete (in ms). + * + * \return Standard Pacemaker return code + */ +int pcmk__fence_validate(pcmk__output_t *out, stonith_t *st, const char *agent, + const char *id, stonith_key_value_t *params, + unsigned int timeout); + +#endif diff --git a/include/pcmki/pcmki_output.h b/include/pcmki/pcmki_output.h new file mode 100644 index 0000000000..fb3be415a7 --- /dev/null +++ b/include/pcmki/pcmki_output.h @@ -0,0 +1,28 @@ +/* + * Copyright 2019 the Pacemaker project contributors + * + * The version control history for this file may have further details. + * + * This source code is licensed under the GNU Lesser General Public License + * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. + */ +#ifndef PCMKI_OUTPUT_H +# define PCMKI_OUTPUT_H + +#ifdef __cplusplus +extern "C" { +#endif + +# include +# include + +extern pcmk__supported_format_t pcmk__out_formats[]; + +int pcmk__out_prologue(pcmk__output_t **out, xmlNodePtr *xml); +void pcmk__out_epilogue(pcmk__output_t *out, xmlNodePtr *xml, int retval); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/lib/common/cmdline.c b/lib/common/cmdline.c index 1d78e5cf07..fd8a2aae9f 100644 --- a/lib/common/cmdline.c +++ b/lib/common/cmdline.c @@ -1,257 +1,261 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include #include #include #include #include static gboolean bump_verbosity(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { pcmk__common_args_t *common_args = (pcmk__common_args_t *) data; common_args->verbosity++; return TRUE; } pcmk__common_args_t * pcmk__new_common_args(const char *summary) { pcmk__common_args_t *args = NULL; args = calloc(1, sizeof(pcmk__common_args_t)); if (args == NULL) { crm_exit(crm_errno2exit(-ENOMEM)); } args->summary = strdup(summary); if (args->summary == NULL) { crm_exit(crm_errno2exit(-ENOMEM)); } return args; } static void free_common_args(gpointer data) { pcmk__common_args_t *common_args = (pcmk__common_args_t *) data; free(common_args->summary); free(common_args->output_ty); free(common_args->output_dest); if (common_args->output_as_descr != NULL) { free(common_args->output_as_descr); } free(common_args); } GOptionContext * pcmk__build_arg_context(pcmk__common_args_t *common_args, const char *fmts, GOptionGroup **output_group) { char *desc = crm_strdup_printf("Report bugs to %s\n", PACKAGE_BUGREPORT); GOptionContext *context; GOptionGroup *main_group; GOptionEntry main_entries[3] = { { "version", '$', 0, G_OPTION_ARG_NONE, &(common_args->version), "Display software version and exit", NULL }, { "verbose", 'V', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, bump_verbosity, "Increase debug output (may be specified multiple times)", NULL }, { NULL } }; main_group = g_option_group_new(NULL, "Application Options:", NULL, common_args, free_common_args); g_option_group_add_entries(main_group, main_entries); context = g_option_context_new(NULL); g_option_context_set_summary(context, common_args->summary); g_option_context_set_description(context, desc); g_option_context_set_main_group(context, main_group); if (fmts != NULL) { GOptionEntry output_entries[3] = { { "output-as", 0, 0, G_OPTION_ARG_STRING, &(common_args->output_ty), NULL, "FORMAT" }, { "output-to", 0, 0, G_OPTION_ARG_STRING, &(common_args->output_dest), "Specify file name for output (or \"-\" for stdout)", "DEST" }, { NULL } }; if (*output_group == NULL) { *output_group = g_option_group_new("output", "Output Options:", "Show output help", NULL, NULL); } common_args->output_as_descr = crm_strdup_printf("Specify output format as one of: %s", fmts); output_entries[0].description = common_args->output_as_descr; g_option_group_add_entries(*output_group, output_entries); g_option_context_add_group(context, *output_group); } free(desc); return context; } void pcmk__free_arg_context(GOptionContext *context) { if (context == NULL) { return; } g_option_context_free(context); } void pcmk__add_main_args(GOptionContext *context, GOptionEntry entries[]) { GOptionGroup *main_group = g_option_context_get_main_group(context); g_option_group_add_entries(main_group, entries); } void pcmk__add_arg_group(GOptionContext *context, const char *name, const char *header, const char *desc, GOptionEntry entries[]) { GOptionGroup *group = NULL; group = g_option_group_new(name, header, desc, NULL, NULL); g_option_group_add_entries(group, entries); g_option_context_add_group(context, group); } -char ** -pcmk__cmdline_preproc(int argc, char **argv, const char *special) { - char **retval = NULL; +gchar ** +pcmk__cmdline_preproc(char **argv, const char *special) { + gchar **retval = NULL; GPtrArray *arr = g_ptr_array_new(); bool saw_dash_dash = false; - for (int i = 0; i < argc; i++) { + if (argv == NULL) { + return retval; + } + + for (int i = 0; argv[i] != NULL; i++) { /* If this is the first time we saw "--" in the command line, set * a flag so we know to just copy everything after it over. We also * want to copy the "--" over so whatever actually parses the command * line when we're done knows where arguments end. */ if (saw_dash_dash == false && strcmp(argv[i], "--") == 0) { saw_dash_dash = true; } if (saw_dash_dash == true) { g_ptr_array_add(arr, strdup(argv[i])); continue; } /* This is just a dash by itself. That could indicate stdin/stdout, or * it could be user error. Copy it over and let glib figure it out. */ if (safe_str_eq(argv[i], "-")) { g_ptr_array_add(arr, strdup(argv[i])); continue; } /* This is a short argument, or perhaps several. Iterate over it * and explode them out into individual arguments. */ if (g_str_has_prefix(argv[i], "-") && !g_str_has_prefix(argv[i], "--")) { /* Skip over leading dash */ char *ch = argv[i]+1; while (*ch != '\0') { /* This is a special short argument that takes an option. getopt * allows values to be interspersed with a list of arguments, but * glib does not. Grab both the argument and its value and * separate them into a new argument. */ if (strchr(special, *ch) != NULL) { /* The argument does not occur at the end of this string of * arguments. Take everything through the end as its value. */ if (*(ch+1) != '\0') { g_ptr_array_add(arr, (gpointer) crm_strdup_printf("-%c", *ch)); g_ptr_array_add(arr, strdup(ch+1)); break; /* The argument occurs at the end of this string. Hopefully * whatever comes next in argv is its value. It may not be, * but that is not for us to decide. */ } else { g_ptr_array_add(arr, (gpointer) crm_strdup_printf("-%c", *ch)); ch++; } /* This is a regular short argument. Just copy it over. */ } else { g_ptr_array_add(arr, (gpointer) crm_strdup_printf("-%c", *ch)); ch++; } } /* This is a long argument, or an option, or something else. * Copy it over - everything else is copied, so this keeps it easy for * the caller to know what to do with the memory when it's done. */ } else { g_ptr_array_add(arr, strdup(argv[i])); } } - /* Convert the GPtrArray into a char **, which the command line parsing + /* Convert the GPtrArray into a gchar **, which the command line parsing * code knows how to deal with. Then we can free the array (but not its * contents). */ retval = calloc(arr->len+1, sizeof(char *)); for (int i = 0; i < arr->len; i++) { - retval [i] = (char *) g_ptr_array_index(arr, i); + retval[i] = (gchar *) g_ptr_array_index(arr, i); } g_ptr_array_free(arr, FALSE); return retval; } G_GNUC_PRINTF(3, 4) gboolean pcmk__force_args(GOptionContext *context, GError **error, const char *format, ...) { int len = 0; char *buf = NULL; gchar **extra_args = NULL; va_list ap; gboolean retval = TRUE; va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len > 0); va_end(ap); if (!g_shell_parse_argv(buf, NULL, &extra_args, error)) { g_strfreev(extra_args); free(buf); return FALSE; } retval = g_option_context_parse_strv(context, &extra_args, error); g_strfreev(extra_args); free(buf); return retval; } diff --git a/lib/common/output.c b/lib/common/output.c index bfce29247e..571be3caa5 100644 --- a/lib/common/output.c +++ b/lib/common/output.c @@ -1,141 +1,141 @@ /* * Copyright 2019-2020 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include static GHashTable *formatters = NULL; void pcmk__output_free(pcmk__output_t *out) { out->free_priv(out); if (out->messages != NULL) { g_hash_table_destroy(out->messages); } - free(out->request); + g_free(out->request); free(out); } int pcmk__output_new(pcmk__output_t **out, const char *fmt_name, const char *filename, char **argv) { pcmk__output_factory_t create = NULL;; if (formatters == NULL) { return EINVAL; } /* If no name was given, just try "text". It's up to each tool to register * what it supports so this also may not be valid. */ if (fmt_name == NULL) { create = g_hash_table_lookup(formatters, "text"); } else { create = g_hash_table_lookup(formatters, fmt_name); } if (create == NULL) { return pcmk_rc_unknown_format; } *out = create(argv); if (*out == NULL) { return ENOMEM; } if (filename == NULL || safe_str_eq(filename, "-")) { (*out)->dest = stdout; } else { (*out)->dest = fopen(filename, "w"); if ((*out)->dest == NULL) { return errno; } } (*out)->messages = g_hash_table_new_full(crm_str_hash, g_str_equal, free, NULL); if ((*out)->init(*out) == false) { pcmk__output_free(*out); return ENOMEM; } return pcmk_rc_ok; } int pcmk__register_format(GOptionGroup *group, const char *name, pcmk__output_factory_t create, GOptionEntry *options) { if (create == NULL) { return -EINVAL; } if (formatters == NULL) { formatters = g_hash_table_new_full(crm_str_hash, g_str_equal, NULL, NULL); } if (options != NULL && group != NULL) { g_option_group_add_entries(group, options); } g_hash_table_insert(formatters, strdup(name), create); return 0; } void pcmk__register_formats(GOptionGroup *group, pcmk__supported_format_t *formats) { pcmk__supported_format_t *entry = NULL; if (formats == NULL) { return; } for (entry = formats; entry->name != NULL; entry++) { pcmk__register_format(group, entry->name, entry->create, entry->options); } } int pcmk__call_message(pcmk__output_t *out, const char *message_id, ...) { va_list args; int rc = 0; pcmk__message_fn_t fn; fn = g_hash_table_lookup(out->messages, message_id); if (fn == NULL) { return -EINVAL; } va_start(args, message_id); rc = fn(out, args); va_end(args); return rc; } void pcmk__register_message(pcmk__output_t *out, const char *message_id, pcmk__message_fn_t fn) { g_hash_table_replace(out->messages, strdup(message_id), fn); } void pcmk__register_messages(pcmk__output_t *out, pcmk__message_entry_t *table) { pcmk__message_entry_t *entry; for (entry = table; entry->message_id != NULL; entry++) { if (safe_str_eq(out->fmt_name, entry->fmt_name)) { pcmk__register_message(out, entry->message_id, entry->fn); } } } diff --git a/lib/common/output_html.c b/lib/common/output_html.c index b27b345f18..ebbb9eed8c 100644 --- a/lib/common/output_html.c +++ b/lib/common/output_html.c @@ -1,420 +1,420 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include static const char *stylesheet_default = ".bold { font-weight: bold }\n" ".maint { color: blue }\n" ".offline { color: red }\n" ".online { color: green }\n" ".rsc-failed { color: red }\n" ".rsc-failure-ignored { color: yellow }\n" ".rsc-managed { color: yellow }\n" ".rsc-multiple { color: orange }\n" ".rsc-ok { color: green }\n" ".standby { color: orange }\n" ".warning { color: red, font-weight: bold }"; static gboolean cgi_output = FALSE; static char *stylesheet_link = NULL; static char *title = NULL; GOptionEntry pcmk__html_output_entries[] = { { "html-cgi", 0, 0, G_OPTION_ARG_NONE, &cgi_output, "Add CGI headers (requires --output-as=html)", NULL }, { "html-stylesheet", 0, 0, G_OPTION_ARG_STRING, &stylesheet_link, "Link to an external stylesheet (requires --output-as=html)", "URI" }, { "html-title", 0, 0, G_OPTION_ARG_STRING, &title, "Specify a page title (requires --output-as=html)", "TITLE" }, { NULL } }; typedef struct private_data_s { xmlNode *root; GQueue *parent_q; GSList *errors; } private_data_t; static void html_free_priv(pcmk__output_t *out) { private_data_t *priv = out->priv; if (priv == NULL) { return; } xmlFreeNode(priv->root); g_queue_free(priv->parent_q); g_slist_free(priv->errors); free(priv); } static bool html_init(pcmk__output_t *out) { private_data_t *priv = NULL; /* If html_init was previously called on this output struct, just return. */ if (out->priv != NULL) { return true; } else { out->priv = calloc(1, sizeof(private_data_t)); if (out->priv == NULL) { return false; } priv = out->priv; } priv->parent_q = g_queue_new(); priv->root = create_xml_node(NULL, "html"); xmlCreateIntSubset(priv->root->doc, (pcmkXmlStr) "html", NULL, NULL); xmlSetProp(priv->root, (pcmkXmlStr) "lang", (pcmkXmlStr) "en"); g_queue_push_tail(priv->parent_q, priv->root); priv->errors = NULL; pcmk__output_xml_create_parent(out, "body"); return true; } static void add_error_node(gpointer data, gpointer user_data) { char *str = (char *) data; pcmk__output_t *out = (pcmk__output_t *) user_data; out->list_item(out, NULL, "%s", str); } static void html_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { private_data_t *priv = out->priv; htmlNodePtr head_node = NULL; htmlNodePtr charset_node = NULL; /* If root is NULL, html_init failed and we are being called from pcmk__output_free * in the pcmk__output_new path. */ if (priv == NULL || priv->root == NULL) { return; } if (cgi_output && print) { fprintf(out->dest, "Content-Type: text/html\n\n"); } /* Add the head node last - it's not needed earlier because it doesn't contain * anything else that the user could add, and we want it done last to pick up * any options that may have been given. */ head_node = xmlNewNode(NULL, (pcmkXmlStr) "head"); if (title != NULL ) { pcmk_create_xml_text_node(head_node, "title", title); } else if (out->request != NULL) { pcmk_create_xml_text_node(head_node, "title", out->request); } charset_node = create_xml_node(head_node, "meta"); xmlSetProp(charset_node, (pcmkXmlStr) "charset", (pcmkXmlStr) "utf-8"); /* Stylesheets are included two different ways. The first is via a built-in * default (see the stylesheet_default const above). The second is via the * html-stylesheet option, and this should obviously be a link to a * stylesheet. The second can override the first. At least one should be * given. */ pcmk_create_xml_text_node(head_node, "style", stylesheet_default); if (stylesheet_link != NULL) { htmlNodePtr link_node = create_xml_node(head_node, "link"); xmlSetProp(link_node, (pcmkXmlStr) "rel", (pcmkXmlStr) "stylesheet"); xmlSetProp(link_node, (pcmkXmlStr) "href", (pcmkXmlStr) stylesheet_link); } xmlAddPrevSibling(priv->root->children, head_node); if (g_slist_length(priv->errors) > 0) { out->begin_list(out, "Errors", NULL, NULL); g_slist_foreach(priv->errors, add_error_node, (gpointer) out); out->end_list(out); } if (print) { htmlDocDump(out->dest, priv->root->doc); } if (copy_dest != NULL) { *copy_dest = copy_xml(priv->root); } } static void html_reset(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); htmlDocDump(out->dest, priv->root->doc); html_free_priv(out); html_init(out); } static void html_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { char *rc_buf = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); rc_buf = crm_strdup_printf("Return code: %d", exit_status); pcmk__output_create_xml_text_node(out, "h2", "Command Output"); pcmk__output_create_html_node(out, "div", NULL, NULL, rc_buf); if (proc_stdout != NULL) { pcmk__output_create_html_node(out, "div", NULL, NULL, "Stdout"); pcmk__output_create_html_node(out, "div", NULL, "output", proc_stdout); } if (proc_stderr != NULL) { pcmk__output_create_html_node(out, "div", NULL, NULL, "Stderr"); pcmk__output_create_html_node(out, "div", NULL, "output", proc_stderr); } free(rc_buf); } static void html_version(pcmk__output_t *out, bool extended) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); pcmk__output_create_xml_text_node(out, "h2", "Version Information"); pcmk__output_create_html_node(out, "div", NULL, NULL, "Program: Pacemaker"); pcmk__output_create_html_node(out, "div", NULL, NULL, crm_strdup_printf("Version: %s", PACEMAKER_VERSION)); pcmk__output_create_html_node(out, "div", NULL, NULL, "Author: Andrew Beekhof"); pcmk__output_create_html_node(out, "div", NULL, NULL, crm_strdup_printf("Build: %s", BUILD_VERSION)); pcmk__output_create_html_node(out, "div", NULL, NULL, crm_strdup_printf("Features: %s", CRM_FEATURES)); } G_GNUC_PRINTF(2, 3) static void html_err(pcmk__output_t *out, const char *format, ...) { private_data_t *priv = out->priv; int len = 0; char *buf = NULL; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len >= 0); va_end(ap); priv->errors = g_slist_append(priv->errors, buf); } G_GNUC_PRINTF(2, 3) static void html_info(pcmk__output_t *out, const char *format, ...) { /* This function intentially left blank */ } static void html_output_xml(pcmk__output_t *out, const char *name, const char *buf) { htmlNodePtr node = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); node = pcmk__output_create_html_node(out, "pre", NULL, NULL, buf); xmlSetProp(node, (pcmkXmlStr) "lang", (pcmkXmlStr) "xml"); } G_GNUC_PRINTF(4, 5) static void html_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { int q_len = 0; private_data_t *priv = out->priv; xmlNodePtr node = NULL; CRM_ASSERT(priv != NULL); /* If we are already in a list (the queue depth is always at least * one because of the element), first create a
  • element * to hold the

    and the new list. */ q_len = g_queue_get_length(priv->parent_q); if (q_len > 2) { pcmk__output_xml_create_parent(out, "li"); } if (format != NULL) { va_list ap; char *buf = NULL; int len; va_start(ap, format); len = vasprintf(&buf, format, ap); va_end(ap); CRM_ASSERT(len >= 0); if (q_len > 2) { pcmk__output_create_xml_text_node(out, "h3", buf); } else { pcmk__output_create_xml_text_node(out, "h2", buf); } free(buf); } node = pcmk__output_xml_create_parent(out, "ul"); g_queue_push_tail(priv->parent_q, node); } G_GNUC_PRINTF(3, 4) static void html_list_item(pcmk__output_t *out, const char *name, const char *format, ...) { private_data_t *priv = out->priv; htmlNodePtr item_node = NULL; va_list ap; char *buf = NULL; int len; CRM_ASSERT(priv != NULL); va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len >= 0); va_end(ap); item_node = pcmk__output_create_xml_text_node(out, "li", buf); free(buf); if (name != NULL) { xmlSetProp(item_node, (pcmkXmlStr) "class", (pcmkXmlStr) name); } } static void html_increment_list(pcmk__output_t *out) { /* This function intentially left blank */ } static void html_end_list(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); /* Remove the
      tag. */ g_queue_pop_tail(priv->parent_q); pcmk__output_xml_pop_parent(out); /* Remove the
    • created for nested lists. */ if (g_queue_get_length(priv->parent_q) > 2) { pcmk__output_xml_pop_parent(out); } } pcmk__output_t * pcmk__mk_html_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "html"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = false; retval->init = html_init; retval->free_priv = html_free_priv; retval->finish = html_finish; retval->reset = html_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = html_subprocess_output; retval->version = html_version; retval->info = html_info; retval->err = html_err; retval->output_xml = html_output_xml; retval->begin_list = html_begin_list; retval->list_item = html_list_item; retval->increment_list = html_increment_list; retval->end_list = html_end_list; return retval; } xmlNodePtr pcmk__output_create_html_node(pcmk__output_t *out, const char *element_name, const char *id, const char *class_name, const char *text) { htmlNodePtr node = pcmk__output_create_xml_text_node(out, element_name, text); if (class_name != NULL) { xmlSetProp(node, (pcmkXmlStr) "class", (pcmkXmlStr) class_name); } if (id != NULL) { xmlSetProp(node, (pcmkXmlStr) "id", (pcmkXmlStr) id); } return node; } void pcmk__html_add_header(xmlNodePtr parent, const char *name, ...) { htmlNodePtr head_node; htmlNodePtr header_node; va_list ap; head_node = find_xml_node(parent, "head", TRUE); va_start(ap, name); header_node = create_xml_node(head_node, name); while (1) { char *key = va_arg(ap, char *); char *value; if (key == NULL) { break; } value = va_arg(ap, char *); xmlSetProp(header_node, (pcmkXmlStr) key, (pcmkXmlStr) value); } va_end(ap); } diff --git a/lib/common/output_log.c b/lib/common/output_log.c index 76209fa379..ec786666ab 100644 --- a/lib/common/output_log.c +++ b/lib/common/output_log.c @@ -1,250 +1,250 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include GOptionEntry pcmk__log_output_entries[] = { { NULL } }; typedef struct private_data_s { /* gathered in log_begin_list */ GQueue/**/ *prefixes; } private_data_t; static void log_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { /* This function intentionally left blank */ } static void log_free_priv(pcmk__output_t *out) { private_data_t *priv = out->priv; if (priv == NULL) { return; } g_queue_free(priv->prefixes); free(priv); } static bool log_init(pcmk__output_t *out) { /* If log_init was previously called on this output struct, just return. */ if (out->priv != NULL) { return true; } out->priv = calloc(1, sizeof(private_data_t)); if (out->priv == NULL) { return false; } ((private_data_t *)out->priv)->prefixes = g_queue_new(); return true; } static void log_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { /* This function intentionally left blank */ } static void log_reset(pcmk__output_t *out) { CRM_ASSERT(out && out->priv); log_free_priv(out); log_init(out); } static void log_version(pcmk__output_t *out, bool extended) { if (extended) { crm_info("Pacemaker %s (Build: %s): %s", PACEMAKER_VERSION, BUILD_VERSION, CRM_FEATURES); } else { crm_info("Pacemaker %s", PACEMAKER_VERSION); crm_info("Written by Andrew Beekhof"); } } G_GNUC_PRINTF(2, 3) static void log_err(pcmk__output_t *out, const char *format, ...) { va_list ap; char* buffer = NULL; int len = 0; va_start(ap, format); /* Informational output does not get indented, to separate it from other * potentially indented list output. */ len = vasprintf(&buffer, format, ap); CRM_ASSERT(len >= 0); va_end(ap); crm_err("%s", buffer); free(buffer); } static void log_output_xml(pcmk__output_t *out, const char *name, const char *buf) { xmlNodePtr node = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); node = create_xml_node(NULL, name); xmlNodeSetContent(node, (pcmkXmlStr) buf); crm_log_xml_info(node, name); free(node); } G_GNUC_PRINTF(4, 5) static void log_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { int len = 0; va_list ap; char* buffer = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); va_start(ap, format); len = vasprintf(&buffer, format, ap); CRM_ASSERT(len >= 0); va_end(ap); /* Don't skip empty prefixes, * otherwise there will be mismatch * in the log_end_list */ if(strcmp(buffer, "") == 0) { /* nothing */ } g_queue_push_tail(priv->prefixes, buffer); } G_GNUC_PRINTF(3, 4) static void log_list_item(pcmk__output_t *out, const char *name, const char *format, ...) { int len = 0; va_list ap; private_data_t *priv = out->priv; char prefix[LINE_MAX] = { 0 }; int offset = 0; char* buffer = NULL; CRM_ASSERT(priv != NULL); for (GList* gIter = priv->prefixes->head; gIter; gIter = gIter->next) { if (strcmp(prefix, "") != 0) { offset += snprintf(prefix + offset, LINE_MAX - offset, ": %s", (char *)gIter->data); } else { offset = snprintf(prefix, LINE_MAX, "%s", (char *)gIter->data); } } va_start(ap, format); len = vasprintf(&buffer, format, ap); CRM_ASSERT(len >= 0); va_end(ap); if (strcmp(buffer, "") != 0) { /* We don't want empty messages */ if ((name != NULL) && (strcmp(name, "") != 0)) { if (strcmp(prefix, "") != 0) { crm_info("%s: %s: %s", prefix, name, buffer); } else { crm_info("%s: %s", name, buffer); } } else { if (strcmp(prefix, "") != 0) { crm_info("%s: %s", prefix, buffer); } else { crm_info("%s", buffer); } } } free(buffer); } static void log_end_list(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); if (priv->prefixes == NULL) { return; } CRM_ASSERT(priv->prefixes->tail != NULL); free((char *)priv->prefixes->tail->data); g_queue_pop_tail(priv->prefixes); } G_GNUC_PRINTF(2, 3) static void log_info(pcmk__output_t *out, const char *format, ...) { int len = 0; va_list ap; char* buffer = NULL; va_start(ap, format); len = vasprintf(&buffer, format, ap); CRM_ASSERT(len >= 0); va_end(ap); crm_info("%s", buffer); free(buffer); } pcmk__output_t * pcmk__mk_log_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "log"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = false; retval->init = log_init; retval->free_priv = log_free_priv; retval->finish = log_finish; retval->reset = log_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = log_subprocess_output; retval->version = log_version; retval->info = log_info; retval->err = log_err; retval->output_xml = log_output_xml; retval->begin_list = log_begin_list; retval->list_item = log_list_item; retval->end_list = log_end_list; return retval; } diff --git a/lib/common/output_none.c b/lib/common/output_none.c index c5066a5865..e27e9fc6b6 100644 --- a/lib/common/output_none.c +++ b/lib/common/output_none.c @@ -1,123 +1,123 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include GOptionEntry pcmk__none_output_entries[] = { { NULL } }; static void none_free_priv(pcmk__output_t *out) { /* This function intentionally left blank */ } static bool none_init(pcmk__output_t *out) { return true; } static void none_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { /* This function intentionally left blank */ } static void none_reset(pcmk__output_t *out) { none_free_priv(out); none_init(out); } static void none_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { /* This function intentionally left blank */ } static void none_version(pcmk__output_t *out, bool extended) { /* This function intentionally left blank */ } G_GNUC_PRINTF(2, 3) static void none_err(pcmk__output_t *out, const char *format, ...) { /* This function intentionally left blank */ } G_GNUC_PRINTF(2, 3) static void none_info(pcmk__output_t *out, const char *format, ...) { /* This function intentionally left blank */ } static void none_output_xml(pcmk__output_t *out, const char *name, const char *buf) { /* This function intentionally left blank */ } G_GNUC_PRINTF(4, 5) static void none_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { /* This function intentionally left blank */ } G_GNUC_PRINTF(3, 4) static void none_list_item(pcmk__output_t *out, const char *id, const char *format, ...) { /* This function intentionally left blank */ } static void none_increment_list(pcmk__output_t *out) { /* This function intentionally left blank */ } static void none_end_list(pcmk__output_t *out) { /* This function intentionally left blank */ } pcmk__output_t * pcmk__mk_none_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "none"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = true; retval->init = none_init; retval->free_priv = none_free_priv; retval->finish = none_finish; retval->reset = none_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = none_subprocess_output; retval->version = none_version; retval->info = none_info; retval->err = none_err; retval->output_xml = none_output_xml; retval->begin_list = none_begin_list; retval->list_item = none_list_item; retval->increment_list = none_increment_list; retval->end_list = none_end_list; return retval; } diff --git a/lib/common/output_text.c b/lib/common/output_text.c index 9a078d2f89..829425011a 100644 --- a/lib/common/output_text.c +++ b/lib/common/output_text.c @@ -1,305 +1,305 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include static gboolean fancy = FALSE; GOptionEntry pcmk__text_output_entries[] = { { "text-fancy", 0, 0, G_OPTION_ARG_NONE, &fancy, "Use more highly formatted output (requires --output-as=text)", NULL }, { NULL } }; typedef struct text_list_data_s { unsigned int len; char *singular_noun; char *plural_noun; } text_list_data_t; typedef struct private_data_s { GQueue *parent_q; } private_data_t; static void text_free_priv(pcmk__output_t *out) { private_data_t *priv = out->priv; if (priv == NULL) { return; } g_queue_free(priv->parent_q); free(priv); } static bool text_init(pcmk__output_t *out) { private_data_t *priv = NULL; /* If text_init was previously called on this output struct, just return. */ if (out->priv != NULL) { return true; } else { out->priv = calloc(1, sizeof(private_data_t)); if (out->priv == NULL) { return false; } priv = out->priv; } priv->parent_q = g_queue_new(); return true; } static void text_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { /* This function intentionally left blank */ } static void text_reset(pcmk__output_t *out) { CRM_ASSERT(out->priv != NULL); text_free_priv(out); text_init(out); } static void text_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { if (proc_stdout != NULL) { fprintf(out->dest, "%s\n", proc_stdout); } if (proc_stderr != NULL) { fprintf(out->dest, "%s\n", proc_stderr); } } static void text_version(pcmk__output_t *out, bool extended) { if (extended) { fprintf(out->dest, "Pacemaker %s (Build: %s): %s\n", PACEMAKER_VERSION, BUILD_VERSION, CRM_FEATURES); } else { fprintf(out->dest, "Pacemaker %s\n", PACEMAKER_VERSION); fprintf(out->dest, "Written by Andrew Beekhof\n"); } } G_GNUC_PRINTF(2, 3) static void text_err(pcmk__output_t *out, const char *format, ...) { va_list ap; int len = 0; va_start(ap, format); /* Informational output does not get indented, to separate it from other * potentially indented list output. */ len = vfprintf(stderr, format, ap); CRM_ASSERT(len >= 0); va_end(ap); /* Add a newline. */ fprintf(stderr, "\n"); } G_GNUC_PRINTF(2, 3) static void text_info(pcmk__output_t *out, const char *format, ...) { va_list ap; int len = 0; va_start(ap, format); /* Informational output does not get indented, to separate it from other * potentially indented list output. */ len = vfprintf(out->dest, format, ap); CRM_ASSERT(len >= 0); va_end(ap); /* Add a newline. */ fprintf(out->dest, "\n"); } static void text_output_xml(pcmk__output_t *out, const char *name, const char *buf) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); pcmk__indented_printf(out, "%s", buf); } G_GNUC_PRINTF(4, 5) static void text_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { private_data_t *priv = out->priv; text_list_data_t *new_list = NULL; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); if (fancy && format) { pcmk__indented_vprintf(out, format, ap); fprintf(out->dest, ":\n"); } va_end(ap); new_list = calloc(1, sizeof(text_list_data_t)); new_list->len = 0; new_list->singular_noun = singular_noun == NULL ? NULL : strdup(singular_noun); new_list->plural_noun = plural_noun == NULL ? NULL : strdup(plural_noun); g_queue_push_tail(priv->parent_q, new_list); } G_GNUC_PRINTF(3, 4) static void text_list_item(pcmk__output_t *out, const char *id, const char *format, ...) { private_data_t *priv = out->priv; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); if (fancy) { if (id != NULL) { /* Not really a good way to do this all in one call, so make it two. * The first handles the indentation and list styling. The second * just prints right after that one. */ pcmk__indented_printf(out, "%s: ", id); vfprintf(out->dest, format, ap); } else { pcmk__indented_vprintf(out, format, ap); } } else { pcmk__indented_vprintf(out, format, ap); } fputc('\n', out->dest); va_end(ap); out->increment_list(out); } static void text_increment_list(pcmk__output_t *out) { private_data_t *priv = out->priv; gpointer tail; CRM_ASSERT(priv != NULL); tail = g_queue_peek_tail(priv->parent_q); CRM_ASSERT(tail != NULL); ((text_list_data_t *) tail)->len++; } static void text_end_list(pcmk__output_t *out) { private_data_t *priv = out->priv; text_list_data_t *node = NULL; CRM_ASSERT(priv != NULL); node = g_queue_pop_tail(priv->parent_q); if (node->singular_noun != NULL && node->plural_noun != NULL) { if (node->len == 1) { pcmk__indented_printf(out, "%d %s found\n", node->len, node->singular_noun); } else { pcmk__indented_printf(out, "%d %s found\n", node->len, node->plural_noun); } } free(node); } pcmk__output_t * pcmk__mk_text_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "text"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = true; retval->init = text_init; retval->free_priv = text_free_priv; retval->finish = text_finish; retval->reset = text_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = text_subprocess_output; retval->version = text_version; retval->info = text_info; retval->err = text_err; retval->output_xml = text_output_xml; retval->begin_list = text_begin_list; retval->list_item = text_list_item; retval->increment_list = text_increment_list; retval->end_list = text_end_list; return retval; } G_GNUC_PRINTF(2, 0) void pcmk__indented_vprintf(pcmk__output_t *out, const char *format, va_list args) { int len = 0; if (fancy) { int level = 0; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); level = g_queue_get_length(priv->parent_q); for (int i = 0; i < level; i++) { fprintf(out->dest, " "); } if (level > 0) { fprintf(out->dest, "* "); } } len = vfprintf(out->dest, format, args); CRM_ASSERT(len >= 0); } G_GNUC_PRINTF(2, 3) void pcmk__indented_printf(pcmk__output_t *out, const char *format, ...) { va_list ap; va_start(ap, format); pcmk__indented_vprintf(out, format, ap); va_end(ap); } diff --git a/lib/common/output_xml.c b/lib/common/output_xml.c index acd7d09dac..4bd9a0aa41 100644 --- a/lib/common/output_xml.c +++ b/lib/common/output_xml.c @@ -1,401 +1,401 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include #include static gboolean legacy_xml = FALSE; static gboolean simple_list = FALSE; GOptionEntry pcmk__xml_output_entries[] = { { "xml-legacy", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &legacy_xml, NULL, NULL }, { "xml-simple-list", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &simple_list, NULL, NULL }, { NULL } }; typedef struct private_data_s { xmlNode *root; GQueue *parent_q; GSList *errors; bool legacy_xml; } private_data_t; static void xml_free_priv(pcmk__output_t *out) { private_data_t *priv = out->priv; if (priv == NULL) { return; } xmlFreeNode(priv->root); g_queue_free(priv->parent_q); g_slist_free(priv->errors); free(priv); } static bool xml_init(pcmk__output_t *out) { private_data_t *priv = NULL; /* If xml_init was previously called on this output struct, just return. */ if (out->priv != NULL) { return true; } else { out->priv = calloc(1, sizeof(private_data_t)); if (out->priv == NULL) { return false; } priv = out->priv; } if (legacy_xml) { priv->root = create_xml_node(NULL, "crm_mon"); xmlSetProp(priv->root, (pcmkXmlStr) "version", (pcmkXmlStr) VERSION); } else { priv->root = create_xml_node(NULL, "pacemaker-result"); xmlSetProp(priv->root, (pcmkXmlStr) "api-version", (pcmkXmlStr) PCMK__API_VERSION); if (out->request != NULL) { xmlSetProp(priv->root, (pcmkXmlStr) "request", (pcmkXmlStr) out->request); } } priv->parent_q = g_queue_new(); priv->errors = NULL; g_queue_push_tail(priv->parent_q, priv->root); /* Copy this from the file-level variable. This means that it is only settable * as a command line option, and that pcmk__output_new must be called after all * command line processing is completed. */ priv->legacy_xml = legacy_xml; return true; } static void add_error_node(gpointer data, gpointer user_data) { char *str = (char *) data; xmlNodePtr node = (xmlNodePtr) user_data; pcmk_create_xml_text_node(node, "error", str); } static void xml_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { xmlNodePtr node; private_data_t *priv = out->priv; /* If root is NULL, xml_init failed and we are being called from pcmk__output_free * in the pcmk__output_new path. */ if (priv == NULL || priv->root == NULL) { return; } if (!legacy_xml) { char *rc_as_str = crm_itoa(exit_status); node = create_xml_node(priv->root, "status"); xmlSetProp(node, (pcmkXmlStr) "code", (pcmkXmlStr) rc_as_str); xmlSetProp(node, (pcmkXmlStr) "message", (pcmkXmlStr) crm_exit_str(exit_status)); if (g_slist_length(priv->errors) > 0) { xmlNodePtr errors_node = create_xml_node(node, "errors"); g_slist_foreach(priv->errors, add_error_node, (gpointer) errors_node); } free(rc_as_str); } if (print) { char *buf = dump_xml_formatted_with_text(priv->root); fprintf(out->dest, "%s", buf); free(buf); } if (copy_dest != NULL) { *copy_dest = copy_xml(priv->root); } } static void xml_reset(pcmk__output_t *out) { char *buf = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); buf = dump_xml_formatted_with_text(priv->root); fprintf(out->dest, "%s", buf); free(buf); xml_free_priv(out); xml_init(out); } static void xml_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { xmlNodePtr node, child_node; char *rc_as_str = NULL; rc_as_str = crm_itoa(exit_status); node = pcmk__output_xml_create_parent(out, "command"); xmlSetProp(node, (pcmkXmlStr) "code", (pcmkXmlStr) rc_as_str); if (proc_stdout != NULL) { child_node = pcmk_create_xml_text_node(node, "output", proc_stdout); xmlSetProp(child_node, (pcmkXmlStr) "source", (pcmkXmlStr) "stdout"); } if (proc_stderr != NULL) { child_node = pcmk_create_xml_text_node(node, "output", proc_stderr); xmlSetProp(child_node, (pcmkXmlStr) "source", (pcmkXmlStr) "stderr"); } pcmk__output_xml_add_node(out, node); free(rc_as_str); } static void xml_version(pcmk__output_t *out, bool extended) { xmlNodePtr node; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); node = pcmk__output_create_xml_node(out, "version"); xmlSetProp(node, (pcmkXmlStr) "program", (pcmkXmlStr) "Pacemaker"); xmlSetProp(node, (pcmkXmlStr) "version", (pcmkXmlStr) PACEMAKER_VERSION); xmlSetProp(node, (pcmkXmlStr) "author", (pcmkXmlStr) "Andrew Beekhof"); xmlSetProp(node, (pcmkXmlStr) "build", (pcmkXmlStr) BUILD_VERSION); xmlSetProp(node, (pcmkXmlStr) "features", (pcmkXmlStr) CRM_FEATURES); } G_GNUC_PRINTF(2, 3) static void xml_err(pcmk__output_t *out, const char *format, ...) { private_data_t *priv = out->priv; int len = 0; char *buf = NULL; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len > 0); va_end(ap); priv->errors = g_slist_append(priv->errors, buf); } G_GNUC_PRINTF(2, 3) static void xml_info(pcmk__output_t *out, const char *format, ...) { /* This function intentially left blank */ } static void xml_output_xml(pcmk__output_t *out, const char *name, const char *buf) { xmlNodePtr parent = NULL; xmlNodePtr cdata_node = NULL; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); parent = pcmk__output_create_xml_node(out, name); cdata_node = xmlNewCDataBlock(getDocPtr(parent), (pcmkXmlStr) buf, strlen(buf)); xmlAddChild(parent, cdata_node); } G_GNUC_PRINTF(4, 5) static void xml_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { va_list ap; char *buf = NULL; int len; va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len >= 0); va_end(ap); if (legacy_xml || simple_list) { pcmk__output_xml_create_parent(out, buf); } else { xmlNodePtr list_node = NULL; list_node = pcmk__output_xml_create_parent(out, "list"); xmlSetProp(list_node, (pcmkXmlStr) "name", (pcmkXmlStr) buf); } free(buf); } G_GNUC_PRINTF(3, 4) static void xml_list_item(pcmk__output_t *out, const char *name, const char *format, ...) { private_data_t *priv = out->priv; xmlNodePtr item_node = NULL; va_list ap; char *buf = NULL; int len; CRM_ASSERT(priv != NULL); va_start(ap, format); len = vasprintf(&buf, format, ap); CRM_ASSERT(len >= 0); va_end(ap); item_node = pcmk__output_create_xml_text_node(out, "item", buf); free(buf); xmlSetProp(item_node, (pcmkXmlStr) "name", (pcmkXmlStr) name); } static void xml_increment_list(pcmk__output_t *out) { /* This function intentially left blank */ } static void xml_end_list(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); if (priv->legacy_xml || simple_list) { g_queue_pop_tail(priv->parent_q); } else { char *buf = NULL; xmlNodePtr node; node = g_queue_pop_tail(priv->parent_q); buf = crm_strdup_printf("%lu", xmlChildElementCount(node)); xmlSetProp(node, (pcmkXmlStr) "count", (pcmkXmlStr) buf); free(buf); } } pcmk__output_t * pcmk__mk_xml_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "xml"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = false; retval->init = xml_init; retval->free_priv = xml_free_priv; retval->finish = xml_finish; retval->reset = xml_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = xml_subprocess_output; retval->version = xml_version; retval->info = xml_info; retval->err = xml_err; retval->output_xml = xml_output_xml; retval->begin_list = xml_begin_list; retval->list_item = xml_list_item; retval->increment_list = xml_increment_list; retval->end_list = xml_end_list; return retval; } xmlNodePtr pcmk__output_xml_create_parent(pcmk__output_t *out, const char *name) { xmlNodePtr node = pcmk__output_create_xml_node(out, name); pcmk__output_xml_push_parent(out, node); return node; } void pcmk__output_xml_add_node(pcmk__output_t *out, xmlNodePtr node) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); CRM_ASSERT(node != NULL); xmlAddChild(g_queue_peek_tail(priv->parent_q), node); } xmlNodePtr pcmk__output_create_xml_node(pcmk__output_t *out, const char *name) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); return create_xml_node(g_queue_peek_tail(priv->parent_q), name); } xmlNodePtr pcmk__output_create_xml_text_node(pcmk__output_t *out, const char *name, const char *content) { xmlNodePtr node = pcmk__output_create_xml_node(out, name); xmlNodeSetContent(node, (pcmkXmlStr) content); return node; } void pcmk__output_xml_push_parent(pcmk__output_t *out, xmlNodePtr parent) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); CRM_ASSERT(parent != NULL); g_queue_push_tail(priv->parent_q, parent); } void pcmk__output_xml_pop_parent(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); CRM_ASSERT(g_queue_get_length(priv->parent_q) > 0); g_queue_pop_tail(priv->parent_q); } xmlNodePtr pcmk__output_xml_peek_parent(pcmk__output_t *out) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); /* If queue is empty NULL will be returned */ return g_queue_peek_tail(priv->parent_q); } diff --git a/lib/pacemaker/Makefile.am b/lib/pacemaker/Makefile.am index 0d6bff2cbc..b1a584286d 100644 --- a/lib/pacemaker/Makefile.am +++ b/lib/pacemaker/Makefile.am @@ -1,46 +1,48 @@ # # Copyright 2004-2019 the Pacemaker project contributors # # The version control history for this file may have further details. # # This source code is licensed under the GNU General Public License version 2 # or later (GPLv2+) WITHOUT ANY WARRANTY. # include $(top_srcdir)/Makefile.common AM_CPPFLAGS += -I$(top_builddir) -I$(top_srcdir) ## libraries lib_LTLIBRARIES = libpacemaker.la ## SOURCES libpacemaker_la_LDFLAGS = -version-info 2:0:1 libpacemaker_la_CFLAGS = $(CFLAGS_HARDENED_LIB) libpacemaker_la_LDFLAGS += $(LDFLAGS_HARDENED_LIB) libpacemaker_la_LIBADD = $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/lrmd/liblrmd.la \ $(top_builddir)/lib/common/libcrmcommon.la # -L$(top_builddir)/lib/pils -lpils -export-dynamic -module -avoid-version # Use += rather than backlashed continuation lines for parsing by bumplibs.sh libpacemaker_la_SOURCES = +libpacemaker_la_SOURCES += pcmk_fence.c +libpacemaker_la_SOURCES += pcmk_output.c libpacemaker_la_SOURCES += pcmk_sched_allocate.c libpacemaker_la_SOURCES += pcmk_sched_bundle.c libpacemaker_la_SOURCES += pcmk_sched_clone.c libpacemaker_la_SOURCES += pcmk_sched_constraints.c libpacemaker_la_SOURCES += pcmk_sched_graph.c libpacemaker_la_SOURCES += pcmk_sched_group.c libpacemaker_la_SOURCES += pcmk_sched_messages.c libpacemaker_la_SOURCES += pcmk_sched_native.c libpacemaker_la_SOURCES += pcmk_sched_notif.c libpacemaker_la_SOURCES += pcmk_sched_promotable.c libpacemaker_la_SOURCES += pcmk_sched_transition.c libpacemaker_la_SOURCES += pcmk_sched_utilization.c libpacemaker_la_SOURCES += pcmk_sched_utils.c libpacemaker_la_SOURCES += pcmk_trans_graph.c libpacemaker_la_SOURCES += pcmk_trans_unpack.c libpacemaker_la_SOURCES += pcmk_trans_utils.c diff --git a/lib/pacemaker/pcmk_fence.c b/lib/pacemaker/pcmk_fence.c new file mode 100644 index 0000000000..9434a76dc8 --- /dev/null +++ b/lib/pacemaker/pcmk_fence.c @@ -0,0 +1,482 @@ +/* + * Copyright 2009-2020 the Pacemaker project contributors + * + * The version control history for this file may have further details. + * + * This source code is licensed under the GNU General Public License version 2 + * or later (GPLv2+) WITHOUT ANY WARRANTY. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int st_opts = st_opt_sync_call | st_opt_allow_suicide; + +static GMainLoop *mainloop = NULL; + +static struct { + stonith_t *st; + const char *target; + const char *action; + char *name; + unsigned int timeout; + unsigned int tolerance; + int rc; +} async_fence_data; + +static int +handle_level(stonith_t *st, char *target, int fence_level, + stonith_key_value_t *devices, bool added) { + char *node = NULL; + char *pattern = NULL; + char *name = NULL; + char *value = NULL; + int rc = pcmk_rc_ok; + + if (target == NULL) { + // Not really possible, but makes static analysis happy + return EINVAL; + } + + /* Determine if targeting by attribute, node name pattern or node name */ + value = strchr(target, '='); + if (value != NULL) { + name = target; + *value++ = '\0'; + } else if (*target == '@') { + pattern = target + 1; + } else { + node = target; + } + + /* Register or unregister level as appropriate */ + if (added) { + rc = st->cmds->register_level_full(st, st_opts, node, pattern, + name, value, fence_level, + devices); + } else { + rc = st->cmds->remove_level_full(st, st_opts, node, pattern, + name, value, fence_level); + } + + return pcmk_legacy2rc(rc); +} + +static void +notify_callback(stonith_t * st, stonith_event_t * e) +{ + if (e->result != pcmk_ok) { + return; + } + + if (safe_str_eq(async_fence_data.target, e->target) && + safe_str_eq(async_fence_data.action, e->action)) { + + async_fence_data.rc = e->result; + g_main_loop_quit(mainloop); + } +} + +static void +fence_callback(stonith_t * stonith, stonith_callback_data_t * data) +{ + async_fence_data.rc = data->rc; + + g_main_loop_quit(mainloop); +} + +static gboolean +async_fence_helper(gpointer user_data) +{ + stonith_t *st = async_fence_data.st; + int call_id = 0; + int rc = stonith_api_connect_retry(st, async_fence_data.name, 10); + + if (rc != pcmk_ok) { + fprintf(stderr, "Could not connect to fencer: %s\n", pcmk_strerror(rc)); + g_main_loop_quit(mainloop); + return TRUE; + } + + st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, notify_callback); + + call_id = st->cmds->fence(st, + st_opt_allow_suicide, + async_fence_data.target, + async_fence_data.action, + async_fence_data.timeout/1000, + async_fence_data.tolerance/1000); + + if (call_id < 0) { + g_main_loop_quit(mainloop); + return TRUE; + } + + st->cmds->register_callback(st, + call_id, + async_fence_data.timeout/1000, + st_opt_timeout_updates, NULL, "callback", fence_callback); + + return TRUE; +} + +int +pcmk__fence_action(stonith_t *st, const char *target, const char *action, + const char *name, unsigned int timeout, unsigned int tolerance) +{ + crm_trigger_t *trig; + + async_fence_data.st = st; + async_fence_data.name = strdup(name); + async_fence_data.target = target; + async_fence_data.action = action; + async_fence_data.timeout = timeout; + async_fence_data.tolerance = tolerance; + async_fence_data.rc = pcmk_err_generic; + + trig = mainloop_add_trigger(G_PRIORITY_HIGH, async_fence_helper, NULL); + mainloop_set_trigger(trig); + + mainloop = g_main_loop_new(NULL, FALSE); + g_main_loop_run(mainloop); + + free(async_fence_data.name); + + return pcmk_legacy2rc(async_fence_data.rc); +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_action(stonith_t *st, const char *target, const char *action, + const char *name, unsigned int timeout, unsigned int tolerance) { + return pcmk__fence_action(st, target, action, name, timeout, tolerance); +} +#endif + +int +pcmk__fence_history(pcmk__output_t *out, stonith_t *st, char *target, + unsigned int timeout, bool quiet, int verbose, + bool broadcast, bool cleanup) { + stonith_history_t *history = NULL, *hp, *latest = NULL; + int rc = pcmk_rc_ok; + + if (!quiet) { + if (cleanup) { + out->info(out, "cleaning up fencing-history%s%s", + target ? " for node " : "", target ? target : ""); + } + if (broadcast) { + out->info(out, "gather fencing-history from all nodes"); + } + } + + rc = st->cmds->history(st, st_opts | (cleanup ? st_opt_cleanup : 0) | + broadcast ? st_opt_broadcast : 0, + safe_str_eq(target, "*") ? NULL : target, + &history, timeout/1000); + + out->begin_list(out, "event", "events", "Fencing history"); + + history = stonith__sort_history(history); + for (hp = history; hp; hp = hp->next) { + if (hp->state == st_done) { + latest = hp; + } + + if (quiet || !verbose) { + continue; + } + + out->message(out, "stonith-event", hp, 1, stonith__later_succeeded(hp, history)); + out->increment_list(out); + } + + if (latest) { + if (quiet && out->supports_quiet) { + out->info(out, "%lld", (long long) latest->completed); + } else if (!verbose) { // already printed if verbose + out->message(out, "stonith-event", latest, 0, FALSE); + out->increment_list(out); + } + } + + out->end_list(out); + + stonith_history_free(history); + return pcmk_legacy2rc(rc); +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_history(xmlNodePtr *xml, stonith_t *st, char *target, unsigned int timeout, + bool quiet, int verbose, bool broadcast, bool cleanup) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_history(out, st, target, timeout, quiet, verbose, + broadcast, cleanup); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_installed(pcmk__output_t *out, stonith_t *st, unsigned int timeout) { + stonith_key_value_t *devices = NULL; + int rc = pcmk_rc_ok; + + rc = st->cmds->list_agents(st, st_opt_sync_call, NULL, &devices, timeout/1000); + if (rc != pcmk_rc_ok) { + return pcmk_legacy2rc(rc); + } + + out->begin_list(out, "fence device", "fence devices", "Installed fence devices"); + for (stonith_key_value_t *dIter = devices; dIter; dIter = dIter->next) { + out->list_item(out, "device", "%s", dIter->value); + } + out->end_list(out); + + stonith_key_value_freeall(devices, 1, 1); + return pcmk_rc_ok; +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_installed(xmlNodePtr *xml, stonith_t *st, unsigned int timeout) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_installed(out, st, timeout); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_last(pcmk__output_t *out, const char *target, bool as_nodeid) { + time_t when = 0; + + if (target == NULL) { + return pcmk_rc_ok; + } + + if (as_nodeid) { + when = stonith_api_time(atol(target), NULL, FALSE); + } else { + when = stonith_api_time(0, target, FALSE); + } + + out->message(out, "last-fenced", target, when); + return pcmk_rc_ok; +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_last(xmlNodePtr *xml, const char *target, bool as_nodeid) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_last(out, target, as_nodeid); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_list_targets(pcmk__output_t *out, stonith_t *st, char *agent, + unsigned int timeout) { + GList *targets = NULL; + char *lists = NULL; + int rc = pcmk_rc_ok; + + rc = st->cmds->list(st, st_opts, agent, &lists, timeout/1000); + if (rc != pcmk_rc_ok) { + return pcmk_legacy2rc(rc); + } + + targets = stonith__parse_targets(lists); + + out->begin_list(out, "fence target", "fence targets", "Fence Targets"); + while (targets != NULL) { + out->list_item(out, NULL, "%s", (const char *) targets->data); + targets = targets->next; + } + out->end_list(out); + + free(lists); + return rc; +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_list_targets(xmlNodePtr *xml, stonith_t *st, char *agent, + unsigned int timeout) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_list_targets(out, st, agent, timeout); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_metadata(pcmk__output_t *out, stonith_t *st, char *agent, + unsigned int timeout) { + char *buffer = NULL; + int rc = st->cmds->metadata(st, st_opt_sync_call, agent, NULL, &buffer, + timeout/1000); + + if (rc != pcmk_rc_ok) { + return pcmk_legacy2rc(rc); + } + + out->output_xml(out, "metadata", buffer); + free(buffer); + return rc; +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_metadata(xmlNodePtr *xml, stonith_t *st, char *agent, + unsigned int timeout) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_metadata(out, st, agent, timeout); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_registered(pcmk__output_t *out, stonith_t *st, char *target, + unsigned int timeout) { + stonith_key_value_t *devices = NULL; + int rc = pcmk_rc_ok; + + rc = st->cmds->query(st, st_opts, target, &devices, timeout/1000); + if (rc != pcmk_rc_ok) { + return pcmk_legacy2rc(rc); + } + + out->begin_list(out, "fence device", "fence devices", "Registered fence devices"); + for (stonith_key_value_t *dIter = devices; dIter; dIter = dIter->next) { + out->list_item(out, "device", "%s", dIter->value); + } + out->end_list(out); + + stonith_key_value_freeall(devices, 1, 1); + return rc; +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_registered(xmlNodePtr *xml, stonith_t *st, char *target, + unsigned int timeout) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_registered(out, st, target, timeout); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif + +int +pcmk__fence_register_level(stonith_t *st, char *target, int fence_level, + stonith_key_value_t *devices) { + return handle_level(st, target, fence_level, devices, true); +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_register_level(stonith_t *st, char *target, int fence_level, + stonith_key_value_t *devices) { + return pcmk__fence_register_level(st, target, fence_level, devices); +} +#endif + +int +pcmk__fence_unregister_level(stonith_t *st, char *target, int fence_level) { + return handle_level(st, target, fence_level, NULL, false); +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_unregister_level(stonith_t *st, char *target, int fence_level) { + return pcmk__fence_unregister_level(st, target, fence_level); +} +#endif + +int +pcmk__fence_validate(pcmk__output_t *out, stonith_t *st, const char *agent, + const char *id, stonith_key_value_t *params, + unsigned int timeout) { + char *output = NULL; + char *error_output = NULL; + int rc; + + rc = st->cmds->validate(st, st_opt_sync_call, id, NULL, agent, params, + timeout/1000, &output, &error_output); + out->message(out, "validate", agent, id, output, error_output, rc); + return pcmk_legacy2rc(rc); +} + +#ifdef BUILD_PUBLIC_LIBPACEMAKER +int +pcmk_fence_validate(xmlNodePtr *xml, stonith_t *st, const char *agent, + const char *id, stonith_key_value_t *params, + unsigned int timeout) { + pcmk__output_t *out = NULL; + int rc = pcmk_rc_ok; + + rc = pcmk__out_prologue(&out, xml); + if (rc != pcmk_rc_ok) { + return rc; + } + + rc = pcmk__fence_validate(out, st, agent, id, params, timeout); + pcmk__out_epilogue(out, xml, rc); + return rc; +} +#endif diff --git a/lib/pacemaker/pcmk_output.c b/lib/pacemaker/pcmk_output.c new file mode 100644 index 0000000000..6867e32711 --- /dev/null +++ b/lib/pacemaker/pcmk_output.c @@ -0,0 +1,48 @@ +/* + * Copyright 2019-2020 the Pacemaker project contributors + * + * The version control history for this file may have further details. + * + * This source code is licensed under the GNU General Public License version 2 + * or later (GPLv2+) WITHOUT ANY WARRANTY. + */ + +#include +#include +#include +#include +#include +#include +#include + +pcmk__supported_format_t pcmk__out_formats[] = { + PCMK__SUPPORTED_FORMAT_XML, + { NULL, NULL, NULL } +}; + +int +pcmk__out_prologue(pcmk__output_t **out, xmlNodePtr *xml) { + int rc = pcmk_rc_ok; + + if (*xml != NULL) { + xmlFreeNode(*xml); + } + + pcmk__register_formats(NULL, pcmk__out_formats); + rc = pcmk__output_new(out, "xml", NULL, NULL); + if (rc != pcmk_rc_ok) { + return rc; + } + + stonith__register_messages(*out); + return rc; +} + +void +pcmk__out_epilogue(pcmk__output_t *out, xmlNodePtr *xml, int retval) { + if (retval == pcmk_rc_ok) { + out->finish(out, 0, FALSE, (void **) xml); + } + + pcmk__output_free(out); +} diff --git a/tools/Makefile.am b/tools/Makefile.am index 29d6890c5c..37498147c2 100644 --- a/tools/Makefile.am +++ b/tools/Makefile.am @@ -1,160 +1,161 @@ # # Copyright 2004-2019 the Pacemaker project contributors # # The version control history for this file may have further details. # # This source code is licensed under the GNU General Public License version 2 # or later (GPLv2+) WITHOUT ANY WARRANTY. # include $(top_srcdir)/Makefile.common if BUILD_SYSTEMD systemdsystemunit_DATA = crm_mon.service endif noinst_HEADERS = crm_mon.h crm_resource.h pcmkdir = $(datadir)/$(PACKAGE) pcmk_DATA = report.common report.collector sbin_SCRIPTS = crm_report crm_standby crm_master crm_failcount if BUILD_CIBSECRETS sbin_SCRIPTS += cibsecret endif noinst_SCRIPTS = pcmk_simtimes EXTRA_DIST = crm_diff.8.inc \ crm_mon.sysconfig \ crm_mon.8.inc \ crm_node.8.inc \ fix-manpages \ stonith_admin.8.inc sbin_PROGRAMS = attrd_updater \ cibadmin \ crmadmin \ crm_simulate \ crm_attribute \ crm_diff \ crm_error \ crm_mon \ crm_node \ crm_resource \ crm_rule \ crm_shadow \ crm_verify \ crm_ticket \ iso8601 \ stonith_admin if BUILD_SERVICELOG sbin_PROGRAMS += notifyServicelogEvent endif if BUILD_OPENIPMI_SERVICELOG sbin_PROGRAMS += ipmiservicelogd endif ## SOURCES # A few tools are just thin wrappers around crm_attribute. # This makes their help get updated when crm_attribute changes # (see Makefile.common). MAN8DEPS = crm_attribute crmadmin_SOURCES = crmadmin.c crmadmin_LDADD = $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_error_SOURCES = crm_error.c crm_error_LDADD = $(top_builddir)/lib/common/libcrmcommon.la cibadmin_SOURCES = cibadmin.c cibadmin_LDADD = $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_shadow_SOURCES = crm_shadow.c crm_shadow_LDADD = $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_node_SOURCES = crm_node.c crm_node_LDADD = $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_simulate_SOURCES = crm_simulate.c crm_simulate_LDADD = $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_diff_SOURCES = crm_diff.c crm_diff_LDADD = $(top_builddir)/lib/common/libcrmcommon.la crm_mon_SOURCES = crm_mon.c crm_mon_curses.c crm_mon_print.c crm_mon_runtime.c crm_mon_xml.c crm_mon_LDADD = $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/fencing/libstonithd.la \ $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la \ $(CURSESLIBS) crm_verify_SOURCES = crm_verify.c crm_verify_LDADD = $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_attribute_SOURCES = crm_attribute.c crm_attribute_LDADD = $(top_builddir)/lib/cluster/libcrmcluster.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_resource_SOURCES = crm_resource.c crm_resource_ban.c crm_resource_runtime.c crm_resource_print.c crm_resource_LDADD = $(top_builddir)/lib/pengine/libpe_rules.la \ $(top_builddir)/lib/fencing/libstonithd.la \ $(top_builddir)/lib/lrmd/liblrmd.la \ $(top_builddir)/lib/services/libcrmservice.la \ $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la crm_rule_SOURCES = crm_rule.c crm_rule_LDADD = $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/pengine/libpe_rules.la \ $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/common/libcrmcommon.la iso8601_SOURCES = iso8601.c iso8601_LDADD = $(top_builddir)/lib/common/libcrmcommon.la attrd_updater_SOURCES = attrd_updater.c attrd_updater_LDADD = $(top_builddir)/lib/common/libcrmcommon.la crm_ticket_SOURCES = crm_ticket.c crm_ticket_LDADD = $(top_builddir)/lib/pengine/libpe_rules.la \ $(top_builddir)/lib/pengine/libpe_status.la \ $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/common/libcrmcommon.la stonith_admin_SOURCES = stonith_admin.c -stonith_admin_LDADD = $(top_builddir)/lib/common/libcrmcommon.la \ +stonith_admin_LDADD = $(top_builddir)/lib/pacemaker/libpacemaker.la \ $(top_builddir)/lib/cib/libcib.la \ $(top_builddir)/lib/pengine/libpe_status.la \ - $(top_builddir)/lib/fencing/libstonithd.la + $(top_builddir)/lib/fencing/libstonithd.la \ + $(top_builddir)/lib/common/libcrmcommon.la if BUILD_SERVICELOG notifyServicelogEvent_SOURCES = notifyServicelogEvent.c notifyServicelogEvent_CFLAGS = $(SERVICELOG_CFLAGS) notifyServicelogEvent_LDADD = $(top_builddir)/lib/common/libcrmcommon.la $(SERVICELOG_LIBS) endif if BUILD_OPENIPMI_SERVICELOG ipmiservicelogd_SOURCES = ipmiservicelogd.c ipmiservicelogd_CFLAGS = $(OPENIPMI_SERVICELOG_CFLAGS) $(SERVICELOG_CFLAGS) ipmiservicelogd_LDFLAGS = $(top_builddir)/lib/common/libcrmcommon.la $(OPENIPMI_SERVICELOG_LIBS) $(SERVICELOG_LIBS) endif CLEANFILES = $(man8_MANS) diff --git a/tools/crm_diff.c b/tools/crm_diff.c index 8722646ea5..a565bb851c 100644 --- a/tools/crm_diff.c +++ b/tools/crm_diff.c @@ -1,394 +1,396 @@ /* * Copyright 2005-2018 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU General Public License version 2 * or later (GPLv2+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SUMMARY "Compare two Pacemaker configurations (in XML format) to produce a custom diff-like output, " \ "or apply such an output as a patch" struct { gboolean apply; gboolean as_cib; gboolean no_version; gboolean raw_1; gboolean raw_2; gboolean use_stdin; char *xml_file_1; char *xml_file_2; } options; gboolean new_string_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean original_string_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean patch_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); static GOptionEntry original_xml_entries[] = { { "original", 'o', 0, G_OPTION_ARG_STRING, &options.xml_file_1, "XML is contained in the named file", "FILE" }, { "original-string", 'O', 0, G_OPTION_ARG_CALLBACK, original_string_cb, "XML is contained in the supplied string", "STRING" }, { NULL } }; static GOptionEntry operation_entries[] = { { "new", 'n', 0, G_OPTION_ARG_STRING, &options.xml_file_2, "Compare the original XML to the contents of the named file", "FILE" }, { "new-string", 'N', 0, G_OPTION_ARG_CALLBACK, new_string_cb, "Compare the original XML with the contents of the supplied string", "STRING" }, { "patch", 'p', 0, G_OPTION_ARG_CALLBACK, patch_cb, "Patch the original XML with the contents of the named file", "FILE" }, { NULL } }; static GOptionEntry addl_entries[] = { { "cib", 'c', 0, G_OPTION_ARG_NONE, &options.as_cib, "Compare/patch the inputs as a CIB (includes versions details)", NULL }, { "stdin", 's', 0, G_OPTION_ARG_NONE, &options.use_stdin, "", NULL }, { "no-version", 'u', 0, G_OPTION_ARG_NONE, &options.no_version, "Generate the difference without versions details", NULL }, { NULL } }; gboolean new_string_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.raw_2 = TRUE; if (options.xml_file_2 != NULL) { free(options.xml_file_2); } options.xml_file_2 = strdup(optarg); return TRUE; } gboolean original_string_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.raw_1 = TRUE; if (options.xml_file_1 != NULL) { free(options.xml_file_1); } options.xml_file_1 = strdup(optarg); return TRUE; } gboolean patch_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.apply = TRUE; if (options.xml_file_2 != NULL) { free(options.xml_file_2); } options.xml_file_2 = strdup(optarg); return TRUE; } static void print_patch(xmlNode *patch) { char *buffer = dump_xml_formatted(patch); printf("%s\n", crm_str(buffer)); free(buffer); fflush(stdout); } static int apply_patch(xmlNode *input, xmlNode *patch, gboolean as_cib) { int rc; xmlNode *output = copy_xml(input); rc = xml_apply_patchset(output, patch, as_cib); if (rc != pcmk_ok) { fprintf(stderr, "Could not apply patch: %s\n", pcmk_strerror(rc)); free_xml(output); return rc; } if (output != NULL) { const char *version; char *buffer; print_patch(output); version = crm_element_value(output, XML_ATTR_CRM_VERSION); buffer = calculate_xml_versioned_digest(output, FALSE, TRUE, version); crm_trace("Digest: %s\n", crm_str(buffer)); free(buffer); free_xml(output); } return pcmk_ok; } static void log_patch_cib_versions(xmlNode *patch) { int add[] = { 0, 0, 0 }; int del[] = { 0, 0, 0 }; const char *fmt = NULL; const char *digest = NULL; xml_patch_versions(patch, add, del); fmt = crm_element_value(patch, "format"); digest = crm_element_value(patch, XML_ATTR_DIGEST); if (add[2] != del[2] || add[1] != del[1] || add[0] != del[0]) { crm_info("Patch: --- %d.%d.%d %s", del[0], del[1], del[2], fmt); crm_info("Patch: +++ %d.%d.%d %s", add[0], add[1], add[2], digest); } } static void strip_patch_cib_version(xmlNode *patch, const char **vfields, size_t nvfields) { int format = 1; crm_element_value_int(patch, "format", &format); if (format == 2) { xmlNode *version_xml = find_xml_node(patch, "version", FALSE); if (version_xml) { free_xml(version_xml); } } else { int i = 0; const char *tags[] = { XML_TAG_DIFF_REMOVED, XML_TAG_DIFF_ADDED, }; for (i = 0; i < DIMOF(tags); i++) { xmlNode *tmp = NULL; int lpc; tmp = find_xml_node(patch, tags[i], FALSE); if (tmp) { for (lpc = 0; lpc < nvfields; lpc++) { xml_remove_prop(tmp, vfields[lpc]); } tmp = find_xml_node(tmp, XML_TAG_CIB, FALSE); if (tmp) { for (lpc = 0; lpc < nvfields; lpc++) { xml_remove_prop(tmp, vfields[lpc]); } } } } } } static int generate_patch(xmlNode *object_1, xmlNode *object_2, const char *xml_file_2, gboolean as_cib, gboolean no_version) { xmlNode *output = NULL; const char *vfields[] = { XML_ATTR_GENERATION_ADMIN, XML_ATTR_GENERATION, XML_ATTR_NUMUPDATES, }; /* If we're ignoring the version, make the version information * identical, so it isn't detected as a change. */ if (no_version) { int lpc; for (lpc = 0; lpc < DIMOF(vfields); lpc++) { crm_copy_xml_element(object_1, object_2, vfields[lpc]); } } xml_track_changes(object_2, NULL, object_2, FALSE); if(as_cib) { xml_calculate_significant_changes(object_1, object_2); } else { xml_calculate_changes(object_1, object_2); } crm_log_xml_debug(object_2, (xml_file_2? xml_file_2: "target")); output = xml_create_patchset(0, object_1, object_2, NULL, FALSE); xml_log_changes(LOG_INFO, __FUNCTION__, object_2); xml_accept_changes(object_2); if (output == NULL) { return pcmk_ok; } patchset_process_digest(output, object_1, object_2, as_cib); if (as_cib) { log_patch_cib_versions(output); } else if (no_version) { strip_patch_cib_version(output, vfields, DIMOF(vfields)); } xml_log_patchset(LOG_NOTICE, __FUNCTION__, output); print_patch(output); free_xml(output); return -pcmk_err_generic; } static GOptionContext * build_arg_context(pcmk__common_args_t *args) { GOptionContext *context = NULL; const char *description = "*Examples*\n\n" "Obtain the two different configuration files by running cibadmin on the two cluster setups to compare:\n\n" "\tcibadmin --query > cib-old.xml\n" "\tcibadmin --query > cib-new.xml\n\n" "Calculate and save the difference between the two files:\n\n" "\tcrm_diff --original cib-old.xml --new cib-new.xml > patch.xml\n\n" "Apply the patch to the original file:\n\n" "\tcrm_diff --original cib-old.xml --patch patch.xml > updated.xml\n\n" "Apply the patch to the running cluster:\n\n" "\tcibadmin --patch patch.xml\n"; context = pcmk__build_arg_context(args, NULL, NULL); g_option_context_set_description(context, description); pcmk__add_arg_group(context, "xml", "Original XML:", "Show original XML options", original_xml_entries); pcmk__add_arg_group(context, "operation", "Operation:", "Show operation options", operation_entries); pcmk__add_arg_group(context, "additional", "Additional Options:", "Show additional options", addl_entries); return context; } int main(int argc, char **argv) { int rc = pcmk_ok; xmlNode *object_1 = NULL; xmlNode *object_2 = NULL; pcmk__common_args_t *args = pcmk__new_common_args(SUMMARY); GError *error = NULL; GOptionContext *context = NULL; gchar **processed_args = NULL; context = build_arg_context(args); crm_log_cli_init("crm_diff"); - processed_args = pcmk__cmdline_preproc(argc, argv, "nopNO"); + processed_args = pcmk__cmdline_preproc(argv, "nopNO"); if (!g_option_context_parse_strv(context, &processed_args, &error)) { fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); rc = CRM_EX_USAGE; goto done; } for (int i = 0; i < args->verbosity; i++) { crm_bump_log_level(argc, argv); } if (args->version) { /* FIXME: When crm_diff is converted to use formatted output, this can go. */ crm_help('v', CRM_EX_USAGE); } if (optind > argc) { fprintf(stderr, "%s", g_option_context_get_help(context, TRUE, NULL)); rc = CRM_EX_USAGE; goto done; } if (options.apply && options.no_version) { fprintf(stderr, "warning: -u/--no-version ignored with -p/--patch\n"); } else if (options.as_cib && options.no_version) { fprintf(stderr, "error: -u/--no-version incompatible with -c/--cib\n"); rc = CRM_EX_USAGE; goto done; } if (options.raw_1) { object_1 = string2xml(options.xml_file_1); } else if (options.use_stdin) { fprintf(stderr, "Input first XML fragment:"); object_1 = stdin2xml(); } else if (options.xml_file_1 != NULL) { object_1 = filename2xml(options.xml_file_1); } if (options.raw_2) { object_2 = string2xml(options.xml_file_2); } else if (options.use_stdin) { fprintf(stderr, "Input second XML fragment:"); object_2 = stdin2xml(); } else if (options.xml_file_2 != NULL) { object_2 = filename2xml(options.xml_file_2); } if (object_1 == NULL) { fprintf(stderr, "Could not parse the first XML fragment\n"); rc = CRM_EX_DATAERR; goto done; } if (object_2 == NULL) { fprintf(stderr, "Could not parse the second XML fragment\n"); rc = CRM_EX_DATAERR; goto done; } if (options.apply) { rc = apply_patch(object_1, object_2, options.as_cib); } else { rc = generate_patch(object_1, object_2, options.xml_file_2, options.as_cib, options.no_version); } done: + g_strfreev(processed_args); + g_clear_error(&error); pcmk__free_arg_context(context); free(options.xml_file_1); free(options.xml_file_2); free_xml(object_1); free_xml(object_2); return crm_errno2exit(rc); } diff --git a/tools/crm_mon.c b/tools/crm_mon.c index d66aec786d..0c64b1fa86 100644 --- a/tools/crm_mon.c +++ b/tools/crm_mon.c @@ -1,1906 +1,1914 @@ /* * Copyright 2004-2020 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU General Public License version 2 * or later (GPLv2+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* crm_ends_with_ext */ #include #include #include #include #include #include #include #include #include #include #include #include #include "crm_mon.h" #define SUMMARY "Provides a summary of cluster's current state.\n\n" \ "Outputs varying levels of detail in a number of different formats." /* * Definitions indicating which items to print */ static unsigned int show = mon_show_default; /* * Definitions indicating how to output */ static mon_output_format_t output_format = mon_output_unset; /* other globals */ static GMainLoop *mainloop = NULL; static guint timer_id = 0; static mainloop_timer_t *refresh_timer = NULL; static pe_working_set_t *mon_data_set = NULL; static cib_t *cib = NULL; static stonith_t *st = NULL; static xmlNode *current_cib = NULL; +static GError *error = NULL; static pcmk__common_args_t *args = NULL; static pcmk__output_t *out = NULL; static GOptionContext *context = NULL; +static gchar **processed_args = NULL; /* FIXME allow, detect, and correctly interpret glob pattern or regex? */ const char *print_neg_location_prefix = ""; static time_t last_refresh = 0; crm_trigger_t *refresh_trigger = NULL; static pcmk__supported_format_t formats[] = { #if CURSES_ENABLED CRM_MON_SUPPORTED_FORMAT_CURSES, #endif PCMK__SUPPORTED_FORMAT_HTML, PCMK__SUPPORTED_FORMAT_NONE, PCMK__SUPPORTED_FORMAT_TEXT, CRM_MON_SUPPORTED_FORMAT_XML, { NULL, NULL, NULL } }; /* Define exit codes for monitoring-compatible output * For nagios plugins, the possibilities are * OK=0, WARN=1, CRIT=2, and UNKNOWN=3 */ #define MON_STATUS_WARN CRM_EX_ERROR #define MON_STATUS_CRIT CRM_EX_INVALID_PARAM #define MON_STATUS_UNKNOWN CRM_EX_UNIMPLEMENT_FEATURE #define RECONNECT_MSECS 5000 struct { int reconnect_msec; int fence_history_level; gboolean daemonize; gboolean show_bans; char *pid_file; char *external_agent; char *external_recipient; unsigned int mon_ops; } options = { .reconnect_msec = RECONNECT_MSECS, .fence_history_level = 1, .mon_ops = mon_op_default }; static void clean_up_connections(void); static crm_exit_t clean_up(crm_exit_t exit_code); static void crm_diff_update(const char *event, xmlNode * msg); static gboolean mon_refresh_display(gpointer user_data); static int cib_connect(gboolean full); static void mon_st_callback_event(stonith_t * st, stonith_event_t * e); static void mon_st_callback_display(stonith_t * st, stonith_event_t * e); static void kick_refresh(gboolean data_updated); static gboolean -as_cgi_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +as_cgi_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("html"); output_format = mon_output_cgi; options.mon_ops |= mon_op_one_shot; return TRUE; } static gboolean -as_html_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +as_html_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { if (args->output_ty != NULL) { free(args->output_ty); } if (args->output_dest != NULL) { free(args->output_dest); } if (optarg != NULL) { args->output_dest = strdup(optarg); } args->output_ty = strdup("html"); output_format = mon_output_html; umask(S_IWGRP | S_IWOTH); return TRUE; } static gboolean -as_simple_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +as_simple_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("text"); output_format = mon_output_monitor; options.mon_ops |= mon_op_one_shot; return TRUE; } static gboolean -as_xml_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +as_xml_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("xml"); output_format = mon_output_legacy_xml; options.mon_ops |= mon_op_one_shot; return TRUE; } static gboolean -fence_history_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +fence_history_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { int rc = crm_atoi(optarg, "2"); if (rc == -1 || rc > 3) { - g_set_error(error, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Fence history must be 0-3"); + g_set_error(err, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Fence history must be 0-3"); return FALSE; } else { options.fence_history_level = rc; } return TRUE; } static gboolean -group_by_node_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +group_by_node_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_group_by_node; return TRUE; } static gboolean -hide_headers_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +hide_headers_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show &= ~mon_show_headers; return TRUE; } static gboolean -inactive_resources_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +inactive_resources_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_inactive_resources; return TRUE; } static gboolean -no_curses_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +no_curses_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { output_format = mon_output_plain; return TRUE; } static gboolean -one_shot_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +one_shot_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_one_shot; return TRUE; } static gboolean -print_brief_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +print_brief_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_print_brief; return TRUE; } static gboolean -print_clone_detail_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +print_clone_detail_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_print_clone_detail; return TRUE; } static gboolean -print_pending_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +print_pending_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_print_pending; return TRUE; } static gboolean -print_timing_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +print_timing_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_print_timing; show |= mon_show_operations; return TRUE; } static gboolean -reconnect_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +reconnect_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { int rc = crm_get_msec(optarg); if (rc == -1) { - g_set_error(error, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Invalid value for -i: %s", optarg); + g_set_error(err, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Invalid value for -i: %s", optarg); return FALSE; } else { options.reconnect_msec = crm_parse_interval_spec(optarg); } return TRUE; } static gboolean -show_attributes_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +show_attributes_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show |= mon_show_attributes; return TRUE; } static gboolean -show_bans_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +show_bans_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show |= mon_show_bans; if (optarg != NULL) { print_neg_location_prefix = optarg; } return TRUE; } static gboolean -show_failcounts_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +show_failcounts_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show |= mon_show_failcounts; return TRUE; } static gboolean -show_operations_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +show_operations_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show |= mon_show_operations; return TRUE; } static gboolean -show_tickets_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +show_tickets_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { show |= mon_show_tickets; return TRUE; } static gboolean -use_cib_file_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +use_cib_file_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { setenv("CIB_file", optarg, 1); options.mon_ops |= mon_op_one_shot; return TRUE; } static gboolean -watch_fencing_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { +watch_fencing_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **err) { options.mon_ops |= mon_op_watch_fencing; return TRUE; } #define INDENT " " /* *INDENT-OFF* */ static GOptionEntry addl_entries[] = { { "interval", 'i', 0, G_OPTION_ARG_CALLBACK, reconnect_cb, "Update frequency (default is 5 seconds)", "TIMESPEC" }, { "one-shot", '1', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, one_shot_cb, "Display the cluster status once on the console and exit", NULL }, { "daemonize", 'd', 0, G_OPTION_ARG_NONE, &options.daemonize, "Run in the background as a daemon.\n" INDENT "Requires at least one of --output-to and --external-agent.", NULL }, { "pid-file", 'p', 0, G_OPTION_ARG_FILENAME, &options.pid_file, "(Advanced) Daemon pid file location", "FILE" }, { "external-agent", 'E', 0, G_OPTION_ARG_FILENAME, &options.external_agent, "A program to run when resource operations take place", "FILE" }, { "external-recipient", 'e', 0, G_OPTION_ARG_STRING, &options.external_recipient, "A recipient for your program (assuming you want the program to send something to someone).", "RCPT" }, { "xml-file", 'x', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, use_cib_file_cb, NULL, NULL }, { NULL } }; static GOptionEntry display_entries[] = { { "group-by-node", 'n', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, group_by_node_cb, "Group resources by node", NULL }, { "inactive", 'r', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, inactive_resources_cb, "Display inactive resources", NULL }, { "failcounts", 'f', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_failcounts_cb, "Display resource fail counts", NULL }, { "operations", 'o', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_operations_cb, "Display resource operation history", NULL }, { "timing-details", 't', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, print_timing_cb, "Display resource operation history with timing details", NULL }, { "tickets", 'c', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_tickets_cb, "Display cluster tickets", NULL }, { "watch-fencing", 'W', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, watch_fencing_cb, "Listen for fencing events. For use with --external-agent", NULL }, { "fence-history", 'm', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, fence_history_cb, "Show fence history:\n" INDENT "0=off, 1=failures and pending (default without option),\n" INDENT "2=add successes (default without value for option),\n" INDENT "3=show full history without reduction to most recent of each flavor", "LEVEL" }, { "neg-locations", 'L', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, show_bans_cb, "Display negative location constraints [optionally filtered by id prefix]", NULL }, { "show-node-attributes", 'A', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_attributes_cb, "Display node attributes", NULL }, { "hide-headers", 'D', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, hide_headers_cb, "Hide all headers", NULL }, { "show-detail", 'R', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, print_clone_detail_cb, "Show more details (node IDs, individual clone instances)", NULL }, { "brief", 'b', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, print_brief_cb, "Brief output", NULL }, { "pending", 'j', G_OPTION_FLAG_HIDDEN|G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, print_pending_cb, "Display pending state if 'record-pending' is enabled", NULL }, { "simple-status", 's', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, as_simple_cb, "Display the cluster status once as a simple one line output (suitable for nagios)", NULL }, { NULL } }; static GOptionEntry deprecated_entries[] = { { "as-html", 'h', G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, as_html_cb, "Write cluster status to the named HTML file.\n" INDENT "Use --output-as=html --output-to=FILE instead.", "FILE" }, { "as-xml", 'X', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, as_xml_cb, "Write cluster status as XML to stdout. This will enable one-shot mode.\n" INDENT "Use --output-as=xml instead.", NULL }, { "disable-ncurses", 'N', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, no_curses_cb, "Disable the use of ncurses.\n" INDENT "Use --output-as=text instead.", NULL }, { "web-cgi", 'w', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, as_cgi_cb, "Web mode with output suitable for CGI (preselected when run as *.cgi).\n" INDENT "Use --output-as=html --html-cgi instead.", NULL }, { NULL } }; /* *INDENT-ON* */ static gboolean mon_timer_popped(gpointer data) { int rc = pcmk_ok; #if CURSES_ENABLED if (output_format == mon_output_console) { clear(); refresh(); } #endif if (timer_id > 0) { g_source_remove(timer_id); timer_id = 0; } print_as(output_format, "Reconnecting...\n"); rc = cib_connect(TRUE); if (rc != pcmk_ok) { timer_id = g_timeout_add(options.reconnect_msec, mon_timer_popped, NULL); } return FALSE; } static void mon_cib_connection_destroy(gpointer user_data) { print_as(output_format, "Connection to the cluster-daemons terminated\n"); if (refresh_timer != NULL) { /* we'll trigger a refresh after reconnect */ mainloop_timer_stop(refresh_timer); } if (timer_id) { /* we'll trigger a new reconnect-timeout at the end */ g_source_remove(timer_id); timer_id = 0; } if (st) { /* the client API won't properly reconnect notifications * if they are still in the table - so remove them */ st->cmds->remove_notification(st, T_STONITH_NOTIFY_DISCONNECT); st->cmds->remove_notification(st, T_STONITH_NOTIFY_FENCE); st->cmds->remove_notification(st, T_STONITH_NOTIFY_HISTORY); if (st->state != stonith_disconnected) { st->cmds->disconnect(st); } } if (cib) { cib->cmds->signoff(cib); timer_id = g_timeout_add(options.reconnect_msec, mon_timer_popped, NULL); } return; } /* * Mainloop signal handler. */ static void mon_shutdown(int nsig) { clean_up(CRM_EX_OK); } #if CURSES_ENABLED static sighandler_t ncurses_winch_handler; static void mon_winresize(int nsig) { static int not_done; int lines = 0, cols = 0; if (!not_done++) { if (ncurses_winch_handler) /* the original ncurses WINCH signal handler does the * magic of retrieving the new window size; * otherwise, we'd have to use ioctl or tgetent */ (*ncurses_winch_handler) (SIGWINCH); getmaxyx(stdscr, lines, cols); resizeterm(lines, cols); mainloop_set_trigger(refresh_trigger); } not_done--; } #endif static int cib_connect(gboolean full) { int rc = pcmk_ok; static gboolean need_pass = TRUE; CRM_CHECK(cib != NULL, return -EINVAL); if (getenv("CIB_passwd") != NULL) { need_pass = FALSE; } if (is_set(options.mon_ops, mon_op_fence_connect) && st == NULL) { st = stonith_api_new(); } if (is_set(options.mon_ops, mon_op_fence_connect) && st != NULL && st->state == stonith_disconnected) { rc = st->cmds->connect(st, crm_system_name, NULL); if (rc == pcmk_ok) { crm_trace("Setting up stonith callbacks"); if (is_set(options.mon_ops, mon_op_watch_fencing)) { st->cmds->register_notification(st, T_STONITH_NOTIFY_DISCONNECT, mon_st_callback_event); st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback_event); } else { st->cmds->register_notification(st, T_STONITH_NOTIFY_DISCONNECT, mon_st_callback_display); st->cmds->register_notification(st, T_STONITH_NOTIFY_HISTORY, mon_st_callback_display); } } } if (cib->state != cib_connected_query && cib->state != cib_connected_command) { crm_trace("Connecting to the CIB"); if ((output_format == mon_output_console) && need_pass && (cib->variant == cib_remote)) { need_pass = FALSE; print_as(output_format, "Password:"); } rc = cib->cmds->signon(cib, crm_system_name, cib_query); if (rc != pcmk_ok) { return rc; } rc = cib->cmds->query(cib, NULL, ¤t_cib, cib_scope_local | cib_sync_call); if (rc == pcmk_ok) { mon_refresh_display(&output_format); } if (rc == pcmk_ok && full) { if (rc == pcmk_ok) { rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy); if (rc == -EPROTONOSUPPORT) { print_as (output_format, "Notification setup not supported, won't be able to reconnect after failure"); if (output_format == mon_output_console) { sleep(2); } rc = pcmk_ok; } } if (rc == pcmk_ok) { cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); } if (rc != pcmk_ok) { print_as(output_format, "Notification setup failed, could not monitor CIB actions"); if (output_format == mon_output_console) { sleep(2); } clean_up_connections(); } } } return rc; } #if CURSES_ENABLED static const char * get_option_desc(char c) { const char *desc = "No help available"; for (GOptionEntry *entry = display_entries; entry != NULL; entry++) { if (entry->short_name == c) { desc = entry->description; break; } } return desc; } #define print_option_help(output_format, option, condition) \ out->info(out, "%c %c: \t%s", ((condition)? '*': ' '), option, get_option_desc(option)); static gboolean detect_user_input(GIOChannel *channel, GIOCondition condition, gpointer user_data) { int c; gboolean config_mode = FALSE; while (1) { /* Get user input */ c = getchar(); switch (c) { case 'm': if (!options.fence_history_level) { options.mon_ops |= mon_op_fence_history; options.mon_ops |= mon_op_fence_connect; if (st == NULL) { mon_cib_connection_destroy(NULL); } } show ^= mon_show_fence_history; break; case 'c': show ^= mon_show_tickets; break; case 'f': show ^= mon_show_failcounts; break; case 'n': options.mon_ops ^= mon_op_group_by_node; break; case 'o': show ^= mon_show_operations; if ((show & mon_show_operations) == 0) { options.mon_ops &= ~mon_op_print_timing; } break; case 'r': options.mon_ops ^= mon_op_inactive_resources; break; case 'R': options.mon_ops ^= mon_op_print_clone_detail; break; case 't': options.mon_ops ^= mon_op_print_timing; if (is_set(options.mon_ops, mon_op_print_timing)) { show |= mon_show_operations; } break; case 'A': show ^= mon_show_attributes; break; case 'L': show ^= mon_show_bans; break; case 'D': /* If any header is shown, clear them all, otherwise set them all */ if (show & mon_show_headers) { show &= ~mon_show_headers; } else { show |= mon_show_headers; } break; case 'b': options.mon_ops ^= mon_op_print_brief; break; case 'j': options.mon_ops ^= mon_op_print_pending; break; case '?': config_mode = TRUE; break; default: goto refresh; } if (!config_mode) goto refresh; blank_screen(); out->info(out, "%s", "Display option change mode\n"); print_option_help(out, 'c', show & mon_show_tickets); print_option_help(out, 'f', show & mon_show_failcounts); print_option_help(out, 'n', is_set(options.mon_ops, mon_op_group_by_node)); print_option_help(out, 'o', show & mon_show_operations); print_option_help(out, 'r', is_set(options.mon_ops, mon_op_inactive_resources)); print_option_help(out, 't', is_set(options.mon_ops, mon_op_print_timing)); print_option_help(out, 'A', show & mon_show_attributes); print_option_help(out, 'L', show & mon_show_bans); print_option_help(out, 'D', (show & mon_show_headers) == 0); print_option_help(out, 'R', is_set(options.mon_ops, mon_op_print_clone_detail)); print_option_help(out, 'b', is_set(options.mon_ops, mon_op_print_brief)); print_option_help(out, 'j', is_set(options.mon_ops, mon_op_print_pending)); print_option_help(out, 'm', (show & mon_show_fence_history)); out->info(out, "%s", "\nToggle fields via field letter, type any other key to return"); } refresh: mon_refresh_display(NULL); return TRUE; } #endif // Basically crm_signal_handler(SIGCHLD, SIG_IGN) plus the SA_NOCLDWAIT flag static void avoid_zombies() { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); if (sigemptyset(&sa.sa_mask) < 0) { crm_warn("Cannot avoid zombies: %s", pcmk_strerror(errno)); return; } sa.sa_handler = SIG_IGN; sa.sa_flags = SA_RESTART|SA_NOCLDWAIT; if (sigaction(SIGCHLD, &sa, NULL) < 0) { crm_warn("Cannot avoid zombies: %s", pcmk_strerror(errno)); } } static GOptionContext * build_arg_context(pcmk__common_args_t *args, GOptionGroup **group) { GOptionContext *context = NULL; GOptionEntry extra_prog_entries[] = { { "quiet", 'Q', 0, G_OPTION_ARG_NONE, &(args->quiet), "Be less descriptive in output.", NULL }, { NULL } }; const char *description = "Notes:\n\n" "If this program is called as crm_mon.cgi, --output-as=html --html-cgi will\n" "automatically be added to the command line arguments.\n\n" "Time Specification:\n\n" "The TIMESPEC in any command line option can be specified in many different\n" "formats. It can be just an integer number of seconds, a number plus units\n" "(ms/msec/us/usec/s/sec/m/min/h/hr), or an ISO 8601 period specification.\n\n" "Examples:\n\n" "Display the cluster status on the console with updates as they occur:\n\n" "\tcrm_mon\n\n" "Display the cluster status on the console just once then exit:\n\n" "\tcrm_mon -1\n\n" "Display your cluster status, group resources by node, and include inactive resources in the list:\n\n" "\tcrm_mon --group-by-node --inactive\n\n" "Start crm_mon as a background daemon and have it write the cluster status to an HTML file:\n\n" "\tcrm_mon --daemonize --output-as html --output-to /path/to/docroot/filename.html\n\n" "Start crm_mon and export the current cluster status as XML to stdout, then exit:\n\n" "\tcrm_mon --output-as xml\n\n"; context = pcmk__build_arg_context(args, "console (default), html, text, xml", group); pcmk__add_main_args(context, extra_prog_entries); g_option_context_set_description(context, description); pcmk__add_arg_group(context, "display", "Display Options:", "Show display options", display_entries); pcmk__add_arg_group(context, "additional", "Additional Options:", "Show additional options", addl_entries); pcmk__add_arg_group(context, "deprecated", "Deprecated Options:", "Show deprecated options", deprecated_entries); return context; } /* If certain format options were specified, we want to set some extra * options. We can just process these like they were given on the * command line. */ static void add_output_args() { - GError *error = NULL; + GError *err = NULL; if (output_format == mon_output_plain) { - if (!pcmk__force_args(context, &error, "%s --text-fancy", g_get_prgname())) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + if (!pcmk__force_args(context, &err, "%s --text-fancy", g_get_prgname())) { + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } else if (output_format == mon_output_html) { - if (!pcmk__force_args(context, &error, "%s --html-title \"Cluster Status\"", + if (!pcmk__force_args(context, &err, "%s --html-title \"Cluster Status\"", g_get_prgname())) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } else if (output_format == mon_output_cgi) { - if (!pcmk__force_args(context, &error, "%s --html-cgi --html-title \"Cluster Status\"", g_get_prgname())) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + if (!pcmk__force_args(context, &err, "%s --html-cgi --html-title \"Cluster Status\"", g_get_prgname())) { + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } else if (output_format == mon_output_xml) { - if (!pcmk__force_args(context, &error, "%s --xml-simple-list", g_get_prgname())) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + if (!pcmk__force_args(context, &err, "%s --xml-simple-list", g_get_prgname())) { + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } else if (output_format == mon_output_legacy_xml) { output_format = mon_output_xml; - if (!pcmk__force_args(context, &error, "%s --xml-legacy", g_get_prgname())) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + if (!pcmk__force_args(context, &err, "%s --xml-legacy", g_get_prgname())) { + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } } /* Which output format to use could come from two places: The --as-xml * style arguments we gave in deprecated_entries above, or the formatted output * arguments added by pcmk__register_formats. If the latter were used, * output_format will be mon_output_unset. * * Call the callbacks as if those older style arguments were provided so * the various things they do get done. */ static void reconcile_output_format(pcmk__common_args_t *args) { gboolean retval = TRUE; - GError *error = NULL; + GError *err = NULL; if (output_format != mon_output_unset) { return; } if (safe_str_eq(args->output_ty, "html")) { char *dest = NULL; if (args->output_dest != NULL) { dest = strdup(args->output_dest); } - retval = as_html_cb("h", dest, NULL, &error); + retval = as_html_cb("h", dest, NULL, &err); free(dest); } else if (safe_str_eq(args->output_ty, "text")) { - retval = no_curses_cb("N", NULL, NULL, &error); + retval = no_curses_cb("N", NULL, NULL, &err); } else if (safe_str_eq(args->output_ty, "xml")) { if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("xml"); output_format = mon_output_xml; options.mon_ops |= mon_op_one_shot; } else if (is_set(options.mon_ops, mon_op_one_shot)) { if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("text"); output_format = mon_output_plain; } else { /* Neither old nor new arguments were given, so set the default. */ if (args->output_ty != NULL) { free(args->output_ty); } args->output_ty = strdup("console"); output_format = mon_output_console; } if (!retval) { - fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); + fprintf(stderr, "%s: %s\n", g_get_prgname(), err->message); + g_clear_error(&err); clean_up(CRM_EX_USAGE); } } int main(int argc, char **argv) { int rc = pcmk_ok; - char **processed_args = NULL; GOptionGroup *output_group = NULL; - GError *error = NULL; - args = pcmk__new_common_args(SUMMARY); context = build_arg_context(args, &output_group); pcmk__register_formats(output_group, formats); options.pid_file = strdup("/tmp/ClusterMon.pid"); crm_log_cli_init("crm_mon"); // Avoid needing to wait for subprocesses forked for -E/--external-agent avoid_zombies(); if (crm_ends_with_ext(argv[0], ".cgi") == TRUE) { output_format = mon_output_cgi; options.mon_ops |= mon_op_one_shot; } - processed_args = pcmk__cmdline_preproc(argc, argv, "ehimpxEL"); + processed_args = pcmk__cmdline_preproc(argv, "ehimpxEL"); if (!g_option_context_parse_strv(context, &processed_args, &error)) { fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); return clean_up(CRM_EX_USAGE); } for (int i = 0; i < args->verbosity; i++) { crm_bump_log_level(argc, argv); } if (!args->version) { if (args->quiet) { show &= ~mon_show_times; } if (is_set(options.mon_ops, mon_op_watch_fencing)) { options.mon_ops |= mon_op_fence_connect; /* don't moan as fence_history_level == 1 is default */ options.fence_history_level = 0; } /* create the cib-object early to be able to do further * decisions based on the cib-source */ cib = cib_new(); if (cib == NULL) { rc = -EINVAL; } else { switch (cib->variant) { case cib_native: /* cib & fencing - everything available */ break; case cib_file: /* Don't try to connect to fencing as we * either don't have a running cluster or * the fencing-information would possibly * not match the cib data from a file. * As we don't expect cib-updates coming * in enforce one-shot. */ options.fence_history_level = 0; options.mon_ops |= mon_op_one_shot; break; case cib_remote: /* updates coming in but no fencing */ options.fence_history_level = 0; break; case cib_undefined: case cib_database: default: /* something is odd */ rc = -EINVAL; break; } } switch (options.fence_history_level) { case 3: options.mon_ops |= mon_op_fence_full_history; /* fall through to next lower level */ case 2: show |= mon_show_fence_history; /* fall through to next lower level */ case 1: options.mon_ops |= mon_op_fence_history; options.mon_ops |= mon_op_fence_connect; break; default: break; } if (is_set(options.mon_ops, mon_op_one_shot)) { if (output_format == mon_output_console) { output_format = mon_output_plain; } } else if (options.daemonize) { if ((output_format == mon_output_console) || (output_format == mon_output_plain)) { output_format = mon_output_none; } crm_enable_stderr(FALSE); if ((args->output_dest == NULL || safe_str_eq(args->output_dest, "-")) && !options.external_agent) { printf("--daemonize requires at least one of --output-to and --external-agent\n"); return clean_up(CRM_EX_USAGE); } if (cib) { /* to be on the safe side don't have cib-object around * when we are forking */ cib_delete(cib); cib = NULL; crm_make_daemon(crm_system_name, TRUE, options.pid_file); cib = cib_new(); if (cib == NULL) { rc = -EINVAL; } /* otherwise assume we've got the same cib-object we've just destroyed * in our parent */ } } else if (output_format == mon_output_console) { #if CURSES_ENABLED crm_enable_stderr(FALSE); #else options.mon_ops |= mon_op_one_shot; output_format = mon_output_plain; printf("Defaulting to one-shot mode\n"); printf("You need to have curses available at compile time to enable console mode\n"); #endif } } if (rc != pcmk_ok) { // Shouldn't really be possible fprintf(stderr, "Invalid CIB source\n"); return clean_up(CRM_EX_ERROR); } reconcile_output_format(args); add_output_args(); /* Create the output format - output_format must not be changed after this point. */ if (args->version && output_format == mon_output_console) { /* Use the text output format here if we are in curses mode but were given * --version. Displaying version information uses printf, and then we * immediately exit. We don't want to initialize curses for that. */ rc = pcmk__output_new(&out, "text", args->output_dest, argv); } else { rc = pcmk__output_new(&out, args->output_ty, args->output_dest, argv); } if (rc != pcmk_rc_ok) { fprintf(stderr, "Error creating output format %s: %s\n", args->output_ty, pcmk_rc_str(rc)); return clean_up(CRM_EX_ERROR); } crm_mon_register_messages(out); pe__register_messages(out); stonith__register_messages(out); if (args->version) { out->version(out, false); return clean_up(CRM_EX_OK); } /* Extra sanity checks when in CGI mode */ if (output_format == mon_output_cgi) { if (cib && cib->variant == cib_file) { fprintf(stderr, "CGI mode used with CIB file\n"); return clean_up(CRM_EX_USAGE); } else if (options.external_agent != NULL) { fprintf(stderr, "CGI mode cannot be used with --external-agent\n"); return clean_up(CRM_EX_USAGE); } else if (options.daemonize == TRUE) { fprintf(stderr, "CGI mode cannot be used with -d\n"); return clean_up(CRM_EX_USAGE); } } /* XML output always prints everything */ if (output_format == mon_output_xml || output_format == mon_output_legacy_xml) { show = mon_show_all; options.mon_ops |= mon_op_print_timing; } crm_info("Starting %s", crm_system_name); if (cib) { do { if (is_not_set(options.mon_ops, mon_op_one_shot)) { print_as(output_format ,"Waiting until cluster is available on this node ...\n"); } rc = cib_connect(is_not_set(options.mon_ops, mon_op_one_shot)); if (is_set(options.mon_ops, mon_op_one_shot)) { break; } else if (rc != pcmk_ok) { sleep(options.reconnect_msec / 1000); #if CURSES_ENABLED if (output_format == mon_output_console) { clear(); refresh(); } #endif } else { if (output_format == mon_output_html && out->dest != stdout) { printf("Writing html to %s ...\n", args->output_dest); } } } while (rc == -ENOTCONN); } if (rc != pcmk_ok) { if (output_format == mon_output_monitor) { printf("CLUSTER CRIT: Connection to cluster failed: %s\n", pcmk_strerror(rc)); return clean_up(MON_STATUS_CRIT); } else { if (rc == -ENOTCONN) { out->err(out, "%s", "\nError: cluster is not available on this node"); } else { out->err(out, "\nConnection to cluster failed: %s", pcmk_strerror(rc)); } } if (output_format == mon_output_console) { sleep(2); } return clean_up(crm_errno2exit(rc)); } if (is_set(options.mon_ops, mon_op_one_shot)) { return clean_up(CRM_EX_OK); } mainloop = g_main_loop_new(NULL, FALSE); mainloop_add_signal(SIGTERM, mon_shutdown); mainloop_add_signal(SIGINT, mon_shutdown); #if CURSES_ENABLED if (output_format == mon_output_console) { ncurses_winch_handler = crm_signal_handler(SIGWINCH, mon_winresize); if (ncurses_winch_handler == SIG_DFL || ncurses_winch_handler == SIG_IGN || ncurses_winch_handler == SIG_ERR) ncurses_winch_handler = NULL; g_io_add_watch(g_io_channel_unix_new(STDIN_FILENO), G_IO_IN, detect_user_input, NULL); } #endif refresh_trigger = mainloop_add_trigger(G_PRIORITY_LOW, mon_refresh_display, NULL); g_main_loop_run(mainloop); g_main_loop_unref(mainloop); crm_info("Exiting %s", crm_system_name); return clean_up(CRM_EX_OK); } /*! * \internal * \brief Print one-line status suitable for use with monitoring software * * \param[in] data_set Working set of CIB state * \param[in] history List of stonith actions * * \note This function's output (and the return code when the program exits) * should conform to https://www.monitoring-plugins.org/doc/guidelines.html */ static void print_simple_status(pcmk__output_t *out, pe_working_set_t * data_set, stonith_history_t *history, unsigned int mon_ops) { GListPtr gIter = NULL; int nodes_online = 0; int nodes_standby = 0; int nodes_maintenance = 0; char *offline_nodes = NULL; gboolean no_dc = FALSE; gboolean offline = FALSE; if (data_set->dc_node == NULL) { mon_ops |= mon_op_has_warnings; no_dc = TRUE; } for (gIter = data_set->nodes; gIter != NULL; gIter = gIter->next) { node_t *node = (node_t *) gIter->data; if (node->details->standby && node->details->online) { nodes_standby++; } else if (node->details->maintenance && node->details->online) { nodes_maintenance++; } else if (node->details->online) { nodes_online++; } else { char *s = crm_strdup_printf("offline node: %s", node->details->uname); offline_nodes = add_list_element(offline_nodes, s); free(s); mon_ops |= mon_op_has_warnings; offline = TRUE; } } if (is_set(mon_ops, mon_op_has_warnings)) { out->info(out, "CLUSTER WARN:%s%s%s", no_dc ? " No DC" : "", no_dc && offline ? "," : "", offline ? offline_nodes : ""); free(offline_nodes); } else { char *nodes_standby_s = NULL; char *nodes_maint_s = NULL; if (nodes_standby > 0) { nodes_standby_s = crm_strdup_printf(", %d standby node%s", nodes_standby, pcmk__plural_s(nodes_standby)); } if (nodes_maintenance > 0) { nodes_maint_s = crm_strdup_printf(", %d maintenance node%s", nodes_maintenance, pcmk__plural_s(nodes_maintenance)); } out->info(out, "CLUSTER OK: %d node%s online%s%s, " "%d resource instance%s configured", nodes_online, pcmk__plural_s(nodes_online), nodes_standby_s != NULL ? nodes_standby_s : "", nodes_maint_s != NULL ? nodes_maint_s : "", data_set->ninstances, pcmk__plural_s(data_set->ninstances)); free(nodes_standby_s); free(nodes_maint_s); } } /*! * \internal * \brief Reduce the stonith-history * for successful actions we keep the last of every action-type & target * for failed actions we record as well who had failed * for actions in progress we keep full track * * \param[in] history List of stonith actions * */ static stonith_history_t * reduce_stonith_history(stonith_history_t *history) { stonith_history_t *new = history, *hp, *np; if (new) { hp = new->next; new->next = NULL; while (hp) { stonith_history_t *hp_next = hp->next; hp->next = NULL; for (np = new; ; np = np->next) { if ((hp->state == st_done) || (hp->state == st_failed)) { /* action not in progress */ if (safe_str_eq(hp->target, np->target) && safe_str_eq(hp->action, np->action) && (hp->state == np->state) && ((hp->state == st_done) || safe_str_eq(hp->delegate, np->delegate))) { /* purge older hp */ stonith_history_free(hp); break; } } if (!np->next) { np->next = hp; break; } } hp = hp_next; } } return new; } static int send_custom_trap(const char *node, const char *rsc, const char *task, int target_rc, int rc, int status, const char *desc) { pid_t pid; /*setenv needs chars, these are ints */ char *rc_s = crm_itoa(rc); char *status_s = crm_itoa(status); char *target_rc_s = crm_itoa(target_rc); crm_debug("Sending external notification to '%s' via '%s'", options.external_recipient, options.external_agent); if(rsc) { setenv("CRM_notify_rsc", rsc, 1); } if (options.external_recipient) { setenv("CRM_notify_recipient", options.external_recipient, 1); } setenv("CRM_notify_node", node, 1); setenv("CRM_notify_task", task, 1); setenv("CRM_notify_desc", desc, 1); setenv("CRM_notify_rc", rc_s, 1); setenv("CRM_notify_target_rc", target_rc_s, 1); setenv("CRM_notify_status", status_s, 1); pid = fork(); if (pid == -1) { crm_perror(LOG_ERR, "notification fork() failed."); } if (pid == 0) { /* crm_debug("notification: I am the child. Executing the nofitication program."); */ execl(options.external_agent, options.external_agent, NULL); exit(CRM_EX_ERROR); } crm_trace("Finished running custom notification program '%s'.", options.external_agent); free(target_rc_s); free(status_s); free(rc_s); return 0; } static void handle_rsc_op(xmlNode * xml, const char *node_id) { int rc = -1; int status = -1; int target_rc = -1; gboolean notify = TRUE; char *rsc = NULL; char *task = NULL; const char *desc = NULL; const char *magic = NULL; const char *id = NULL; const char *node = NULL; xmlNode *n = xml; xmlNode * rsc_op = xml; if(strcmp((const char*)xml->name, XML_LRM_TAG_RSC_OP) != 0) { xmlNode *cIter; for(cIter = xml->children; cIter; cIter = cIter->next) { handle_rsc_op(cIter, node_id); } return; } id = crm_element_value(rsc_op, XML_LRM_ATTR_TASK_KEY); if (id == NULL) { /* Compatibility with <= 1.1.5 */ id = ID(rsc_op); } magic = crm_element_value(rsc_op, XML_ATTR_TRANSITION_MAGIC); if (magic == NULL) { /* non-change */ return; } if (!decode_transition_magic(magic, NULL, NULL, NULL, &status, &rc, &target_rc)) { crm_err("Invalid event %s detected for %s", magic, id); return; } if (parse_op_key(id, &rsc, &task, NULL) == FALSE) { crm_err("Invalid event detected for %s", id); goto bail; } node = crm_element_value(rsc_op, XML_LRM_ATTR_TARGET); while (n != NULL && safe_str_neq(XML_CIB_TAG_STATE, TYPE(n))) { n = n->parent; } if(node == NULL && n) { node = crm_element_value(n, XML_ATTR_UNAME); } if (node == NULL && n) { node = ID(n); } if (node == NULL) { node = node_id; } if (node == NULL) { crm_err("No node detected for event %s (%s)", magic, id); goto bail; } /* look up where we expected it to be? */ desc = pcmk_strerror(pcmk_ok); if (status == PCMK_LRM_OP_DONE && target_rc == rc) { crm_notice("%s of %s on %s completed: %s", task, rsc, node, desc); if (rc == PCMK_OCF_NOT_RUNNING) { notify = FALSE; } } else if (status == PCMK_LRM_OP_DONE) { desc = services_ocf_exitcode_str(rc); crm_warn("%s of %s on %s failed: %s", task, rsc, node, desc); } else { desc = services_lrm_status_str(status); crm_warn("%s of %s on %s failed: %s", task, rsc, node, desc); } if (notify && options.external_agent) { send_custom_trap(node, rsc, task, target_rc, rc, status, desc); } bail: free(rsc); free(task); } static gboolean mon_trigger_refresh(gpointer user_data) { mainloop_set_trigger(refresh_trigger); return FALSE; } #define NODE_PATT "/lrm[@id=" static char * get_node_from_xpath(const char *xpath) { char *nodeid = NULL; char *tmp = strstr(xpath, NODE_PATT); if(tmp) { tmp += strlen(NODE_PATT); tmp += 1; nodeid = strdup(tmp); tmp = strstr(nodeid, "\'"); CRM_ASSERT(tmp); tmp[0] = 0; } return nodeid; } static void crm_diff_update_v2(const char *event, xmlNode * msg) { xmlNode *change = NULL; xmlNode *diff = get_message_xml(msg, F_CIB_UPDATE_RESULT); for (change = __xml_first_child(diff); change != NULL; change = __xml_next(change)) { const char *name = NULL; const char *op = crm_element_value(change, XML_DIFF_OP); const char *xpath = crm_element_value(change, XML_DIFF_PATH); xmlNode *match = NULL; const char *node = NULL; if(op == NULL) { continue; } else if(strcmp(op, "create") == 0) { match = change->children; } else if(strcmp(op, "move") == 0) { continue; } else if(strcmp(op, "delete") == 0) { continue; } else if(strcmp(op, "modify") == 0) { match = first_named_child(change, XML_DIFF_RESULT); if(match) { match = match->children; } } if(match) { name = (const char *)match->name; } crm_trace("Handling %s operation for %s %p, %s", op, xpath, match, name); if(xpath == NULL) { /* Version field, ignore */ } else if(name == NULL) { crm_debug("No result for %s operation to %s", op, xpath); CRM_ASSERT(strcmp(op, "delete") == 0 || strcmp(op, "move") == 0); } else if(strcmp(name, XML_TAG_CIB) == 0) { xmlNode *state = NULL; xmlNode *status = first_named_child(match, XML_CIB_TAG_STATUS); for (state = __xml_first_child_element(status); state != NULL; state = __xml_next_element(state)) { node = crm_element_value(state, XML_ATTR_UNAME); if (node == NULL) { node = ID(state); } handle_rsc_op(state, node); } } else if(strcmp(name, XML_CIB_TAG_STATUS) == 0) { xmlNode *state = NULL; for (state = __xml_first_child_element(match); state != NULL; state = __xml_next_element(state)) { node = crm_element_value(state, XML_ATTR_UNAME); if (node == NULL) { node = ID(state); } handle_rsc_op(state, node); } } else if(strcmp(name, XML_CIB_TAG_STATE) == 0) { node = crm_element_value(match, XML_ATTR_UNAME); if (node == NULL) { node = ID(match); } handle_rsc_op(match, node); } else if(strcmp(name, XML_CIB_TAG_LRM) == 0) { node = ID(match); handle_rsc_op(match, node); } else if(strcmp(name, XML_LRM_TAG_RESOURCES) == 0) { char *local_node = get_node_from_xpath(xpath); handle_rsc_op(match, local_node); free(local_node); } else if(strcmp(name, XML_LRM_TAG_RESOURCE) == 0) { char *local_node = get_node_from_xpath(xpath); handle_rsc_op(match, local_node); free(local_node); } else if(strcmp(name, XML_LRM_TAG_RSC_OP) == 0) { char *local_node = get_node_from_xpath(xpath); handle_rsc_op(match, local_node); free(local_node); } else { crm_trace("Ignoring %s operation for %s %p, %s", op, xpath, match, name); } } } static void crm_diff_update_v1(const char *event, xmlNode * msg) { /* Process operation updates */ xmlXPathObject *xpathObj = xpath_search(msg, "//" F_CIB_UPDATE_RESULT "//" XML_TAG_DIFF_ADDED "//" XML_LRM_TAG_RSC_OP); int lpc = 0, max = numXpathResults(xpathObj); for (lpc = 0; lpc < max; lpc++) { xmlNode *rsc_op = getXpathResult(xpathObj, lpc); handle_rsc_op(rsc_op, NULL); } freeXpathObject(xpathObj); } static void crm_diff_update(const char *event, xmlNode * msg) { int rc = -1; static bool stale = FALSE; gboolean cib_updated = FALSE; xmlNode *diff = get_message_xml(msg, F_CIB_UPDATE_RESULT); print_dot(output_format); if (current_cib != NULL) { rc = xml_apply_patchset(current_cib, diff, TRUE); switch (rc) { case -pcmk_err_diff_resync: case -pcmk_err_diff_failed: crm_notice("[%s] Patch aborted: %s (%d)", event, pcmk_strerror(rc), rc); free_xml(current_cib); current_cib = NULL; break; case pcmk_ok: cib_updated = TRUE; break; default: crm_notice("[%s] ABORTED: %s (%d)", event, pcmk_strerror(rc), rc); free_xml(current_cib); current_cib = NULL; } } if (current_cib == NULL) { crm_trace("Re-requesting the full cib"); cib->cmds->query(cib, NULL, ¤t_cib, cib_scope_local | cib_sync_call); } if (options.external_agent) { int format = 0; crm_element_value_int(diff, "format", &format); switch(format) { case 1: crm_diff_update_v1(event, msg); break; case 2: crm_diff_update_v2(event, msg); break; default: crm_err("Unknown patch format: %d", format); } } if (current_cib == NULL) { if(!stale) { print_as(output_format, "--- Stale data ---"); } stale = TRUE; return; } stale = FALSE; kick_refresh(cib_updated); } static gboolean mon_refresh_display(gpointer user_data) { xmlNode *cib_copy = copy_xml(current_cib); stonith_history_t *stonith_history = NULL; last_refresh = time(NULL); if (cli_config_update(&cib_copy, NULL, FALSE) == FALSE) { if (cib) { cib->cmds->signoff(cib); } print_as(output_format, "Upgrade failed: %s", pcmk_strerror(-pcmk_err_schema_validation)); if (output_format == mon_output_console) { sleep(2); } clean_up(CRM_EX_CONFIG); return FALSE; } /* get the stonith-history if there is evidence we need it */ while (is_set(options.mon_ops, mon_op_fence_history)) { if (st != NULL) { if (st->cmds->history(st, st_opt_sync_call, NULL, &stonith_history, 120)) { fprintf(stderr, "Critical: Unable to get stonith-history\n"); mon_cib_connection_destroy(NULL); } else { stonith_history = stonith__sort_history(stonith_history); if (is_not_set(options.mon_ops, mon_op_fence_full_history) && output_format != mon_output_xml) { stonith_history = reduce_stonith_history(stonith_history); } break; /* all other cases are errors */ } } else { fprintf(stderr, "Critical: No stonith-API\n"); } free_xml(cib_copy); print_as(output_format, "Reading stonith-history failed"); if (output_format == mon_output_console) { sleep(2); } return FALSE; } if (mon_data_set == NULL) { mon_data_set = pe_new_working_set(); CRM_ASSERT(mon_data_set != NULL); } mon_data_set->input = cib_copy; cluster_status(mon_data_set); /* Unpack constraints if any section will need them * (tickets may be referenced in constraints but not granted yet, * and bans need negative location constraints) */ if (show & (mon_show_bans | mon_show_tickets)) { xmlNode *cib_constraints = get_object_root(XML_CIB_TAG_CONSTRAINTS, mon_data_set->input); unpack_constraints(cib_constraints, mon_data_set); } switch (output_format) { case mon_output_html: case mon_output_cgi: if (print_html_status(out, output_format, mon_data_set, stonith_history, options.mon_ops, show, print_neg_location_prefix) != 0) { fprintf(stderr, "Critical: Unable to output html file\n"); clean_up(CRM_EX_CANTCREAT); return FALSE; } break; case mon_output_legacy_xml: case mon_output_xml: print_xml_status(out, output_format, mon_data_set, stonith_history, options.mon_ops, show, print_neg_location_prefix); break; case mon_output_monitor: print_simple_status(out, mon_data_set, stonith_history, options.mon_ops); if (is_set(options.mon_ops, mon_op_has_warnings)) { clean_up(MON_STATUS_WARN); return FALSE; } break; case mon_output_console: /* If curses is not enabled, this will just fall through to the plain * text case. */ #if CURSES_ENABLED blank_screen(); print_status(out, output_format, mon_data_set, stonith_history, options.mon_ops, show, print_neg_location_prefix); refresh(); break; #endif case mon_output_plain: print_status(out, output_format, mon_data_set, stonith_history, options.mon_ops, show, print_neg_location_prefix); break; case mon_output_unset: case mon_output_none: break; } stonith_history_free(stonith_history); stonith_history = NULL; pe_reset_working_set(mon_data_set); return TRUE; } static void mon_st_callback_event(stonith_t * st, stonith_event_t * e) { if (st->state == stonith_disconnected) { /* disconnect cib as well and have everything reconnect */ mon_cib_connection_destroy(NULL); } else if (options.external_agent) { char *desc = crm_strdup_printf("Operation %s requested by %s for peer %s: %s (ref=%s)", e->operation, e->origin, e->target, pcmk_strerror(e->result), e->id); send_custom_trap(e->target, NULL, e->operation, pcmk_ok, e->result, 0, desc); free(desc); } } static void kick_refresh(gboolean data_updated) { static int updates = 0; time_t now = time(NULL); if (data_updated) { updates++; } if(refresh_timer == NULL) { refresh_timer = mainloop_timer_add("refresh", 2000, FALSE, mon_trigger_refresh, NULL); } /* Refresh * - immediately if the last update was more than 5s ago * - every 10 cib-updates * - at most 2s after the last update */ if ((now - last_refresh) > (options.reconnect_msec / 1000)) { mainloop_set_trigger(refresh_trigger); mainloop_timer_stop(refresh_timer); updates = 0; } else if(updates >= 10) { mainloop_set_trigger(refresh_trigger); mainloop_timer_stop(refresh_timer); updates = 0; } else { mainloop_timer_start(refresh_timer); } } static void mon_st_callback_display(stonith_t * st, stonith_event_t * e) { if (st->state == stonith_disconnected) { /* disconnect cib as well and have everything reconnect */ mon_cib_connection_destroy(NULL); } else { print_dot(output_format); kick_refresh(TRUE); } } static void clean_up_connections(void) { if (cib != NULL) { cib->cmds->signoff(cib); cib_delete(cib); cib = NULL; } if (st != NULL) { if (st->state != stonith_disconnected) { st->cmds->remove_notification(st, T_STONITH_NOTIFY_DISCONNECT); st->cmds->remove_notification(st, T_STONITH_NOTIFY_FENCE); st->cmds->remove_notification(st, T_STONITH_NOTIFY_HISTORY); st->cmds->disconnect(st); } stonith_api_delete(st); st = NULL; } } static void handle_html_output(crm_exit_t exit_code) { xmlNodePtr html = NULL; out->finish(out, exit_code, false, (void **) &html); pcmk__html_add_header(html, "meta", "http-equiv", "refresh", "content", crm_itoa(options.reconnect_msec/1000), NULL); htmlDocDump(out->dest, html->doc); } /* * De-init ncurses, disconnect from the CIB manager, disconnect fencing, * deallocate memory and show usage-message if requested. * * We don't actually return, but nominally returning crm_exit_t allows a usage * like "return clean_up(exit_code);" which helps static analysis understand the * code flow. */ static crm_exit_t clean_up(crm_exit_t exit_code) { #if CURSES_ENABLED if (output_format == mon_output_console) { output_format = mon_output_plain; echo(); nocbreak(); endwin(); } #endif clean_up_connections(); free(options.pid_file); pe_free_working_set(mon_data_set); mon_data_set = NULL; if (exit_code == CRM_EX_USAGE) { if (output_format == mon_output_cgi) { fprintf(stdout, "Content-Type: text/plain\n" "Status: 500\n\n"); } else { fprintf(stderr, "%s", g_option_context_get_help(context, TRUE, NULL)); } } pcmk__free_arg_context(context); + g_clear_error(&error); + if (out != NULL) { if (output_format == mon_output_cgi || output_format == mon_output_html) { handle_html_output(exit_code); } else { out->finish(out, exit_code, true, NULL); } pcmk__output_free(out); } + g_strfreev(processed_args); crm_exit(exit_code); } diff --git a/tools/crm_mon_curses.c b/tools/crm_mon_curses.c index ecd0584fe8..b686217c1f 100644 --- a/tools/crm_mon_curses.c +++ b/tools/crm_mon_curses.c @@ -1,380 +1,380 @@ /* * Copyright 2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include "crm_mon.h" #if CURSES_ENABLED GOptionEntry crm_mon_curses_output_entries[] = { { NULL } }; typedef struct curses_list_data_s { unsigned int len; char *singular_noun; char *plural_noun; } curses_list_data_t; typedef struct private_data_s { GQueue *parent_q; } private_data_t; static void curses_free_priv(pcmk__output_t *out) { private_data_t *priv = out->priv; if (priv == NULL) { return; } g_queue_free(priv->parent_q); free(priv); } static bool curses_init(pcmk__output_t *out) { private_data_t *priv = NULL; /* If curses_init was previously called on this output struct, just return. */ if (out->priv != NULL) { return true; } else { out->priv = calloc(1, sizeof(private_data_t)); if (out->priv == NULL) { return false; } priv = out->priv; } priv->parent_q = g_queue_new(); initscr(); cbreak(); noecho(); return true; } static void curses_finish(pcmk__output_t *out, crm_exit_t exit_status, bool print, void **copy_dest) { } static void curses_reset(pcmk__output_t *out) { CRM_ASSERT(out->priv != NULL); curses_free_priv(out); curses_init(out); } static void curses_subprocess_output(pcmk__output_t *out, int exit_status, const char *proc_stdout, const char *proc_stderr) { if (proc_stdout != NULL) { printw("%s\n", proc_stdout); } if (proc_stderr != NULL) { printw("%s\n", proc_stderr); } clrtoeol(); refresh(); } /* curses_version is defined in curses.h, so we can't use that name here. * Note that this function prints out via text, not with curses. */ static void curses_ver(pcmk__output_t *out, bool extended) { if (extended) { printf("Pacemaker %s (Build: %s): %s\n", PACEMAKER_VERSION, BUILD_VERSION, CRM_FEATURES); } else { printf("Pacemaker %s\n", PACEMAKER_VERSION); printf("Written by Andrew Beekhof\n"); } } G_GNUC_PRINTF(2, 3) static void curses_err_info(pcmk__output_t *out, const char *format, ...) { va_list ap; /* Informational output does not get indented, to separate it from other * potentially indented list output. */ va_start(ap, format); vw_printw(stdscr, format, ap); va_end(ap); /* Add a newline. */ addch('\n'); clrtoeol(); refresh(); } static void curses_output_xml(pcmk__output_t *out, const char *name, const char *buf) { private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); curses_indented_printf(out, "%s", buf); } G_GNUC_PRINTF(4, 5) static void curses_begin_list(pcmk__output_t *out, const char *singular_noun, const char *plural_noun, const char *format, ...) { private_data_t *priv = out->priv; curses_list_data_t *new_list = NULL; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); curses_indented_vprintf(out, format, ap); printw(":\n"); va_end(ap); new_list = calloc(1, sizeof(curses_list_data_t)); new_list->len = 0; new_list->singular_noun = singular_noun == NULL ? NULL : strdup(singular_noun); new_list->plural_noun = plural_noun == NULL ? NULL : strdup(plural_noun); g_queue_push_tail(priv->parent_q, new_list); } G_GNUC_PRINTF(3, 4) static void curses_list_item(pcmk__output_t *out, const char *id, const char *format, ...) { private_data_t *priv = out->priv; va_list ap; CRM_ASSERT(priv != NULL); va_start(ap, format); if (id != NULL) { curses_indented_printf(out, "%s: ", id); vw_printw(stdscr, format, ap); } else { curses_indented_vprintf(out, format, ap); } addch('\n'); va_end(ap); out->increment_list(out); } static void curses_increment_list(pcmk__output_t *out) { private_data_t *priv = out->priv; gpointer tail; CRM_ASSERT(priv != NULL); tail = g_queue_peek_tail(priv->parent_q); CRM_ASSERT(tail != NULL); ((curses_list_data_t *) tail)->len++; } static void curses_end_list(pcmk__output_t *out) { private_data_t *priv = out->priv; curses_list_data_t *node = NULL; CRM_ASSERT(priv != NULL); node = g_queue_pop_tail(priv->parent_q); if (node->singular_noun != NULL && node->plural_noun != NULL) { if (node->len == 1) { curses_indented_printf(out, "%d %s found\n", node->len, node->singular_noun); } else { curses_indented_printf(out, "%d %s found\n", node->len, node->plural_noun); } } free(node); } pcmk__output_t * crm_mon_mk_curses_output(char **argv) { pcmk__output_t *retval = calloc(1, sizeof(pcmk__output_t)); if (retval == NULL) { return NULL; } retval->fmt_name = "console"; - retval->request = g_strjoinv(" ", argv); + retval->request = argv == NULL ? NULL : g_strjoinv(" ", argv); retval->supports_quiet = true; retval->init = curses_init; retval->free_priv = curses_free_priv; retval->finish = curses_finish; retval->reset = curses_reset; retval->register_message = pcmk__register_message; retval->message = pcmk__call_message; retval->subprocess_output = curses_subprocess_output; retval->version = curses_ver; retval->err = curses_err_info; retval->info = curses_err_info; retval->output_xml = curses_output_xml; retval->begin_list = curses_begin_list; retval->list_item = curses_list_item; retval->increment_list = curses_increment_list; retval->end_list = curses_end_list; return retval; } G_GNUC_PRINTF(2, 0) void curses_indented_vprintf(pcmk__output_t *out, const char *format, va_list args) { int level = 0; private_data_t *priv = out->priv; CRM_ASSERT(priv != NULL); level = g_queue_get_length(priv->parent_q); for (int i = 0; i < level; i++) { printw(" "); } if (level > 0) { printw("* "); } vw_printw(stdscr, format, args); clrtoeol(); refresh(); } G_GNUC_PRINTF(2, 3) void curses_indented_printf(pcmk__output_t *out, const char *format, ...) { va_list ap; va_start(ap, format); curses_indented_vprintf(out, format, ap); va_end(ap); } static int stonith_event_console(pcmk__output_t *out, va_list args) { stonith_history_t *event = va_arg(args, stonith_history_t *); gboolean full_history = va_arg(args, gboolean); gboolean later_succeeded = va_arg(args, gboolean); crm_time_t *crm_when = crm_time_new(NULL); char *buf = NULL; crm_time_set_timet(crm_when, &(event->completed)); buf = crm_time_as_string(crm_when, crm_time_log_date | crm_time_log_timeofday | crm_time_log_with_timezone); switch (event->state) { case st_failed: curses_indented_printf(out, "%s of %s failed: delegate=%s, client=%s, origin=%s, %s='%s %s'\n", stonith_action_str(event->action), event->target, event->delegate ? event->delegate : "", event->client, event->origin, full_history ? "completed" : "last-failed", buf, later_succeeded ? "(a later attempt succeeded)" : ""); break; case st_done: curses_indented_printf(out, "%s of %s successful: delegate=%s, client=%s, origin=%s, %s='%s'\n", stonith_action_str(event->action), event->target, event->delegate ? event->delegate : "", event->client, event->origin, full_history ? "completed" : "last-successful", buf); break; default: curses_indented_printf(out, "%s of %s pending: client=%s, origin=%s\n", stonith_action_str(event->action), event->target, event->client, event->origin); break; } free(buf); crm_time_free(crm_when); return 0; } static pcmk__message_entry_t fmt_functions[] = { { "ban", "console", pe__ban_text }, { "bundle", "console", pe__bundle_text }, { "clone", "console", pe__clone_text }, { "cluster-counts", "console", pe__cluster_counts_text }, { "cluster-dc", "console", pe__cluster_dc_text }, { "cluster-options", "console", pe__cluster_options_text }, { "cluster-stack", "console", pe__cluster_stack_text }, { "cluster-times", "console", pe__cluster_times_text }, { "failed-action", "console", pe__failed_action_text }, { "group", "console", pe__group_text }, { "node", "console", pe__node_text }, { "node-attribute", "console", pe__node_attribute_text }, { "op-history", "console", pe__op_history_text }, { "primitive", "console", pe__resource_text }, { "resource-history", "console", pe__resource_history_text }, { "stonith-event", "console", stonith_event_console }, { "ticket", "console", pe__ticket_text }, { NULL, NULL, NULL } }; void crm_mon_register_messages(pcmk__output_t *out) { pcmk__register_messages(out, fmt_functions); } #else pcmk__output_t * crm_mon_mk_curses_output(char **argv) { /* curses was disabled in the build, so fall back to text. */ return pcmk__mk_text_output(argv); } G_GNUC_PRINTF(2, 0) void curses_indented_vprintf(pcmk__output_t *out, const char *format, va_list args) { return; } G_GNUC_PRINTF(2, 3) void curses_indented_printf(pcmk__output_t *out, const char *format, ...) { return; } void crm_mon_register_messages(pcmk__output_t *out) { return; } #endif diff --git a/tools/crm_node.c b/tools/crm_node.c index 0214afde34..45909170fd 100644 --- a/tools/crm_node.c +++ b/tools/crm_node.c @@ -1,664 +1,665 @@ /* * Copyright 2004-2019 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU General Public License version 2 * or later (GPLv2+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include #include #include #define SUMMARY "crm_node - Tool for displaying low-level node information" struct { gboolean corosync; gboolean dangerous_cmd; gboolean force_flag; char command; int nodeid; char *target_uname; } options = { .command = '\0', .force_flag = FALSE }; gboolean command_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean name_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean remove_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); static char *pid_s = NULL; static GMainLoop *mainloop = NULL; static crm_exit_t exit_code = CRM_EX_OK; #define INDENT " " static GOptionEntry command_entries[] = { { "cluster-id", 'i', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, command_cb, "Display this node's cluster id", NULL }, { "list", 'l', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, command_cb, "Display all known members (past and present) of this cluster", NULL }, { "name", 'n', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, command_cb, "Display the name used by the cluster for this node", NULL }, { "partition", 'p', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, command_cb, "Display the members of this partition", NULL }, { "quorum", 'q', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, command_cb, "Display a 1 if our partition has quorum, 0 if not", NULL }, { "name-for-id", 'N', 0, G_OPTION_ARG_CALLBACK, name_cb, "Display the name used by the cluster for the node with the specified ID", "ID" }, { "remove", 'R', 0, G_OPTION_ARG_CALLBACK, remove_cb, "(Advanced) Remove the (stopped) node with the specified name from Pacemaker's\n" INDENT "configuration and caches (the node must already have been removed from\n" INDENT "the underlying cluster stack configuration", "NAME" }, { NULL } }; static GOptionEntry addl_entries[] = { { "force", 'f', 0, G_OPTION_ARG_NONE, &options.force_flag, NULL, NULL }, #if SUPPORT_COROSYNC /* Unused and deprecated */ { "corosync", 'C', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &options.corosync, NULL, NULL }, #endif // @TODO add timeout option for when IPC replies are needed { NULL } }; gboolean command_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { if (safe_str_eq("-i", option_name) || safe_str_eq("--cluster-id", option_name)) { options.command = 'i'; } else if (safe_str_eq("-l", option_name) || safe_str_eq("--list", option_name)) { options.command = 'l'; } else if (safe_str_eq("-n", option_name) || safe_str_eq("--name", option_name)) { options.command = 'n'; } else if (safe_str_eq("-p", option_name) || safe_str_eq("--partition", option_name)) { options.command = 'p'; } else if (safe_str_eq("-q", option_name) || safe_str_eq("--quorum", option_name)) { options.command = 'q'; } else { g_set_error(error, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Unknown param passed to command_cb: %s\n", option_name); return FALSE; } return TRUE; } gboolean name_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.command = 'N'; options.nodeid = crm_parse_int(optarg, NULL); return TRUE; } gboolean remove_cb(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { if (optarg == NULL) { crm_err("-R option requires an argument"); g_set_error(error, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "-R option requires an argument"); return FALSE; } options.command = 'R'; options.dangerous_cmd = TRUE; options.target_uname = strdup(optarg); return TRUE; } /*! * \internal * \brief Exit crm_node * Clean up memory, and either quit mainloop (if running) or exit * * \param[in] value Exit status */ static void crm_node_exit(crm_exit_t value) { if (pid_s) { free(pid_s); pid_s = NULL; } exit_code = value; if (mainloop && g_main_loop_is_running(mainloop)) { g_main_loop_quit(mainloop); } else { crm_exit(exit_code); } } static void exit_disconnect(gpointer user_data) { fprintf(stderr, "error: Lost connection to cluster\n"); crm_node_exit(CRM_EX_DISCONNECT); } typedef int (*ipc_dispatch_fn) (const char *buffer, ssize_t length, gpointer userdata); static crm_ipc_t * new_mainloop_for_ipc(const char *system, ipc_dispatch_fn dispatch) { mainloop_io_t *source = NULL; crm_ipc_t *ipc = NULL; struct ipc_client_callbacks ipc_callbacks = { .dispatch = dispatch, .destroy = exit_disconnect }; mainloop = g_main_loop_new(NULL, FALSE); source = mainloop_add_ipc_client(system, G_PRIORITY_DEFAULT, 0, NULL, &ipc_callbacks); ipc = mainloop_get_ipc_client(source); if (ipc == NULL) { fprintf(stderr, "error: Could not connect to cluster (is it running?)\n"); crm_node_exit(CRM_EX_DISCONNECT); } return ipc; } static void run_mainloop_and_exit() { g_main_loop_run(mainloop); g_main_loop_unref(mainloop); mainloop = NULL; crm_node_exit(exit_code); } static int send_controller_hello(crm_ipc_t *controller) { xmlNode *hello = NULL; int rc; pid_s = crm_getpid_s(); hello = create_hello_message(pid_s, crm_system_name, "1", "0"); rc = crm_ipc_send(controller, hello, 0, 0, NULL); free_xml(hello); return (rc < 0)? rc : 0; } static int send_node_info_request(crm_ipc_t *controller, uint32_t nodeid) { xmlNode *ping = NULL; int rc; ping = create_request(CRM_OP_NODE_INFO, NULL, NULL, CRM_SYSTEM_CRMD, crm_system_name, pid_s); if (nodeid > 0) { crm_xml_add_int(ping, XML_ATTR_ID, nodeid); } rc = crm_ipc_send(controller, ping, 0, 0, NULL); free_xml(ping); return (rc < 0)? rc : 0; } static int dispatch_controller(const char *buffer, ssize_t length, gpointer userdata) { xmlNode *message = string2xml(buffer); xmlNode *data = NULL; const char *value = NULL; if (message == NULL) { fprintf(stderr, "error: Could not understand reply from controller\n"); crm_node_exit(CRM_EX_PROTOCOL); return 0; } crm_log_xml_trace(message, "controller reply"); exit_code = CRM_EX_PROTOCOL; // Validate reply value = crm_element_value(message, F_CRM_MSG_TYPE); if (safe_str_neq(value, XML_ATTR_RESPONSE)) { fprintf(stderr, "error: Message from controller was not a reply\n"); goto done; } value = crm_element_value(message, XML_ATTR_REFERENCE); if (value == NULL) { fprintf(stderr, "error: Controller reply did not specify original message\n"); goto done; } data = get_message_xml(message, F_CRM_DATA); if (data == NULL) { fprintf(stderr, "error: Controller reply did not contain any data\n"); goto done; } switch (options.command) { case 'i': value = crm_element_value(data, XML_ATTR_ID); if (value == NULL) { fprintf(stderr, "error: Controller reply did not contain node ID\n"); } else { printf("%s\n", value); exit_code = CRM_EX_OK; } break; case 'n': case 'N': value = crm_element_value(data, XML_ATTR_UNAME); if (value == NULL) { fprintf(stderr, "Node is not known to cluster\n"); exit_code = CRM_EX_NOHOST; } else { printf("%s\n", value); exit_code = CRM_EX_OK; } break; case 'q': value = crm_element_value(data, XML_ATTR_HAVE_QUORUM); if (value == NULL) { fprintf(stderr, "error: Controller reply did not contain quorum status\n"); } else { bool quorum = crm_is_true(value); printf("%d\n", quorum); exit_code = quorum? CRM_EX_OK : CRM_EX_QUORUM; } break; default: fprintf(stderr, "internal error: Controller reply not expected\n"); exit_code = CRM_EX_SOFTWARE; break; } done: free_xml(message); crm_node_exit(exit_code); return 0; } static void run_controller_mainloop(uint32_t nodeid) { crm_ipc_t *controller = NULL; int rc; controller = new_mainloop_for_ipc(CRM_SYSTEM_CRMD, dispatch_controller); rc = send_controller_hello(controller); if (rc < 0) { fprintf(stderr, "error: Could not register with controller: %s\n", pcmk_strerror(rc)); crm_node_exit(crm_errno2exit(rc)); } rc = send_node_info_request(controller, nodeid); if (rc < 0) { fprintf(stderr, "error: Could not ping controller: %s\n", pcmk_strerror(rc)); crm_node_exit(crm_errno2exit(rc)); } // Run main loop to get controller reply via dispatch_controller() run_mainloop_and_exit(); } static void print_node_name() { // Check environment first (i.e. when called by resource agent) const char *name = getenv("OCF_RESKEY_" CRM_META "_" XML_LRM_ATTR_TARGET); if (name != NULL) { printf("%s\n", name); crm_node_exit(CRM_EX_OK); } else { // Otherwise ask the controller run_controller_mainloop(0); } } static int cib_remove_node(long id, const char *name) { int rc; cib_t *cib = NULL; xmlNode *node = NULL; xmlNode *node_state = NULL; crm_trace("Removing %s from the CIB", name); if(name == NULL && id == 0) { return -ENOTUNIQ; } node = create_xml_node(NULL, XML_CIB_TAG_NODE); node_state = create_xml_node(NULL, XML_CIB_TAG_STATE); crm_xml_add(node, XML_ATTR_UNAME, name); crm_xml_add(node_state, XML_ATTR_UNAME, name); if (id > 0) { crm_xml_set_id(node, "%ld", id); crm_xml_add(node_state, XML_ATTR_ID, ID(node)); } cib = cib_new(); cib->cmds->signon(cib, crm_system_name, cib_command); rc = cib->cmds->remove(cib, XML_CIB_TAG_NODES, node, cib_sync_call); if (rc != pcmk_ok) { printf("Could not remove %s[%ld] from " XML_CIB_TAG_NODES ": %s", name, id, pcmk_strerror(rc)); } rc = cib->cmds->remove(cib, XML_CIB_TAG_STATUS, node_state, cib_sync_call); if (rc != pcmk_ok) { printf("Could not remove %s[%ld] from " XML_CIB_TAG_STATUS ": %s", name, id, pcmk_strerror(rc)); } cib->cmds->signoff(cib); cib_delete(cib); return rc; } static int tools_remove_node_cache(const char *node_name, long nodeid, const char *target) { int rc = -1; crm_ipc_t *conn = crm_ipc_new(target, 0); xmlNode *cmd = NULL; if (!conn) { return -ENOTCONN; } if (!crm_ipc_connect(conn)) { crm_perror(LOG_ERR, "Connection to %s failed", target); crm_ipc_destroy(conn); return -ENOTCONN; } if(safe_str_eq(target, CRM_SYSTEM_CRMD)) { // The controller requires a hello message before sending a request rc = send_controller_hello(conn); if (rc < 0) { fprintf(stderr, "error: Could not register with controller: %s\n", pcmk_strerror(rc)); return rc; } } crm_trace("Removing %s[%ld] from the %s membership cache", node_name, nodeid, target); if(safe_str_eq(target, T_ATTRD)) { cmd = create_xml_node(NULL, __FUNCTION__); crm_xml_add(cmd, F_TYPE, T_ATTRD); crm_xml_add(cmd, F_ORIG, crm_system_name); crm_xml_add(cmd, F_ATTRD_TASK, ATTRD_OP_PEER_REMOVE); crm_xml_add(cmd, F_ATTRD_HOST, node_name); if (nodeid > 0) { crm_xml_add_int(cmd, F_ATTRD_HOST_ID, (int) nodeid); } } else { cmd = create_request(CRM_OP_RM_NODE_CACHE, NULL, NULL, target, crm_system_name, pid_s); if (nodeid > 0) { crm_xml_set_id(cmd, "%ld", nodeid); } crm_xml_add(cmd, XML_ATTR_UNAME, node_name); } rc = crm_ipc_send(conn, cmd, 0, 0, NULL); crm_debug("%s peer cache cleanup for %s (%ld): %d", target, node_name, nodeid, rc); if (rc > 0) { rc = cib_remove_node(nodeid, node_name); } if (conn) { crm_ipc_close(conn); crm_ipc_destroy(conn); } free_xml(cmd); return rc > 0 ? 0 : rc; } static void remove_node(const char *target_uname) { int d = 0; long nodeid = 0; const char *node_name = NULL; char *endptr = NULL; const char *daemons[] = { CRM_SYSTEM_CRMD, "stonith-ng", T_ATTRD, CRM_SYSTEM_MCP, }; // Check whether node was specified by name or numeric ID errno = 0; nodeid = strtol(target_uname, &endptr, 10); if ((errno != 0) || (endptr == target_uname) || (*endptr != '\0') || (nodeid <= 0)) { // It's not a positive integer, so assume it's a node name nodeid = 0; node_name = target_uname; } for (d = 0; d < DIMOF(daemons); d++) { if (tools_remove_node_cache(node_name, nodeid, daemons[d])) { crm_err("Failed to connect to %s to remove node '%s'", daemons[d], target_uname); crm_node_exit(CRM_EX_ERROR); return; } } crm_node_exit(CRM_EX_OK); } static gint compare_node_xml(gconstpointer a, gconstpointer b) { const char *a_name = crm_element_value((xmlNode*) a, "uname"); const char *b_name = crm_element_value((xmlNode*) b, "uname"); return strcmp((a_name? a_name : ""), (b_name? b_name : "")); } static int node_mcp_dispatch(const char *buffer, ssize_t length, gpointer userdata) { GList *nodes = NULL; xmlNode *node = NULL; xmlNode *msg = string2xml(buffer); const char *uname; const char *state; if (msg == NULL) { fprintf(stderr, "error: Could not understand pacemakerd response\n"); crm_node_exit(CRM_EX_PROTOCOL); return 0; } crm_log_xml_trace(msg, "message"); for (node = __xml_first_child(msg); node != NULL; node = __xml_next(node)) { nodes = g_list_insert_sorted(nodes, node, compare_node_xml); } for (GList *iter = nodes; iter; iter = iter->next) { node = (xmlNode*) iter->data; uname = crm_element_value(node, "uname"); state = crm_element_value(node, "state"); if (options.command == 'l') { int id = 0; crm_element_value_int(node, "id", &id); printf("%d %s %s\n", id, (uname? uname : ""), (state? state : "")); // This is CRM_NODE_MEMBER but we don't want to include cluster header } else if ((options.command == 'p') && safe_str_eq(state, "member")) { printf("%s ", (uname? uname : "")); } } if (options.command == 'p') { fprintf(stdout, "\n"); } free_xml(msg); crm_node_exit(CRM_EX_OK); return 0; } static void run_pacemakerd_mainloop() { crm_ipc_t *ipc = NULL; xmlNode *poke = NULL; ipc = new_mainloop_for_ipc(CRM_SYSTEM_MCP, node_mcp_dispatch); // Sending anything will get us a list of nodes poke = create_xml_node(NULL, "poke"); crm_ipc_send(ipc, poke, 0, 0, NULL); free_xml(poke); // Handle reply via node_mcp_dispatch() run_mainloop_and_exit(); } static GOptionContext * build_arg_context(pcmk__common_args_t *args, GOptionGroup *group) { GOptionContext *context = NULL; GOptionEntry extra_prog_entries[] = { { "quiet", 'Q', 0, G_OPTION_ARG_NONE, &(args->quiet), "Be less descriptive in output.", NULL }, { NULL } }; context = pcmk__build_arg_context(args, NULL, &group); /* Add the -q option, which cannot be part of the globally supported options * because some tools use that flag for something else. */ pcmk__add_main_args(context, extra_prog_entries); pcmk__add_arg_group(context, "commands", "Commands:", "Show command help", command_entries); pcmk__add_arg_group(context, "additional", "Additional Options:", "Show additional options", addl_entries); return context; } int main(int argc, char **argv) { pcmk__common_args_t *args = pcmk__new_common_args(SUMMARY); GError *error = NULL; GOptionContext *context = NULL; GOptionGroup *output_group = NULL; gchar **processed_args = NULL; context = build_arg_context(args, output_group); crm_log_cli_init("crm_node"); - processed_args = pcmk__cmdline_preproc(argc, argv, "NR"); + processed_args = pcmk__cmdline_preproc(argv, "NR"); if (!g_option_context_parse_strv(context, &processed_args, &error)) { fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); exit_code = CRM_EX_USAGE; goto done; } for (int i = 0; i < args->verbosity; i++) { crm_bump_log_level(argc, argv); } if (args->version) { /* FIXME: When crm_node is converted to use formatted output, this can go. */ crm_help('v', CRM_EX_USAGE); } if (optind > argc || options.command == 0) { fprintf(stderr, "%s", g_option_context_get_help(context, TRUE, NULL)); exit_code = CRM_EX_USAGE; goto done; } if (options.dangerous_cmd && options.force_flag == FALSE) { fprintf(stderr, "The supplied command is considered dangerous." " To prevent accidental destruction of the cluster," " the --force flag is required in order to proceed.\n"); exit_code = CRM_EX_USAGE; goto done; } switch (options.command) { case 'n': print_node_name(); break; case 'R': remove_node(options.target_uname); break; case 'i': case 'q': case 'N': run_controller_mainloop(options.nodeid); break; case 'l': case 'p': run_pacemakerd_mainloop(); break; default: break; } done: g_strfreev(processed_args); + g_clear_error(&error); pcmk__free_arg_context(context); crm_node_exit(exit_code); return exit_code; } diff --git a/tools/stonith_admin.c b/tools/stonith_admin.c index e228a06846..e003acfd73 100644 --- a/tools/stonith_admin.c +++ b/tools/stonith_admin.c @@ -1,853 +1,613 @@ /* * Copyright 2009-2020 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU General Public License version 2 * or later (GPLv2+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include #include #include #include #include #include #include +#include #define SUMMARY "stonith_admin - Access the Pacemaker fencing API" char action = 0; struct { gboolean as_nodeid; gboolean broadcast; gboolean cleanup; gboolean installed; gboolean metadata; gboolean registered; gboolean validate_cfg; stonith_key_value_t *devices; stonith_key_value_t *params; int fence_level; int timeout ; int tolerance; char *agent; char *confirm_host; char *fence_host; char *history; char *last_fenced; char *query; char *reboot_host; char *register_dev; char *register_level; char *targets; char *terminate; char *unfence_host; char *unregister_dev; char *unregister_level; } options = { .timeout = 120 }; gboolean add_env_params(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean add_stonith_device(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean add_stonith_params(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean add_tolerance(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); gboolean set_tag(const gchar *option_name, const gchar *optarg, gpointer data, GError **error); #define INDENT " " /* *INDENT-OFF* */ static GOptionEntry defn_entries[] = { { "register", 'R', 0, G_OPTION_ARG_STRING, &options.register_dev, "Register the named stonith device. Requires: --agent.\n" INDENT "Optional: --option, --env-option.", "DEVICE" }, { "deregister", 'D', 0, G_OPTION_ARG_STRING, &options.unregister_dev, "De-register the named stonith device.", "DEVICE" }, { "register-level", 'r', 0, G_OPTION_ARG_STRING, &options.register_level, "Register a stonith level for the named target,\n" INDENT "specified as one of NAME, @PATTERN, or ATTR=VALUE.\n" INDENT "Requires: --index and one or more --device entries.", "TARGET" }, { "deregister-level", 'd', 0, G_OPTION_ARG_STRING, &options.unregister_level, "Unregister a stonith level for the named target,\n" INDENT "specified as for --register-level. Requires: --index", "TARGET" }, { NULL } }; static GOptionEntry query_entries[] = { { "list", 'l', 0, G_OPTION_ARG_STRING, &options.terminate, "List devices that can terminate the specified host.\n" INDENT "Optional: --timeout", "HOST" }, { "list-registered", 'L', 0, G_OPTION_ARG_NONE, &options.registered, "List all registered devices. Optional: --timeout.", NULL }, { "list-installed", 'I', 0, G_OPTION_ARG_NONE, &options.installed, "List all installed devices. Optional: --timeout.", NULL }, { "list-targets", 's', 0, G_OPTION_ARG_STRING, &options.targets, "List the targets that can be fenced by the\n" INDENT "named device. Optional: --timeout.", "DEVICE" }, { "metadata", 'M', 0, G_OPTION_ARG_NONE, &options.metadata, "Show agent metadata. Requires: --agent.\n" INDENT "Optional: --timeout.", NULL }, { "query", 'Q', 0, G_OPTION_ARG_STRING, &options.query, "Check the named device's status. Optional: --timeout.", "DEVICE" }, { "history", 'H', 0, G_OPTION_ARG_STRING, &options.history, "Show last successful fencing operation for named node\n" INDENT "(or '*' for all nodes). Optional: --timeout, --cleanup,\n" INDENT "--quiet (show only the operation's epoch timestamp),\n" INDENT "--verbose (show all recorded and pending operations),\n" INDENT "--broadcast (update history from all nodes available).", "NODE" }, { "last", 'h', 0, G_OPTION_ARG_STRING, &options.last_fenced, "Indicate when the named node was last fenced.\n" INDENT "Optional: --as-node-id.", "NODE" }, { "validate", 'K', 0, G_OPTION_ARG_NONE, &options.validate_cfg, "Validate a fence device configuration.\n" INDENT "Requires: --agent. Optional: --option, --env-option,\n" INDENT "--quiet (print no output, only return status).", NULL }, { NULL } }; static GOptionEntry fence_entries[] = { { "fence", 'F', 0, G_OPTION_ARG_STRING, &options.fence_host, "Fence named host. Optional: --timeout, --tolerance.", "HOST" }, { "unfence", 'U', 0, G_OPTION_ARG_STRING, &options.unfence_host, "Unfence named host. Optional: --timeout, --tolerance.", "HOST" }, { "reboot", 'B', 0, G_OPTION_ARG_STRING, &options.reboot_host, "Reboot named host. Optional: --timeout, --tolerance.", "HOST" }, { "confirm", 'C', 0, G_OPTION_ARG_STRING, &options.confirm_host, "Tell cluster that named host is now safely down.", "HOST", }, { NULL } }; static GOptionEntry addl_entries[] = { { "cleanup", 'c', 0, G_OPTION_ARG_NONE, &options.cleanup, "Cleanup wherever appropriate. Requires --history.", NULL }, { "broadcast", 'b', 0, G_OPTION_ARG_NONE, &options.broadcast, "Broadcast wherever appropriate.", NULL }, { "agent", 'a', 0, G_OPTION_ARG_STRING, &options.agent, "The agent to use (for example, fence_xvm;\n" INDENT "with --register, --metadata, --validate).", "AGENT" }, { "option", 'o', 0, G_OPTION_ARG_CALLBACK, add_stonith_params, "Specify a device configuration parameter as NAME=VALUE\n" INDENT "(may be specified multiple times; with --register,\n" INDENT "--validate).", "PARAM" }, { "env-option", 'e', 0, G_OPTION_ARG_CALLBACK, add_env_params, "Specify a device configuration parameter with the\n" INDENT "specified name, using the value of the\n" INDENT "environment variable of the same name prefixed with\n" INDENT "OCF_RESKEY_ (may be specified multiple times;\n" INDENT "with --register, --validate).", "PARAM" }, { "tag", 'T', 0, G_OPTION_ARG_CALLBACK, set_tag, "Identify fencing operations in logs with the specified\n" INDENT "tag; useful when multiple entities might invoke\n" INDENT "stonith_admin (used with most commands).", "TAG" }, { "device", 'v', 0, G_OPTION_ARG_CALLBACK, add_stonith_device, "Device ID (with --register-level, device to associate with\n" INDENT "a given host and level; may be specified multiple times)" #if SUPPORT_CIBSECRETS "\n" INDENT "(with --validate, name to use to load CIB secrets)" #endif ".", "DEVICE" }, { "index", 'i', 0, G_OPTION_ARG_INT, &options.fence_level, "The stonith level (1-9) (with --register-level,\n" INDENT "--deregister-level).", "LEVEL" }, { "timeout", 't', 0, G_OPTION_ARG_INT, &options.timeout, "Operation timeout in seconds (default 120;\n" INDENT "used with most commands).", "SECONDS" }, { "as-node-id", 'n', 0, G_OPTION_ARG_NONE, &options.as_nodeid, "(Advanced) The supplied node is the corosync node ID\n" INDENT "(with --last).", NULL }, { "tolerance", 0, 0, G_OPTION_ARG_CALLBACK, add_tolerance, "(Advanced) Do nothing if an equivalent --fence request\n" INDENT "succeeded less than this many seconds earlier\n" INDENT "(with --fence, --unfence, --reboot).", "SECONDS" }, { NULL } }; /* *INDENT-ON* */ static pcmk__supported_format_t formats[] = { PCMK__SUPPORTED_FORMAT_HTML, PCMK__SUPPORTED_FORMAT_TEXT, PCMK__SUPPORTED_FORMAT_XML, { NULL, NULL, NULL } }; static int st_opts = st_opt_sync_call | st_opt_allow_suicide; -static GMainLoop *mainloop = NULL; -struct { - stonith_t *st; - const char *target; - const char *action; - char *name; - int timeout; - int tolerance; - int rc; -} async_fence_data; +static char *name = NULL; gboolean add_env_params(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { char *key = crm_concat("OCF_RESKEY", optarg, '_'); const char *env = getenv(key); gboolean retval = TRUE; if (env == NULL) { crm_err("Invalid option: -e %s", optarg); g_set_error(error, G_OPTION_ERROR, CRM_EX_INVALID_PARAM, "Invalid option: -e %s", optarg); retval = FALSE; } else { crm_info("Got: '%s'='%s'", optarg, env); options.params = stonith_key_value_add(options.params, optarg, env); } free(key); return retval; } gboolean add_stonith_device(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.devices = stonith_key_value_add(options.devices, NULL, optarg); return TRUE; } gboolean add_tolerance(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { options.tolerance = crm_get_msec(optarg) / 1000; return TRUE; } gboolean add_stonith_params(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { char *name = NULL; char *value = NULL; int rc = 0; gboolean retval = TRUE; crm_info("Scanning: -o %s", optarg); rc = pcmk_scan_nvpair(optarg, &name, &value); if (rc != 2) { crm_err("Invalid option: -o %s: %s", optarg, pcmk_strerror(rc)); g_set_error(error, G_OPTION_ERROR, rc, "Invalid option: -o %s: %s", optarg, pcmk_strerror(rc)); retval = FALSE; } else { crm_info("Got: '%s'='%s'", name, value); options.params = stonith_key_value_add(options.params, name, value); } free(name); free(value); return retval; } gboolean set_tag(const gchar *option_name, const gchar *optarg, gpointer data, GError **error) { - free(async_fence_data.name); - async_fence_data.name = crm_strdup_printf("%s.%s", crm_system_name, optarg); - return TRUE; -} - -static void -notify_callback(stonith_t * st, stonith_event_t * e) -{ - if (e->result != pcmk_ok) { - return; - } - - if (safe_str_eq(async_fence_data.target, e->target) && - safe_str_eq(async_fence_data.action, e->action)) { - - async_fence_data.rc = e->result; - g_main_loop_quit(mainloop); - } -} - -static void -fence_callback(stonith_t * stonith, stonith_callback_data_t * data) -{ - async_fence_data.rc = data->rc; - - g_main_loop_quit(mainloop); -} - -static gboolean -async_fence_helper(gpointer user_data) -{ - stonith_t *st = async_fence_data.st; - int call_id = 0; - int rc = stonith_api_connect_retry(st, async_fence_data.name, 10); - - if (rc != pcmk_ok) { - fprintf(stderr, "Could not connect to fencer: %s\n", pcmk_strerror(rc)); - g_main_loop_quit(mainloop); - return TRUE; - } - - st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, notify_callback); - - call_id = st->cmds->fence(st, - st_opt_allow_suicide, - async_fence_data.target, - async_fence_data.action, - async_fence_data.timeout, async_fence_data.tolerance); - - if (call_id < 0) { - g_main_loop_quit(mainloop); - return TRUE; - } - - st->cmds->register_callback(st, - call_id, - async_fence_data.timeout, - st_opt_timeout_updates, NULL, "callback", fence_callback); - + free(name); + name = crm_strdup_printf("%s.%s", crm_system_name, optarg); return TRUE; } -static int -mainloop_fencing(stonith_t * st, const char *target, const char *action, int timeout, int tolerance) -{ - crm_trigger_t *trig; - - async_fence_data.st = st; - async_fence_data.target = target; - async_fence_data.action = action; - async_fence_data.timeout = timeout; - async_fence_data.tolerance = tolerance; - async_fence_data.rc = -1; - - trig = mainloop_add_trigger(G_PRIORITY_HIGH, async_fence_helper, NULL); - mainloop_set_trigger(trig); - - mainloop = g_main_loop_new(NULL, FALSE); - g_main_loop_run(mainloop); - - return async_fence_data.rc; -} - -static int -handle_level(stonith_t *st, char *target, int fence_level, - stonith_key_value_t *devices, bool added) -{ - char *node = NULL; - char *pattern = NULL; - char *name = NULL; - char *value = NULL; - - if (target == NULL) { - // Not really possible, but makes static analysis happy - return -EINVAL; - } - - /* Determine if targeting by attribute, node name pattern or node name */ - value = strchr(target, '='); - if (value != NULL) { - name = target; - *value++ = '\0'; - } else if (*target == '@') { - pattern = target + 1; - } else { - node = target; - } - - /* Register or unregister level as appropriate */ - if (added) { - return st->cmds->register_level_full(st, st_opts, node, pattern, - name, value, fence_level, - devices); - } - return st->cmds->remove_level_full(st, st_opts, node, pattern, - name, value, fence_level); -} - -static int -handle_history(stonith_t *st, const char *target, int timeout, int quiet, - int verbose, int cleanup, int broadcast, pcmk__output_t *out) -{ - stonith_history_t *history = NULL, *hp, *latest = NULL; - int rc = 0; - - if (!quiet) { - if (cleanup) { - out->info(out, "cleaning up fencing-history%s%s", - target ? " for node " : "", target ? target : ""); - } - if (broadcast) { - out->info(out, "gather fencing-history from all nodes"); - } - } - - rc = st->cmds->history(st, st_opts | (cleanup?st_opt_cleanup:0) | - (broadcast?st_opt_broadcast:0), - (safe_str_eq(target, "*")? NULL : target), - &history, timeout); - - out->begin_list(out, "event", "events", "Fencing history"); - - history = stonith__sort_history(history); - for (hp = history; hp; hp = hp->next) { - if (hp->state == st_done) { - latest = hp; - } - - if (quiet || !verbose) { - continue; - } - - out->message(out, "stonith-event", hp, 1, stonith__later_succeeded(hp, history)); - out->increment_list(out); - } - - if (latest) { - if (quiet && out->supports_quiet) { - out->info(out, "%lld", (long long) latest->completed); - } else if (!verbose) { // already printed if verbose - out->message(out, "stonith-event", latest, 0, FALSE); - out->increment_list(out); - } - } - - out->end_list(out); - - stonith_history_free(history); - return rc; -} - -static int -validate(stonith_t *st, const char *agent, const char *id, - stonith_key_value_t *params, int timeout, int quiet, - pcmk__output_t *out) -{ - int rc = 1; - char *output = NULL; - char *error_output = NULL; - - rc = st->cmds->validate(st, st_opt_sync_call, id, NULL, agent, params, - timeout, &output, &error_output); - - if (quiet) { - return rc; - } - - out->message(out, "validate", agent, id, output, error_output, rc); - return rc; -} - -static void -show_last_fenced(pcmk__output_t *out, const char *target) -{ - time_t when = 0; - - if (target == NULL) { - // Not really possible, but makes static analysis happy - return; - } - if (options.as_nodeid) { - uint32_t nodeid = atol(target); - when = stonith_api_time(nodeid, NULL, FALSE); - } else { - when = stonith_api_time(0, target, FALSE); - } - out->message(out, "last-fenced", target, when); -} - -static int -show_metadata(pcmk__output_t *out, stonith_t *st, char *agent, int timeout) -{ - char *buffer = NULL; - int rc = st->cmds->metadata(st, st_opt_sync_call, agent, NULL, &buffer, - timeout); - - if (rc == pcmk_ok) { - out->output_xml(out, "metadata", buffer); - } else { - out->err(out, "Can't get fence agent meta-data: %s", - pcmk_strerror(rc)); - } - free(buffer); - return rc; -} - static GOptionContext * build_arg_context(pcmk__common_args_t *args, GOptionGroup **group) { GOptionContext *context = NULL; GOptionEntry extra_prog_entries[] = { { "quiet", 'q', 0, G_OPTION_ARG_NONE, &(args->quiet), "Be less descriptive in output.", NULL }, { NULL } }; context = pcmk__build_arg_context(args, "text (default), html, xml", group); /* Add the -q option, which cannot be part of the globally supported options * because some tools use that flag for something else. */ pcmk__add_main_args(context, extra_prog_entries); pcmk__add_arg_group(context, "definition", "Device Definition Commands:", "Show device definition help", defn_entries); pcmk__add_arg_group(context, "queries", "Queries:", "Show query help", query_entries); pcmk__add_arg_group(context, "fence", "Fencing Commands:", "Show fence help", fence_entries); pcmk__add_arg_group(context, "additional", "Additional Options:", "Show additional options", addl_entries); return context; } int main(int argc, char **argv) { int rc = 0; bool no_connect = false; bool required_agent = false; char *target = NULL; - char *lists = NULL; const char *device = NULL; crm_exit_t exit_code = CRM_EX_OK; stonith_t *st = NULL; - stonith_key_value_t *dIter = NULL; pcmk__output_t *out = NULL; pcmk__common_args_t *args = pcmk__new_common_args(SUMMARY); GError *error = NULL; GOptionContext *context = NULL; GOptionGroup *output_group = NULL; gchar **processed_args = NULL; context = build_arg_context(args, &output_group); pcmk__register_formats(output_group, formats); crm_log_cli_init("stonith_admin"); - async_fence_data.name = strdup(crm_system_name); + name = strdup(crm_system_name); - processed_args = pcmk__cmdline_preproc(argc, argv, "adehilorstvBCDFHQRTU"); + processed_args = pcmk__cmdline_preproc(argv, "adehilorstvBCDFHQRTU"); if (!g_option_context_parse_strv(context, &processed_args, &error)) { fprintf(stderr, "%s: %s\n", g_get_prgname(), error->message); exit_code = CRM_EX_USAGE; goto done; } for (int i = 0; i < args->verbosity; i++) { crm_bump_log_level(argc, argv); } rc = pcmk__output_new(&out, args->output_ty, args->output_dest, argv); if (rc != pcmk_rc_ok) { fprintf(stderr, "Error creating output format %s: %s\n", args->output_ty, pcmk_rc_str(rc)); exit_code = CRM_EX_ERROR; goto done; } stonith__register_messages(out); if (args->version) { out->version(out, false); goto done; } if (options.validate_cfg) { required_agent = true; no_connect = true; action = 'K'; } if (options.installed) { no_connect = true; action = 'I'; } if (options.registered) { action = 'L'; } if (options.register_dev != NULL) { required_agent = true; action = 'R'; device = options.register_dev; } if (options.query != NULL) { action = 'Q'; device = options.query; } if (options.unregister_dev != NULL) { action = 'D'; device = options.unregister_dev; } if (options.targets != NULL) { action = 's'; device = options.targets; } if (options.terminate != NULL) { action = 'L'; target = options.terminate; } if (options.metadata) { no_connect = true; required_agent = true; action = 'M'; } if (options.reboot_host != NULL) { no_connect = true; action = 'B'; target = options.reboot_host; crm_log_args(argc, argv); } if (options.fence_host != NULL) { no_connect = true; action = 'F'; target = options.fence_host; crm_log_args(argc, argv); } if (options.unfence_host != NULL) { no_connect = true; action = 'U'; target = options.unfence_host; crm_log_args(argc, argv); } if (options.confirm_host != NULL) { action = 'C'; target = options.confirm_host; crm_log_args(argc, argv); } if (options.last_fenced != NULL) { action = 'h'; target = options.last_fenced; } if (options.history != NULL) { action = 'H'; target = options.history; } if (options.register_level != NULL) { action = 'r'; target = options.register_level; } if (options.unregister_level != NULL) { action = 'd'; target = options.unregister_level; } if (optind > argc || action == 0) { out->err(out, "%s", g_option_context_get_help(context, TRUE, NULL)); exit_code = CRM_EX_USAGE; goto done; } if (required_agent && options.agent == NULL) { out->err(out, "Please specify an agent to query using -a,--agent [value]"); out->err(out, "%s", g_option_context_get_help(context, TRUE, NULL)); exit_code = CRM_EX_USAGE; goto done; } st = stonith_api_new(); if (st == NULL) { rc = -ENOMEM; } else if (!no_connect) { - rc = st->cmds->connect(st, async_fence_data.name, NULL); + rc = st->cmds->connect(st, name, NULL); } if (rc < 0) { out->err(out, "Could not connect to fencer: %s", pcmk_strerror(rc)); exit_code = CRM_EX_DISCONNECT; goto done; } switch (action) { case 'I': - rc = st->cmds->list_agents(st, st_opt_sync_call, NULL, &options.devices, options.timeout); + rc = pcmk__fence_installed(out, st, options.timeout); if (rc < 0) { out->err(out, "Failed to list installed devices: %s", pcmk_strerror(rc)); - break; - } - - out->begin_list(out, "fence device", "fence devices", "Installed fence devices"); - for (dIter = options.devices; dIter; dIter = dIter->next) { - out->list_item(out, "device", "%s", dIter->value); } - out->end_list(out); - rc = 0; - - stonith_key_value_freeall(options.devices, 1, 1); break; case 'L': - rc = st->cmds->query(st, st_opts, target, &options.devices, options.timeout); + rc = pcmk__fence_registered(out, st, target, options.timeout); if (rc < 0) { out->err(out, "Failed to list registered devices: %s", pcmk_strerror(rc)); - break; } - out->begin_list(out, "fence device", "fence devices", "Registered fence devices"); - for (dIter = options.devices; dIter; dIter = dIter->next) { - out->list_item(out, "device", "%s", dIter->value); - } - - out->end_list(out); - rc = 0; - - stonith_key_value_freeall(options.devices, 1, 1); break; case 'Q': rc = st->cmds->monitor(st, st_opts, device, options.timeout); if (rc < 0) { rc = st->cmds->list(st, st_opts, device, NULL, options.timeout); } break; + case 's': - rc = st->cmds->list(st, st_opts, device, &lists, options.timeout); - if (rc == 0) { - GList *targets = stonith__parse_targets(lists); - - out->begin_list(out, "fence target", "fence targets", "Fence Targets"); - while (targets != NULL) { - out->list_item(out, NULL, "%s", (const char *) targets->data); - targets = targets->next; - } - out->end_list(out); - free(lists); - - } else if (rc != 0) { + rc = pcmk__fence_list_targets(out, st, target, options.timeout); + if (rc < 0) { out->err(out, "Couldn't list targets: %s", pcmk_strerror(rc)); } + break; + case 'R': rc = st->cmds->register_device(st, st_opts, device, NULL, options.agent, options.params); break; + case 'D': rc = st->cmds->remove_device(st, st_opts, device); break; + case 'd': + rc = pcmk__fence_unregister_level(st, target, options.fence_level); + break; + case 'r': - rc = handle_level(st, target, options.fence_level, options.devices, action == 'r'); + rc = pcmk__fence_register_level(st, target, options.fence_level, options.devices); break; + case 'M': - rc = show_metadata(out, st, options.agent, options.timeout); + rc = pcmk__fence_metadata(out, st, options.agent, options.timeout); + if (rc != 0) { + out->err(out, "Can't get fence agent meta-data: %s", pcmk_strerror(rc)); + } + break; + case 'C': rc = st->cmds->confirm(st, st_opts, target); break; + case 'B': - rc = mainloop_fencing(st, target, "reboot", options.timeout, options.tolerance); + rc = pcmk__fence_action(st, target, "reboot", name, options.timeout, + options.tolerance); break; + case 'F': - rc = mainloop_fencing(st, target, "off", options.timeout, options.tolerance); + rc = pcmk__fence_action(st, target, "off", name, options.timeout, + options.tolerance); break; + case 'U': - rc = mainloop_fencing(st, target, "on", options.timeout, options.tolerance); + rc = pcmk__fence_action(st, target, "on", name, options.timeout, + options.tolerance); break; + case 'h': - show_last_fenced(out, target); + rc = pcmk__fence_last(out, target, options.as_nodeid); break; + case 'H': - rc = handle_history(st, target, options.timeout, args->quiet, - args->verbosity, options.cleanup, - options.broadcast, out); + rc = pcmk__fence_history(out, st, target, options.timeout, args->quiet, + args->verbosity, options.broadcast, options.cleanup); break; + case 'K': - device = (options.devices ? options.devices->key : NULL); - rc = validate(st, options.agent, device, options.params, - options.timeout, args->quiet, out); + device = options.devices ? options.devices->key : NULL; + rc = pcmk__fence_validate(out, st, options.agent, device, options.params, + options.timeout); break; } crm_info("Command returned: %s (%d)", pcmk_strerror(rc), rc); exit_code = crm_errno2exit(rc); done: g_strfreev(processed_args); + g_clear_error(&error); pcmk__free_arg_context(context); if (out != NULL) { out->finish(out, exit_code, true, NULL); pcmk__output_free(out); } - free(async_fence_data.name); + free(name); stonith_key_value_freeall(options.params, 1, 1); if (st != NULL) { st->cmds->disconnect(st); stonith_api_delete(st); } return exit_code; }