Package ganeti :: Module cli
[hide private]
[frames] | no frames]

Module cli

source code

Module dealing with command line parsing

Classes [hide private]
  _Argument
  ArgSuggest
Suggesting argument.
  ArgChoice
Choice argument.
  ArgUnknown
Unknown argument to program (e.g.
  ArgInstance
Instances argument.
  ArgNode
Node argument.
  ArgNetwork
Network argument.
  ArgGroup
Node group argument.
  ArgJobId
Job ID argument.
  ArgFile
File path argument.
  ArgCommand
Command argument.
  ArgHost
Host argument.
  ArgOs
OS argument.
  ArgExtStorage
ExtStorage argument.
  ArgFilter
Filter UUID argument.
  _ShowUsage
Exception class for _ParseArgs.
  _ShowVersion
Exception class for _ParseArgs.
  JobSubmittedException
Job was submitted, client should exit.
  JobPollCbBase
Base class for GenericPollJob callbacks.
  JobPollReportCbBase
Base class for GenericPollJob reporting callbacks.
  _LuxiJobPollCb
  FeedbackFnJobPollReportCb
  StdioJobPollReportCb
  _RunWhileDaemonsStoppedHelper
Helper class for RunWhileDaemonsStopped to simplify state management
  _QueryColumnFormatter
Callable class for formatting fields of a query.
  TableColumn
Describes a column for FormatTable.
  JobExecutor
Class which manages the submission and execution of multiple jobs.
Functions [hide private]
 
_ExtractTagsObject(opts, args)
Extract the tag type object.
source code
 
_ExtendTags(opts, args)
Extend the args if a source file has been given.
source code
 
ListTags(opts, args)
List the tags on a given object.
source code
 
AddTags(opts, args)
Add tags on a given object.
source code
 
RemoveTags(opts, args)
Remove tags from a given object.
source code
 
_ParseArgs(binary, argv, commands, aliases, env_override)
Parser for the command line arguments.
source code
 
_FormatUsage(binary, commands)
Generates a nice description of all commands.
source code
 
_CheckArguments(cmd, args_def, args)
Verifies the arguments using the argument definition.
source code
 
SplitNodeOption(value)
Splits the value of a --node option.
source code
list
CalculateOSNames(os_name, os_variants)
Calculates all the names an OS can be called, according to its variants.
source code
 
ParseFields(selected, default)
Parses the values of "--field"-like options.
source code
 
UsesRPC(fn)
RPC-wrapper decorator.
source code
 
AskUser(text, choices=None)
Ask the user a question.
source code
 
SendJob(ops, cl=None)
Function to submit an opcode without waiting for the results.
source code
 
GenericPollJob(job_id, cbs, report_cbs)
Generic job-polling function.
source code
 
FormatLogMessage(log_type, log_msg)
Formats a job message according to its type.
source code
 
PollJob(job_id, cl=None, feedback_fn=None, reporter=None)
Function to poll for the result of a job.
source code
 
SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None)
Legacy function to submit an opcode.
source code
 
SubmitOpCodeToDrainedQueue(op)
Forcefully insert a job in the queue, even if it is drained.
source code
 
SubmitOrSend(op, opts, cl=None, feedback_fn=None)
Wrapper around SubmitOpCode or SendJob.
source code
 
_InitReasonTrail(op, opts)
Builds the first part of the reason trail
source code
 
SetGenericOpcodeOpts(opcode_list, options)
Processor for generic options.
source code
 
FormatError(err)
Return a formatted error message for a given error.
source code
 
GenericMain(commands, override=None, aliases=None, env_override=frozenset())
Generic main function for all the gnt-* commands.
source code
 
ParseNicOption(optvalue)
Parses the value of the --net option(s).
source code
 
FixHvParams(hvparams) source code
int
GenericInstanceCreate(mode, opts, args)
Add an instance to the cluster via either creation or import.
source code
 
RunWhileDaemonsStopped(feedback_fn, exclude_daemons, fn, *args, **kwargs)
Calls a function while all cluster daemons are stopped.
source code
 
RunWhileClusterStopped(feedback_fn, fn, *args)
Calls a function while all cluster daemons are stopped.
source code
 
GenerateTable(headers, fields, separator, data, numfields=None, unitfields=None, units=None)
Prints a table with headers and different fields.
source code
 
_FormatBool(value)
Formats a boolean value as a string.
source code
tuple; (callable, bool)
_GetColumnFormatter(fdef, override, unit)
Returns formatting function for a field.
source code
 
FormatResultError(status, verbose)
Formats result status other than constants.RS_NORMAL.
source code
 
