uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41eaaba132ef22e78cca1f87 | train | function | def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
"""Builds environment variables for master IP hooks.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of the master
@type use_external_mip_script: boolean
@param use_external_mip_script: whethe... | def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
| """Builds environment variables for master IP hooks.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of the master
@type use_external_mip_script: boolean
@param use_external_mip_script: whether to use an external master IP
address setup script (unused, but... | .GetMasterNode())
hm.RunPhase(constants.HOOKS_PHASE_PRE)
result = fn(*args, **kwargs)
hm.RunPhase(constants.HOOKS_PHASE_POST)
return result
return wrapper
return decorator
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
| 64 | 64 | 182 | 16 | 47 | jfut/ganeti | lib/backend.py | Python | _BuildMasterIpEnv | _BuildMasterIpEnv | 357 | 377 | 357 | 357 | 4a0549faffb536ae4539543bd5410700801c8255 | bigcode/the-stack | train |
4d54b3b4020bbd22b751ed1e | train | function | def RunOob(oob_program, command, node, timeout):
"""Executes oob_program with given command on given node.
@param oob_program: The path to the executable oob_program
@param command: The command to invoke on oob_program
@param node: The node given as an argument to the program
@param timeout: Timeout after wh... | def RunOob(oob_program, command, node, timeout):
| """Executes oob_program with given command on given node.
@param oob_program: The path to the executable oob_program
@param command: The command to invoke on oob_program
@param node: The node given as an argument to the program
@param timeout: Timeout after which we kill the oob program
@return: stdout
... | gid = getents.LookupGroup(gid)
utils.SafeWriteFile(file_name, None,
data=raw_data, mode=mode, uid=uid, gid=gid,
atime=atime, mtime=mtime)
def RunOob(oob_program, command, node, timeout):
| 64 | 64 | 167 | 14 | 50 | jfut/ganeti | lib/backend.py | Python | RunOob | RunOob | 3,979 | 3,997 | 3,979 | 3,979 | fc466e9b3b6909d671ec619335d92647ff98edbd | bigcode/the-stack | train |
b752cc5ba9fe2698f0b49402 | train | function | def PowercycleNode(hypervisor_type, hvparams=None):
"""Hard-powercycle the node.
Because we need to return first, and schedule the powercycle in the
background, we won't be able to report failures nicely.
"""
hyper = hypervisor.GetHypervisor(hypervisor_type)
try:
pid = os.fork()
except OSError:
... | def PowercycleNode(hypervisor_type, hvparams=None):
| """Hard-powercycle the node.
Because we need to return first, and schedule the powercycle in the
background, we won't be able to report failures nicely.
"""
hyper = hypervisor.GetHypervisor(hypervisor_type)
try:
pid = os.fork()
except OSError:
# if we can't fork, we'll pretend that we're in the ... | GetDrbdUsermodeHelper():
"""Returns DRBD usermode helper currently configured.
"""
try:
return drbd.DRBD8.GetUsermodeHelper()
except errors.BlockDeviceError as err:
_Fail(str(err))
def PowercycleNode(hypervisor_type, hvparams=None):
| 64 | 64 | 171 | 13 | 51 | jfut/ganeti | lib/backend.py | Python | PowercycleNode | PowercycleNode | 5,629 | 5,650 | 5,629 | 5,629 | 49690af864a7effdea0fb866d48d68f0741c64ff | bigcode/the-stack | train |
d57f893736167455f3d1d563 | train | function | def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
"""Reboot an instance.
@type instance: L{objects.Instance}
@param instance: the instance object to reboot
@type reboot_type: str
@param reboot_type: the type of reboot, one the following
constants:
- L{constants.INSTANCE_REBOOT_SO... | def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
| """Reboot an instance.
@type instance: L{objects.Instance}
@param instance: the instance object to reboot
@type reboot_type: str
@param reboot_type: the type of reboot, one the following
constants:
- L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
instance OS, do not recreate the VM
... | error could simply be "instance ... unknown"!
if _GetInstanceInfo(instance):
_Fail("Failed to force stop instance '%s': %s", instance.name, err)
time.sleep(1)
if _GetInstanceInfo(instance):
_Fail("Could not shutdown instance '%s' even by destroy", instance.name)
try:
hype... | 137 | 137 | 458 | 14 | 123 | jfut/ganeti | lib/backend.py | Python | InstanceReboot | InstanceReboot | 3,002 | 3,045 | 3,002 | 3,002 | 4b18e8bfa36eb8afc0fbde4bbf1054f1213e7abb | bigcode/the-stack | train |
6d3227923d16c71e57ea5e18 | train | function | def _CheckLvmStorageParams(params):
"""Performs sanity check for the 'exclusive storage' flag.
@see: C{_CheckStorageParams}
"""
_CheckStorageParams(params, 1)
excl_stor = params[0]
if not isinstance(params[0], bool):
raise errors.ProgrammerError("Exclusive storage parameter is not"
... | def _CheckLvmStorageParams(params):
| """Performs sanity check for the 'exclusive storage' flag.
@see: C{_CheckStorageParams}
"""
_CheckStorageParams(params, 1)
excl_stor = params[0]
if not isinstance(params[0], bool):
raise errors.ProgrammerError("Exclusive storage parameter is not"
" boolean: '%s'." % ex... | '%s'" % params)
if not len(params) == num_params:
raise errors.ProgrammerError("Did not receive the expected number of"
"storage parameters: expected %s,"
" received '%s'" % (num_params, len(params)))
def _CheckLvmStorageParams(params):
| 63 | 64 | 97 | 9 | 54 | jfut/ganeti | lib/backend.py | Python | _CheckLvmStorageParams | _CheckLvmStorageParams | 611 | 622 | 611 | 611 | 5090e861efab76d21a1645f920710d604fc4ecf0 | bigcode/the-stack | train |
5ddef775f53eef945d8dc9ab | train | function | def ExportInfo(dest):
"""Get export configuration information.
@type dest: str
@param dest: directory containing the export
@rtype: L{objects.SerializableConfigParser}
@return: a serializable config file containing the
export info
"""
cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
conf... | def ExportInfo(dest):
| """Get export configuration information.
@type dest: str
@param dest: directory containing the export
@rtype: L{objects.SerializableConfigParser}
@return: a serializable config file containing the
export info
"""
cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
config = objects.Serializa... | .set(constants.INISECT_OSP_PRIVATE, name, str(value.Get()))
utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
data=config.Dumps())
shutil.rmtree(finaldestdir, ignore_errors=True)
shutil.move(destdir, finaldestdir)
def ExportInfo(dest):
| 64 | 64 | 132 | 5 | 59 | jfut/ganeti | lib/backend.py | Python | ExportInfo | ExportInfo | 4,589 | 4,609 | 4,589 | 4,589 | bc5996ae1ff78323da8f43bd3c6b072d4c74d1cc | bigcode/the-stack | train |
8f8ed90905a7cc42ea4d1e35 | train | class | class DevCacheManager(object):
"""Simple class for managing a cache of block device information.
"""
_DEV_PREFIX = "/dev/"
_ROOT_DIR = pathutils.BDEV_CACHE_DIR
@classmethod
def _ConvertPath(cls, dev_path):
"""Converts a /dev/name path to the cache file name.
This replaces slashes with underscores... | class DevCacheManager(object):
| """Simple class for managing a cache of block device information.
"""
_DEV_PREFIX = "/dev/"
_ROOT_DIR = pathutils.BDEV_CACHE_DIR
@classmethod
def _ConvertPath(cls, dev_path):
"""Converts a /dev/name path to the cache file name.
This replaces slashes with underscores and strips the /dev
prefix... | @return: two element tuple of:
- status
- either error message or stdout of allocator (for success)
"""
alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
os.path.isfile)
if alloc_script is None:
_Fail("iallocator module '%s' not ... | 185 | 185 | 619 | 6 | 178 | jfut/ganeti | lib/backend.py | Python | DevCacheManager | DevCacheManager | 6,045 | 6,125 | 6,045 | 6,045 | 67191157faaecff290672a6e19c2c7ac1ab56416 | bigcode/the-stack | train |
6d05f9fe8e89e4ea5e8743c3 | train | function | def BlockdevRemove(disk):
"""Remove a block device.
@note: This is intended to be called recursively.
@type disk: L{objects.Disk}
@param disk: the disk object we should remove
@rtype: boolean
@return: the success of the operation
"""
msgs = []
try:
rdev = _RecursiveFindBD(disk)
except errors.... | def BlockdevRemove(disk):
| """Remove a block device.
@note: This is intended to be called recursively.
@type disk: L{objects.Disk}
@param disk: the disk object we should remove
@rtype: boolean
@return: the success of the operation
"""
msgs = []
try:
rdev = _RecursiveFindBD(disk)
except errors.BlockDeviceError as err:
... | result = rdev.PauseResumeSync(pause)
if result:
success.append((result, None))
else:
if pause:
msg = "Pause"
else:
msg = "Resume"
success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
return success
def BlockdevRemove(disk):
| 78 | 78 | 260 | 7 | 70 | jfut/ganeti | lib/backend.py | Python | BlockdevRemove | BlockdevRemove | 3,557 | 3,600 | 3,557 | 3,557 | 420e09df8c1aecf3845bb6453f550401cdeaf814 | bigcode/the-stack | train |
dc1101b3e7f9e1c9f5566467 | train | function | def _TryOSFromDisk(name, base_dir=None):
"""Create an OS instance from disk.
This function will return an OS instance if the given name is a
valid OS name.
@type base_dir: string
@keyword base_dir: Base directory containing OS installations.
Defaults to a search in all the OS_SEARCH_PAT... | def _TryOSFromDisk(name, base_dir=None):
| """Create an OS instance from disk.
This function will return an OS instance if the given name is a
valid OS name.
@type base_dir: string
@keyword base_dir: Base directory containing OS installations.
Defaults to a search in all the OS_SEARCH_PATH dirs.
@rtype: tuple
@return: succes... | (name, help) parameters, if any
- api_version is a list of support OS API versions
"""
if top_dirs is None:
top_dirs = pathutils.OS_SEARCH_PATH
result = []
for dir_name in top_dirs:
if os.path.isdir(dir_name):
try:
f_names = utils.ListVisibleFiles(dir_name)
except Enviro... | 256 | 256 | 1,017 | 12 | 243 | jfut/ganeti | lib/backend.py | Python | _TryOSFromDisk | _TryOSFromDisk | 4,090 | 4,200 | 4,090 | 4,090 | 55c7ff6c7aa4ba14d884f89daa4b86ecdaf9b545 | bigcode/the-stack | train |
68ad348343a945a009c8ab8f | train | function | def StartImportExportDaemon(mode, opts, host, port, instance, component,
ieio, ieioargs):
"""Starts an import or export daemon.
@param mode: Import/output mode
@type opts: L{objects.ImportExportOptions}
@param opts: Daemon options
@type host: string
@param host: Remote host for ... | def StartImportExportDaemon(mode, opts, host, port, instance, component,
ieio, ieioargs):
| """Starts an import or export daemon.
@param mode: Import/output mode
@type opts: L{objects.ImportExportOptions}
@param opts: Daemon options
@type host: string
@param host: Remote host for export (None for import)
@type port: int
@param port: Remote port for export (None for import)
@type instance: L... | .dev_path
uri = _CalculateDeviceURI(instance, disk, real_disk)
if uri:
env["EXPORT_DISK_URI"] = uri
env["EXPORT_INDEX"] = str(disk_index)
script = inst_os.export_script
# TODO: Pass special environment only to script
script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os... | 255 | 256 | 1,043 | 25 | 230 | jfut/ganeti | lib/backend.py | Python | StartImportExportDaemon | StartImportExportDaemon | 5,274 | 5,404 | 5,274 | 5,275 | 6e78d8996b05670f81a067fa9949a3a684063cb1 | bigcode/the-stack | train |
a18f83795f6db2045f7575df | train | function | def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
"""Write a file to the filesystem.
This allows the master to overwrite(!) a file. It will only perform
the operation if the file belongs to a list of configuration files.
@type file_name: str
@param file_name: the target file name
@type data: ... | def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
| """Write a file to the filesystem.
This allows the master to overwrite(!) a file. It will only perform
the operation if the file belongs to a list of configuration files.
@type file_name: str
@param file_name: the target file name
@type data: str
@param data: the new contents of the file
@type mode: i... | disk cannot be found,
otherwise the pair (size, spindles), where spindles is None if the
device doesn't support that
"""
result = []
for cf in disks:
try:
rbd = _RecursiveFindBD(cf)
except errors.BlockDeviceError:
result.append(None)
continue
if rbd is None:
resul... | 119 | 119 | 399 | 20 | 98 | jfut/ganeti | lib/backend.py | Python | UploadFile | UploadFile | 3,933 | 3,976 | 3,933 | 3,933 | 6dea6f2b4fc796ce768ff29970d31bd613c4046b | bigcode/the-stack | train |
5ebc6cdb25c07465c117b232 | train | function | def _VerifySshSetup(node_status_list, my_name, ssh_key_type,
ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS):
"""Verifies the state of the SSH key files.
@type node_status_list: list of tuples
@param node_status_list: list of nodes of the cluster associated with a
couple of flags: (uuid, nam... | def _VerifySshSetup(node_status_list, my_name, ssh_key_type,
ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS):
| """Verifies the state of the SSH key files.
@type node_status_list: list of tuples
@param node_status_list: list of nodes of the cluster associated with a
couple of flags: (uuid, name, is_master_candidate,
is_potential_master_candidate, online)
@type my_name: str
@param my_name: name of this node
@... | not self-signed. Self-
signed client certificates stem from Ganeti versions 2.12.0 - 2.12.4
and should be replaced by client certificates signed by the server
certificate. Hence we output a warning when we encounter a self-signed
one.
"""
create_cert_cmd = "gnt-cluster renew-crypto --new-node-certificates... | 256 | 256 | 1,223 | 32 | 224 | jfut/ganeti | lib/backend.py | Python | _VerifySshSetup | _VerifySshSetup | 976 | 1,082 | 976 | 977 | 83c314e41273684d52b89fd90cf719c9c8b93230 | bigcode/the-stack | train |
a44ac4d719cd5335285f7691 | train | function | def _OSOndiskAPIVersion(os_dir):
"""Compute and return the API version of a given OS.
This function will try to read the API version of the OS residing in
the 'os_dir' directory.
@type os_dir: str
@param os_dir: the directory in which we should look for the OS
@rtype: tuple
@return: tuple (status, data)... | def _OSOndiskAPIVersion(os_dir):
| """Compute and return the API version of a given OS.
This function will try to read the API version of the OS residing in
the 'os_dir' directory.
@type os_dir: str
@param os_dir: the directory in which we should look for the OS
@rtype: tuple
@return: tuple (status, data) with status denoting the validit... | timeout: Timeout after which we kill the oob program
@return: stdout
@raise RPCFail: If execution fails for some reason
"""
result = utils.RunCmd([oob_program, command, node], timeout=timeout)
if result.failed:
_Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
result.fail_reason,... | 102 | 102 | 341 | 11 | 90 | jfut/ganeti | lib/backend.py | Python | _OSOndiskAPIVersion | _OSOndiskAPIVersion | 4,000 | 4,037 | 4,000 | 4,000 | b16fb3dd763169d98914b8b88abde1b76b047704 | bigcode/the-stack | train |
1d01d2a774dd56d32b587ed1 | train | function | def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
"""Verifies the node info.
@type what: C{dict}
@param what: a dictionary of things to check
@type vm_capable: boolean
@param vm_capable: whether or not this node is vm capable
@type result: dict
@param result: dictionary of verification results... | def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
| """Verifies the node info.
@type what: C{dict}
@param what: a dictionary of things to check
@type vm_capable: boolean
@param vm_capable: whether or not this node is vm capable
@type result: dict
@param result: dictionary of verification results; results of the
verifications in this function will be a... | [constants.NV_INSTANCELIST],
all_hvparams=all_hvparams)
except RPCFail as err:
val = str(err)
result[constants.NV_INSTANCELIST] = val
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
| 64 | 64 | 212 | 19 | 44 | jfut/ganeti | lib/backend.py | Python | _VerifyNodeInfo | _VerifyNodeInfo | 927 | 945 | 927 | 927 | 896a3241accfc0b4165278d809d617cee7f190c0 | bigcode/the-stack | train |
447c3e0f89e52d6be1b13a1b | train | function | def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
"""Creates a new X509 certificate for SSL/TLS.
@type validity: int
@param validity: Validity in seconds
@rtype: tuple; (string, string)
@return: Certificate name and public part
"""
serial_no = int(time.time())
(key_pem, cert_pe... | def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
| """Creates a new X509 certificate for SSL/TLS.
@type validity: int
@param validity: Validity in seconds
@rtype: tuple; (string, string)
@return: Certificate name and public part
"""
serial_no = int(time.time())
(key_pem, cert_pem) = \
utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName()... | """Returns the full paths for the private key and certificate.
"""
return (utils.PathJoin(cryptodir, name),
utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
| 81 | 81 | 273 | 19 | 62 | jfut/ganeti | lib/backend.py | Python | CreateX509Certificate | CreateX509Certificate | 5,102 | 5,132 | 5,102 | 5,102 | c054da2bf0068719cb954df6a0f42c2da24d39f1 | bigcode/the-stack | train |
7838f9345194c355e4da0dfb | train | function | def _InstanceLogName(kind, os_name, instance, component):
"""Compute the OS log filename for a given instance and operation.
The instance name and os name are passed in as strings since not all
operations have these as part of an instance object.
@type kind: string
@param kind: the operation type (e.g. add,... | def _InstanceLogName(kind, os_name, instance, component):
| """Compute the OS log filename for a given instance and operation.
The instance name and os name are passed in as strings since not all
operations have these as part of an instance object.
@type kind: string
@param kind: the operation type (e.g. add, import, etc.)
@type os_name: string
@param os_name: t... | Dict(pnode)
group = objects.NodeGroup.FromDict(group)
h = get_hv_fn(instance.hypervisor)
output[inst_name] = h.GetInstanceConsole(instance, pnode, group,
hvparams, beparams).ToDict()
return output
def _InstanceLogName(kind, os_name, instance, component):
| 71 | 71 | 239 | 14 | 56 | jfut/ganeti | lib/backend.py | Python | _InstanceLogName | _InstanceLogName | 2,677 | 2,702 | 2,677 | 2,677 | 4b6839326091cb79dbae4b7eb571297370034d0c | bigcode/the-stack | train |
5b0e9d5875b981074a75b52a | train | function | def OSCoreEnv(os_name, inst_os, os_params, debug=0):
"""Calculate the basic environment for an os script.
@type os_name: str
@param os_name: full operating system name (including variant)
@type inst_os: L{objects.OS}
@param inst_os: operating system for which the environment is being built
@type os_params:... | def OSCoreEnv(os_name, inst_os, os_params, debug=0):
| """Calculate the basic environment for an os script.
@type os_name: str
@param os_name: full operating system name (including variant)
@type inst_os: L{objects.OS}
@param inst_os: operating system for which the environment is being built
@type os_params: dict
@param os_params: the OS parameters
@type d... | directory containing OS installations.
Defaults to a search in all the OS_SEARCH_PATH dirs.
@rtype: L{objects.OS}
@return: the OS instance if we find a valid one
@raise RPCFail: if we don't find a valid OS
"""
name_only = objects.OS.GetName(name)
status, payload = _TryOSFromDisk(name_... | 114 | 114 | 381 | 17 | 96 | jfut/ganeti | lib/backend.py | Python | OSCoreEnv | OSCoreEnv | 4,230 | 4,272 | 4,230 | 4,230 | f46d1e9750a4d2199a177c893bef6fad7b2fa823 | bigcode/the-stack | train |
08de22c8cd6387ffa8f74732 | train | function | def BlockdevWipe(disk, offset, size):
"""Wipes a block device.
@type disk: L{objects.Disk}
@param disk: the disk object we want to wipe
@type offset: int
@param offset: The offset in MiB in the file
@type size: int
@param size: The size in MiB to write
"""
try:
rdev = _RecursiveFindBD(disk)
ex... | def BlockdevWipe(disk, offset, size):
| """Wipes a block device.
@type disk: L{objects.Disk}
@param disk: the disk object we want to wipe
@type offset: int
@param offset: The offset in MiB in the file
@type size: int
@param size: The size in MiB to write
"""
try:
rdev = _RecursiveFindBD(disk)
except errors.BlockDeviceError:
rdev... | (src_cmd),
utils.ShellQuoteArgs(dest_cmd))
result = utils.RunCmd(command)
if result.failed:
_Fail("Disk conversion command '%s' exited with error: %s; output: %s",
result.cmd, result.fail_reason, result.output)
def BlockdevWipe(disk, offset, size):
| 70 | 70 | 234 | 12 | 58 | jfut/ganeti | lib/backend.py | Python | BlockdevWipe | BlockdevWipe | 3,453 | 3,480 | 3,453 | 3,453 | 647a3f8d184d40452e98d2bc5b1b84cc9b9faa80 | bigcode/the-stack | train |
0e9f771de8647470aa747e09 | train | function | def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
"""Returns symlink path for block device.
"""
if _dir is None:
_dir = pathutils.DISK_LINKS_DIR
return utils.PathJoin(_dir,
("%s%s%s" %
(instance_name, constants.DISK_SEPARATOR, idx)))
| def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
| """Returns symlink path for block device.
"""
if _dir is None:
_dir = pathutils.DISK_LINKS_DIR
return utils.PathJoin(_dir,
("%s%s%s" %
(instance_name, constants.DISK_SEPARATOR, idx)))
| .TailFile(logfile, lines=20)]
_Fail("OS rename script failed (%s), last lines in the"
" log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
| 64 | 64 | 75 | 17 | 47 | jfut/ganeti | lib/backend.py | Python | _GetBlockDevSymlinkPath | _GetBlockDevSymlinkPath | 2,770 | 2,779 | 2,770 | 2,770 | 23834b7b60490e9182257630afb8899cd1b9494c | bigcode/the-stack | train |
31bf3f9fbfbb52ce1b0d9938 | train | function | def _BuildUploadFileList():
"""Build the list of allowed upload files.
This is abstracted so that it's built only once at module import time.
"""
allowed_files = set([
pathutils.CLUSTER_CONF_FILE,
pathutils.ETC_HOSTS,
pathutils.SSH_KNOWN_HOSTS_FILE,
pathutils.VNC_PASSWORD_FILE,
pathutils.R... | def _BuildUploadFileList():
| """Build the list of allowed upload files.
This is abstracted so that it's built only once at module import time.
"""
allowed_files = set([
pathutils.CLUSTER_CONF_FILE,
pathutils.ETC_HOSTS,
pathutils.SSH_KNOWN_HOSTS_FILE,
pathutils.VNC_PASSWORD_FILE,
pathutils.RAPI_CERT_FILE,
pathutils... | for rel_name in utils.ListVisibleFiles(path):
full_name = utils.PathJoin(path, rel_name)
if full_name in exclude:
continue
if os.path.isfile(full_name) and not os.path.islink(full_name):
utils.RemoveFile(full_name)
def _BuildUploadFileList():
| 64 | 64 | 208 | 7 | 57 | jfut/ganeti | lib/backend.py | Python | _BuildUploadFileList | _BuildUploadFileList | 264 | 290 | 264 | 264 | 3dd39db6d9e7295d40aead15c45ff53f588a9bba | bigcode/the-stack | train |
731f3f222e32a440a53981a2 | train | function | def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
"""Creates a block device for an instance.
@type disk: L{objects.Disk}
@param disk: the object describing the disk we should create
@type size: int
@param size: the size of the physical underlying device, in MiB
@type owner: str
@param o... | def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
| """Creates a block device for an instance.
@type disk: L{objects.Disk}
@param disk: the object describing the disk we should create
@type size: int
@param size: the size of the physical underlying device, in MiB
@type owner: str
@param owner: the name of the instance for which disk is created,
used... | The daemon must be enabled during at configuration time.
@type metadata: dict
@param metadata: instance metadata obtained by calling
L{objects.Instance.ToDict} on an instance object
"""
if not constants.ENABLE_METAD:
raise errors.ProgrammerError("The metadata deamon is disabled, yet"
... | 171 | 171 | 571 | 20 | 151 | jfut/ganeti | lib/backend.py | Python | BlockdevCreate | BlockdevCreate | 3,257 | 3,319 | 3,257 | 3,257 | 0df111994f9732e9618c71d3bf5247cc2ae8c09f | bigcode/the-stack | train |
b8b53239135d99ff98318d3a | train | function | def _VerifySshClutter(node_status_list, my_name):
"""Verifies that the 'authorized_keys' files are not cluttered up.
@type node_status_list: list of tuples
@param node_status_list: list of nodes of the cluster associated with a
couple of flags: (uuid, name, is_master_candidate,
is_potential_master_candid... | def _VerifySshClutter(node_status_list, my_name):
| """Verifies that the 'authorized_keys' files are not cluttered up.
@type node_status_list: list of tuples
@param node_status_list: list of nodes of the cluster associated with a
couple of flags: (uuid, name, is_master_candidate,
is_potential_master_candidate, online)
@type my_name: str
@param my_name... | "
% (name, uuid, my_name))
if name == my_name and not ssh.HasAuthorizedKey(auth_key_file, key):
result.append("A SSH key of normal node '%s' (UUID: '%s') is not"
" in the 'authorized_keys' file of itself."
% (my_name, uuid))
re... | 89 | 89 | 298 | 14 | 74 | jfut/ganeti | lib/backend.py | Python | _VerifySshClutter | _VerifySshClutter | 1,085 | 1,111 | 1,085 | 1,085 | a6ea8443dab133e31699eda3be0dcb3e25cdf452 | bigcode/the-stack | train |
83a496559c7d42593f0be2e1 | train | function | def _GenerateNodeSshKey(node_uuid, node_name, ssh_port_map, ssh_key_type,
ssh_key_bits, pub_key_file=pathutils.SSH_PUB_KEYS,
ssconf_store=None,
noded_cert_file=pathutils.NODED_CERT_FILE,
run_cmd_fn=ssh.RunSshCmdWithStdin,
... | def _GenerateNodeSshKey(node_uuid, node_name, ssh_port_map, ssh_key_type,
ssh_key_bits, pub_key_file=pathutils.SSH_PUB_KEYS,
ssconf_store=None,
noded_cert_file=pathutils.NODED_CERT_FILE,
run_cmd_fn=ssh.RunSshCmdWithStdin,
... | """Generates the root SSH key pair on the node.
@type node_uuid: str
@param node_uuid: UUID of the node whose key is removed
@type node_name: str
@param node_name: name of the node whose key is remove
@type ssh_port_map: dict of str to int
@param ssh_port_map: mapping of node names to their SSH port
@t... | s" % (node_info.name, last_exception))))
if all_keys_to_remove and from_public_keys:
for node_uuid in nodes_remove_from_public_keys:
ssh.RemovePublicKey(node_uuid, key_file=pub_key_file)
return result_msgs
def _GenerateNodeSshKey(node_uuid, node_name, ssh_port_map, ssh_key_type,
... | 128 | 128 | 428 | 75 | 52 | jfut/ganeti | lib/backend.py | Python | _GenerateNodeSshKey | _GenerateNodeSshKey | 1,991 | 2,028 | 1,991 | 1,996 | 2c879ff07b5d404eb04e2b4eb1369f15335ab9cf | bigcode/the-stack | train |
3aba577d7aa772e52b930b3d | train | class | class IAllocatorRunner(object):
"""IAllocator runner.
This class is instantiated on the node side (ganeti-noded) and not on
the master side.
"""
@staticmethod
def Run(name, idata, ial_params):
"""Run an iallocator script.
@type name: str
@param name: the iallocator script name
@type idata... | class IAllocatorRunner(object):
| """IAllocator runner.
This class is instantiated on the node side (ganeti-noded) and not on
the master side.
"""
@staticmethod
def Run(name, idata, ial_params):
"""Run an iallocator script.
@type name: str
@param name: the iallocator script name
@type idata: str
@param idata: the allo... | error: %s" % runresult
elif relstatus == constants.RUNPARTS_RUN:
if runresult.failed:
rrval = constants.HKR_FAIL
else:
rrval = constants.HKR_SUCCESS
output = utils.SafeEncode(runresult.output.strip())
results.append(("%s/%s" % (subdir, relname), rrval, output))
... | 90 | 90 | 302 | 6 | 83 | jfut/ganeti | lib/backend.py | Python | IAllocatorRunner | IAllocatorRunner | 6,002 | 6,042 | 6,002 | 6,002 | 978141c5e375fbff1fac41ee53c7122cfac8a517 | bigcode/the-stack | train |
c50d56effeed379c498d584e | train | function | def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
"""Rename the file storage directory.
@type old_file_storage_dir: str
@param old_file_storage_dir: the current path
@type new_file_storage_dir: str
@param new_file_storage_dir: the name we should rename to
@rtype: tuple (success,)
@ret... | def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
| """Rename the file storage directory.
@type old_file_storage_dir: str
@param old_file_storage_dir: the current path
@type new_file_storage_dir: str
@param new_file_storage_dir: the name we should rename to
@rtype: tuple (success,)
@return: tuple of one element, C{success}, denoting
whether the oper... | not a directory",
file_storage_dir)
# deletes dir only if empty, otherwise we want to fail the rpc call
try:
os.rmdir(file_storage_dir)
except OSError as err:
_Fail("Cannot remove file storage directory '%s': %s",
file_storage_dir, err)
def RenameFileStorageDir(old_file_... | 81 | 81 | 273 | 15 | 66 | jfut/ganeti | lib/backend.py | Python | RenameFileStorageDir | RenameFileStorageDir | 4,747 | 4,774 | 4,747 | 4,747 | d994dedbad3e03a96c4b44b82e4d24b92a61c998 | bigcode/the-stack | train |
8d767b104460752fb4a18d10 | train | function | def GetInstanceList(hypervisor_list, all_hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
"""Provides a list of instances.
@type hypervisor_list: list
@param hypervisor_list: the list of hypervisors to query information
@type all_hvparams: dict of dict of strings
@param all_hvparams: a... | def GetInstanceList(hypervisor_list, all_hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
| """Provides a list of instances.
@type hypervisor_list: list
@param hypervisor_list: the list of hypervisors to query information
@type all_hvparams: dict of dict of strings
@param all_hvparams: a dictionary mapping hypervisor types to respective
cluster-wide hypervisor parameters
@type get_hv_fn: func... | vparams=hvparams)
except errors.HypervisorError as err:
_Fail("Error enumerating instances (hypervisor %s): %s",
hname, err, exc=True)
def GetInstanceList(hypervisor_list, all_hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
| 69 | 69 | 232 | 27 | 42 | jfut/ganeti | lib/backend.py | Python | GetInstanceList | GetInstanceList | 2,497 | 2,521 | 2,497 | 2,498 | 81edb914422bf5a35949850a6e309d1bae59ec94 | bigcode/the-stack | train |
5aab2e7ba59c1fc6b73755fa | train | function | def BlockdevPauseResumeSync(disks, pause):
"""Pause or resume the sync of the block device.
@type disks: list of L{objects.Disk}
@param disks: the disks object we want to pause/resume
@type pause: bool
@param pause: Wheater to pause or resume
"""
success = []
for disk in disks:
try:
rdev = _... | def BlockdevPauseResumeSync(disks, pause):
| """Pause or resume the sync of the block device.
@type disks: list of L{objects.Disk}
@param disks: the disks object we want to pause/resume
@type pause: bool
@param pause: Wheater to pause or resume
"""
success = []
for disk in disks:
try:
rdev = _RecursiveFindBD(disk)
except errors.Blo... | Fail("Image size is bigger than device size")
if utils.IsUrl(image):
_DownloadAndDumpDevice(image, rdev.dev_path, size)
else:
_DumpDevice(image, rdev.dev_path, 0, size, False)
def BlockdevPauseResumeSync(disks, pause):
| 64 | 64 | 216 | 11 | 53 | jfut/ganeti | lib/backend.py | Python | BlockdevPauseResumeSync | BlockdevPauseResumeSync | 3,522 | 3,554 | 3,522 | 3,522 | c891a7a1cb905ee67e4f66bfbbe0e131f1d18b62 | bigcode/the-stack | train |
f692e95a7d05d7b3d98c00d6 | train | function | def VerifyMasterIP(my_name, test_config):
"""Verify master IP is reachable.
@type my_name: string
@param my_name: name of the node this test is running on
@type test_config: tuple (master_name, master_up, master_candidates)
@param test_config: configuration for test as passed from
LUClusterVerify() in... | def VerifyMasterIP(my_name, test_config):
| """Verify master IP is reachable.
@type my_name: string
@param my_name: name of the node this test is running on
@type test_config: tuple (master_name, master_up, master_candidates)
@param test_config: configuration for test as passed from
LUClusterVerify() in what[constants.NV_MASTERIP]
@rtype: bo... | if not netutils.TcpPing(sip, port, source=my_sip):
fail.append("secondary")
if fail:
result[name] = ("failure using the %s interface(s)" %
" and ".join(fail))
return result
def VerifyMasterIP(my_name, test_config):
| 64 | 64 | 188 | 10 | 53 | jfut/ganeti | lib/backend.py | Python | VerifyMasterIP | VerifyMasterIP | 1,157 | 1,179 | 1,157 | 1,157 | b15b5e690fa5289092a6f16699f2f5e914d773af | bigcode/the-stack | train |
c3e87744af2c6e8167462f2b | train | function | def _InitSshUpdateData(data, noded_cert_file, ssconf_store):
(_, noded_cert) = \
utils.ExtractX509Certificate(utils.ReadFile(noded_cert_file))
data[constants.SSHS_NODE_DAEMON_CERTIFICATE] = noded_cert
cluster_name = ssconf_store.GetClusterName()
data[constants.SSHS_CLUSTER_NAME] = cluster_name
| def _InitSshUpdateData(data, noded_cert_file, ssconf_store):
| (_, noded_cert) = \
utils.ExtractX509Certificate(utils.ReadFile(noded_cert_file))
data[constants.SSHS_NODE_DAEMON_CERTIFICATE] = noded_cert
cluster_name = ssconf_store.GetClusterName()
data[constants.SSHS_CLUSTER_NAME] = cluster_name
| if daemon_name not in allowed_daemons:
fn = lambda _: False
elif run:
fn = utils.EnsureDaemon
else:
fn = utils.StopDaemon
return fn(daemon_name)
def _InitSshUpdateData(data, noded_cert_file, ssconf_store):
| 64 | 64 | 85 | 18 | 46 | jfut/ganeti | lib/backend.py | Python | _InitSshUpdateData | _InitSshUpdateData | 1,455 | 1,461 | 1,455 | 1,455 | 315499c45038cc44c151a52ecc48348ebcd95c81 | bigcode/the-stack | train |
e4ef9326a994064ca021b2a9 | train | function | def _DumpDevice(source_path, target_path, offset, size, truncate):
"""This function images/wipes the device using a local file.
@type source_path: string
@param source_path: path of the image or data source (e.g., "/dev/zero")
@type target_path: string
@param target_path: path of the device to image/wipe
... | def _DumpDevice(source_path, target_path, offset, size, truncate):
| """This function images/wipes the device using a local file.
@type source_path: string
@param source_path: path of the image or data source (e.g., "/dev/zero")
@type target_path: string
@param target_path: path of the device to image/wipe
@type offset: int
@param offset: offset in MiB in the output fil... | unusual event: %s", err)
if on_primary or disk.OpenOnSecondary():
try:
device.Open(force=True)
except errors.BlockDeviceError as err:
_Fail("Can't make device r/w after creation, unusual event: %s", err)
DevCacheManager.UpdateCache(device.dev_path, owner,
... | 104 | 104 | 348 | 16 | 87 | jfut/ganeti | lib/backend.py | Python | _DumpDevice | _DumpDevice | 3,322 | 3,360 | 3,322 | 3,322 | 6b686cb82c188100ebe77a9306dcea3d71c90e3d | bigcode/the-stack | train |
d6bfc54ae3fe1dd5ee4697d0 | train | function | def GetDrbdUsermodeHelper():
"""Returns DRBD usermode helper currently configured.
"""
try:
return drbd.DRBD8.GetUsermodeHelper()
except errors.BlockDeviceError as err:
_Fail(str(err))
| def GetDrbdUsermodeHelper():
| """Returns DRBD usermode helper currently configured.
"""
try:
return drbd.DRBD8.GetUsermodeHelper()
except errors.BlockDeviceError as err:
_Fail(str(err))
| rd is None:
faulty_disks.append(disk)
continue
stats = rd.GetProcStatus()
if stats.is_standalone or stats.is_diskless:
faulty_disks.append(disk)
return [disk.uuid for disk in faulty_disks]
def GetDrbdUsermodeHelper():
| 64 | 64 | 52 | 8 | 56 | jfut/ganeti | lib/backend.py | Python | GetDrbdUsermodeHelper | GetDrbdUsermodeHelper | 5,619 | 5,626 | 5,619 | 5,619 | b1834645d42f373fc54b48a78771344531af86a6 | bigcode/the-stack | train |
066a9cf2fe3fa49dda11658a | train | function | def _CheckOSVariant(os_obj, name):
"""Check whether an OS name conforms to the os variants specification.
@type os_obj: L{objects.OS}
@param os_obj: OS object to check
@type name: string
@param name: OS name passed by the user, to check for validity
@rtype: NoneType
@return: None
@raise RPCFail: if O... | def _CheckOSVariant(os_obj, name):
| """Check whether an OS name conforms to the os variants specification.
@type os_obj: L{objects.OS}
@param os_obj: OS object to check
@type name: string
@param name: OS name passed by the user, to check for validity
@rtype: NoneType
@return: None
@raise RPCFail: if OS variant is not valid
"""
var... | ed_parameters]
delta = frozenset(parameters).difference(supported)
if delta:
_Fail("The following parameters are not supported"
" by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
def _CheckOSVariant(os_obj, name):
| 63 | 64 | 211 | 10 | 53 | jfut/ganeti | lib/backend.py | Python | _CheckOSVariant | _CheckOSVariant | 4,933 | 4,960 | 4,933 | 4,933 | 23baa47bc29f1464de2b11464c0a30bc6eaddbe1 | bigcode/the-stack | train |
f80b01b7a3503c0821f37a08 | train | function | def AcceptInstance(instance, info, target):
"""Prepare the node to accept an instance.
@type instance: L{objects.Instance}
@param instance: the instance definition
@type info: string/data (opaque)
@param info: migration information, from the source node
@type target: string
@param target: target host (us... | def AcceptInstance(instance, info, target):
| """Prepare the node to accept an instance.
@type instance: L{objects.Instance}
@param instance: the instance definition
@type info: string/data (opaque)
@param info: migration information, from the source node
@type target: string
@param target: target host (usually ip), on this node
"""
hyper = hyp... | hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
info = hyper.MigrationInfo(instance)
except errors.HypervisorError as err:
_Fail("Failed to fetch migration information: %s", err, exc=True)
return info
def AcceptInstance(instance, info, target):
| 64 | 64 | 137 | 9 | 54 | jfut/ganeti | lib/backend.py | Python | AcceptInstance | AcceptInstance | 3,084 | 3,099 | 3,084 | 3,084 | 46af9b278ba3c2cf8afcfb57f4d2a22faabfc550 | bigcode/the-stack | train |
e728c7735b40ecc69ea67777 | train | function | def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
"""Creates or removes the watcher pause file.
@type until: None or number
@param until: Unix timestamp saying until when the watcher shouldn't run
"""
if until is None:
logging.info("Received request to no longer pause watcher")
util... | def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
| """Creates or removes the watcher pause file.
@type until: None or number
@param until: Unix timestamp saying until when the watcher shouldn't run
"""
if until is None:
logging.info("Received request to no longer pause watcher")
utils.RemoveFile(_filename)
else:
logging.info("Received request ... | , cmdresult.fail_reason, cmdresult.output)
else:
return cmdresult.output
finally:
if lock is not None:
# Release lock at last
lock.Close()
lock = None
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
| 64 | 64 | 139 | 19 | 44 | jfut/ganeti | lib/backend.py | Python | SetWatcherPause | SetWatcherPause | 5,837 | 5,853 | 5,837 | 5,837 | 2fb820c498e81a4723cbebf354b9feb0f2534a48 | bigcode/the-stack | train |
9cbbea95ab74677382902c60 | train | function | def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
"""Retrieves node information for all hypervisors.
See C{_GetHvInfo} for information on the output.
@type hv_specs: list of pairs (string, dict of strings)
@param hv_specs: list of pairs of a hypervisor's name and its hvparams
"""
if hv_spe... | def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
| """Retrieves node information for all hypervisors.
See C{_GetHvInfo} for information on the output.
@type hv_specs: list of pairs (string, dict of strings)
@param hv_specs: list of pairs of a hypervisor's name and its hvparams
"""
if hv_specs is None:
return None
result = []
for hvname, hvparams... | @type hvparams: dict of string
@param hvparams: the hypervisor's hvparams
"""
return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
| 64 | 64 | 135 | 21 | 43 | jfut/ganeti | lib/backend.py | Python | _GetHvInfoAll | _GetHvInfoAll | 716 | 731 | 716 | 716 | 1371c74e68ce5733cc1db0be1bbc8f4fd6bc1bd5 | bigcode/the-stack | train |
26730a8d3d7c0b1e6b9080e7 | train | function | def ValidateOS(required, osname, checks, osparams, force_variant):
"""Validate the given OS parameters.
@type required: boolean
@param required: whether absence of the OS should translate into
failure or not
@type osname: string
@param osname: the OS to be validated
@type checks: list
@param checks... | def ValidateOS(required, osname, checks, osparams, force_variant):
| """Validate the given OS parameters.
@type required: boolean
@param required: whether absence of the OS should translate into
failure or not
@type osname: string
@param osname: the OS to be validated
@type checks: list
@param checks: list of the checks to run (currently only 'parameters')
@type o... | objects.OS.GetVariant(name)
if not os_obj.supported_variants:
if variant:
_Fail("OS '%s' does not support variants ('%s' passed)" %
(os_obj.name, variant))
else:
return
if not variant:
_Fail("OS name '%s' must include a variant" % name)
if variant not in os_obj.supported_va... | 126 | 126 | 423 | 16 | 110 | jfut/ganeti | lib/backend.py | Python | ValidateOS | ValidateOS | 4,963 | 5,012 | 4,963 | 4,963 | be889292ecb870c33e51de04ab9cd90fdb92fb96 | bigcode/the-stack | train |
4ed317302329c7d56a84b9d1 | train | function | def _DownloadAndDumpDevice(source_url, target_path, size):
"""This function images a device using a downloaded image file.
@type source_url: string
@param source_url: URL of image to dump to disk
@type target_path: string
@param target_path: path of the device to image
@type size: int
@param size: maxi... | def _DownloadAndDumpDevice(source_url, target_path, size):
| """This function images a device using a downloaded image file.
@type source_url: string
@param source_url: URL of image to dump to disk
@type target_path: string
@param target_path: path of the device to image
@type size: int
@param size: maximum size in MiB to write (data source might be smaller)
... | =%d" % offset,
"bs=%s" % block_size, "oflag=direct", "of=%s" % target_path,
"count=%d" % size]
if not truncate:
cmd.append("conv=notrunc")
result = utils.RunCmd(cmd)
if result.failed:
_Fail("Dump command '%s' exited with error: %s; output: %s", result.cmd,
result.fail_reason... | 114 | 114 | 380 | 14 | 100 | jfut/ganeti | lib/backend.py | Python | _DownloadAndDumpDevice | _DownloadAndDumpDevice | 3,363 | 3,412 | 3,363 | 3,363 | 67c222c11fc3c7d061013eede451e212a4386a5d | bigcode/the-stack | train |
2719ef1f12675752f4225a5a | train | function | def GetVolumeList(vg_names):
"""Compute list of logical volumes and their size.
@type vg_names: list
@param vg_names: the volume groups whose LVs we should list, or
empty for all volume groups
@rtype: dict
@return:
dictionary of all partions (key) with value being a tuple of
their size (in ... | def GetVolumeList(vg_names):
| """Compute list of logical volumes and their size.
@type vg_names: list
@param vg_names: the volume groups whose LVs we should list, or
empty for all volume groups
@rtype: dict
@return:
dictionary of all partions (key) with value being a tuple of
their size (in MiB), inactive and online sta... | if stat.S_ISBLK(st.st_mode):
result = utils.RunCmd(["blockdev", "--getsize64", devpath])
if result.failed:
# We don't want to fail, just do not list this device as available
logging.warning("Cannot get size for block device %s", devpath)
continue
size = int(result.stdout) ... | 111 | 111 | 372 | 8 | 102 | jfut/ganeti | lib/backend.py | Python | GetVolumeList | GetVolumeList | 2,353 | 2,396 | 2,353 | 2,353 | 73030f065da217a387e510d804fa8bfe52febbb6 | bigcode/the-stack | train |
5d5d517bfa153bf42de365e3 | train | function | 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, whic... | 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 nam... | return _DiskSnapshot(disk, snap_name, snap_size)
else:
_Fail("Cannot snapshot block device '%s' of type '%s'",
disk.logical_id, disk.dev_type)
def BlockdevSetInfo(disk, info):
"""Sets 'metadata' information on block devices.
This function sets 'info' metadata on block devices. Initial
informat... | 256 | 256 | 1,043 | 10 | 246 | jfut/ganeti | lib/backend.py | Python | FinalizeExport | FinalizeExport | 4,492 | 4,586 | 4,492 | 4,492 | 4962a2f7dd2c0bc083ed5f5f8d34bd27fc39c235 | bigcode/the-stack | train |
3d08994b48214e9dce268b79 | train | function | def DrbdAttachNet(disks, multimaster):
"""Attaches the network on a list of drbd devices.
"""
bdevs = _FindDisks(disks)
# reconnect disks, switch to new master configuration and if
# needed primary mode
for rd in bdevs:
try:
rd.AttachNet(multimaster)
except errors.BlockDeviceError as err:
... | def DrbdAttachNet(disks, multimaster):
| """Attaches the network on a list of drbd devices.
"""
bdevs = _FindDisks(disks)
# reconnect disks, switch to new master configuration and if
# needed primary mode
for rd in bdevs:
try:
rd.AttachNet(multimaster)
except errors.BlockDeviceError as err:
_Fail("Can't change network configu... | """
bdevs = []
for disk in disks:
rd = _RecursiveFindBD(disk)
if rd is None:
_Fail("Can't find device %s", disk)
bdevs.append(rd)
return bdevs
def DrbdDisconnectNet(disks):
"""Disconnects the network on a list of drbd devices.
"""
bdevs = _FindDisks(disks)
# disconnect disks
for ... | 153 | 153 | 513 | 11 | 142 | jfut/ganeti | lib/backend.py | Python | DrbdAttachNet | DrbdAttachNet | 5,510 | 5,567 | 5,510 | 5,510 | cce4107c49d62fa8d9be7bb7584c01d2c1fcb6ab | bigcode/the-stack | train |
612935a13ae08e48650f96fc | train | function | def InstanceOsAdd(instance, reinstall, debug):
"""Add an OS to an instance.
@type instance: L{objects.Instance}
@param instance: Instance whose OS is to be installed
@type reinstall: boolean
@param reinstall: whether this is an instance reinstall
@type debug: integer
@param debug: debug level, passed to ... | def InstanceOsAdd(instance, reinstall, debug):
| """Add an OS to an instance.
@type instance: L{objects.Instance}
@param instance: Instance whose OS is to be installed
@type reinstall: boolean
@param reinstall: whether this is an instance reinstall
@type debug: integer
@param debug: debug level, passed to the OS scripts
@rtype: None
"""
inst_os ... |
if component:
assert "/" not in component
c_msg = "-%s" % component
else:
c_msg = ""
base = ("%s-%s-%s%s-%s.log" %
(kind, os_name, instance, c_msg, utils.TimestampForFilename()))
return utils.PathJoin(pathutils.LOG_OS_DIR, base)
def InstanceOsAdd(instance, reinstall, debug):
| 86 | 86 | 288 | 10 | 76 | jfut/ganeti | lib/backend.py | Python | InstanceOsAdd | InstanceOsAdd | 2,705 | 2,734 | 2,705 | 2,705 | 5cf5e94082ab88c248f684523777c5e725a8bcac | bigcode/the-stack | train |
4ca36fdab34359b160513104 | train | function | def _RecursiveFindBD(disk, lvs_cache=None):
"""Check if a device is activated.
If so, return information about the real device.
@type disk: L{objects.Disk}
@param disk: the disk object we need to find
@return: None if the device can't be found,
otherwise the device instance
"""
children = []
i... | def _RecursiveFindBD(disk, lvs_cache=None):
| """Check if a device is activated.
If so, return information about the real device.
@type disk: L{objects.Disk}
@param disk: the disk object we need to find
@return: None if the device can't be found,
otherwise the device instance
"""
children = []
if disk.children:
for chdisk in disk.chil... | is a plain disk type
"""
if disk.dev_type == constants.DT_PLAIN:
return True
if disk.children:
return compat.any([_CheckForPlainDisk(d) for d in disk.children])
return False
def _RecursiveFindBD(disk, lvs_cache=None):
| 64 | 64 | 129 | 13 | 50 | jfut/ganeti | lib/backend.py | Python | _RecursiveFindBD | _RecursiveFindBD | 3,847 | 3,864 | 3,847 | 3,847 | cf39819d6a18b014d0b34f0c22f1c4a481874635 | bigcode/the-stack | train |
7d9d118a1d780c6f1a00d916 | train | function | def _GetMasterNodeUUID(node_uuid_name_map, master_node_name):
master_node_uuids = [node_uuid for (node_uuid, node_name)
in node_uuid_name_map
if node_name == master_node_name]
if len(master_node_uuids) != 1:
raise errors.SshUpdateError("No (unique) master UUID found... | def _GetMasterNodeUUID(node_uuid_name_map, master_node_name):
| master_node_uuids = [node_uuid for (node_uuid, node_name)
in node_uuid_name_map
if node_name == master_node_name]
if len(master_node_uuids) != 1:
raise errors.SshUpdateError("No (unique) master UUID found. Master node"
" name: '%s', M... | )
run_cmd_fn(cluster_name, node_name, pathutils.SSH_UPDATE,
ssh_port_map.get(node_name), data,
debug=False, verbose=False, use_cluster_key=False,
ask_key=False, strict_host_check=False)
def _GetMasterNodeUUID(node_uuid_name_map, master_node_name):
| 64 | 64 | 117 | 15 | 49 | jfut/ganeti | lib/backend.py | Python | _GetMasterNodeUUID | _GetMasterNodeUUID | 2,031 | 2,039 | 2,031 | 2,031 | 28ae89f5b72f06efa7051b1c22d23c729be021b4 | bigcode/the-stack | train |
54157f0ff700f3b9c89008f4 | train | function | def BlockdevRename(devlist):
"""Rename a list of block devices.
@type devlist: list of tuples
@param devlist: list of tuples of the form (disk, new_unique_id); disk is
an L{objects.Disk} object describing the current disk, and new
unique_id is the name we rename it to
@rtype: boolean
@return: Tr... | def BlockdevRename(devlist):
| """Rename a list of block devices.
@type devlist: list of tuples
@param devlist: list of tuples of the form (disk, new_unique_id); disk is
an L{objects.Disk} object describing the current disk, and new
unique_id is the name we rename it to
@rtype: boolean
@return: True if all renames succeeded, ... | _Fail("No exports directory")
def RemoveExport(export):
"""Remove an existing export from the node.
@type export: str
@param export: the name of the export to remove
@rtype: None
"""
target = utils.PathJoin(pathutils.EXPORT_DIR, export)
try:
shutil.rmtree(target)
except EnvironmentError as ... | 106 | 106 | 355 | 7 | 99 | jfut/ganeti | lib/backend.py | Python | BlockdevRename | BlockdevRename | 4,641 | 4,677 | 4,641 | 4,641 | 624535ad68c470f36745d5fcd84a3944aca172be | bigcode/the-stack | train |
92e01e20d1b5e9b5752d4f43 | train | function | def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
"""Retrieves node information from a hypervisor.
The information returned depends on the hypervisor. Common items:
- vg_size is the size of the configured volume group in MiB
- vg_free is the free size of the volume group in MiB
- mem... | def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
| """Retrieves node information from a hypervisor.
The information returned depends on the hypervisor. Common items:
- vg_size is the size of the configured volume group in MiB
- vg_free is the free size of the volume group in MiB
- memory_dom0 is the memory allocated for domain0 in MiB
- memory_fre... | _size = 0
return {
"type": constants.ST_LVM_PV,
"name": name,
"storage_free": vg_free,
"storage_size": vg_size,
}
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
| 64 | 64 | 179 | 21 | 43 | jfut/ganeti | lib/backend.py | Python | _GetHvInfo | _GetHvInfo | 697 | 713 | 697 | 697 | 3620a6ff1fdf50392ec55dc62381b2a90d2f4f0c | bigcode/the-stack | train |
3f5eb7c4db16bbc9a1ea77fa | train | function | def MigrateInstance(cluster_name, instance, target, live):
"""Migrates an instance to another node.
@type cluster_name: string
@param cluster_name: name of the cluster
@type instance: L{objects.Instance}
@param instance: the instance definition
@type target: string
@param target: the target node name
@... | def MigrateInstance(cluster_name, instance, target, live):
| """Migrates an instance to another node.
@type cluster_name: string
@param cluster_name: name of the cluster
@type instance: L{objects.Instance}
@param instance: the instance definition
@type target: string
@param target: the target node name
@type live: boolean
@param live: whether the migration sho... | visor(instance.hypervisor)
try:
hyper.FinalizeMigrationDst(instance, info, success)
except errors.HypervisorError as err:
_Fail("Failed to finalize migration on the target node: %s", err, exc=True)
def MigrateInstance(cluster_name, instance, target, live):
| 64 | 64 | 185 | 13 | 51 | jfut/ganeti | lib/backend.py | Python | MigrateInstance | MigrateInstance | 3,120 | 3,140 | 3,120 | 3,120 | d25d4af64c1c78474a6ea4a3f46f60c080b61ea8 | bigcode/the-stack | train |
f9273918e8cf59152cb6c3fb | train | function | def _GetLvmPvSpaceInfo(name, params):
"""Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
@see: C{_GetLvmVgSpaceInfo}
"""
excl_stor = _CheckLvmStorageParams(params)
return _GetVgSpindlesInfo(name, excl_stor)
| def _GetLvmPvSpaceInfo(name, params):
| """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
@see: C{_GetLvmVgSpaceInfo}
"""
excl_stor = _CheckLvmStorageParams(params)
return _GetVgSpindlesInfo(name, excl_stor)
| else:
vg_free = None
vg_size = None
return {
"type": constants.ST_LVM_VG,
"name": name,
"storage_free": vg_free,
"storage_size": vg_size,
}
def _GetLvmPvSpaceInfo(name, params):
| 64 | 64 | 77 | 12 | 52 | jfut/ganeti | lib/backend.py | Python | _GetLvmPvSpaceInfo | _GetLvmPvSpaceInfo | 661 | 668 | 661 | 661 | a4bd8041e56a85d6f27672cac9b0c99aebe18ed1 | bigcode/the-stack | train |
9cecf303cf92a8ef1e81f8e3 | train | function | def ModifyInstanceMetadata(metadata):
"""Sends instance data to the metadata daemon.
Uses the Luxi transport layer to communicate with the metadata
daemon configuration server. It starts the metadata daemon if it is
not running.
The daemon must be enabled during at configuration time.
@type metadata: dic... | def ModifyInstanceMetadata(metadata):
| """Sends instance data to the metadata daemon.
Uses the Luxi transport layer to communicate with the metadata
daemon configuration server. It starts the metadata daemon if it is
not running.
The daemon must be enabled during at configuration time.
@type metadata: dict
@param metadata: instance metadata... | Checks if hotplug is generally supported.
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
hyper.HotplugSupported(instance)
except errors.HotplugError as err:
_Fail("Hotplug is not supported: %s", err)
def ModifyInstanceMetadata(metadata):
| 64 | 64 | 200 | 6 | 58 | jfut/ganeti | lib/backend.py | Python | ModifyInstanceMetadata | ModifyInstanceMetadata | 3,231 | 3,254 | 3,231 | 3,231 | 87690adcbf0372dce6645ec7c26781e015768b4c | bigcode/the-stack | train |
5428f0aa52fd9b6372c207c4 | train | function | def _CheckForPlainDisk(disk):
"""Check within a disk and its children if there is a plain disk type.
@type disk: L{objects.Disk}
@param disk: the disk we are checking
@rtype: bool
@return: whether or not there is a plain disk type
"""
if disk.dev_type == constants.DT_PLAIN:
return True
if disk.chi... | def _CheckForPlainDisk(disk):
| """Check within a disk and its children if there is a plain disk type.
@type disk: L{objects.Disk}
@param disk: the disk we are checking
@rtype: bool
@return: whether or not there is a plain disk type
"""
if disk.dev_type == constants.DT_PLAIN:
return True
if disk.children:
return compat.any([... | Status()
except errors.BlockDeviceError as err:
logging.exception("Error while getting disk status")
result.append((False, str(err)))
else:
result.append((True, status))
assert len(disks) == len(result)
return result
def _CheckForPlainDisk(disk):
| 64 | 64 | 113 | 9 | 54 | jfut/ganeti | lib/backend.py | Python | _CheckForPlainDisk | _CheckForPlainDisk | 3,831 | 3,844 | 3,831 | 3,831 | d9dbaa110a944787c326257692b51ffa12749fd1 | bigcode/the-stack | train |
a5e2453a1d5e63f9e9ac4189 | train | function | def OSFromDisk(name, base_dir=None):
"""Create an OS instance from disk.
This function will return an OS instance if the given name is a
valid OS name. Otherwise, it will raise an appropriate
L{RPCFail} exception, detailing why this is not a valid OS.
This is just a wrapper over L{_TryOSFromDisk}, which doe... | def OSFromDisk(name, base_dir=None):
| """Create an OS instance from disk.
This function will return an OS instance if the given name is a
valid OS name. Otherwise, it will raise an appropriate
L{RPCFail} exception, detailing why this is not a valid OS.
This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
an exception but returns... | ],
rename_script=os_files[constants.OS_SCRIPT_RENAME],
verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
None),
supported_variants=variants,
supported_parameters=parameters,
... | 64 | 64 | 206 | 10 | 53 | jfut/ganeti | lib/backend.py | Python | OSFromDisk | OSFromDisk | 4,203 | 4,227 | 4,203 | 4,203 | 523699c9b31e3ff47b1aff6cbafa48bbf16ab1fa | bigcode/the-stack | train |
f3595ddaa1cdbd6e30dc986f | train | function | def MigrationInfo(instance):
"""Gather information about an instance to be migrated.
@type instance: L{objects.Instance}
@param instance: the instance definition
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
info = hyper.MigrationInfo(instance)
except errors.HypervisorError as err:
... | def MigrationInfo(instance):
| """Gather information about an instance to be migrated.
@type instance: L{objects.Instance}
@param instance: the instance definition
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
info = hyper.MigrationInfo(instance)
except errors.HypervisorError as err:
_Fail("Failed to fetch mi... | ("Instance %s is not running, cannot balloon", instance.name)
return
try:
hyper.BalloonInstanceMemory(instance, memory)
except errors.HypervisorError as err:
_Fail("Failed to balloon instance memory: %s", err, exc=True)
def MigrationInfo(instance):
| 64 | 64 | 93 | 5 | 59 | jfut/ganeti | lib/backend.py | Python | MigrationInfo | MigrationInfo | 3,069 | 3,081 | 3,069 | 3,069 | a5fb5acbbcf600020795230e1a8b3cc42baa2528 | bigcode/the-stack | train |
3559653a9b8d69c12ac001fb | train | function | @RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
_BuildMasterIpEnv)
def ActivateMasterIp(master_params, use_external_mip_script):
"""Activate the IP address of the master daemon.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of ... | @RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
_BuildMasterIpEnv)
def ActivateMasterIp(master_params, use_external_mip_script):
| """Activate the IP address of the master daemon.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of the master
@type use_external_mip_script: boolean
@param use_external_mip_script: whether to use an external master IP
address setup script
@raise RPCFail... | return value: %s, output: '%s'" %
(action, result.exit_code, result.output), log=True)
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
_BuildMasterIpEnv)
def ActivateMasterIp(master_params, use_external_mip_script):
| 64 | 64 | 144 | 38 | 26 | jfut/ganeti | lib/backend.py | Python | ActivateMasterIp | ActivateMasterIp | 409 | 423 | 409 | 411 | 139f072d1fab53b8c81c68a01d67ae02c1ba1e53 | bigcode/the-stack | train |
16c2cef0122e65f7d8a75586 | train | function | def _CommonRestrictedCmdCheck(path, owner):
"""Common checks for restricted command file system directories and files.
@type path: string
@param path: Path to check
@param owner: C{None} or tuple containing UID and GID
@rtype: tuple; (boolean, string or C{os.stat} result)
@return: The tuple's first element... | def _CommonRestrictedCmdCheck(path, owner):
| """Common checks for restricted command file system directories and files.
@type path: string
@param path: Path to check
@param owner: C{None} or tuple containing UID and GID
@rtype: tuple; (boolean, string or C{os.stat} result)
@return: The tuple's first element is the status; if C{False}, the second
... | C{None}
"""
if not cmd.strip():
return (False, "Missing command name")
if os.path.basename(cmd) != cmd:
return (False, "Invalid command name")
if not constants.EXT_PLUGIN_MASK.match(cmd):
return (False, "Command name contains forbidden characters")
return (True, None)
def _CommonRestrictedCmd... | 82 | 82 | 275 | 10 | 72 | jfut/ganeti | lib/backend.py | Python | _CommonRestrictedCmdCheck | _CommonRestrictedCmdCheck | 5,675 | 5,702 | 5,675 | 5,675 | f63c1e00e588dc4c58d854c9c70b94de16595da3 | bigcode/the-stack | train |
b5b233114505fbbc95577e7f | train | function | def GetImportExportStatus(names):
"""Returns import/export daemon status.
@type names: sequence
@param names: List of names
@rtype: List of dicts
@return: Returns a list of the state of each named import/export or None if a
status couldn't be read
"""
result = []
for name in names:
sta... | def GetImportExportStatus(names):
| """Returns import/export daemon status.
@type names: sequence
@param names: List of names
@rtype: List of dicts
@return: Returns a list of the state of each named import/export or None if a
status couldn't be read
"""
result = []
for name in names:
status_file = utils.PathJoin(pathutil... | , env=cmd_env, pidfile=pid_file,
output=logfile)
# The import/export name is simply the status directory name
return os.path.basename(status_dir)
except Exception:
shutil.rmtree(status_dir, ignore_errors=True)
raise
def GetImportExportStatus(names):
| 64 | 64 | 163 | 7 | 56 | jfut/ganeti | lib/backend.py | Python | GetImportExportStatus | GetImportExportStatus | 5,407 | 5,436 | 5,407 | 5,407 | a343869168af1148db34f1c2d8b8373d5be8f2a5 | bigcode/the-stack | train |
0066e2e048db6e76e1477d3f | train | function | def _CheckExclusivePvs(pvi_list):
"""Check that PVs are not shared among LVs
@type pvi_list: list of L{objects.LvmPvInfo} objects
@param pvi_list: information about the PVs
@rtype: list of tuples (string, list of strings)
@return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
"""
res... | def _CheckExclusivePvs(pvi_list):
| """Check that PVs are not shared among LVs
@type pvi_list: list of L{objects.LvmPvInfo} objects
@param pvi_list: information about the PVs
@rtype: list of tuples (string, list of strings)
@return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
"""
res = []
for pvi in pvi_list:
i... | Error: for storage types who don't support space
reporting yet
"""
fn = _STORAGE_TYPE_INFO_FN[storage_type]
if fn is not None:
return fn(storage_key, *args)
else:
raise NotImplementedError
def _CheckExclusivePvs(pvi_list):
| 64 | 64 | 137 | 10 | 53 | jfut/ganeti | lib/backend.py | Python | _CheckExclusivePvs | _CheckExclusivePvs | 827 | 841 | 827 | 827 | af81ce760f44ca71d5f0d820b29f0c33ee0d4bd3 | bigcode/the-stack | train |
bd282d86f8021005d19b56ad | train | function | def DemoteFromMC():
"""Demotes the current node from master candidate role.
"""
# try to ensure we're not the master by mistake
master, myself = ssconf.GetMasterAndMyself()
if master == myself:
_Fail("ssconf status shows I'm the master node, will not demote")
result = utils.RunCmd([pathutils.DAEMON_UT... | def DemoteFromMC():
| """Demotes the current node from master candidate role.
"""
# try to ensure we're not the master by mistake
master, myself = ssconf.GetMasterAndMyself()
if master == myself:
_Fail("ssconf status shows I'm the master node, will not demote")
result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constan... | (["rm", "-rf", temp_dir])
if result.failed:
_Fail("Failed to remove copy of OS package '%s' in '%s': %s, output '%s'",
inst_os, temp_dir, result.fail_reason, result.output)
return os_package
def DemoteFromMC():
| 64 | 64 | 186 | 6 | 57 | jfut/ganeti | lib/backend.py | Python | DemoteFromMC | DemoteFromMC | 5,070 | 5,090 | 5,070 | 5,070 | 145264b8ea67f4fae5f761847d2b911d8863e080 | bigcode/the-stack | train |
96fd1a02237adc83dd1baee9 | train | function | def _GetX509Filenames(cryptodir, name):
"""Returns the full paths for the private key and certificate.
"""
return (utils.PathJoin(cryptodir, name),
utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
| def _GetX509Filenames(cryptodir, name):
| """Returns the full paths for the private key and certificate.
"""
return (utils.PathJoin(cryptodir, name),
utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
| _FILE)
except EnvironmentError as err:
if err.errno != errno.ENOENT:
_Fail("Error while backing up cluster file: %s", err, exc=True)
utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
def _GetX509Filenames(cryptodir, name):
| 64 | 64 | 76 | 14 | 50 | jfut/ganeti | lib/backend.py | Python | _GetX509Filenames | _GetX509Filenames | 5,093 | 5,099 | 5,093 | 5,093 | aec29524284f5e0ef6ad8aa8fa083ef57d0cd825 | bigcode/the-stack | train |
59c146ea6c84850ba370e312 | train | function | def _GetNamedNodeInfo(names, fn):
"""Calls C{fn} for all names in C{names} and returns a list of dictionaries.
@rtype: None or list of dict
"""
if names is None:
return None
else:
return [fn(n) for n in names]
| def _GetNamedNodeInfo(names, fn):
| """Calls C{fn} for all names in C{names} and returns a list of dictionaries.
@rtype: None or list of dict
"""
if names is None:
return None
else:
return [fn(n) for n in names]
| hvparams
"""
if hv_specs is None:
return None
result = []
for hvname, hvparams in hv_specs:
result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
return result
def _GetNamedNodeInfo(names, fn):
| 64 | 64 | 68 | 10 | 53 | jfut/ganeti | lib/backend.py | Python | _GetNamedNodeInfo | _GetNamedNodeInfo | 734 | 743 | 734 | 734 | 70954c71edc9eadbd8e119339387fc864b7308b0 | bigcode/the-stack | train |
5c6704fbd3f6d03f20c2130a | train | function | def BlockdevOpen(instance_name, disks, exclusive):
"""Opens the given block devices.
"""
bdevs = []
for cf in disks:
rd = _RecursiveFindBD(cf)
if rd is None:
_Fail("Can't find device %s", cf)
bdevs.append(rd)
msg = []
for idx, rd in enumerate(bdevs):
try:
rd.Open(exclusive=excl... | def BlockdevOpen(instance_name, disks, exclusive):
| """Opens the given block devices.
"""
bdevs = []
for cf in disks:
rd = _RecursiveFindBD(cf)
if rd is None:
_Fail("Can't find device %s", cf)
bdevs.append(rd)
msg = []
for idx, rd in enumerate(bdevs):
try:
rd.Open(exclusive=exclusive)
_SymlinkBlockDev(instance_name, rd.dev... | except errors.BlockDeviceError as err:
msg.append(str(err))
if msg:
_Fail("Can't close devices: %s", ",".join(msg))
else:
if instance_name:
_RemoveBlockDevLinks(instance_name, disks)
def BlockdevOpen(instance_name, disks, exclusive):
| 64 | 64 | 144 | 11 | 53 | jfut/ganeti | lib/backend.py | Python | BlockdevOpen | BlockdevOpen | 4,877 | 4,897 | 4,877 | 4,877 | 654f6aa460d2cbfb367575d7c6aadb507d2436e7 | bigcode/the-stack | train |
a373b029e9b52794466435c6 | train | function | def GetCryptoTokens(token_requests):
"""Perform actions on the node's cryptographic tokens.
Token types can be 'ssl' or 'ssh'. So far only some actions are implemented
for 'ssl'. Action 'get' returns the digest of the public client ssl
certificate. Action 'create' creates a new client certificate and private k... | def GetCryptoTokens(token_requests):
| """Perform actions on the node's cryptographic tokens.
Token types can be 'ssl' or 'ssh'. So far only some actions are implemented
for 'ssl'. Action 'get' returns the digest of the public client ssl
certificate. Action 'create' creates a new client certificate and private key
and also returns the digest of t... | FileStoragePath(
what[constants.NV_FILE_STORAGE_PATH])
if pathresult:
result[constants.NV_FILE_STORAGE_PATH] = pathresult
if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
pathresult = filestorage.CheckFileStoragePath(
what[constants.NV_SHARED_FILE_STORAGE_PATH])
if pathresult:
... | 99 | 99 | 333 | 7 | 91 | jfut/ganeti | lib/backend.py | Python | GetCryptoTokens | GetCryptoTokens | 1,395 | 1,426 | 1,395 | 1,395 | 82ac34dafbacf0b88ea7330b85bd3c379b3f109b | bigcode/the-stack | train |
dcb0adb7ca533b3af18ce3eb | train | function | def HotplugDevice(instance, action, dev_type, device, extra, seq):
"""Hotplug a device
Hotplug is currently supported only for KVM Hypervisor.
@type instance: L{objects.Instance}
@param instance: the instance to which we hotplug a device
@type action: string
@param action: the hotplug action to perform
@... | def HotplugDevice(instance, action, dev_type, device, extra, seq):
| """Hotplug a device
Hotplug is currently supported only for KVM Hypervisor.
@type instance: L{objects.Instance}
@param instance: the instance to which we hotplug a device
@type action: string
@param action: the hotplug action to perform
@type dev_type: string
@param dev_type: the device type to hotplug... | additional
progress info that can be retrieved from the hypervisor
@raise RPCFail: If the migration status cannot be retrieved
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
return hyper.GetMigrationStatus(instance)
except Exception as err: # pylint: disable=W0703
_Fail("... | 103 | 103 | 346 | 17 | 86 | jfut/ganeti | lib/backend.py | Python | HotplugDevice | HotplugDevice | 3,183 | 3,217 | 3,183 | 3,183 | 923a23eb412fae759e5c604a5ccb4580195fefa4 | bigcode/the-stack | train |
c088ca6a53b9cf44a392d025 | train | function | def _GetOldMasterKeys(master_node_uuid, pub_key_file):
old_master_keys_by_uuid = ssh.QueryPubKeyFile([master_node_uuid],
key_file=pub_key_file)
if not old_master_keys_by_uuid:
raise errors.SshUpdateError("No public key of the master node (UUID '%s')"
... | def _GetOldMasterKeys(master_node_uuid, pub_key_file):
| old_master_keys_by_uuid = ssh.QueryPubKeyFile([master_node_uuid],
key_file=pub_key_file)
if not old_master_keys_by_uuid:
raise errors.SshUpdateError("No public key of the master node (UUID '%s')"
" found, not generating a new key."
... | UpdateError("No (unique) master UUID found. Master node"
" name: '%s', Master UUID: '%s'" %
(master_node_name, master_node_uuids))
return master_node_uuids[0]
def _GetOldMasterKeys(master_node_uuid, pub_key_file):
| 64 | 64 | 93 | 14 | 50 | jfut/ganeti | lib/backend.py | Python | _GetOldMasterKeys | _GetOldMasterKeys | 2,042 | 2,049 | 2,042 | 2,042 | 497f2ff81d2bd0c54d88e2ecae07de45916e494b | bigcode/the-stack | train |
f9cd38443ade767f41a9b561 | train | function | def _OpenRealBD(disk):
"""Opens the underlying block device of a disk.
@type disk: L{objects.Disk}
@param disk: the disk object we want to open
"""
real_disk = _RecursiveFindBD(disk)
if real_disk is None:
_Fail("Block device '%s' is not set up", disk)
real_disk.Open()
return real_disk
| def _OpenRealBD(disk):
| """Opens the underlying block device of a disk.
@type disk: L{objects.Disk}
@param disk: the disk object we want to open
"""
real_disk = _RecursiveFindBD(disk)
if real_disk is None:
_Fail("Block device '%s' is not set up", disk)
real_disk.Open()
return real_disk
| instance
"""
children = []
if disk.children:
for chdisk in disk.children:
children.append(_RecursiveFindBD(chdisk, lvs_cache=lvs_cache))
return bdev.FindDevice(disk, children, lvs_cache=lvs_cache)
def _OpenRealBD(disk):
| 64 | 64 | 90 | 8 | 56 | jfut/ganeti | lib/backend.py | Python | _OpenRealBD | _OpenRealBD | 3,867 | 3,880 | 3,867 | 3,867 | 0263daf7120c76255633438c85cfb4baa79cb9ea | bigcode/the-stack | train |
4b2404f99325aa700a6a8922 | train | function | def OSEnvironment(instance, inst_os, debug=0):
"""Calculate the environment for an os script.
@type instance: L{objects.Instance}
@param instance: target instance for the os script run
@type inst_os: L{objects.OS}
@param inst_os: operating system for which the environment is being built
@type debug: intege... | def OSEnvironment(instance, inst_os, debug=0):
| """Calculate the environment for an os script.
@type instance: L{objects.Instance}
@param instance: target instance for the os script run
@type inst_os: L{objects.OS}
@param inst_os: operating system for which the environment is being built
@type debug: integer
@param debug: debug level (0 or 1, for OS A... | errors.BlockDeviceError: if the block device
cannot be found
"""
result = {}
api_version = \
max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
result["OS_API_VERSION"] = "%d" % api_version
result["OS_NAME"] = inst_os.name
result["DEBUG_LEVEL"] = "%d" % debug
# OS variants
if... | 256 | 256 | 871 | 14 | 241 | jfut/ganeti | lib/backend.py | Python | OSEnvironment | OSEnvironment | 4,275 | 4,349 | 4,275 | 4,275 | ee1de6af4a13aeb2347a99426ab45a6c986d2f70 | bigcode/the-stack | train |
e4a2444dc3081a2fee6292b0 | train | function | def RemoveExport(export):
"""Remove an existing export from the node.
@type export: str
@param export: the name of the export to remove
@rtype: None
"""
target = utils.PathJoin(pathutils.EXPORT_DIR, export)
try:
shutil.rmtree(target)
except EnvironmentError as err:
_Fail("Error while removing... | def RemoveExport(export):
| """Remove an existing export from the node.
@type export: str
@param export: the name of the export to remove
@rtype: None
"""
target = utils.PathJoin(pathutils.EXPORT_DIR, export)
try:
shutil.rmtree(target)
except EnvironmentError as err:
_Fail("Error while removing the export: %s", err, exc... | exports currently available on this machine.
@rtype: list
@return: list of the exports
"""
if os.path.isdir(pathutils.EXPORT_DIR):
return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
else:
_Fail("No exports directory")
def RemoveExport(export):
| 64 | 64 | 91 | 5 | 59 | jfut/ganeti | lib/backend.py | Python | RemoveExport | RemoveExport | 4,625 | 4,638 | 4,625 | 4,625 | 9e7a4242c4d5333d2938b0663d86147ab6ab1671 | bigcode/the-stack | train |
5f688cf8317468e10b73d23a | train | function | def CleanupImportExport(name):
"""Cleanup after an import or export.
If the import/export daemon is still running it's killed. Afterwards the
whole status directory is removed.
"""
logging.info("Finalizing import/export %s", name)
status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
pid = ut... | def CleanupImportExport(name):
| """Cleanup after an import or export.
If the import/export daemon is still running it's killed. Afterwards the
whole status directory is removed.
"""
logging.info("Finalizing import/export %s", name)
status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
pid = utils.ReadLockedPidFile(utils.Pat... | LockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
if pid:
logging.info("Import/export %s is running with PID %s, sending SIGTERM",
name, pid)
utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
def CleanupImportExport(name):
| 64 | 64 | 134 | 6 | 58 | jfut/ganeti | lib/backend.py | Python | CleanupImportExport | CleanupImportExport | 5,454 | 5,472 | 5,454 | 5,454 | 11f5f08484a468273ef3fd6c927ca740786aaa8e | bigcode/the-stack | train |
6b34bcec8c658c4a0b6e1a85 | train | function | def _VerifyRestrictedCmdName(cmd):
"""Verifies a restricted command name.
@type cmd: string
@param cmd: Command name
@rtype: tuple; (boolean, string or None)
@return: The tuple's first element is the status; if C{False}, the second
element is an error message string, otherwise it's C{None}
"""
if no... | def _VerifyRestrictedCmdName(cmd):
| """Verifies a restricted command name.
@type cmd: string
@param cmd: Command name
@rtype: tuple; (boolean, string or None)
@return: The tuple's first element is the status; if C{False}, the second
element is an error message string, otherwise it's C{None}
"""
if not cmd.strip():
return (False, "... | 5 seconds"
# ensure the child is running on ram
try:
utils.Mlockall()
except Exception: # pylint: disable=W0703
pass
time.sleep(5)
hyper.PowercycleNode(hvparams=hvparams)
def _VerifyRestrictedCmdName(cmd):
| 64 | 64 | 148 | 8 | 56 | jfut/ganeti | lib/backend.py | Python | _VerifyRestrictedCmdName | _VerifyRestrictedCmdName | 5,653 | 5,672 | 5,653 | 5,653 | 85f948f154fea7a1b59fb91a2eac762e6573e5dd | bigcode/the-stack | train |
d3e6883208fe7aed376d7f2f | train | function | def _Decompress(data):
"""Unpacks data compressed by the RPC client.
@type data: list or tuple
@param data: Data sent by RPC client
@rtype: str
@return: Decompressed data
"""
assert isinstance(data, (list, tuple))
assert len(data) == 2
(encoding, content) = data
if encoding == constants.RPC_ENCODI... | def _Decompress(data):
| """Unpacks data compressed by the RPC client.
@type data: list or tuple
@param data: Data sent by RPC client
@rtype: str
@return: Decompressed data
"""
assert isinstance(data, (list, tuple))
assert len(data) == 2
(encoding, content) = data
if encoding == constants.RPC_ENCODING_NONE:
return con... | _name: str
@param cluster_name: the cluster name, which is needed
by the SshRunner constructor
@rtype: L{ssh.SshRunner}
@return: an SshRunner instance
"""
return ssh.SshRunner(cluster_name)
def _Decompress(data):
| 64 | 64 | 133 | 6 | 58 | jfut/ganeti | lib/backend.py | Python | _Decompress | _Decompress | 214 | 231 | 214 | 214 | 58256bb817088e861f992d9a5358660ae4a39f6f | bigcode/the-stack | train |
858b07360de55b91287a699d | train | function | def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
"""Decorator that runs hooks before and after the decorated function.
@type hook_opcode: string
@param hook_opcode: opcode of the hook
@type hooks_path: string
@param hooks_path: path of the hooks
@type env_builder_fn: function
@param env_builde... | def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
| """Decorator that runs hooks before and after the decorated function.
@type hook_opcode: string
@param hook_opcode: opcode of the hook
@type hooks_path: string
@param hooks_path: path of the hooks
@type env_builder_fn: function
@param env_builder_fn: function that returns a dictionary containing the
... | the master node name.
@rtype: string
@return: name of the master node
@raise RPCFail: in case of errors
"""
try:
return _GetConfig().GetMasterNode()
except errors.ConfigurationError as err:
_Fail("Cluster configuration incomplete: %s", err, exc=True)
def RunLocalHooks(hook_opcode, hooks_path, env... | 86 | 86 | 287 | 15 | 71 | jfut/ganeti | lib/backend.py | Python | RunLocalHooks | RunLocalHooks | 321 | 354 | 321 | 321 | 46836f23b008adc8ceb43b1eaae789c69ee15679 | bigcode/the-stack | train |
1b91786ff98e9979b8ec01f9 | train | function | def HotplugSupported(instance):
"""Checks if hotplug is generally supported.
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
hyper.HotplugSupported(instance)
except errors.HotplugError as err:
_Fail("Hotplug is not supported: %s", err)
| def HotplugSupported(instance):
| """Checks if hotplug is generally supported.
"""
hyper = hypervisor.GetHypervisor(instance.hypervisor)
try:
hyper.HotplugSupported(instance)
except errors.HotplugError as err:
_Fail("Hotplug is not supported: %s", err)
| hyper.HotDelDevice
elif action == constants.HOTPLUG_ACTION_MODIFY:
fn = hyper.HotModDevice
else:
assert action in constants.HOTPLUG_ALL_ACTIONS
return fn(instance, dev_type, device, extra, seq)
def HotplugSupported(instance):
| 64 | 64 | 66 | 6 | 58 | jfut/ganeti | lib/backend.py | Python | HotplugSupported | HotplugSupported | 3,220 | 3,228 | 3,220 | 3,220 | 9e53840de6f8f9394c1a2db180cbd64cd2d2d60b | bigcode/the-stack | train |
28be05340bfbcdbec689dfe7 | train | function | @RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
_BuildMasterIpEnv)
def DeactivateMasterIp(master_params, use_external_mip_script):
"""Deactivate the master IP on this node.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of t... | @RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
_BuildMasterIpEnv)
def DeactivateMasterIp(master_params, use_external_mip_script):
| """Deactivate the master IP on this node.
@type master_params: L{objects.MasterNetworkParameters}
@param master_params: network parameters of the master
@type use_external_mip_script: boolean
@param use_external_mip_script: whether to use an external master IP
address setup script
@raise RPCFail: in ca... | start Ganeti master: %s" % result.output
logging.error(msg)
_Fail(msg)
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
_BuildMasterIpEnv)
def DeactivateMasterIp(master_params, use_external_mip_script):
| 64 | 64 | 149 | 42 | 22 | jfut/ganeti | lib/backend.py | Python | DeactivateMasterIp | DeactivateMasterIp | 455 | 469 | 455 | 457 | a8c5a3fde188b5c83c0c05088ec2dda1543a4d1e | bigcode/the-stack | train |
b4f7bc0436b06d4b9b3e7d22 | train | function | def StartMasterDaemons(no_voting):
"""Activate local node as master node.
The function will start the master daemons (ganeti-masterd and ganeti-rapi).
@type no_voting: boolean
@param no_voting: whether to start ganeti-masterd without a node vote
but still non-interactively
@rtype: None
"""
if no... | def StartMasterDaemons(no_voting):
| """Activate local node as master node.
The function will start the master daemons (ganeti-masterd and ganeti-rapi).
@type no_voting: boolean
@param no_voting: whether to start ganeti-masterd without a node vote
but still non-interactively
@rtype: None
"""
if no_voting:
daemon_args = "--no-vo... | _external_mip_script: whether to use an external master IP
address setup script
@raise RPCFail: in case of errors during the IP startup
"""
_RunMasterSetupScript(master_params, _MASTER_START,
use_external_mip_script)
def StartMasterDaemons(no_voting):
| 64 | 64 | 193 | 9 | 55 | jfut/ganeti | lib/backend.py | Python | StartMasterDaemons | StartMasterDaemons | 426 | 452 | 426 | 426 | d7aa8bd8e3960488a5a1af341dc7c051f4cd81a8 | bigcode/the-stack | train |
b01bad8f72b53cddee44d240 | train | function | def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
get_hv_fn=hypervisor.GetHypervisor):
"""Verifies the hypervisor. Appends the results to the 'results' list.
@type what: C{dict}
@param what: a dictionary of things to check
@type vm_capable: boolean
@param vm_capable: wheth... | def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
get_hv_fn=hypervisor.GetHypervisor):
| """Verifies the hypervisor. Appends the results to the 'results' list.
@type what: C{dict}
@param what: a dictionary of things to check
@type vm_capable: boolean
@param vm_capable: whether or not this node is vm capable
@type result: dict
@param result: dictionary of verification results; results of the
... | : offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
"""
res = []
for pvi in pvi_list:
if len(pvi.lv_list) > 1:
res.append((pvi.name, pvi.lv_list))
return res
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
get_hv_fn=hypervisor.GetHypervisor):
| 97 | 97 | 324 | 32 | 64 | jfut/ganeti | lib/backend.py | Python | _VerifyHypervisors | _VerifyHypervisors | 844 | 872 | 844 | 845 | 5a4611946fefa813481d8049ea4a834433aec209 | bigcode/the-stack | train |
929ebbcf5650a5d95ebae4f0 | train | function | def _GetInstanceInfo(instance):
"""Helper function L{GetInstanceInfo}"""
return GetInstanceInfo(instance.name, instance.hypervisor,
hvparams=instance.hvparams)
| def _GetInstanceInfo(instance):
| """Helper function L{GetInstanceInfo}"""
return GetInstanceInfo(instance.name, instance.hypervisor,
hvparams=instance.hvparams)
| )
block_devices.append((disk, link_name, uri))
return block_devices
def _IsInstanceUserDown(instance_info):
return instance_info and \
"state" in instance_info and \
hv_base.HvInstanceState.IsShutdown(instance_info["state"])
def _GetInstanceInfo(instance):
| 63 | 64 | 39 | 7 | 56 | jfut/ganeti | lib/backend.py | Python | _GetInstanceInfo | _GetInstanceInfo | 2,886 | 2,889 | 2,886 | 2,886 | eea7063df0b0173710285c12ec7276ddfe51bdd7 | bigcode/the-stack | train |
2eb027002d66a92d3b9bc753 | train | function | def StopMasterDaemons():
"""Stop the master daemons on this node.
Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
@rtype: None
"""
# TODO: log and report back to the caller the error failures; we
# need to decide in which case we fail the RPC for this
result = utils.RunCmd([path... | def StopMasterDaemons():
| """Stop the master daemons on this node.
Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
@rtype: None
"""
# TODO: log and report back to the caller the error failures; we
# need to decide in which case we fail the RPC for this
result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-... | use_external_mip_script: whether to use an external master IP
address setup script
@raise RPCFail: in case of errors during the IP turndown
"""
_RunMasterSetupScript(master_params, _MASTER_STOP,
use_external_mip_script)
def StopMasterDaemons():
| 64 | 64 | 140 | 6 | 58 | jfut/ganeti | lib/backend.py | Python | StopMasterDaemons | StopMasterDaemons | 472 | 487 | 472 | 472 | 3039ff1271a5abef5d6b59f2aa97e715646815e9 | bigcode/the-stack | train |
f6f4df7c3e03d5c53a0d5103 | train | function | def _EnsureJobQueueFile(file_name):
"""Checks whether the given filename is in the queue directory.
@type file_name: str
@param file_name: the file name we should check
@rtype: None
@raises RPCFail: if the file is not valid
"""
if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
_Fail("Passed j... | def _EnsureJobQueueFile(file_name):
| """Checks whether the given filename is in the queue directory.
@type file_name: str
@param file_name: the file name we should check
@rtype: None
@raises RPCFail: if the file is not valid
"""
if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
_Fail("Passed job queue file '%s' does not belong t... | '%s' is not a directory",
old_file_storage_dir)
else:
if os.path.exists(old_file_storage_dir):
_Fail("Cannot rename '%s' to '%s': both locations exist",
old_file_storage_dir, new_file_storage_dir)
def _EnsureJobQueueFile(file_name):
| 64 | 64 | 113 | 9 | 55 | jfut/ganeti | lib/backend.py | Python | _EnsureJobQueueFile | _EnsureJobQueueFile | 4,777 | 4,788 | 4,777 | 4,777 | 3ca0c9d50ba2c9bb24edc79fa6d13e5d53b4ac40 | bigcode/the-stack | train |
c4b263c8cc6c20974deb8542 | train | function | def RenewSshKeys(node_uuids, node_names, master_candidate_uuids,
potential_master_candidates, old_key_type, new_key_type,
new_key_bits,
ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS,
ssconf_store=None,
noded_cert_file=pathutils.NODED_CER... | def RenewSshKeys(node_uuids, node_names, master_candidate_uuids,
potential_master_candidates, old_key_type, new_key_type,
new_key_bits,
ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS,
ssconf_store=None,
noded_cert_file=pathutils.NODED_CER... | """Renews all SSH keys and updates authorized_keys and ganeti_pub_keys.
@type node_uuids: list of str
@param node_uuids: list of node UUIDs whose keys should be renewed
@type node_names: list of str
@param node_names: list of node names whose keys should be removed. This list
should match the C{node_uuid... | .join(key_dir,
private_key_file_tmp)
public_key_path_tmp = os.path.join(key_dir,
public_key_file_tmp)
if os.path.exists(public_key_file):
utils.CreateBackup(public_key_file)
utils.RemoveFile(public_key_file)
if os.pat... | 255 | 256 | 2,164 | 85 | 170 | jfut/ganeti | lib/backend.py | Python | RenewSshKeys | RenewSshKeys | 2,097 | 2,312 | 2,097 | 2,103 | 4cc19304408d8efbcd5f8da49e8e878638c043d3 | bigcode/the-stack | train |
305cea80fcb15b873499b0a9 | train | function | def BlockdevClose(instance_name, disks):
"""Closes the given block devices.
This means they will be switched to secondary mode (in case of
DRBD).
@param instance_name: if the argument is not empty, the symlinks
of this instance will be removed
@type disks: list of L{objects.Disk}
@param disks: the l... | def BlockdevClose(instance_name, disks):
| """Closes the given block devices.
This means they will be switched to secondary mode (in case of
DRBD).
@param instance_name: if the argument is not empty, the symlinks
of this instance will be removed
@type disks: list of L{objects.Disk}
@param disks: the list of disks to be closed
@rtype: tuple... | cluster.LocalizeVirtualPath(new)
_EnsureJobQueueFile(old)
_EnsureJobQueueFile(new)
getents = runtime.GetEnts()
utils.RenameFile(old, new, mkdir=True, mkdir_mode=0o750,
dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
def BlockdevClose(instance_name, disks):
| 77 | 77 | 259 | 9 | 68 | jfut/ganeti | lib/backend.py | Python | BlockdevClose | BlockdevClose | 4,840 | 4,874 | 4,840 | 4,840 | 0bc1fcfa69add122b72ff77f84831128cf187694 | bigcode/the-stack | train |
4abbdc371c96fde734e7d661 | train | function | def NodeVolumes():
"""List all volumes on this node.
@rtype: list
@return:
A list of dictionaries, each having four keys:
- name: the logical volume name,
- size: the size of the logical volume
- dev: the physical device on which the LV lives
- vg: the volume group to which it belongs... | def NodeVolumes():
| """List all volumes on this node.
@rtype: list
@return:
A list of dictionaries, each having four keys:
- name: the logical volume name,
- size: the size of the logical volume
- dev: the physical device on which the LV lives
- vg: the volume group to which it belongs
In case of er... | if virtual:
# we don't want to report such volumes as existing, since they
# don't really hold data
continue
lvs[vg_name + "/" + name] = (size, inactive, online)
return lvs
def ListVolumeGroups():
"""List the volume groups and their size.
@rtype: dict
@return: dictionary with keys ... | 106 | 106 | 354 | 4 | 102 | jfut/ganeti | lib/backend.py | Python | NodeVolumes | NodeVolumes | 2,410 | 2,453 | 2,410 | 2,410 | bed156d087a95c9d3301ea10d3916a442013f9d3 | bigcode/the-stack | train |
2e40029704821c4061aabaae | train | function | def _GetConfig():
"""Simple wrapper to return a SimpleStore.
@rtype: L{ssconf.SimpleStore}
@return: a SimpleStore instance
"""
return ssconf.SimpleStore()
| def _GetConfig():
| """Simple wrapper to return a SimpleStore.
@rtype: L{ssconf.SimpleStore}
@return: a SimpleStore instance
"""
return ssconf.SimpleStore()
| msg = msg % args
if "log" not in kwargs or kwargs["log"]: # if we should log this error
if "exc" in kwargs and kwargs["exc"]:
logging.exception(msg)
else:
logging.error(msg)
raise RPCFail(msg)
def _GetConfig():
| 64 | 64 | 44 | 5 | 59 | jfut/ganeti | lib/backend.py | Python | _GetConfig | _GetConfig | 191 | 198 | 191 | 191 | df65a585d2b36fa15cfa8e3b2f8f4fa4992df4ca | bigcode/the-stack | train |
f395b85b1b6e1a1c6045f0bd | train | function | def BlockdevGetmirrorstatus(disks):
"""Get the mirroring status of a list of devices.
@type disks: list of L{objects.Disk}
@param disks: the list of disks which we should query
@rtype: disk
@return: List of L{objects.BlockDevStatus}, one for each disk
@raise errors.BlockDeviceError: if any of the disks can... | def BlockdevGetmirrorstatus(disks):
| """Get the mirroring status of a list of devices.
@type disks: list of L{objects.Disk}
@param disks: the list of disks which we should query
@rtype: disk
@return: List of L{objects.BlockDevStatus}, one for each disk
@raise errors.BlockDeviceError: if any of the disks cannot be
found
"""
stats = ... | .append(bd.dev_path)
else:
if not utils.IsNormAbsPath(rpath):
_Fail("Strange path returned from StaticDevPath: '%s'", rpath)
devs.append(rpath)
parent_bdev.RemoveChildren(devs)
def BlockdevGetmirrorstatus(disks):
| 64 | 64 | 150 | 9 | 55 | jfut/ganeti | lib/backend.py | Python | BlockdevGetmirrorstatus | BlockdevGetmirrorstatus | 3,774 | 3,793 | 3,774 | 3,774 | 2177742e4b36c1b3b4494cda4f46d2cab34a6728 | bigcode/the-stack | train |
c89a1851cdc7dd57a5749944 | train | function | def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
"""Looks up and applies the correct function to calculate free and total
storage for the given storage type.
@type storage_type: string
@param storage_type: the storage type for which the storage shall be reported.
@type storage_key: string
@... | def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
| """Looks up and applies the correct function to calculate free and total
storage for the given storage type.
@type storage_type: string
@param storage_type: the storage type for which the storage shall be reported.
@type storage_key: string
@param storage_key: identifier of a storage unit, e.g. the volume ... | constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
constants.ST_SHARED_FILE: None,
constants.ST_GLUSTER: None,
constants.ST_RADOS: None,
}
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
| 72 | 72 | 242 | 15 | 57 | jfut/ganeti | lib/backend.py | Python | _ApplyStorageInfoFunction | _ApplyStorageInfoFunction | 801 | 824 | 801 | 801 | dd73aaa0d58619417e2fcc58fada6c092851c2f1 | bigcode/the-stack | train |
a298a36a930abbce62071d6e | train | function | def ValidateHVParams(hvname, hvparams):
"""Validates the given hypervisor parameters.
@type hvname: string
@param hvname: the hypervisor name
@type hvparams: dict
@param hvparams: the hypervisor parameters to be validated
@rtype: None
"""
try:
hv_type = hypervisor.GetHypervisor(hvname)
hv_type... | def ValidateHVParams(hvname, hvparams):
| """Validates the given hypervisor parameters.
@type hvname: string
@param hvname: the hypervisor name
@type hvparams: dict
@param hvparams: the hypervisor parameters to be validated
@rtype: None
"""
try:
hv_type = hypervisor.GetHypervisor(hvname)
hv_type.ValidateParameters(hvparams)
except e... | =exclusive)
_SymlinkBlockDev(instance_name, rd.dev_path, idx)
except errors.BlockDeviceError as err:
msg.append(str(err))
if msg:
_Fail("Can't open devices: %s", ",".join(msg))
def ValidateHVParams(hvname, hvparams):
| 64 | 64 | 114 | 11 | 53 | jfut/ganeti | lib/backend.py | Python | ValidateHVParams | ValidateHVParams | 4,900 | 4,914 | 4,900 | 4,900 | 8f55c63d4fba6b26483f04aafd07bfca1867cf19 | bigcode/the-stack | train |
d0041cb658a11c5ae9f17567 | train | class | class AuxLabels2Mapper(_AuxLabels2Mapper):
def __init__(self, labels_in: AuxLabels, arc_map: IntArray2):
super().__init__(labels_in.get_base(), arc_map.get_base())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: Aux... | class AuxLabels2Mapper(_AuxLabels2Mapper):
| def __init__(self, labels_in: AuxLabels, arc_map: IntArray2):
super().__init__(labels_in.get_base(), arc_map.get_base())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: AuxLabels) -> None:
return super().get_... | ())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: AuxLabels) -> None:
return super().get_output(labels_out.get_base())
class AuxLabels2Mapper(_AuxLabels2Mapper):
| 64 | 64 | 98 | 11 | 53 | sequeender/k2 | k2/python/host/k2host/aux_labels.py | Python | AuxLabels2Mapper | AuxLabels2Mapper | 32 | 41 | 32 | 33 | 237f2c21079f0dbf240d985273e658a2444aa2bf | bigcode/the-stack | train |
22e2601f1f3ca5ca6e6d384b | train | class | class AuxLabels1Mapper(_AuxLabels1Mapper):
def __init__(self, labels_in: AuxLabels, arc_map: IntArray1):
super().__init__(labels_in.get_base(), arc_map.get_base())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: Aux... | class AuxLabels1Mapper(_AuxLabels1Mapper):
| def __init__(self, labels_in: AuxLabels, arc_map: IntArray1):
super().__init__(labels_in.get_base(), arc_map.get_base())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: AuxLabels) -> None:
return super().get_... | host import _AuxLabels2Mapper
from k2._k2host import _FstInverter
from .fsa import Fsa
from .array import IntArray1
from .array import IntArray2
AuxLabels = IntArray2
class AuxLabels1Mapper(_AuxLabels1Mapper):
| 64 | 64 | 98 | 11 | 52 | sequeender/k2 | k2/python/host/k2host/aux_labels.py | Python | AuxLabels1Mapper | AuxLabels1Mapper | 20 | 29 | 20 | 21 | a2e3ab6dd8c1519f0c586012c149c4fdf011e34c | bigcode/the-stack | train |
ab3c576aa9d945f808aaa7e3 | train | class | class FstInverter(_FstInverter):
def __init__(self, fsa_in: Fsa, labels_in: AuxLabels):
super().__init__(fsa_in.get_base(), labels_in.get_base())
def get_sizes(self, fsa_size: IntArray2Size,
aux_size: IntArray2Size) -> None:
return super().get_sizes(fsa_size, aux_size)
d... | class FstInverter(_FstInverter):
| def __init__(self, fsa_in: Fsa, labels_in: AuxLabels):
super().__init__(fsa_in.get_base(), labels_in.get_base())
def get_sizes(self, fsa_size: IntArray2Size,
aux_size: IntArray2Size) -> None:
return super().get_sizes(fsa_size, aux_size)
def get_output(self, fsa_out: Fsa, ... | ())
def get_sizes(self, aux_size: IntArray2Size) -> None:
return super().get_sizes(aux_size)
def get_output(self, labels_out: AuxLabels) -> None:
return super().get_output(labels_out.get_base())
class FstInverter(_FstInverter):
| 64 | 64 | 126 | 11 | 53 | sequeender/k2 | k2/python/host/k2host/aux_labels.py | Python | FstInverter | FstInverter | 44 | 54 | 44 | 45 | a220ff1fefebd98a40376decaa82ba018f8eb9c2 | bigcode/the-stack | train |
cd55cedb205b4bd406214813 | train | function | def schematic2layout(netlist_dir, pdk_dir, netlist_file=None, subckt=None, working_dir=None, flatten=False, unit_size_mos=10, unit_size_cap=10, nvariants=1, effort=0, check=False, extract=False, log_level=None, generate=False):
if log_level:
logging.getLogger().setLevel(logging.getLevelName(log_level))
... | def schematic2layout(netlist_dir, pdk_dir, netlist_file=None, subckt=None, working_dir=None, flatten=False, unit_size_mos=10, unit_size_cap=10, nvariants=1, effort=0, check=False, extract=False, log_level=None, generate=False):
| if log_level:
logging.getLogger().setLevel(logging.getLevelName(log_level))
if working_dir is None:
working_dir = pathlib.Path.cwd().resolve()
if not working_dir.is_dir():
logger.error(f"Working directory {working_dir} doesn't exist. Please enter a valid directory path.")
ra... | import pathlib
from .compiler import generate_hierarchy
from .primitive import generate_primitive
from .pnr import generate_pnr
from .gdsconv.json2gds import convert_GDSjson_GDS
from .utils.gds2png import generate_png
import logging
logger = logging.getLogger(__name__)
def schematic2layout(netlist_dir, pdk_dir, netli... | 130 | 256 | 945 | 63 | 67 | rbarzic/ALIGN-public | align/main.py | Python | schematic2layout | schematic2layout | 12 | 85 | 12 | 13 | 1a1907b2d29e2497304cd37b1cc8bbc1d4dc0404 | bigcode/the-stack | train |
02d16b45e38e0147d3f0b5df | train | class | class CallbackOutput(CollectingOutputChannel):
@classmethod
def name(cls) -> Text:
return "callback"
def __init__(self, endpoint: EndpointConfig) -> None:
self.callback_endpoint = endpoint
super().__init__()
async def _persist_message(self, message: Dict[Text, Any]) -> None:
... | class CallbackOutput(CollectingOutputChannel):
@classmethod
| def name(cls) -> Text:
return "callback"
def __init__(self, endpoint: EndpointConfig) -> None:
self.callback_endpoint = endpoint
super().__init__()
async def _persist_message(self, message: Dict[Text, Any]) -> None:
await super()._persist_message(message)
try:
... | ingOutputChannel,
UserMessage,
InputChannel,
)
from rasa.core.channels.rest import RestInput
from rasa.utils.endpoints import EndpointConfig, ClientResponseError
from sanic.response import HTTPResponse
logger = logging.getLogger(__name__)
class CallbackOutput(CollectingOutputChannel):
@classmethod
| 64 | 64 | 150 | 13 | 51 | fintzd/rasa | rasa/core/channels/callback.py | Python | CallbackOutput | CallbackOutput | 19 | 41 | 19 | 20 | f6fa9d4aea43f27bc24a6dade073465916ef6d1c | bigcode/the-stack | train |
2abaf9875ec81c6eb8d8432d | train | class | class CallbackInput(RestInput):
"""A custom REST http input channel that responds using a callback server.
Incoming messages are received through a REST interface. Responses
are sent asynchronously by calling a configured external REST endpoint."""
@classmethod
def name(cls) -> Text:
retur... | class CallbackInput(RestInput):
| """A custom REST http input channel that responds using a callback server.
Incoming messages are received through a REST interface. Responses
are sent asynchronously by calling a configured external REST endpoint."""
@classmethod
def name(cls) -> Text:
return "callback"
@classmethod
... | , Any]) -> None:
await super()._persist_message(message)
try:
await self.callback_endpoint.request(
"post", content_type="application/json", json=message
)
except ClientResponseError as e:
logger.error(
"Failed to send output m... | 90 | 90 | 301 | 6 | 84 | fintzd/rasa | rasa/core/channels/callback.py | Python | CallbackInput | CallbackInput | 44 | 84 | 44 | 44 | 5219226695f74343e6156668e1c70d8ba7ec78b4 | bigcode/the-stack | train |
ae4c35977faeb598e9adf48d | train | class | class ViT_H_14_Weights(WeightsEnum):
IMAGENET1K_SWAG_V1 = Weights(
url="https://download.pytorch.org/models/vit_h_14_swag-80465313.pth",
transforms=partial(
ImageClassification,
crop_size=518,
resize_size=518,
interpolation=InterpolationMode.BICUBIC,
... | class ViT_H_14_Weights(WeightsEnum):
| IMAGENET1K_SWAG_V1 = Weights(
url="https://download.pytorch.org/models/vit_h_14_swag-80465313.pth",
transforms=partial(
ImageClassification,
crop_size=518,
resize_size=518,
interpolation=InterpolationMode.BICUBIC,
),
meta={
... | ytorch/vision/tree/main/references/classification#vit_l_32",
"acc@1": 76.972,
"acc@5": 93.07,
},
)
DEFAULT = IMAGENET1K_V1
class ViT_H_14_Weights(WeightsEnum):
| 64 | 64 | 164 | 12 | 51 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | ViT_H_14_Weights | ViT_H_14_Weights | 440 | 458 | 440 | 440 | 3f681795ef72f2f309e1018a0b39aaf957c01ad0 | bigcode/the-stack | train |
5221c4cf963af754c72cc260 | train | function | @handle_legacy_interface(weights=("pretrained", ViT_L_32_Weights.IMAGENET1K_V1))
def vit_l_32(*, weights: Optional[ViT_L_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
"""
Constructs a vit_l_32 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recogni... | @handle_legacy_interface(weights=("pretrained", ViT_L_32_Weights.IMAGENET1K_V1))
def vit_l_32(*, weights: Optional[ViT_L_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| """
Constructs a vit_l_32 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
Args:
weights (ViT_L_32_Weights, optional): The pretrained weights for the model
progress (bool): If True, displays a progress ... | kwargs,
)
@handle_legacy_interface(weights=("pretrained", ViT_L_32_Weights.IMAGENET1K_V1))
def vit_l_32(*, weights: Optional[ViT_L_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| 66 | 66 | 222 | 62 | 4 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | vit_l_32 | vit_l_32 | 533 | 554 | 533 | 534 | 4c063f74e9b10adef138932ddeb23fe921c32d90 | bigcode/the-stack | train |
d012cb9b99377097d2cc1711 | train | class | class MLPBlock(nn.Sequential):
"""Transformer MLP block."""
def __init__(self, in_dim: int, mlp_dim: int, dropout: float):
super().__init__()
self.linear_1 = nn.Linear(in_dim, mlp_dim)
self.act = nn.GELU()
self.dropout_1 = nn.Dropout(dropout)
self.linear_2 = nn.Linear(ml... | class MLPBlock(nn.Sequential):
| """Transformer MLP block."""
def __init__(self, in_dim: int, mlp_dim: int, dropout: float):
super().__init__()
self.linear_1 = nn.Linear(in_dim, mlp_dim)
self.act = nn.GELU()
self.dropout_1 = nn.Dropout(dropout)
self.linear_2 = nn.Linear(mlp_dim, in_dim)
self.dro... | ",
]
class ConvStemConfig(NamedTuple):
out_channels: int
kernel_size: int
stride: int
norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d
activation_layer: Callable[..., nn.Module] = nn.ReLU
class MLPBlock(nn.Sequential):
| 64 | 64 | 167 | 7 | 56 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | MLPBlock | MLPBlock | 40 | 54 | 40 | 40 | e0c18db2b70a57e4def244da2750a0e9ddcbd744 | bigcode/the-stack | train |
7415efb3f8a25ef1ecb461fa | train | class | class ConvStemConfig(NamedTuple):
out_channels: int
kernel_size: int
stride: int
norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d
activation_layer: Callable[..., nn.Module] = nn.ReLU
| class ConvStemConfig(NamedTuple):
| out_channels: int
kernel_size: int
stride: int
norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d
activation_layer: Callable[..., nn.Module] = nn.ReLU
| "ViT_L_32_Weights",
"ViT_H_14_Weights",
"vit_b_16",
"vit_b_32",
"vit_l_16",
"vit_l_32",
"vit_h_14",
]
class ConvStemConfig(NamedTuple):
| 64 | 64 | 55 | 8 | 56 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | ConvStemConfig | ConvStemConfig | 32 | 37 | 32 | 32 | 76e21e323f454715a9f7a2de8b60bec5abee7356 | bigcode/the-stack | train |
05437649d3be61dc328a6b5d | train | class | class ViT_B_32_Weights(WeightsEnum):
IMAGENET1K_V1 = Weights(
url="https://download.pytorch.org/models/vit_b_32-d86f8d99.pth",
transforms=partial(ImageClassification, crop_size=224),
meta={
**_COMMON_META,
"num_params": 88224232,
"size": (224, 224),
... | class ViT_B_32_Weights(WeightsEnum):
| IMAGENET1K_V1 = Weights(
url="https://download.pytorch.org/models/vit_b_32-d86f8d99.pth",
transforms=partial(ImageClassification, crop_size=224),
meta={
**_COMMON_META,
"num_params": 88224232,
"size": (224, 224),
"min_size": (224, 224),
... | , 384),
"min_size": (384, 384),
"acc@1": 85.304,
"acc@5": 97.650,
},
)
DEFAULT = IMAGENET1K_V1
class ViT_B_32_Weights(WeightsEnum):
| 64 | 64 | 162 | 12 | 51 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | ViT_B_32_Weights | ViT_B_32_Weights | 372 | 386 | 372 | 372 | 745944d18ba79472857997b9e7c8cece2d58c5e7 | bigcode/the-stack | train |
bd702d385e78d2dc5a49392b | train | class | class ViT_L_32_Weights(WeightsEnum):
IMAGENET1K_V1 = Weights(
url="https://download.pytorch.org/models/vit_l_32-c7638314.pth",
transforms=partial(ImageClassification, crop_size=224),
meta={
**_COMMON_META,
"num_params": 306535400,
"size": (224, 224),
... | class ViT_L_32_Weights(WeightsEnum):
| IMAGENET1K_V1 = Weights(
url="https://download.pytorch.org/models/vit_l_32-c7638314.pth",
transforms=partial(ImageClassification, crop_size=224),
meta={
**_COMMON_META,
"num_params": 306535400,
"size": (224, 224),
"min_size": (224, 224),
... | , 512),
"min_size": (512, 512),
"acc@1": 88.064,
"acc@5": 98.512,
},
)
DEFAULT = IMAGENET1K_V1
class ViT_L_32_Weights(WeightsEnum):
| 64 | 64 | 160 | 12 | 51 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | ViT_L_32_Weights | ViT_L_32_Weights | 423 | 437 | 423 | 423 | 09568ca35b49d3a9a07af9b4a8234d92ef0cf571 | bigcode/the-stack | train |
d3a2cf92ff626b5d0a17c063 | train | function | @handle_legacy_interface(weights=("pretrained", ViT_L_16_Weights.IMAGENET1K_V1))
def vit_l_16(*, weights: Optional[ViT_L_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
"""
Constructs a vit_l_16 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recogni... | @handle_legacy_interface(weights=("pretrained", ViT_L_16_Weights.IMAGENET1K_V1))
def vit_l_16(*, weights: Optional[ViT_L_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| """
Constructs a vit_l_16 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
Args:
weights (ViT_L_16_Weights, optional): The pretrained weights for the model
progress (bool): If True, displays a progress ... | kwargs,
)
@handle_legacy_interface(weights=("pretrained", ViT_L_16_Weights.IMAGENET1K_V1))
def vit_l_16(*, weights: Optional[ViT_L_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| 66 | 66 | 222 | 62 | 4 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | vit_l_16 | vit_l_16 | 509 | 530 | 509 | 510 | ad3fabe0e9626da7a86459680d73ef58ca92274f | bigcode/the-stack | train |
1c52683c8035cdbe37553423 | train | class | class Encoder(nn.Module):
"""Transformer Model Encoder for sequence to sequence translation."""
def __init__(
self,
seq_length: int,
num_layers: int,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float,
attention_dropout: float,
... | class Encoder(nn.Module):
| """Transformer Model Encoder for sequence to sequence translation."""
def __init__(
self,
seq_length: int,
num_layers: int,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float,
attention_dropout: float,
norm_layer: Callable[..., ... | "Expected (seq_length, batch_size, hidden_dim) got {input.shape}")
x = self.ln_1(input)
x, _ = self.self_attention(query=x, key=x, value=x, need_weights=False)
x = self.dropout(x)
x = x + input
y = self.ln_2(x)
y = self.mlp(y)
return x + y
class Encoder(nn.Module... | 91 | 91 | 306 | 5 | 85 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | Encoder | Encoder | 93 | 128 | 93 | 93 | 6140afb0cf005903dccb71bf4cb8791d75b9b6f4 | bigcode/the-stack | train |
3902b39a11af36e1ee4e17ca | train | function | def vit_h_14(*, weights: Optional[ViT_H_14_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
"""
Constructs a vit_h_14 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
Args:
weights (... | def vit_h_14(*, weights: Optional[ViT_H_14_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| """
Constructs a vit_h_14 architecture from
`"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
Args:
weights (ViT_H_14_Weights, optional): The pretrained weights for the model
progress (bool): If True, displays a progress ... | 1024,
mlp_dim=4096,
weights=weights,
progress=progress,
**kwargs,
)
def vit_h_14(*, weights: Optional[ViT_H_14_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer:
| 64 | 64 | 197 | 37 | 27 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | vit_h_14 | vit_h_14 | 557 | 577 | 557 | 557 | 7b6659f8d2fea32fd474aa5285a74b47ac17b179 | bigcode/the-stack | train |
ef04060d948e453c6a67d153 | train | class | class VisionTransformer(nn.Module):
"""Vision Transformer as per https://arxiv.org/abs/2010.11929."""
def __init__(
self,
image_size: int,
patch_size: int,
num_layers: int,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float = 0.0,
... | class VisionTransformer(nn.Module):
| """Vision Transformer as per https://arxiv.org/abs/2010.11929."""
def __init__(
self,
image_size: int,
patch_size: int,
num_layers: int,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float = 0.0,
attention_dropout: float = 0.0,
... | : float,
attention_dropout: float,
norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
):
super().__init__()
# Note that batch_size is on the first dim because
# we have batch_first=True in nn.MultiAttention() by default
self.pos_embedding = ... | 255 | 256 | 1,361 | 6 | 249 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | VisionTransformer | VisionTransformer | 131 | 276 | 131 | 131 | 2db3e9c27c62053f7a5e7d52287fe285fc140c1f | bigcode/the-stack | train |
4e19430c013766e3653c6300 | train | class | class EncoderBlock(nn.Module):
"""Transformer encoder block."""
def __init__(
self,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float,
attention_dropout: float,
norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
... | class EncoderBlock(nn.Module):
| """Transformer encoder block."""
def __init__(
self,
num_heads: int,
hidden_dim: int,
mlp_dim: int,
dropout: float,
attention_dropout: float,
norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
):
super().__init__()
... | , in_dim)
self.dropout_2 = nn.Dropout(dropout)
nn.init.xavier_uniform_(self.linear_1.weight)
nn.init.xavier_uniform_(self.linear_2.weight)
nn.init.normal_(self.linear_1.bias, std=1e-6)
nn.init.normal_(self.linear_2.bias, std=1e-6)
class EncoderBlock(nn.Module):
| 84 | 84 | 282 | 6 | 78 | YosuaMichael/vision | torchvision/models/vision_transformer.py | Python | EncoderBlock | EncoderBlock | 57 | 90 | 57 | 57 | 83fb1df45b84c6d940b46c790f9b7369be74710b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.