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.TestInst...
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 el...
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 ...
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 no...
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 t...
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 ...
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...
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=W...
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=W...
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=W...
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 ...
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 op...
_, 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["pr...
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:...
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...
_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 fr...
_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.TestInst...
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...
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...
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 gener...
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 gener...
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 gener...
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 gener...
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 gener...
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 gener...
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 gener...
@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, error...
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, error...
_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, si...
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, si...
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 te...
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 te...
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 te...
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[...
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...