FormatQueryResult(result, unit=None, format_override=None, separator=None, header=False, verbose=False)
Formats data in objects.QueryResponse.
source code
 
_GetUnknownFields(fdefs)
Returns list of unknown fields included in fdefs.
source code
 
_WarnUnknownFields(fdefs)
Prints a warning to stderr if a query included unknown fields.
source code
 
GenericList(resource, fields, names, unit, separator, header, cl=None, format_override=None, verbose=False, force_filter=False, namefield=None, qfilter=None, isnumeric=False)
Generic implementation for listing all items of a resource.
source code
list
_FieldDescValues(fdef)
Helper function for GenericListFields to get query field description.
source code
 
GenericListFields(resource, fields, separator, header, cl=None)
Generic implementation for listing fields for a resource.
source code
 
_GetColFormatString(width, align_right)
Returns the format string for a field.
source code
 
FormatTable(rows, columns, header, separator)
Formats data as a table.
source code
string
FormatTimestamp(ts)
Formats a given timestamp.
source code
 
ParseTimespec(value)
Parse a time specification.
source code
 
GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False, filter_master=False, nodegroup=None)
Returns the names of online nodes.
source code
a list of tuples
GetNodesSshPorts(nodes, cl)
Retrieves SSH ports of given nodes.
source code
a list of tuples
GetNodeUUIDs(nodes, cl)
Retrieves the UUIDs of given nodes.
source code
 
_ToStream(stream, txt, *args)
Write a message to a stream, bypassing the logging system
source code
 
ToStdout(txt, *args)
Write a message to stdout only, bypassing the logging system
source code
 
ToStdoutAndLoginfo(txt, *args)
Write a message to stdout and additionally log it at INFO level
source code
 
ToStderr(txt, *args)
Write a message to stderr only, bypassing the logging system
source code
dict
FormatParamsDictInfo(param_dict, actual, roman=False)
Formats a parameter dictionary.
source code
 
_FormatListInfoDefault(data, def_data) source code
list of pairs
FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster, roman=False)
Formats an instance policy.
source code
 
_PrintSpecsParameters(buf, specs) source code
 
PrintIPolicyCommand(buf, ipolicy, isgroup)
Print the command option used to generate the given instance policy.
source code
boolean
ConfirmOperation(names, list_type, text, extra="")
Ask the user to confirm an operation on a list of list_type.
source code
 
_MaybeParseUnit(elements)
Parses and returns an array of potential values with units.
source code
 
_InitISpecsFromSplitOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count, ispecs_disk_count, ispecs_disk_size, ispecs_nic_count, group_ipolicy, fill_all) source code
 
_ParseSpecUnit(spec, keyname) source code
 
_ParseISpec(spec, keyname, required) source code
 
_GetISpecsInAllowedValues(minmax_ispecs, allowed_values) source code
 
_InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs, group_ipolicy, allowed_values) source code
 
CreateIPolicyFromOpts(ispecs_mem_size=None, ispecs_cpu_count=None, ispecs_disk_count=None, ispecs_disk_size=None, ispecs_nic_count=None, minmax_ispecs=None, std_ispecs=None, ipolicy_disk_templates=None, ipolicy_vcpu_ratio=None, ipolicy_spindle_ratio=None, ipolicy_memory_ratio=None, group_ipolicy=False, allowed_values=None, fill_all=False)
Creation of instance policy based on command line options.
source code
bool
_NotAContainer(data)
Checks whether the input is not a container data type.
source code
dict of any to int
_GetAlignmentMapping(data)
Returns info about alignment if present in an encoded ordered dictionary.
source code
 
_SerializeGenericInfo(buf, data, level, afterkey=False)
Formatting core of PrintGenericInfo.
source code
 
