rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
print qa_utils.FormatError("Can rename instance, 'rename' entry is" | print qa_utils.FormatError("Can not rename instance, 'rename' entry is" | def RunCommonInstanceTests(instance): """Runs a few tests that are common to all disk types. """ if qa_config.TestEnabled('instance-shutdown'): RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('instance-list'): RunTest(qa_instance.TestInstanceList) if qa_config.TestEnabled('instance-info'): RunTest(qa_instance.TestInstanceInfo, instance) if qa_config.TestEnabled('instance-modify'): RunTest(qa_instance.TestInstanceModify, instance) if qa_rapi.Enabled(): RunTest(qa_rapi.TestRapiInstanceModify, instance) if qa_config.TestEnabled('instance-console'): RunTest(qa_instance.TestInstanceConsole, instance) if qa_config.TestEnabled('instance-reinstall'): RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceReinstall, instance) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('instance-reboot'): RunTest(qa_instance.TestInstanceReboot, instance) if qa_config.TestEnabled('instance-rename'): rename_target = qa_config.get("rename", None) if rename_target is None: print qa_utils.FormatError("Can rename instance, 'rename' entry is" " missing from configuration") else: RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceRename, instance, rename_target) if qa_rapi.Enabled(): RunTest(qa_rapi.TestRapiInstanceRename, instance, rename_target) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('tags'): RunTest(qa_tags.TestInstanceTags, instance) if qa_rapi.Enabled(): RunTest(qa_rapi.TestInstance, instance) |
if test: | if res.offline: | def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result): """Analyze the post-hooks' result |
_ErrorIf(test, self.ENODETIME, node, "Node returned invalid time") | _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time") | def Exec(self, feedback_fn): """Verify integrity of cluster, performing various test on nodes. |
self.op.master_candidate == True): | self.op.master_candidate == True and not node.master_candidate): | def CheckPrereq(self): """Check prerequisites. |
if remaining_time is not None and remaining_time < 0.0: break | if remaining_time is not None: if remaining_time < 0.0: break remaining_time *= 1000 | def __call__(self, timeout): """Wait for something to happen on the pipe. |
result = self._poller.poll(1000 * remaining_time) | result = self._poller.poll(remaining_time) | def __call__(self, timeout): """Wait for something to happen on the pipe. |
@type job: L{_QueuedOpCode} @param job: Opcode object | @type op: L{_QueuedOpCode} @param op: Opcode object | def _MarkWaitlock(job, op): """Marks an opcode as waiting for locks. |
_DRY_RUN_OPT = cli_option("--dry-run", default=False, action="store_true", help=("Do not execute the operation, just run the" " check steps and verify it it could be" " executed")) | DRY_RUN_OPT = cli_option("--dry-run", default=False, action="store_true", help=("Do not execute the operation, just run the" " check steps and verify it it could be" " executed")) | def check_bool(option, opt, value): # pylint: disable-msg=W0613 """Custom parser for yes/no options. This will store the parsed value as either True or False. """ value = value.lower() if value == constants.VALUE_FALSE or value == "no": return False elif value == constants.VALUE_TRUE or value == "yes": return True else: raise errors.ParameterError("Invalid boolean value '%s'" % value) |
parser = OptionParser(option_list=parser_opts + [_DRY_RUN_OPT, DEBUG_OPT], | parser = OptionParser(option_list=parser_opts + [DEBUG_OPT], | def _ParseArgs(argv, commands, aliases): """Parser for the command line arguments. This function parses the arguments and returns the function which must be executed together with its (modified) arguments. @param argv: the command line @param commands: dictionary with special contents, see the design doc for cmdline handling @param aliases: dictionary with command aliases {'alias': 'target, ...} """ if len(argv) == 0: binary = "<command>" else: binary = argv[0].split("/")[-1] if len(argv) > 1 and argv[1] == "--version": ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION, constants.RELEASE_VERSION) # Quit right away. That way we don't have to care about this special # argument. optparse.py does it the same. sys.exit(0) if len(argv) < 2 or not (argv[1] in commands or argv[1] in aliases): # let's do a nice thing sortedcmds = commands.keys() sortedcmds.sort() ToStdout("Usage: %s {command} [options...] [argument...]", binary) ToStdout("%s <command> --help to see details, or man %s", binary, binary) ToStdout("") # compute the max line length for cmd + usage mlen = max([len(" %s" % cmd) for cmd in commands]) mlen = min(60, mlen) # should not get here... # and format a nice command list ToStdout("Commands:") for cmd in sortedcmds: cmdstr = " %s" % (cmd,) help_text = commands[cmd][4] help_lines = textwrap.wrap(help_text, 79 - 3 - mlen) ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0)) for line in help_lines: ToStdout("%-*s %s", mlen, "", line) ToStdout("") return None, None, None # get command, unalias it, and look it up in commands cmd = argv.pop(1) if cmd in aliases: if cmd in commands: raise errors.ProgrammerError("Alias '%s' overrides an existing" " command" % cmd) if aliases[cmd] not in commands: raise errors.ProgrammerError("Alias '%s' maps to non-existing" " command '%s'" % (cmd, aliases[cmd])) cmd = aliases[cmd] func, args_def, parser_opts, usage, description = commands[cmd] parser = OptionParser(option_list=parser_opts + [_DRY_RUN_OPT, DEBUG_OPT], description=description, formatter=TitledHelpFormatter(), usage="%%prog %s %s" % (cmd, usage)) parser.disable_interspersed_args() options, args = parser.parse_args() if not _CheckArguments(cmd, args_def, args): return None, None, None return func, options, args |
op.dry_run = options.dry_run | if hasattr(options, "dry_run"): op.dry_run = options.dry_run | def SetGenericOpcodeOpts(opcode_list, options): """Processor for generic options. This function updates the given opcodes based on generic command line options (like debug, dry-run, etc.). @param opcode_list: list of opcodes @param options: command line options or None @return: None (in-place modification) """ if not options: return for op in opcode_list: op.dry_run = options.dry_run op.debug_level = options.debug |
for instlist in [node_image[nname].pinst, node_image[nname].sinst] for inst in instlist | for inst in node_instances | def _CollectDiskInfo(self, nodelist, node_image, instanceinfo): """Gets per-disk status information for all instances. |
config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge) | for param in constants.NICS_PARAMETER_TYPES: config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param), '%s' % nic.nicparams.get(param, None)) | def FinalizeExport(instance, snap_disks): """Write out the export configuration information. @type instance: L{objects.Instance} @param instance: the instance which we export, used for saving configuration @type snap_disks: list of L{objects.Disk} @param snap_disks: list of snapshot block devices, which will be used to get the actual name of the dump file @rtype: None """ destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new") finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name) config = objects.SerializableConfigParser() config.add_section(constants.INISECT_EXP) config.set(constants.INISECT_EXP, 'version', '0') config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time())) config.set(constants.INISECT_EXP, 'source', instance.primary_node) config.set(constants.INISECT_EXP, 'os', instance.os) config.set(constants.INISECT_EXP, 'compression', 'gzip') config.add_section(constants.INISECT_INS) config.set(constants.INISECT_INS, 'name', instance.name) config.set(constants.INISECT_INS, 'memory', '%d' % instance.beparams[constants.BE_MEMORY]) config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.beparams[constants.BE_VCPUS]) config.set(constants.INISECT_INS, 'disk_template', instance.disk_template) nic_total = 0 for nic_count, nic in enumerate(instance.nics): nic_total += 1 config.set(constants.INISECT_INS, 'nic%d_mac' % nic_count, '%s' % nic.mac) config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip) config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge) # TODO: redundant: on load can read nics until it doesn't exist config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total) disk_total = 0 for disk_count, disk in enumerate(snap_disks): if disk: disk_total += 1 config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count, ('%s' % disk.iv_name)) config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count, ('%s' % disk.physical_id[1])) config.set(constants.INISECT_INS, 'disk%d_size' % disk_count, ('%d' % disk.size)) config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total) utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE), data=config.Dumps()) shutil.rmtree(finaldestdir, ignore_errors=True) shutil.move(destdir, finaldestdir) |
result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST]) | try: val = GetVolumeList(what[constants.NV_LVLIST]) except RPCFail, err: val = str(err) result[constants.NV_LVLIST] = val | def VerifyNode(what, cluster_name): """Verify the status of the local node. Based on the input L{what} parameter, various checks are done on the local node. If the I{filelist} key is present, this list of files is checksummed and the file/checksum pairs are returned. If the I{nodelist} key is present, we check that we have connectivity via ssh with the target nodes (and check the hostname report). If the I{node-net-test} key is present, we check that we have connectivity to the given nodes via both primary IP and, if applicable, secondary IPs. @type what: C{dict} @param what: a dictionary of things to check: - filelist: list of files for which to compute checksums - nodelist: list of nodes we should check ssh communication with - node-net-test: list of nodes we should check node daemon port connectivity with - hypervisor: list with hypervisors to run the verify for @rtype: dict @return: a dictionary with the same keys as the input dict, and values representing the result of the checks """ result = {} if constants.NV_HYPERVISOR in what: result[constants.NV_HYPERVISOR] = tmp = {} for hv_name in what[constants.NV_HYPERVISOR]: try: val = hypervisor.GetHypervisor(hv_name).Verify() except errors.HypervisorError, err: val = "Error while checking hypervisor: %s" % str(err) tmp[hv_name] = val if constants.NV_FILELIST in what: result[constants.NV_FILELIST] = utils.FingerprintFiles( what[constants.NV_FILELIST]) if constants.NV_NODELIST in what: result[constants.NV_NODELIST] = tmp = {} random.shuffle(what[constants.NV_NODELIST]) for node in what[constants.NV_NODELIST]: success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node) if not success: tmp[node] = message if constants.NV_NODENETTEST in what: result[constants.NV_NODENETTEST] = tmp = {} my_name = utils.HostInfo().name my_pip = my_sip = None for name, pip, sip in what[constants.NV_NODENETTEST]: if name == my_name: my_pip = pip my_sip = sip break if not my_pip: tmp[my_name] = ("Can't find my own primary/secondary IP" " in the node list") else: port = utils.GetDaemonPort(constants.NODED) for name, pip, sip in what[constants.NV_NODENETTEST]: fail = [] if not utils.TcpPing(pip, port, source=my_pip): fail.append("primary") if sip != pip: if not utils.TcpPing(sip, port, source=my_sip): fail.append("secondary") if fail: tmp[name] = ("failure using the %s interface(s)" % " and ".join(fail)) if constants.NV_LVLIST in what: result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST]) if constants.NV_INSTANCELIST in what: # GetInstanceList can fail try: val = GetInstanceList(what[constants.NV_INSTANCELIST]) except RPCFail, err: val = str(err) result[constants.NV_INSTANCELIST] = val if constants.NV_VGLIST in what: result[constants.NV_VGLIST] = utils.ListVolumeGroups() if constants.NV_PVLIST in what: result[constants.NV_PVLIST] = \ bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST], filter_allocatable=False) if constants.NV_VERSION in what: result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION, constants.RELEASE_VERSION) if constants.NV_HVINFO in what: hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO]) result[constants.NV_HVINFO] = hyper.GetNodeInfo() if constants.NV_DRBDLIST in what: try: used_minors = bdev.DRBD8.GetUsedDevs().keys() except errors.BlockDeviceError, err: logging.warning("Can't get used minors list", exc_info=True) used_minors = str(err) result[constants.NV_DRBDLIST] = used_minors if constants.NV_NODESETUP in what: result[constants.NV_NODESETUP] = tmpr = [] if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"): tmpr.append("The sysfs filesytem doesn't seem to be mounted" " under /sys, missing required directories /sys/block" " and /sys/class/net") if (not os.path.isdir("/proc/sys") or not os.path.isfile("/proc/sysrq-trigger")): tmpr.append("The procfs filesystem doesn't seem to be mounted" " under /proc, missing required directory /proc/sys and" " the file /proc/sysrq-trigger") if constants.NV_TIME in what: result[constants.NV_TIME] = utils.SplitTime(time.time()) return result |
os.chdir("/") os.umask(077) os.setsid() | SetupDaemonEnv() | def _StartDaemonChild(errpipe_read, errpipe_write, pidpipe_read, pidpipe_write, args, env, cwd, output, fd_output, pidfile): """Child process for starting daemon. """ try: # Close parent's side _CloseFDNoErr(errpipe_read) _CloseFDNoErr(pidpipe_read) # First child process os.chdir("/") os.umask(077) os.setsid() # And fork for the second time pid = os.fork() if pid != 0: # Exit first child process os._exit(0) # pylint: disable-msg=W0212 # Make sure pipe is closed on execv* (and thereby notifies original process) SetCloseOnExecFlag(errpipe_write, True) # List of file descriptors to be left open noclose_fds = [errpipe_write] # Open PID file if pidfile: try: # TODO: Atomic replace with another locked file instead of writing into # it after creating fd_pidfile = os.open(pidfile, os.O_WRONLY | os.O_CREAT, 0600) # Lock the PID file (and fail if not possible to do so). Any code # wanting to send a signal to the daemon should try to lock the PID # file before reading it. If acquiring the lock succeeds, the daemon is # no longer running and the signal should not be sent. LockFile(fd_pidfile) os.write(fd_pidfile, "%d\n" % os.getpid()) except Exception, err: raise Exception("Creating and locking PID file failed: %s" % err) # Keeping the file open to hold the lock noclose_fds.append(fd_pidfile) SetCloseOnExecFlag(fd_pidfile, False) else: fd_pidfile = None # Open /dev/null fd_devnull = os.open(os.devnull, os.O_RDWR) assert not output or (bool(output) ^ (fd_output is not None)) if fd_output is not None: pass elif output: # Open output file try: # TODO: Implement flag to set append=yes/no fd_output = os.open(output, os.O_WRONLY | os.O_CREAT, 0600) except EnvironmentError, err: raise Exception("Opening output file failed: %s" % err) else: fd_output = fd_devnull # Redirect standard I/O os.dup2(fd_devnull, 0) os.dup2(fd_output, 1) os.dup2(fd_output, 2) # Send daemon PID to parent RetryOnSignal(os.write, pidpipe_write, str(os.getpid())) # Close all file descriptors except stdio and error message pipe CloseFDs(noclose_fds=noclose_fds) # Change working directory os.chdir(cwd) if env is None: os.execvp(args[0], args) else: os.execvpe(args[0], args, env) except: # pylint: disable-msg=W0702 try: # Report errors to original process buf = str(sys.exc_info()[1]) RetryOnSignal(os.write, errpipe_write, buf) except: # pylint: disable-msg=W0702 # Ignore errors in error handling pass os._exit(1) # pylint: disable-msg=W0212 |
UMASK = 077 WORKDIR = "/" | def Daemonize(logfile): """Daemonize the current process. This detaches the current process from the controlling terminal and runs it in the background as a daemon. @type logfile: str @param logfile: the logfile to which we should redirect stdout/stderr @rtype: int @return: the value zero """ # pylint: disable-msg=W0212 # yes, we really want os._exit UMASK = 077 WORKDIR = "/" # this might fail pid = os.fork() if (pid == 0): # The first child. os.setsid() # this might fail pid = os.fork() # Fork a second child. if (pid == 0): # The second child. os.chdir(WORKDIR) os.umask(UMASK) else: # exit() or _exit()? See below. os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. for fd in range(3): _CloseFDNoErr(fd) i = os.open("/dev/null", os.O_RDONLY) # stdin assert i == 0, "Can't close/reopen stdin" i = os.open(logfile, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0600) # stdout assert i == 1, "Can't close/reopen stdout" # Duplicate standard output to standard error. os.dup2(1, 2) return 0 | |
os.setsid() | SetupDaemonEnv() | def Daemonize(logfile): """Daemonize the current process. This detaches the current process from the controlling terminal and runs it in the background as a daemon. @type logfile: str @param logfile: the logfile to which we should redirect stdout/stderr @rtype: int @return: the value zero """ # pylint: disable-msg=W0212 # yes, we really want os._exit UMASK = 077 WORKDIR = "/" # this might fail pid = os.fork() if (pid == 0): # The first child. os.setsid() # this might fail pid = os.fork() # Fork a second child. if (pid == 0): # The second child. os.chdir(WORKDIR) os.umask(UMASK) else: # exit() or _exit()? See below. os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. for fd in range(3): _CloseFDNoErr(fd) i = os.open("/dev/null", os.O_RDONLY) # stdin assert i == 0, "Can't close/reopen stdin" i = os.open(logfile, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0600) # stdout assert i == 1, "Can't close/reopen stdout" # Duplicate standard output to standard error. os.dup2(1, 2) return 0 |
os.chdir(WORKDIR) os.umask(UMASK) | pass | def Daemonize(logfile): """Daemonize the current process. This detaches the current process from the controlling terminal and runs it in the background as a daemon. @type logfile: str @param logfile: the logfile to which we should redirect stdout/stderr @rtype: int @return: the value zero """ # pylint: disable-msg=W0212 # yes, we really want os._exit UMASK = 077 WORKDIR = "/" # this might fail pid = os.fork() if (pid == 0): # The first child. os.setsid() # this might fail pid = os.fork() # Fork a second child. if (pid == 0): # The second child. os.chdir(WORKDIR) os.umask(UMASK) else: # exit() or _exit()? See below. os._exit(0) # Exit parent (the first child) of the second child. else: os._exit(0) # Exit parent of the first child. for fd in range(3): _CloseFDNoErr(fd) i = os.open("/dev/null", os.O_RDONLY) # stdin assert i == 0, "Can't close/reopen stdin" i = os.open(logfile, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0600) # stdout assert i == 1, "Can't close/reopen stdout" # Duplicate standard output to standard error. os.dup2(1, 2) return 0 |
handlers.append(urllib2.HTTPBasicAuthHandler(pwmgr)) | self._httpauthhandler = urllib2.HTTPBasicAuthHandler(pwmgr) handlers.append(self._httpauthhandler) | def __init__(self, host, port=GANETI_RAPI_PORT, username=None, password=None, config_ssl_verification=None, ignore_proxy=False, logger=logging): """Constructor. |
dir_name = "%s/%s" % (self._ROOT_DIR, instance_name) | dir_name = self._InstanceDir(instance_name) | def GetInstanceInfo(self, instance_name): """Get instance properties. |
root_dir = "%s/%s" % (self._ROOT_DIR, instance.name) | root_dir = self._InstanceDir(instance.name) | def StartInstance(self, instance, block_devices): """Start an instance. |
root_dir = "%s/%s" % (self._ROOT_DIR, instance.name) | root_dir = self._InstanceDir(instance.name) | def StopInstance(self, instance, force=False, retry=False): """Stop an instance. |
root_dir = "%s/%s" % (cls._ROOT_DIR, instance.name) | root_dir = cls._InstanceDir(instance.name) | def GetShellCommandForConsole(cls, instance, hvparams, beparams): """Return a command for connecting to the console of an instance. |
all_nodes.remove(self.op.node_name) | try: all_nodes.remove(self.op.node_name) except ValueError: logging.warning("Node %s which is about to be removed not found" " in the all nodes list", self.op.node_name) | def BuildHooksEnv(self): """Build hooks env. |
pidfile, _, alive = self._InstancePidAlive(instance.name) | def _ExecuteKVMRuntime(self, instance, kvm_runtime, incoming=None): """Execute a KVM cmd, after completing it with some last minute data | |
if alive: raise errors.HypervisorError("Failed to start instance %s: %s" % (instance.name, "already running")) | name = instance.name self._CheckDown(name) | def _ExecuteKVMRuntime(self, instance, kvm_runtime, incoming=None): """Execute a KVM cmd, after completing it with some last minute data |
(instance.name, result.fail_reason, result.output)) if not utils.IsProcessAlive(utils.ReadPidFile(pidfile)): raise errors.HypervisorError("Failed to start instance %s" % (instance.name)) | (name, result.fail_reason, result.output)) if not self._InstancePidAlive(name)[2]: raise errors.HypervisorError("Failed to start instance %s" % name) | def _ExecuteKVMRuntime(self, instance, kvm_runtime, incoming=None): """Execute a KVM cmd, after completing it with some last minute data |
pidfile, pid, alive = self._InstancePidAlive(instance.name) if alive: raise errors.HypervisorError("Failed to start instance %s: %s" % (instance.name, "already running")) | self._CheckDown(instance.name) | def StartInstance(self, instance, block_devices): """Start an instance. |
@type shared: int | @type shared: integer (0/1) used as a boolean | def acquire(self, shared=0, timeout=None, test_notify=None): """Acquire a shared lock. |
@param level: the level at which the locks shall be acquired; it must be a member of LEVELS. | @type level: member of locking.LEVELS @param level: the level at which the locks shall be acquired @type names: list of strings (or string) | def acquire(self, level, names, timeout=None, shared=0): """Acquire a set of resource locks, at the same level. |
@param level: the level at which the locks shall be released; it must be a member of LEVELS | @type level: member of locking.LEVELS @param level: the level at which the locks shall be released @type names: list of strings, or None | def release(self, level, names=None): """Release a set of resource locks, at the same level. |
@param level: the level at which the locks shall be added; it must be a member of LEVELS_MOD. | @type level: member of locking.LEVELS_MOD @param level: the level at which the locks shall be added @type names: list of strings | def add(self, level, names, acquired=0, shared=0): """Add locks at the specified level. |
@param level: the level at which the locks shall be removed; it must be a member of LEVELS_MOD | @type level: member of locking.LEVELS_MOD @param level: the level at which the locks shall be removed @type names: list of strings | def remove(self, level, names): """Remove locks from the specified level. |
if idx == len(fields) - 1 and not numfields.Matches(name): mlens[idx] = 0 else: mlens[idx] = max(mlens[idx], len(hdr)) | mlens[idx] = max(mlens[idx], len(hdr)) | def GenerateTable(headers, fields, separator, data, numfields=None, unitfields=None, units=None): """Prints a table with headers and different fields. @type headers: dict @param headers: dictionary mapping field names to headers for the table @type fields: list @param fields: the field names corresponding to each row in the data field @param 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 @type data: list @param data: a list of lists, each sublist being one row to be output @type numfields: list @param numfields: a list with the fields that hold numeric values and thus should be right-aligned @type unitfields: list @param unitfields: a list with the fields that hold numeric values that should be formatted with the units field @type units: string or None @param units: 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 """ if units is None: if separator: units = "m" else: units = "h" if numfields is None: numfields = [] if unitfields is None: unitfields = [] numfields = utils.FieldSet(*numfields) # pylint: disable-msg=W0142 unitfields = utils.FieldSet(*unitfields) # pylint: disable-msg=W0142 format_fields = [] for field in fields: if headers and field not in headers: # TODO: handle better unknown fields (either revert to old # style of raising exception, or deal more intelligently with # variable fields) headers[field] = field if separator is not None: format_fields.append("%s") elif numfields.Matches(field): format_fields.append("%*s") else: format_fields.append("%-*s") if separator is None: mlens = [0 for name in fields] format = ' '.join(format_fields) else: format = separator.replace("%", "%%").join(format_fields) for row in data: if row is None: continue for idx, val in enumerate(row): if unitfields.Matches(fields[idx]): try: val = int(val) except ValueError: pass else: val = row[idx] = utils.FormatUnit(val, units) val = row[idx] = str(val) if separator is None: mlens[idx] = max(mlens[idx], len(val)) result = [] if headers: args = [] for idx, name in enumerate(fields): hdr = headers[name] if separator is None: if idx == len(fields) - 1 and not numfields.Matches(name): mlens[idx] = 0 else: mlens[idx] = max(mlens[idx], len(hdr)) args.append(mlens[idx]) args.append(hdr) result.append(format % tuple(args)) for line in data: args = [] if line is None: line = ['-' for _ in fields] for idx in range(len(fields)): if separator is None: args.append(mlens[idx]) args.append(line[idx]) result.append(format % tuple(args)) return result |
if state == "RUNNING": return (instance_name, 0, 0, len(cpu_list), 0, 0) return None | return (instance_name, 0, 0, len(cpu_list), 0, 0) | def GetInstanceInfo(self, instance_name): """Get instance properties. |
if name is None: name = self.GetSysName() self.name = self.GetNormalizedName(name) | self.name = self.GetNormalizedName(self.GetFqdn(name)) | def __init__(self, name=None, family=None): """Initialize the host name object. |
def GetSysName(): """Return the current system's name. This is simply a wrapper over C{socket.gethostname()}. """ return socket.gethostname() | def GetFqdn(hostname=None): """Return fqdn. If hostname is None the system's fqdn is returned. @type hostname: str @param hostname: name to be fqdn'ed @rtype: str @return: fqdn of given name, if it exists, unmodified name otherwise """ if hostname is None: return socket.getfqdn() else: return socket.getfqdn(hostname) | def GetSysName(): """Return the current system's name. |
@staticmethod def Loads(data): | @classmethod def Loads(cls, data): | def Dumps(self): """Dump this instance and return the string representation.""" buf = StringIO() self.write(buf) return buf.getvalue() |
for elem in data.split(","): | for elem in utils.UnescapeAndSplit(data, sep=","): | def _SplitKeyVal(opt, data): """Convert a KeyVal string into a dict. This function will convert a key=val[,...] string into a dict. Empty values will be converted specially: keys which have the prefix 'no_' will have the value=False and the prefix stripped, the others will have value=True. @type opt: string @param opt: a string holding the option name for which we process the data, used in building error messages @type data: string @param data: a string of the format key=val,key=val,... @rtype: dict @return: {key=val, key=val} @raises errors.ParameterError: if there are duplicate keys """ kv_dict = {} if data: for elem in data.split(","): if "=" in elem: key, val = elem.split("=", 1) else: if elem.startswith(NO_PREFIX): key, val = elem[len(NO_PREFIX):], False elif elem.startswith(UN_PREFIX): key, val = elem[len(UN_PREFIX):], None else: key, val = elem, True if key in kv_dict: raise errors.ParameterError("Duplicate key '%s' in option %s" % (key, opt)) kv_dict[key] = val return kv_dict |
_, v_major, v_min, v_rev = kvm_version | _, v_major, v_min, _ = kvm_version | def _ExecuteKVMRuntime(self, instance, kvm_runtime, incoming=None): """Execute a KVM cmd, after completing it with some last minute data |
sorted(fields)) | utils.NiceSort(fields)) | def GenericQueryFieldsTest(cmd, fields): master = qa_config.GetMasterNode() # Listing fields AssertCommand([cmd, "list-fields"]) AssertCommand([cmd, "list-fields"] + fields) # Check listed fields (all, must be sorted) realcmd = [cmd, "list-fields", "--separator=|", "--no-headers"] output = GetCommandOutput(master["primary"], utils.ShellQuoteArgs(realcmd)).splitlines() AssertEqual([line.split("|", 1)[0] for line in output], sorted(fields)) # Check exit code for listing unknown field AssertEqual(AssertCommand([cmd, "list-fields", "field/does/not/exist"], fail=True), constants.EXIT_UNKNOWN_FIELD) |
def _Acquire(lock, shared, ev): | def _Acquire(lock, shared, ev, notify): | def _Acquire(lock, shared, ev): lock.acquire(shared=shared) try: ev.wait() finally: lock.release() |
if tlock3 == tlock2: | if tlock3 in (tlock2, tlock1): | def _Acquire(lock, shared, ev): lock.acquire(shared=shared) try: ev.wait() finally: lock.release() |
ev = threading.Event() | releaseev = threading.Event() | def _Acquire(lock, shared, ev): lock.acquire(shared=shared) try: ev.wait() finally: lock.release() |
args=(tlock1, 1, ev))) tthread2 = self._addThread(target=_Acquire, args=(tlock2, 1, ev)) tthread3 = self._addThread(target=_Acquire, args=(tlock3, 0, ev)) | args=(tlock1, 1, releaseev, ev))) acquireev.append(ev) ev = threading.Event() tthread2 = self._addThread(target=_Acquire, args=(tlock2, 1, releaseev, ev)) acquireev.append(ev) ev = threading.Event() tthread3 = self._addThread(target=_Acquire, args=(tlock3, 0, releaseev, ev)) acquireev.append(ev) for i in acquireev: i.wait() | def _Acquire(lock, shared, ev): lock.acquire(shared=shared) try: ev.wait() finally: lock.release() |
ev.set() | releaseev.set() | def _Acquire(lock, shared, ev): lock.acquire(shared=shared) try: ev.wait() finally: lock.release() |
uidpool.ParseUidPool('1-100,200,'), | uidpool.ParseUidPool("1-100,200,"), | def testParseUidPool(self): self.assertEqualValues( uidpool.ParseUidPool('1-100,200,'), [(1, 100), (200, 200)]) |
'1-100, 200'), | "1-100, 200") self.assertEqualValues( uidpool.FormatUidPool([(1, 100), (200, 200)], separator=":"), "1-100:200") self.assertEqualValues( uidpool.FormatUidPool([(1, 100), (200, 200)], separator="\n"), "1-100\n200") | def testFormatUidPool(self): self.assertEqualValues( uidpool.FormatUidPool([(1, 100), (200, 200)]), '1-100, 200'), |
nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(), self.op.hypervisor) for node in nodenames: info = nodeinfo[node] info.Raise("Cannot get current information from node %s" % node) info = info.payload vg_free = info.get('vg_free', None) if not isinstance(vg_free, int): raise errors.OpPrereqError("Can't compute free disk space on" " node %s" % node, errors.ECODE_ENVIRON) if req_size > vg_free: raise errors.OpPrereqError("Not enough disk space on target node %s." " %d MB available, %d MB required" % (node, vg_free, req_size), errors.ECODE_NORES) | _CheckNodesFreeDisk(self, nodenames, req_size) | def CheckPrereq(self): """Check prerequisites. |
nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(), instance.hypervisor) for node in nodenames: info = nodeinfo[node] info.Raise("Cannot get current information from node %s" % node) vg_free = info.payload.get('vg_free', None) if not isinstance(vg_free, int): raise errors.OpPrereqError("Can't compute free disk space on" " node %s" % node, errors.ECODE_ENVIRON) if self.op.amount > vg_free: raise errors.OpPrereqError("Not enough disk space on target node %s:" " %d MiB available, %d MiB required" % (node, vg_free, self.op.amount), errors.ECODE_NORES) | _CheckNodesFreeDisk(self, nodenames, self.op.amount) | def CheckPrereq(self): """Check prerequisites. |
" cannot copy", errors.ECODE_STATE) | " cannot copy" % idx, errors.ECODE_STATE) | def CheckPrereq(self): """Check prerequisites. |
"""Starts up an instance. | """Migrates an instance. | def MigrateInstance(self, instance, mode=None, cleanup=None): """Starts up an instance. |
result = self._poller.poll(remaining_time) | result = self._poller.poll(1000 * remaining_time) | def __call__(self, timeout): """Wait for something to happen on the pipe. |
data.append((name, 0, 0, 0, 0, 0)) | data.append(self.GetInstanceInfo(name)) | def GetAllInstancesInfo(self): """Get properties of all instances. |
elif item.uuid in self._AllIDs(temporary=True): raise errors.ConfigurationError("Cannot add '%s': UUID already in use" % (item.name, item.uuid)) | elif item.uuid in self._AllIDs(include_temporary=True): raise errors.ConfigurationError("Cannot add '%s': UUID %s already" " in use" % (item.name, item.uuid)) | def _EnsureUUID(self, item, ec_id): """Ensures a given object has a valid UUID. |
queue.acquire(shared=1) try: try: job.lock_status = None job.end_timestamp = TimeStampNow() queue.UpdateJobUnlocked(job) finally: job_id = job.id status = job.CalcStatus() finally: queue.release() logging.info("Finished job %s, status = %s", job_id, status) | status = job.CalcStatus() logging.info("Finished job %s, status = %s", job.id, status) | def RunTask(self, job): # pylint: disable-msg=W0221 """Job executor. |
if not (compat.all(dresults) and fin_resu): feedback_fn("Not removing instance %s as parts of the export failed" % instance.name) else: feedback_fn("Removing instance %s" % instance.name) _RemoveInstance(self, feedback_fn, instance, self.op.ignore_remove_failures) | feedback_fn("Removing instance %s" % instance.name) _RemoveInstance(self, feedback_fn, instance, self.op.ignore_remove_failures) | def Exec(self, feedback_fn): """Export an instance to an image in the cluster. |
if qa_rapi.Enabled(): RunTest(qa_rapi.TestInstance, instance) | def RunCommonInstanceTests(instance): """Runs a few tests that are common to all disk types. """ if qa_config.TestEnabled('instance-shutdown'): RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('instance-list'): RunTest(qa_instance.TestInstanceList) if qa_config.TestEnabled('instance-info'): RunTest(qa_instance.TestInstanceInfo, instance) if qa_config.TestEnabled('instance-modify'): RunTest(qa_instance.TestInstanceModify, instance) if qa_rapi.Enabled(): RunTest(qa_rapi.TestRapiInstanceModify, instance) if qa_config.TestEnabled('instance-console'): RunTest(qa_instance.TestInstanceConsole, instance) if qa_config.TestEnabled('instance-reinstall'): RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceReinstall, instance) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('instance-reboot'): RunTest(qa_instance.TestInstanceReboot, instance) if qa_config.TestEnabled('instance-rename'): rename_target = qa_config.get("rename", None) if rename_target is None: print qa_utils.FormatError("Can rename instance, 'rename' entry is" " missing from configuration") else: RunTest(qa_instance.TestInstanceShutdown, instance) RunTest(qa_instance.TestInstanceRename, instance, rename_target) if qa_rapi.Enabled(): RunTest(qa_rapi.TestRapiInstanceRename, instance, rename_target) RunTest(qa_instance.TestInstanceStartup, instance) if qa_config.TestEnabled('tags'): RunTest(qa_tags.TestInstanceTags, instance) if qa_config.TestEnabled('node-volumes'): RunTest(qa_node.TestNodeVolumes) if qa_config.TestEnabled("node-storage"): RunTest(qa_node.TestNodeStorage) if qa_rapi.Enabled(): RunTest(qa_rapi.TestInstance, instance) | |
code = 400 response = "Bad request" | code = 501 response = "Method not implemented" | def FetchResponse(self, path, method): code = 200 response = None |
self.assertEqual((400, "Bad request"), | self.assertEqual((501, "Method not implemented"), | def test(self): rapi = RapiMock() path = "/version" self.assertEqual((404, None), rapi.FetchResponse("/foo", "GET")) self.assertEqual((400, "Bad request"), rapi.FetchResponse("/version", "POST")) rapi.AddResponse("2") code, response = rapi.FetchResponse("/version", "GET") self.assertEqual(200, code) self.assertEqual("2", response) self.failUnless(isinstance(rapi.GetLastHandler(), rlib2.R_version)) |
except socket.gaierror, err: | except (socket.gaierror, socket.herror, socket.error), err: | def LookupHostname(hostname): """Look up hostname |
raise _LockAcquireTimeout() | raise LockAcquireTimeout() | def _LockAndExecLU(self, lu, level, calc_timeout): """Execute a Logical Unit, with the needed locks. |
def ExecOpCode(self, op, cbs): | def ExecOpCode(self, op, cbs, timeout=None): | def ExecOpCode(self, op, cbs): """Execute an opcode. |
lu_class = self.DISPATCH_TABLE.get(op.__class__, None) if lu_class is None: raise errors.OpCodeUnknown("Unknown opcode") timeout_strategy = _LockAttemptTimeoutStrategy() while True: | if self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL, not lu_class.REQ_BGL, calc_timeout()) is None: raise LockAcquireTimeout() try: lu = lu_class(self, op, self.context, self.rpc) lu.ExpandNames() assert lu.needed_locks is not None, "needed_locks not set by LU" | def ExecOpCode(self, op, cbs): """Execute an opcode. |
acquire_timeout = timeout_strategy.CalcRemainingTimeout() if self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL, not lu_class.REQ_BGL, acquire_timeout) is None: raise _LockAcquireTimeout() try: lu = lu_class(self, op, self.context, self.rpc) lu.ExpandNames() assert lu.needed_locks is not None, "needed_locks not set by LU" try: return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, timeout_strategy.CalcRemainingTimeout) finally: if self._ec_id: self.context.cfg.DropECReservations(self._ec_id) finally: self.context.glm.release(locking.LEVEL_CLUSTER) except _LockAcquireTimeout: pass timeout_strategy = timeout_strategy.NextAttempt() | return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout) finally: if self._ec_id: self.context.cfg.DropECReservations(self._ec_id) finally: self.context.glm.release(locking.LEVEL_CLUSTER) | def ExecOpCode(self, op, cbs): """Execute an opcode. |
rapi_cert_pem=None): | rapi_cert_pem=None, nodecert_file=constants.NODED_CERT_FILE, rapicert_file=constants.RAPI_CERT_FILE, hmackey_file=constants.CONFD_HMAC_KEY): | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) | cluster_cert_exists = os.path.exists(nodecert_file) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) | utils.CreateBackup(nodecert_file) logging.debug("Generating new cluster certificate at %s", nodecert_file) GenerateSelfSignedSslCert(nodecert_file) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) | if new_confd_hmac_key or not os.path.exists(hmackey_file): logging.debug("Writing new confd HMAC key to %s", hmackey_file) GenerateHmacKey(hmackey_file) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) | rapi_cert_exists = os.path.exists(rapicert_file) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) | logging.debug("Writing RAPI certificate at %s", rapicert_file) utils.WriteFile(rapicert_file, data=rapi_cert_pem, backup=True) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) | utils.CreateBackup(rapicert_file) logging.debug("Generating new RAPI certificate at %s", rapicert_file) GenerateSelfSignedSslCert(rapicert_file) | def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, rapi_cert_pem=None): """Updates the cluster certificates, keys and secrets. @type new_cluster_cert: bool @param new_cluster_cert: Whether to generate a new cluster certificate @type new_rapi_cert: bool @param new_rapi_cert: Whether to generate a new RAPI certificate @type new_confd_hmac_key: bool @param new_confd_hmac_key: Whether to generate a new HMAC key @type rapi_cert_pem: string @param rapi_cert_pem: New RAPI certificate in PEM format """ # noded SSL certificate cluster_cert_exists = os.path.exists(constants.NODED_CERT_FILE) if new_cluster_cert or not cluster_cert_exists: if cluster_cert_exists: utils.CreateBackup(constants.NODED_CERT_FILE) logging.debug("Generating new cluster certificate at %s", constants.NODED_CERT_FILE) GenerateSelfSignedSslCert(constants.NODED_CERT_FILE) # confd HMAC key if new_confd_hmac_key or not os.path.exists(constants.CONFD_HMAC_KEY): logging.debug("Writing new confd HMAC key to %s", constants.CONFD_HMAC_KEY) GenerateHmacKey(constants.CONFD_HMAC_KEY) # RAPI rapi_cert_exists = os.path.exists(constants.RAPI_CERT_FILE) if rapi_cert_pem: # Assume rapi_pem contains a valid PEM-formatted certificate and key logging.debug("Writing RAPI certificate at %s", constants.RAPI_CERT_FILE) utils.WriteFile(constants.RAPI_CERT_FILE, data=rapi_cert_pem, backup=True) elif new_rapi_cert or not rapi_cert_exists: if rapi_cert_exists: utils.CreateBackup(constants.RAPI_CERT_FILE) logging.debug("Generating new RAPI certificate at %s", constants.RAPI_CERT_FILE) GenerateSelfSignedSslCert(constants.RAPI_CERT_FILE) |
@warning: this function will call L{_WriteConfig()}, so it needs to either be called with the lock held or from a safe place (the constructor) | @warning: this function will call L{_WriteConfig()}, but also L{DropECReservations} so it needs to be called only from a "safe" place (the constructor). If one wanted to call it with the lock held, a DropECReservationUnlocked would need to be created first, to avoid causing deadlock. | def _UpgradeConfig(self): """Run upgrade steps that cannot be done purely in the objects. |
class TestIsAbsNormPath(unittest.TestCase): """Testing case for IsAbsNormPath""" | class TestIsNormAbsPath(unittest.TestCase): """Testing case for IsNormAbsPath""" | def testErrors(self): self.assertRaises(errors.TypeEnforcementError, self._fdt, {'a': 'astring'}) self.assertRaises(errors.TypeEnforcementError, self._fdt, {'c': True}) self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': 'astring'}) self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': '4 L'}) |
if self.op.snode is None: raise errors.OpPrereqError("The networked disk templates need" " a mirror node", errors.ECODE_INVAL) | def CheckPrereq(self): """Check prerequisites. | |
if self.target_node != self.instance.primary_node: self._ReleaseNodeLock(self.target_node) | self._ReleaseNodeLock([self.target_node, self.other_node]) | def _ExecDrbd8DiskOnly(self, feedback_fn): """Replace a disk on the primary or secondary for DRBD 8. |
self._ReleaseNodeLock([self.target_node, self.new_node]) | self._ReleaseNodeLock([self.instance.primary_node, self.target_node, self.new_node]) | def _ExecDrbd8Secondary(self, feedback_fn): """Replace the secondary node for DRBD 8. |
def _CheckNodeOnline(lu, node): | def _CheckNodeOnline(lu, node, msg=None): | def _CheckNodeOnline(lu, node): """Ensure that a given node is online. @param lu: the LU on behalf of which we make the check @param node: the node to check @raise errors.OpPrereqError: if the node is offline """ if lu.cfg.GetNodeInfo(node).offline: raise errors.OpPrereqError("Can't use offline node %s" % node, errors.ECODE_STATE) |
raise errors.OpPrereqError("Can't use offline node %s" % node, errors.ECODE_STATE) | raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE) | def _CheckNodeOnline(lu, node): """Ensure that a given node is online. @param lu: the LU on behalf of which we make the check @param node: the node to check @raise errors.OpPrereqError: if the node is offline """ if lu.cfg.GetNodeInfo(node).offline: raise errors.OpPrereqError("Can't use offline node %s" % node, errors.ECODE_STATE) |
_CheckNodeOnline(self, instance.primary_node) | _CheckNodeOnline(self, instance.primary_node, "Instance primary node" " offline, cannot reinstall") for node in instance.secondary_nodes: _CheckNodeOnline(self, node, "Instance secondary node offline," " cannot reinstall") | def CheckPrereq(self): """Check prerequisites. |
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name, | def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name, | def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name, p_minor, s_minor): """Generate a drbd8 device complete with its children. """ port = lu.cfg.AllocatePort() vgname = lu.cfg.GetVGName() shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId()) dev_data = objects.Disk(dev_type=constants.LD_LV, size=size, logical_id=(vgname, names[0])) dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128, logical_id=(vgname, names[1])) drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size, logical_id=(primary, secondary, port, p_minor, s_minor, shared_secret), children=[dev_data, dev_meta], iv_name=iv_name) return drbd_dev |
vgname = lu.cfg.GetVGName() | def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name, p_minor, s_minor): """Generate a drbd8 device complete with its children. """ port = lu.cfg.AllocatePort() vgname = lu.cfg.GetVGName() shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId()) dev_data = objects.Disk(dev_type=constants.LD_LV, size=size, logical_id=(vgname, names[0])) dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128, logical_id=(vgname, names[1])) drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size, logical_id=(primary, secondary, port, p_minor, s_minor, shared_secret), children=[dev_data, dev_meta], iv_name=iv_name) return drbd_dev | |
base_index): | base_index, feedback_fn): | def _GenerateDiskTemplate(lu, template_name, instance_name, primary_node, secondary_nodes, disk_info, file_storage_dir, file_driver, base_index): """Generate the entire disk layout for a given template type. """ #TODO: compute space requirements vgname = lu.cfg.GetVGName() disk_count = len(disk_info) disks = [] if template_name == constants.DT_DISKLESS: pass elif template_name == constants.DT_PLAIN: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]) for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"], logical_id=(vgname, names[idx]), iv_name="disk/%d" % disk_index, mode=disk["mode"]) disks.append(disk_dev) elif template_name == constants.DT_DRBD8: if len(secondary_nodes) != 1: raise errors.ProgrammerError("Wrong template configuration") remote_node = secondary_nodes[0] minors = lu.cfg.AllocateDRBDMinor( [primary_node, remote_node] * len(disk_info), instance_name) names = [] for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]): names.append(lv_prefix + "_data") names.append(lv_prefix + "_meta") for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node, disk["size"], names[idx*2:idx*2+2], "disk/%d" % disk_index, minors[idx*2], minors[idx*2+1]) disk_dev.mode = disk["mode"] disks.append(disk_dev) elif template_name == constants.DT_FILE: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") _RequireFileStorage() for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"], iv_name="disk/%d" % disk_index, logical_id=(file_driver, "%s/disk%d" % (file_storage_dir, disk_index)), mode=disk["mode"]) disks.append(disk_dev) else: raise errors.ProgrammerError("Invalid disk template '%s'" % template_name) return disks |
logical_id=(vgname, names[idx]), | logical_id=(vg, names[idx]), | def _GenerateDiskTemplate(lu, template_name, instance_name, primary_node, secondary_nodes, disk_info, file_storage_dir, file_driver, base_index): """Generate the entire disk layout for a given template type. """ #TODO: compute space requirements vgname = lu.cfg.GetVGName() disk_count = len(disk_info) disks = [] if template_name == constants.DT_DISKLESS: pass elif template_name == constants.DT_PLAIN: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]) for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"], logical_id=(vgname, names[idx]), iv_name="disk/%d" % disk_index, mode=disk["mode"]) disks.append(disk_dev) elif template_name == constants.DT_DRBD8: if len(secondary_nodes) != 1: raise errors.ProgrammerError("Wrong template configuration") remote_node = secondary_nodes[0] minors = lu.cfg.AllocateDRBDMinor( [primary_node, remote_node] * len(disk_info), instance_name) names = [] for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]): names.append(lv_prefix + "_data") names.append(lv_prefix + "_meta") for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node, disk["size"], names[idx*2:idx*2+2], "disk/%d" % disk_index, minors[idx*2], minors[idx*2+1]) disk_dev.mode = disk["mode"] disks.append(disk_dev) elif template_name == constants.DT_FILE: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") _RequireFileStorage() for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"], iv_name="disk/%d" % disk_index, logical_id=(file_driver, "%s/disk%d" % (file_storage_dir, disk_index)), mode=disk["mode"]) disks.append(disk_dev) else: raise errors.ProgrammerError("Invalid disk template '%s'" % template_name) return disks |
disk["size"], names[idx*2:idx*2+2], | disk["size"], vg, names[idx*2:idx*2+2], | def _GenerateDiskTemplate(lu, template_name, instance_name, primary_node, secondary_nodes, disk_info, file_storage_dir, file_driver, base_index): """Generate the entire disk layout for a given template type. """ #TODO: compute space requirements vgname = lu.cfg.GetVGName() disk_count = len(disk_info) disks = [] if template_name == constants.DT_DISKLESS: pass elif template_name == constants.DT_PLAIN: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]) for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"], logical_id=(vgname, names[idx]), iv_name="disk/%d" % disk_index, mode=disk["mode"]) disks.append(disk_dev) elif template_name == constants.DT_DRBD8: if len(secondary_nodes) != 1: raise errors.ProgrammerError("Wrong template configuration") remote_node = secondary_nodes[0] minors = lu.cfg.AllocateDRBDMinor( [primary_node, remote_node] * len(disk_info), instance_name) names = [] for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i) for i in range(disk_count)]): names.append(lv_prefix + "_data") names.append(lv_prefix + "_meta") for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node, disk["size"], names[idx*2:idx*2+2], "disk/%d" % disk_index, minors[idx*2], minors[idx*2+1]) disk_dev.mode = disk["mode"] disks.append(disk_dev) elif template_name == constants.DT_FILE: if len(secondary_nodes) != 0: raise errors.ProgrammerError("Wrong template configuration") _RequireFileStorage() for idx, disk in enumerate(disk_info): disk_index = idx + base_index disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"], iv_name="disk/%d" % disk_index, logical_id=(file_driver, "%s/disk%d" % (file_storage_dir, disk_index)), mode=disk["mode"]) disks.append(disk_dev) else: raise errors.ProgrammerError("Invalid disk template '%s'" % template_name) return disks |
new_disk = {"size": size, "mode": mode} | vg = disk.get("vg", self.cfg.GetVGName()) new_disk = {"size": size, "mode": mode, "vg": vg} | def CheckPrereq(self): """Check prerequisites. |
0) | 0, feedback_fn) | def Exec(self, feedback_fn): """Create and add the instance to the cluster. |
disk_info, None, None, 0) | disk_info, None, None, 0, feedback_fn) | def _ConvertPlainToDrbd(self, feedback_fn): """Converts an instance from plain to drbd. |
disk_idx_base)[0] | disk_idx_base, feedback_fn)[0] | def Exec(self, feedback_fn): """Modifies an instance. |
self.oob_program = self.cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM] | self.oob_program = _SupportsOob(self.cfg, node) | def CheckPrereq(self): """Check prerequisites. |
cfg = config.ConfigWriter() cluster_info = cfg.GetClusterInfo() cluster_info.master_node = new_master cfg.Update(cluster_info, logging.error) | logging.info("Starting the master daemons on the new master") | def _check_ip(): if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT): raise utils.RetryAgain() |
logging.warning("KVM: unknown 'info migrate' result: %s" % | logging.warning("KVM: unknown 'info migrate' result: %s", | def MigrateInstance(self, instance, target, live): """Migrate an instance to a target node. |
mask = (pyinotify.EventsCodes.IN_MODIFY | pyinotify.EventsCodes.IN_IGNORED) | mask = (pyinotify.EventsCodes.ALL_FLAGS["IN_MODIFY"] | pyinotify.EventsCodes.ALL_FLAGS["IN_IGNORED"]) | def enable(self): """Watch the given file. |
self.env.log.info("Sending SMTP notification to %s:%d to %s" % (self.smtp_server, self.smtp_port, recipients)) | self.env.log.info("Sending SMTP notification to %s"%recipients) | def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if not rcpt in all: tmp.append(rcpt) all.append(rcpt) return (tmp, all) |
self.server.sendmail(msg['From'], recipients, msgtext) | NotificationSystem(self.env).send_email(msg['From'], recipients, msgtext) | def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if not rcpt in all: tmp.append(rcpt) all.append(rcpt) return (tmp, all) |
self._svnserve_conf = Configuration(os.path.join(repo_dir, 'svnserve.conf')) | self._svnserve_conf = Configuration(os.path.join(os.path.join( repo_dir, 'conf'), 'svnserve.conf')) | def __init__(self): repo_dir = RepositoryManager(self.env).repository_dir self._svnserve_conf = Configuration(os.path.join(repo_dir, 'svnserve.conf')) self._userconf = None |
, user=tag.b(req.args.get('user'))))) | "Registration has been finished successfully." " You may login as user ", tag.b(req.args.get('user')), " now."))) | def process_request(self, req): if req.authname != 'anonymous': req.redirect(req.href.prefs('account')) action = req.args.get('action') data = {'acctmgr' : { 'username' : None, 'name' : None, 'email' : None, }, } if req.method == 'POST' and action == 'create': try: _create_user(req, self.env) except TracError, e: data['registration_error'] = e.message data['acctmgr'] = e.acctmgr else: chrome.add_notice(req, Markup(tag( """Registration has been finished successfully. You may login as user %(user)s now.""", user=tag.b(req.args.get('user'))))) req.redirect(req.href.login()) data['reset_password_enabled'] = \ (self.env.is_component_enabled(AccountModule) and AccountModule(self.env).reset_password) |
if req.path_info != redirect_url: | if req.href(req.path_info) != redirect_url: | def post_process_request(self, req, template, data, content_type): if req.authname and req.authname != 'anonymous': if req.session.get('force_change_passwd', False): redirect_url = req.href.prefs('account') if req.path_info != redirect_url: req.redirect(redirect_url) return (template, data, content_type) |
filename = self.filename | filename = str(self.filename) | def get_users(self): filename = self.filename if not os.path.exists(filename): self.log.debug('acct_mgr: get_users() -- Can\'t locate "%s"' % str(filename)) return [] return self._get_users(filename) |
self.log.debug('acct_mgr: get_users() -- Can\'t locate "%s"' % str(filename)) | self.log.debug('acct_mgr: get_users() -- ' 'Can\'t locate "%s"' % filename) | def get_users(self): filename = self.filename if not os.path.exists(filename): self.log.debug('acct_mgr: get_users() -- Can\'t locate "%s"' % str(filename)) return [] return self._get_users(filename) |
filename = self.filename | filename = str(self.filename) | def check_password(self, user, password): filename = self.filename if not os.path.exists(filename): self.log.debug('acct_mgr: check_password() -- Can\'t locate "%s"' % str(filename)) return False user = user.encode('utf-8') password = password.encode('utf-8') prefix = self.prefix(user) fd = file(filename) try: for line in fd: if line.startswith(prefix): return self._check_userline(user, password, line[len(prefix):].rstrip('\n')) finally: fd.close() return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.