PrintGenericInfo(data)
Print information formatted according to the hierarchy.
source code
Variables [hide private]
  sys
  textwrap
  time
  logging
  errno
  itertools
  shlex
  StringIO
  utils
  errors
  constants
  opcodes
  rpcerr
  rpc
  ssh
  compat
  netutils
  qlang
  objects
  pathutils
  serializer
  TO_GROUP_OPT
  POWER_DELAY_OPT
  NEW_RAPI_CERT_OPT
  OPT_COMPL_ALL
  OOB_TIMEOUT_OPT
  IPOLICY_SPINDLE_RATIO
  MAC_PREFIX_OPT
  IPOLICY_DISK_TEMPLATES
  ZERO_FREE_SPACE_OPT
  NOSHUTDOWN_OPT
  SHUTDOWN_TIMEOUT_OPT
  ZEROING_TIMEOUT_FIXED_OPT
  UIDPOOL_OPT
  ALLOC_POLICY_OPT
  NEW_NODE_CERT_OPT
  NOVOTING_OPT
  HOTPLUG_OPT
  ERROR_CODES_OPT
  SPECS_CPU_COUNT_OPT
  SPECS_DISK_SIZE_OPT
  SECONDARY_IP_OPT
  CLEANUP_OPT
  NETWORK6_OPT
  REMOVE_INSTANCE_OPT
  NWSYNC_OPT
  RQL_OPT
  IPOLICY_STD_SPECS_OPT
  MAX_TRACK_OPT
  DEFAULT_IALLOCATOR_PARAMS_OPT
  IGNORE_SIZE_OPT
  AUTO_PROMOTE_OPT
  READD_OPT
  NO_REMEMBER_OPT
  SUBMIT_OPTS
  BACKEND_OPT
  RAPI_CERT_OPT
  HV_STATE_OPT
  HOTPLUG_IF_POSSIBLE_OPT
  ABSOLUTE_OPT
  FILESTORE_DIR_OPT
  RUNTIME_MEM_OPT
  ROMAN_OPT
  SEP_OPT
  OSPARAMS_PRIVATE_OPT
  USE_EXTERNAL_MIP_SCRIPT
  GLOBAL_SHARED_FILEDIR_OPT
  MAINTAIN_NODE_HEALTH_OPT
  INPUT_OPT
  TRANSPORT_COMPRESSION_OPT
  NODE_FORCE_JOIN_OPT
  DRY_RUN_OPT
  CAPAB_VM_OPT
  NODE_POWERED_OPT
  NODE_PLACEMENT_OPT
  RESERVED_LVS_OPT
  SINGLE_NODE_OPT
  INSTALL_IMAGE_OPT
  TAG_ADD_OPT
  FORCE_VARIANT_OPT
  PRIMARY_ONLY_OPT
  NIC_PARAMS_OPT
  SPICE_CACERT_OPT
  IGNORE_ERRORS_OPT
  AUTO_REPLACE_OPT
  OSPARAMS_SECRET_OPT
  cli_option
  ENABLED_DISK_TEMPLATES_OPT
  DISK_STATE_OPT
  HVOPTS_OPT
  EARLY_RELEASE_OPT
  VERBOSE_OPT
  CONFIRM_OPT
  ALL_OPT
  COMMON_CREATE_OPTS
  MAINT_BALANCE_THRESHOLD_OPT
  OS_OPT
  NONAMECHECK_OPT
  FAILURE_ONLY_OPT
  ALLOW_FAILOVER_OPT
  SELECT_OS_OPT
  INSTANCE_COMMUNICATION_NETWORK_OPT
  SPECS_NIC_COUNT_OPT
  OS_SIZE_OPT
  IGNORE_OFFLINE_OPT
  ON_PRIMARY_OPT
  SRC_NODE_OPT
  ADD_UIDS_OPT
  SUBMIT_OPT
  MASTER_NETMASK_OPT
  SPICE_CERT_OPT
  NEW_CLUSTER_CERT_OPT
  INTERVAL_OPT
  OSPARAMS_OPT
  IPOLICY_STD_SPECS_STR
  VERIFY_CLUTTER_OPT
  NONICS_OPT
  NODE_PARAMS_OPT
  SSH_KEY_BITS_OPT
  SPLIT_ISPECS_OPTS
  BLK_OS_OPT
  GLOBAL_FILEDIR_OPT
  GATEWAY_OPT
  CAPAB_MASTER_OPT
  MODIFY_ETCHOSTS_OPT
  SPECS_MEM_SIZE_OPT
  TAG_SRC_OPT
  NOSSH_KEYCHECK_OPT
  INSTANCE_POLICY_OPTS
  NET_OPT
  IGNORE_FAILURES_OPT
  IGNORE_HVVERSIONS_OPT
  MASTER_NETDEV_OPT
  USE_REPL_NET_OPT
  NODEGROUP_OPT
  SRC_DIR_OPT
  NOMODIFY_SSH_SETUP_OPT
  SYNC_OPT
  IDENTIFY_DEFAULTS_OPT
  REMOVE_UIDS_OPT
  INSTANCE_COMMUNICATION_OPT
  HYPERVISOR_OPT
  IGNORE_IPOLICY_OPT
  DEBUG_OPT
  MC_OPT
  ONLINE_INST_OPT
  IPOLICY_MEMORY_RATIO
  REBOOT_TYPE_OPT
  NONPLUS1_OPT
  IGNORE_CONSIST_OPT
  NEW_SPICE_CERT_OPT
  MAINT_BALANCE_OPT
  NEW_SSH_KEY_OPT
  FORTHCOMING_OPT
  SPECS_DISK_COUNT_OPT
  NONLIVE_OPT
  ENABLED_USER_SHUTDOWN_OPT
  DISK_OPT
  FORCE_FAILOVER_OPT
  DEBUG_SIMERR_OPT
  SECONDARY_ONLY_OPT
  NEW_PRIMARY_OPT
  ADD_RESERVED_IPS_OPT
  NETWORK_OPT
  TIMEOUT_OPT
  NODE_LIST_OPT
  ON_SECONDARY_OPT
  FILESTORE_DRIVER_OPT
  IGNORE_REMOVE_FAILURES_OPT
  MIGRATION_MODE_OPT
  GATEWAY6_OPT
  NOIPCHECK_OPT
  COMMIT_OPT
  IPOLICY_BOUNDS_SPECS_STR
  SEQUENTIAL_OPT
  ZEROING_TIMEOUT_PER_MIB_OPT
  HELPER_SHUTDOWN_TIMEOUT_OPT
  STATIC_OPT
  COMPRESSION_TOOLS_OPT
  DISK_TEMPLATE_OPT
  NOSTART_OPT
  REASON_OPT
  NO_INSTALL_OPT
  YES_DOIT_OPT
  FORCE_OPT
  PRINT_JOBID_OPT
  SHOWCMD_OPT
  DEFAULT_IALLOCATOR_OPT
  OFFLINE_INST_OPT
  SSH_KEY_TYPE_OPT
  NOCONFLICTSCHECK_OPT
  PRIORITY_OPT
  NEW_CLUSTER_DOMAIN_SECRET_OPT
  COMMON_OPTS
  DRAINED_OPT
  HVLIST_OPT
  LONG_SLEEP_OPT
  REMOVE_RESERVED_IPS_OPT
  IGNORE_SECONDARIES_OPT
  IGNORE_SOFT_ERRORS_OPT
  WFSYNC_OPT
  NORUNTIME_CHGS_OPT
  PRIMARY_IP_VERSION_OPT
  NODEGROUP_OPT_NAME
  CP_SIZE_OPT
  CLUSTER_DOMAIN_SECRET_OPT
  HID_OS_OPT
  SHOW_MACHINE_OPT
  ALLOCATABLE_OPT
  PREALLOC_WIPE_DISKS_OPT
  FORCE_FILTER_OPT
  DIAGNOSE_DATA_COLLECTOR_FILENAME_OPT
  ENABLED_DATA_COLLECTORS_OPT
  COMPRESS_OPT
  MAINT_INTERVAL_OPT
  USEUNITS_OPT
  IPOLICY_VCPU_RATIO
  NOHDR_OPT
  ZEROING_IMAGE_OPT
  OFFLINE_OPT
  EXT_PARAMS_OPT
  NOMODIFY_ETCHOSTS_OPT
  DRBD_HELPER_OPT
  ENABLED_HV_OPT
  NEW_SECONDARY_OPT
  VG_NAME_OPT
  DISK_PARAMS_OPT
  FIELDS_OPT
  GLOBAL_GLUSTER_FILEDIR_OPT
  DST_NODE_OPT
  IALLOCATOR_OPT
  NEW_CONFD_HMAC_KEY_OPT
  HELPER_STARTUP_TIMEOUT_OPT
  INCLUDEDEFAULTS_OPT
  STARTUP_PAUSED_OPT
  DISKIDX_OPT
  GetClient
  OptionParser
  TitledHelpFormatter
  _CHOOSE_BATCH = 25
Maximum batch size for ChooseJob
  TISPECS_GROUP_TYPES = {constants.ISPECS_MIN: constants.VTYPE_I...
  TISPECS_CLUSTER_TYPES = {constants.ISPECS_MIN: constants.VTYPE...
  _QFT_NAMES = {constants.QFT_UNKNOWN: "Unknown", constants.QFT_...
User-friendly names for query2 field types
  ARGS_NONE = []
  ARGS_MANY_INSTANCES = [ArgInstance()]
  ARGS_MANY_NETWORKS = [ArgNetwork()]
  ARGS_MANY_NODES = [ArgNode()]
  ARGS_MANY_GROUPS = [ArgGroup()]
  ARGS_MANY_FILTERS = [ArgFilter()]
  ARGS_ONE_INSTANCE = [ArgInstance(min= 1, max= 1)]
  ARGS_ONE_NETWORK = [ArgNetwork(min= 1, max= 1)]
  ARGS_ONE_NODE = [ArgNode(min= 1, max= 1)]
  ARGS_ONE_GROUP = [ArgGroup(min= 1, max= 1)]
  ARGS_ONE_OS = [ArgOs(min= 1, max= 1)]
  ARGS_ONE_FILTER = [ArgFilter(min= 1, max= 1)]
  _DEFAULT_FORMAT_QUERY = {constants.QFT_TEXT:(str, False), cons...
Default formatting for query results; (callback, align right)
Function Details [hide private]

_ExtractTagsObject(opts, args)

source code 

Extract the tag type object.

Note that this function will modify its args parameter.

_ExtendTags(opts, args)

source code 

Extend the args if a source file has been given.

This function will extend the tags with the contents of the file passed in the 'tags_source' attribute of the opts parameter. A file named '-' will be replaced by stdin.

ListTags(opts, args)

source code 

List the tags on a given object.

This is a generic implementation that knows how to deal with all three cases of tag objects (cluster, node, instance). The opts argument is expected to contain a tag_type field denoting what object type we work on.

AddTags(opts, args)

source code 

Add tags on a given object.

This is a generic implementation that knows how to deal with all three cases of tag objects (cluster, node, instance). The opts argument is expected to contain a tag_type field denoting what object type we work on.

RemoveTags(opts, args)

source code 

Remove tags from a given object.

This is a generic implementation that knows how to deal with all three cases of tag objects (cluster, node, instance). The opts argument is expected to contain a tag_type field denoting what object type we work on.

_ParseArgs(binary, argv, commands, aliases, env_override)

source code 

Parser for the command line arguments.

This function parses the arguments and returns the function which must be executed together with its (modified) arguments.

Parameters:
  • binary - Script name
  • argv - Command line arguments
  • commands - Dictionary containing command definitions
  • aliases - dictionary with command aliases {"alias": "target", ...}
  • env_override - list of env variables allowed for default args
Raises:

_FormatUsage(binary, commands)

source code 

Generates a nice description of all commands.

Parameters:
  • binary - Script name
  • commands - Dictionary containing command definitions

_CheckArguments(cmd, args_def, args)

source code 

Verifies the arguments using the argument definition.

Algorithm:

  1. Abort with error if values specified by user but none expected.
  1. For each argument in definition
    1. Keep running count of minimum number of values (min_count)
    1. Keep running count of maximum number of values (max_count)
    1. If it has an unlimited number of values
      1. Abort with error if it's not the last argument in the definition
  1. If last argument has limited number of values
    1. Abort with error if number of values doesn't match or is too large
  1. Abort with error if user didn't pass enough values (min_count)

CalculateOSNames(os_name, os_variants)

source code 

Calculates all the names an OS can be called, according to its variants.

Parameters:
  • os_name (string) - base name of the os
  • os_variants (list or None) - list of supported variants
Returns: list
list of valid names

ParseFields(selected, default)

source code 

Parses the values of "--field"-like options.

Parameters:
  • selected (string or None) - User-selected options
  • default (list) - Default fields

UsesRPC(fn)

source code 

RPC-wrapper decorator.

When applied to a function, it runs it with the RPC system initialized, and it shutsdown the system afterwards. This means the function must be called without RPC being initialized.

AskUser(text, choices=None)

source code 

Ask the user a question.

Parameters:
  • text - the question to ask
  • choices - list with elements tuples (input_char, return_value, description); if not given, it will default to: [('y', True, 'Perform the operation'), ('n', False, 'Do no do the operation')]; note that the '?' char is reserved for help
Returns:
one of the return values from the choices list; if input is not possible (i.e. not running with a tty, we return the last entry from the list

SendJob(ops, cl=None)

source code 

Function to submit an opcode without waiting for the results.

Parameters:
  • ops (list) - list of opcodes
  • cl (luxi.Client) - the luxi client to use for communicating with the master; if None, a new client will be created

GenericPollJob(job_id, cbs, report_cbs)

source code 

Generic job-polling function.

Parameters:
Returns:
the opresult of the job
Raises:

PollJob(job_id, cl=None, feedback_fn=None, reporter=None)

source code 

Function to poll for the result of a job.

Parameters:
  • job_id (job identified) - the job to poll for results
  • cl (luxi.Client) - the luxi client to use for communicating with the master; if None, a new client will be created

SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None)

source code 

Legacy function to submit an opcode.

This is just a simple wrapper over the construction of the processor instance. It should be extended to better handle feedback and interaction functions.

SubmitOrSend(op, opts, cl=None, feedback_fn=None)

source code 

Wrapper around SubmitOpCode or SendJob.

This function will decide, based on the 'opts' parameter, whether to submit and wait for the result of the opcode (and return it), or whether to just send the job and print its identifier. It is used in order to simplify the implementation of the '--submit' option.

It will also process the opcodes if we're sending the via SendJob (otherwise SubmitOpCode does it).

_InitReasonTrail(op, opts)

source code 

Builds the first part of the reason trail

Builds the initial part of the reason trail, adding the user provided reason (if it exists) and the name of the command starting the operation.

Parameters:
  • op - the opcode the reason trail will be added to
  • opts - the command line options selected by the user

SetGenericOpcodeOpts(opcode_list, options)

source code 

Processor for generic options.

This function updates the given opcodes based on generic command line options (like debug, dry-run, etc.).

Parameters:
  • opcode_list - list of opcodes
  • options - command line options or None
Returns:
None (in-place modification)

FormatError(err)

source code 

Return a formatted error message for a given error.

This function takes an exception instance and returns a tuple consisting of two values: first, the recommended exit code, and second, a string describing the error message (not newline-terminated).

GenericMain(commands, override=None, aliases=None, env_override=frozenset())

source code 

Generic main function for all the gnt-* commands.

Parameters:
  • commands - a dictionary with a special structure, see the design doc for command line handling.
  • override - if not None, we expect a dictionary with keys that will override command line options; this can be used to pass options from the scripts to generic functions
  • aliases - dictionary with command aliases {'alias': 'target, ...}
  • env_override - list of environment names which are allowed to submit default args for commands

GenericInstanceCreate(mode, opts, args)

source code 

Add an instance to the cluster via either creation or import.

Parameters:
  • mode - constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
  • opts - the command line options selected by the user
  • args (list) - should contain only one element, the new instance name
Returns: int
the desired exit code

RunWhileDaemonsStopped(feedback_fn, exclude_daemons, fn, *args, **kwargs)

source code 

Calls a function while all cluster daemons are stopped.

Parameters:
  • feedback_fn (callable) - Feedback function
  • exclude_daemons (list of string) - list of daemons that stopped, but immediately restarted on the master to be available when calling 'fn'. If None, all daemons will be stopped and none will be started before calling 'fn'.
  • fn (callable) - Function to be called when daemons are stopped

RunWhileClusterStopped(feedback_fn, fn, *args)

source code 

Calls a function while all cluster daemons are stopped.

Parameters:
  • feedback_fn (callable) - Feedback function
  • fn (callable) - Function to be called when daemons are stopped

GenerateTable(headers, fields, separator, data, numfields=None, unitfields=None, units=None)

source code 

Prints a table with headers and different fields.

Parameters:
  • headers (dict) - dictionary mapping field names to headers for the table
  • fields (list) - the field names corresponding to each row in the data field
  • separator - the separator to be used; if this is None, the default 'smart' algorithm is used which computes optimal field width, otherwise just the separator is used between each field
  • data (list) - a list of lists, each sublist being one row to be output
  • numfields (list) - a list with the fields that hold numeric values and thus should be right-aligned
  • unitfields (list) - a list with the fields that hold numeric values that should be formatted with the units field
  • units (string or None) - the units we should use for formatting, or None for automatic choice (human-readable for non-separator usage, otherwise megabytes); this is a one-letter string

_GetColumnFormatter(fdef, override, unit)

source code 

Returns formatting function for a field.

Parameters:
Returns: tuple; (callable, bool)
Returns the function to format a value (takes one parameter) and a boolean for aligning the value on the right-hand side

FormatResultError(status, verbose)

source code 

Formats result status other than constants.RS_NORMAL.

Parameters:
  • status - The result status
  • verbose (boolean) - Whether to return the verbose text
Returns:
Text of result status

FormatQueryResult(result, unit=None, format_override=None, separator=None, header=False, verbose=False)

source code 

Formats data in objects.QueryResponse.

Parameters:
  • result (objects.QueryResponse) - result of query operation
  • unit (string) - Unit used for formatting fields of type constants.QFT_UNIT, see utils.text.FormatUnit
  • format_override (dict) - Dictionary for overriding field formatting functions, indexed by field name, contents like _DEFAULT_FORMAT_QUERY
  • separator (string or None) - String used to separate fields
  • header (bool) - Whether to output header row
  • verbose (boolean) - whether to use verbose field descriptions or not

_GetUnknownFields(fdefs)

source code 

Returns list of unknown fields included in fdefs.

Parameters:

_WarnUnknownFields(fdefs)

source code 

Prints a warning to stderr if a query included unknown fields.

Parameters:

GenericList(resource, fields, names, unit, separator, header, cl=None, format_override=None, verbose=False, force_filter=False, namefield=None, qfilter=None, isnumeric=False)

source code 

Generic implementation for listing all items of a resource.

Parameters:
  • resource - One of constants.QR_VIA_LUXI
  • fields (list of strings) - List of fields to query for
  • names (list of strings) - Names of items to query for
  • unit (string or None) - Unit used for formatting fields of type constants.QFT_UNIT or None for automatic choice (human-readable for non-separator usage, otherwise megabytes); this is a one-letter string
  • separator (string or None) - String used to separate fields
  • header (bool) - Whether to show header row
  • force_filter (bool) - Whether to always treat names as filter
  • format_override (dict) - Dictionary for overriding field formatting functions, indexed by field name, contents like _DEFAULT_FORMAT_QUERY
  • verbose (boolean) - whether to use verbose field descriptions or not
  • namefield (string) - Name of field to use for simple filters (see qlang.MakeFilter for details)
  • qfilter (list or None) - Query filter (in addition to names)
  • isnumeric - bool
  • isnumeric - Whether the namefield's type is numeric, and therefore any simple filters built by namefield should use integer values to reflect that

_FieldDescValues(fdef)

source code 

Helper function for GenericListFields to get query field description.

Parameters:
Returns: list

GenericListFields(resource, fields, separator, header, cl=None)

source code 

Generic implementation for listing fields for a resource.

Parameters:
  • resource - One of constants.QR_VIA_LUXI
  • fields (list of strings) - List of fields to query for
  • separator (string or None) - String used to separate fields
  • header (bool) - Whether to show header row

FormatTable(rows, columns, header, separator)

source code 

Formats data as a table.

Parameters:
  • rows (list of lists) - Row data, one list per row
  • columns (list of TableColumn) - Column descriptions
  • header (bool) - Whether to show header row
  • separator (string or None) - String used to separate columns

FormatTimestamp(ts)

source code 

Formats a given timestamp.

Parameters:
  • ts (timestamp) - a timeval-type timestamp, a tuple of seconds and microseconds
Returns: string
a string with the formatted timestamp

ParseTimespec(value)

source code 

Parse a time specification.

The following suffixed will be recognized:

  • s: seconds
  • m: minutes
  • h: hours
  • d: day
  • w: weeks

Without any suffix, the value will be taken to be in seconds.

GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False, filter_master=False, nodegroup=None)

source code 

Returns the names of online nodes.

This function will also log a warning on stderr with the names of the online nodes.

Parameters:
  • nodes - if not empty, use only this subset of nodes (minus the offline ones)
  • cl - if not None, luxi client to use
  • nowarn (boolean) - by default, this function will output a note with the offline nodes that are skipped; if this parameter is True the note is not displayed
  • secondary_ips (boolean) - if True, return the secondary IPs instead of the names, useful for doing network traffic over the replication interface (if any)
  • filter_master (boolean) - if True, do not return the master node in the list (useful in coordination with secondary_ips where we cannot check our node name against the list)
  • nodegroup (string) - If set, only return nodes in this node group

GetNodesSshPorts(nodes, cl)

source code 

Retrieves SSH ports of given nodes.

Parameters:
  • nodes (a list of strings) - the names of nodes
  • cl (ganeti.luxi.Client) - a client to use for the query
Returns: a list of tuples
the list of SSH ports corresponding to the nodes

GetNodeUUIDs(nodes, cl)

source code 

Retrieves the UUIDs of given nodes.

Parameters:
  • nodes (a list of string) - the names of nodes
  • cl (ganeti.luxi.Client) - a client to use for the query
Returns: a list of tuples
the list of UUIDs corresponding to the nodes

_ToStream(stream, txt, *args)

source code 

Write a message to a stream, bypassing the logging system

Parameters:
  • stream (file object) - the file to which we should write
  • txt (str) - the message

ToStdout(txt, *args)

source code 

Write a message to stdout only, bypassing the logging system

This is just a wrapper over _ToStream.

Parameters:
  • txt (str) - the message

ToStderr(txt, *args)

source code 

Write a message to stderr only, bypassing the logging system

This is just a wrapper over _ToStream.

Parameters:
  • txt (str) - the message

FormatParamsDictInfo(param_dict, actual, roman=False)

source code 

Formats a parameter dictionary.

Parameters:
  • param_dict (dict) - the own parameters
  • actual (dict) - the current parameter set (including defaults)
Returns: dict
dictionary where the value of each parameter is either a fully formatted string or a dictionary containing formatted strings

FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster, roman=False)

source code 

Formats an instance policy.

Parameters:
  • custom_ipolicy (dict) - own policy
  • eff_ipolicy (dict) - effective policy (including defaults); ignored for cluster
  • iscluster (bool) - the policy is at cluster level
  • roman (bool) - whether to print the values in roman numerals
Returns: list of pairs
formatted data, suitable for PrintGenericInfo

PrintIPolicyCommand(buf, ipolicy, isgroup)

source code 

Print the command option used to generate the given instance policy.

Currently only the parts dealing with specs are supported.

Parameters:
  • buf (StringIO) - stream to write into
  • ipolicy (dict) - instance policy
  • isgroup (bool) - whether the policy is at group level

ConfirmOperation(names, list_type, text, extra="")

source code 

Ask the user to confirm an operation on a list of list_type.

This function is used to request confirmation for doing an operation on a given list of list_type.

Parameters:
  • names (list) - the list of names that we display when we ask for confirmation
  • list_type (str) - Human readable name for elements in the list (e.g. nodes)
  • text (str) - the operation that the user should confirm
Returns: boolean
True or False depending on user's confirmation.

CreateIPolicyFromOpts(ispecs_mem_size=None, ispecs_cpu_count=None, ispecs_disk_count=None, ispecs_disk_size=None, ispecs_nic_count=None, minmax_ispecs=None, std_ispecs=None, ipolicy_disk_templates=None, ipolicy_vcpu_ratio=None, ipolicy_spindle_ratio=None, ipolicy_memory_ratio=None, group_ipolicy=False, allowed_values=None, fill_all=False)

source code 

Creation of instance policy based on command line options.

Parameters:
  • fill_all - whether for cluster policies we should ensure that all values are filled

_GetAlignmentMapping(data)

source code 

Returns info about alignment if present in an encoded ordered dictionary.

Parameters:
Returns: dict of any to int
The dictionary mapping alignment groups to the maximum length of the dictionary key found in the group.

_SerializeGenericInfo(buf, data, level, afterkey=False)

source code 

Formatting core of PrintGenericInfo.

Parameters:
  • buf - (string) stream to accumulate the result into
  • data - data to format
  • level (int) - depth in the data hierarchy, used for indenting
  • afterkey (bool) - True when we are in the middle of a line after a key (used to properly add newlines or indentation)

PrintGenericInfo(data)

source code 

Print information formatted according to the hierarchy.

The output is a valid YAML string.

Parameters:
  • data - the data to print. It's a hierarchical structure whose elements can be:
    • dictionaries, where keys are strings and values are of any of the types listed here
    • lists of tuples (key, value) or (key, value, alignment_group), where key is a string, value is of any of the types listed here, and alignment_group can be any hashable value; it's a way to encode ordered dictionaries; any entries sharing the same alignment group are aligned by appending whitespace before the value as needed
    • lists of any of the types listed here
    • strings

Variables Details [hide private]

TISPECS_GROUP_TYPES

Value:
{constants.ISPECS_MIN: constants.VTYPE_INT, constants.ISPECS_MAX: cons\
tants.VTYPE_INT,}

TISPECS_CLUSTER_TYPES

Value:
{constants.ISPECS_MIN: constants.VTYPE_INT, constants.ISPECS_MAX: cons\
tants.VTYPE_INT, constants.ISPECS_STD: constants.VTYPE_INT,}

_QFT_NAMES

User-friendly names for query2 field types

Value:
{constants.QFT_UNKNOWN: "Unknown", constants.QFT_TEXT: "Text", constan\
ts.QFT_BOOL: "Boolean", constants.QFT_NUMBER: "Number", constants.QFT_\
NUMBER_FLOAT: "Floating-point number", constants.QFT_UNIT: "Storage si\
ze", constants.QFT_TIMESTAMP: "Timestamp", constants.QFT_OTHER: "Custo\
m",}

_DEFAULT_FORMAT_QUERY

Default formatting for query results; (callback, align right)

Value:
{constants.QFT_TEXT:(str, False), constants.QFT_BOOL:(_FormatBool, Fal\
se), constants.QFT_NUMBER:(str, True), constants.QFT_NUMBER_FLOAT:(str\
, True), constants.QFT_TIMESTAMP:(utils.FormatTime, False), constants.\
QFT_OTHER:(str, False), constants.QFT_UNKNOWN:(str, False),}