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
7b3ec85cdbab067fcb0462a6
train
function
def _haiss_m3(Aspr, Cau, exp=True): ''' See descriptoin for haiss_m3 ''' term=5.89*10**-6 ### Calculate diameter from experimental fit parameters if exp: C1=-4.75 C2=0.314 ### Calculate diameter from theoretical fit parameters else: C1=-4.70 C2=0.300 ret...
def _haiss_m3(Aspr, Cau, exp=True):
''' See descriptoin for haiss_m3 ''' term=5.89*10**-6 ### Calculate diameter from experimental fit parameters if exp: C1=-4.75 C2=0.314 ### Calculate diameter from theoretical fit parameters else: C1=-4.70 C2=0.300 return ( (Aspr * term )/ (Cau * math.ex...
(axis=0) ### Scale up Aspr based on dilution factor. if dilution: Aspr=Aspr/dilution return Aspr.apply(_haiss_m3, Cau=Cau, exp=exp) def _haiss_m3(Aspr, Cau, exp=True):
64
64
126
15
49
hugadams/scikit-spectra
skspec/nptools/haiss.py
Python
_haiss_m3
_haiss_m3
271
286
271
271
43b7538c6976078c1d3266cf344d4d03e33d3018
bigcode/the-stack
train
eb023fad43bd68f1fae57278
train
class
class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--check", action="store_true", dest="check", help="Include this option to check the counts but not do any updating", ) def handle(self, **options): open_se...
class Command(BaseCommand):
def add_arguments(self, parser): parser.add_argument( "--check", action="store_true", dest="check", help="Include this option to check the counts but not do any updating", ) def handle(self, **options): open_sessions = SQLXFormsSession.obj...
from datetime import datetime from django.core.management.base import BaseCommand from corehq.apps.smsforms.models import SQLXFormsSession class Command(BaseCommand):
32
87
290
5
26
dimagilg/commcare-hq
corehq/apps/smsforms/management/commands/smsforms_sessions_backfill.py
Python
Command
Command
8
48
8
9
d44195712451d2feb8e7c42127b0f993614f4829
bigcode/the-stack
train
961015651a8aa95925b75380
train
class
class AbsDeepQNetwork(metaclass=abc.ABCMeta): @abc.abstractmethod def build_model(self, obs_t_ph: tf.placeholder): pass
class AbsDeepQNetwork(metaclass=abc.ABCMeta): @abc.abstractmethod
def build_model(self, obs_t_ph: tf.placeholder): pass
import abc import tensorflow as tf class AbsDeepQNetwork(metaclass=abc.ABCMeta): @abc.abstractmethod
28
64
36
20
7
xiaojianyang820/StandardRL
DQN/model.py
Python
AbsDeepQNetwork
AbsDeepQNetwork
5
8
5
6
af976b1fa544da24754bb33e4956e074c738af06
bigcode/the-stack
train
e192e423219681234f705e10
train
class
class DeepQNetwork(AbsDeepQNetwork): def __init__(self, act_dim: int, conv_1_filter_num: int = 32, conv_1_kernel_size: tuple = (8, 8), conv_1_strides: int = 4, conv_2_filter_num: int = 64, conv_2_kernel_size: tuple = (4, 4), conv_2_strides: int = 2, conv_3_filt...
class DeepQNetwork(AbsDeepQNetwork):
def __init__(self, act_dim: int, conv_1_filter_num: int = 32, conv_1_kernel_size: tuple = (8, 8), conv_1_strides: int = 4, conv_2_filter_num: int = 64, conv_2_kernel_size: tuple = (4, 4), conv_2_strides: int = 2, conv_3_filter_num: int = 64, conv_3_kernel_size: ...
import abc import tensorflow as tf class AbsDeepQNetwork(metaclass=abc.ABCMeta): @abc.abstractmethod def build_model(self, obs_t_ph: tf.placeholder): pass class DeepQNetwork(AbsDeepQNetwork):
54
226
756
10
43
xiaojianyang820/StandardRL
DQN/model.py
Python
DeepQNetwork
DeepQNetwork
11
54
11
11
f05e91e4f1495c298d6df4d4852454a04eb68680
bigcode/the-stack
train
f0bfd9416e99d3ec3a810859
train
class
class mhd_jet(py3Pluto): """ This is a sub-class of py3Pluto, designed to visualise all MHD specific data sets calculated in the superclass. data_path: str - path to .h5 files output by PLUTO time_step: int - the number which is in the name of the file representing time-step Def...
class mhd_jet(py3Pluto):
""" This is a sub-class of py3Pluto, designed to visualise all MHD specific data sets calculated in the superclass. data_path: str - path to .h5 files output by PLUTO time_step: int - the number which is in the name of the file representing time-step Defaults to 0 dpi: i...
#%% """ The module contains the subclass of the package that deals with all the magnetohydrodynamic visualisation. It selects the variable to use for each visualisation method when they are called. Current version has data selection happening in this class to have physics specific data access from superclass. """ from...
127
256
12,575
10
116
mateczentye/pluto_python
pluto_python/mhd_jet.py
Python
mhd_jet
mhd_jet
19
1,107
19
19
fe5793092ef5bbb5b72e5f00ba8e0f2134adfedc
bigcode/the-stack
train
dd08557f25b4708b9d97ac26
train
function
def main(): "Read the Advent of Code problem and solve it" # 1. Get the command line options args = parse_command_line() # 2. Read the puzzle file input_text = from_file(args.filepath) # 3. Process the appropiate part of the puzzle if args.part == 1: result = part_one(args, input_...
def main():
"Read the Advent of Code problem and solve it" # 1. Get the command line options args = parse_command_line() # 2. Read the puzzle file input_text = from_file(args.filepath) # 3. Process the appropiate part of the puzzle if args.part == 1: result = part_one(args, input_text) el...
r') if not line: continue if line.startswith('!'): continue # 4. Add the line lines.append(line) # 5. Return a list of clean lines return lines # ---------------------------------------------------------------------- # ...
63
64
134
3
60
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
main
main
137
155
137
137
1f2328499c5b42d7b4b0675685f57f2040eebe5a
bigcode/the-stack
train
b65622e714c93770e41ecc29
train
function
def part_two(args, input_lines): "Process part two of the puzzle" # 1. Create the puzzle solver solver = fuelcell.Fuelcell(part2=True, text=input_lines) # 2. Determine the solution for part two solution = solver.part_two(verbose=args.verbose, limit=args.limit) if solution is None: prin...
def part_two(args, input_lines):
"Process part two of the puzzle" # 1. Create the puzzle solver solver = fuelcell.Fuelcell(part2=True, text=input_lines) # 2. Determine the solution for part two solution = solver.part_two(verbose=args.verbose, limit=args.limit) if solution is None: print("There is no solution") els...
print("There is no solution") else: print("The solution for part one is (%d,%d)" % (solution)) # 3. Return result return solution is not None # ---------------------------------------------------------------------- # part_two # ...
63
64
121
8
55
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
part_two
part_two
77
92
77
77
c3dc6f8a498c6cd383255de8ae804f3e77095694
bigcode/the-stack
train
5a87f258cc33be232532feb4
train
function
def parse_command_line(): "Parse the command line options" # 1. Create the command line parser desc = 'Chronal Charge - Day 11 of Advent of Code 2018' sample = 'sample: python aoc_11.py input.txt' parser = argparse.ArgumentParser(description=desc, epilog=sample)...
def parse_command_line():
"Parse the command line options" # 1. Create the command line parser desc = 'Chronal Charge - Day 11 of Advent of Code 2018' sample = 'sample: python aoc_11.py input.txt' parser = argparse.ArgumentParser(description=desc, epilog=sample) parser.add_argument('...
# ====================================================================== "Solve the puzzles for Advent of Code 2018 day 11" # ---------------------------------------------------------------------- # import # ----------------------------------------------...
67
68
229
5
62
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
parse_command_line
parse_command_line
30
49
30
30
1527d5959db220eb5eaeca40f9963a32146e7a3d
bigcode/the-stack
train
062f7a79e4bb981798349a1e
train
function
def part_one(args, input_lines): "Process part one of the puzzle" # 1. Create the puzzle solver solver = fuelcell.Fuelcell(part2=False, text=input_lines) # 2. Determine the solution for part one solution = solver.part_one(verbose=args.verbose, limit=args.limit) if solution is None: pri...
def part_one(args, input_lines):
"Process part one of the puzzle" # 1. Create the puzzle solver solver = fuelcell.Fuelcell(part2=False, text=input_lines) # 2. Determine the solution for part one solution = solver.part_one(verbose=args.verbose, limit=args.limit) if solution is None: print("There is no solution") el...
parser.add_argument('filepath', metavar='FILENAME', action='store', type=str, help="Location of puzzle input") # 2. Get the options and arguments return parser.parse_args() # ---------------------------------------------------------------------- # ...
63
64
119
8
55
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
part_one
part_one
56
70
56
56
c77b8414577032371b8b16f63142c5df57d924d1
bigcode/the-stack
train
ef60ada12dc27e3bbaa563c6
train
function
def from_text(text): "Break the text into trimed, non-comment lines" # 1. We start with no lines lines = [] # 2. Loop for lines in the text for line in text.split('\n'): # 3. But ignore blank and non-claim lines line = line.rstrip(' \r') if not line: continue ...
def from_text(text):
"Break the text into trimed, non-comment lines" # 1. We start with no lines lines = [] # 2. Loop for lines in the text for line in text.split('\n'): # 3. But ignore blank and non-claim lines line = line.rstrip(' \r') if not line: continue if line.starts...
# 3. Return result return solution is not None # ---------------------------------------------------------------------- # from_file # ---------------------------------------------------------------------- def from_file(filepath): "Read the fil...
63
64
126
5
58
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
from_text
from_text
110
130
110
110
3456ab784977bf51a1f93d72ac7441725a409411
bigcode/the-stack
train
185c98b0bc43363f530b45d6
train
function
def from_file(filepath): "Read the file" return from_text(open(filepath).read())
def from_file(filepath):
"Read the file" return from_text(open(filepath).read())
: print("There is no solution") else: print("The solution for part two is (%d,%d,%d)" % (solution)) # 3. Return result return solution is not None # ---------------------------------------------------------------------- # from_...
63
64
20
5
58
deanearlwright/AdventOfCode
2018/11_ChronalCharge/aoc_11.py
Python
from_file
from_file
100
103
100
100
da755c5da258dd30abbe58d8e87f2093d4f889c0
bigcode/the-stack
train
f2e80b60a3e21327fc96f0fb
train
function
def run( image: str, name: str, command: Union[List[str], str, None] = None, volumes: Dict[_Path, _Path] = {"/mnt": "/mnt"}, # noqa: B006 tty: bool = False, pull: bool = False, follow_logs: bool = False, rm: bool = False, args: List[str] = [ # noqa: B006 "--network=host", ...
def run( image: str, name: str, command: Union[List[str], str, None] = None, volumes: Dict[_Path, _Path] = {"/mnt": "/mnt"}, # noqa: B006 tty: bool = False, pull: bool = False, follow_logs: bool = False, rm: bool = False, args: List[str] = [ # noqa: B006 "--network=host", ...
"""Start the container.""" cmd = [] if not command else command if isinstance(cmd, str): cmd = shlex.split(cmd) if pull: subprocess.run(["docker", "pull", image], stdout=sys.stdout, stderr=sys.stderr) print("") args = ["docker", "run", f"--name={name}", "-it" if tty else "-...
def run( image: str, name: str, command: Union[List[str], str, None] = None, volumes: Dict[_Path, _Path] = {"/mnt": "/mnt"}, # noqa: B006 tty: bool = False, pull: bool = False, follow_logs: bool = False, rm: bool = False, args: List[str] = [ # noqa: B006 "--network=host", ...
203
152
508
203
0
BYU-PCCL/conversational-ai
docker.py
Python
run
run
18
69
18
37
e3016255df35c6250c316d3e7276331789288a06
bigcode/the-stack
train
15df10941612f0be3e9f40d3
train
function
def DrbdNeedsActivation(disks): """Checks which of the passed disks needs activation and returns their UUIDs. """ faulty_disks = [] for disk in disks: rd = _RecursiveFindBD(disk) if rd is None: faulty_disks.append(disk) continue stats = rd.GetProcStatus() if stats.is_standalone or...
def DrbdNeedsActivation(disks):
"""Checks which of the passed disks needs activation and returns their UUIDs. """ faulty_disks = [] for disk in disks: rd = _RecursiveFindBD(disk) if rd is None: faulty_disks.append(disk) continue stats = rd.GetProcStatus() if stats.is_standalone or stats.is_diskless: faulty...
=%s", rd, stats) alldone = alldone and (not stats.is_in_resync) if stats.sync_percent is not None: min_resync = min(min_resync, stats.sync_percent) return (alldone, min_resync) def DrbdNeedsActivation(disks):
64
64
106
8
56
jfut/ganeti
lib/backend.py
Python
DrbdNeedsActivation
DrbdNeedsActivation
5,600
5,616
5,600
5,600
c6f9121c674ead30c727e0f7af31e3f04ef5e223
bigcode/the-stack
train
539666bb30eabd3e5e49d071
train
class
class RPCFail(Exception): """Class denoting RPC failure. Its argument is the error message. """
class RPCFail(Exception):
"""Class denoting RPC failure. Its argument is the error message. """
10 #: How long to wait to acquire lock for restricted commands (shorter than #: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many #: command requests arrive _RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8 class RPCFail(Exception):
64
64
23
5
58
jfut/ganeti
lib/backend.py
Python
RPCFail
RPCFail
128
133
128
128
788d794376860bccbf0cb19b7343b333b525963e
bigcode/the-stack
train
9f8f2a58da561d9bba375b84
train
function
def GetInstanceInfo(instance, hname, hvparams=None): """Gives back the information about an instance as a dictionary. @type instance: string @param instance: the instance name @type hname: string @param hname: the hypervisor type of the instance @type hvparams: dict of strings @param hvparams: the instan...
def GetInstanceInfo(instance, hname, hvparams=None):
"""Gives back the information about an instance as a dictionary. @type instance: string @param instance: the instance name @type hname: string @param hname: the hypervisor type of the instance @type hvparams: dict of strings @param hvparams: the instance's hvparams @rtype: dict @return: dictionary w...
""" results = [] for hname in hypervisor_list: hvparams = all_hvparams[hname] results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams, get_hv_fn=get_hv_fn)) return results def GetInstanceInfo(instance, hname, hvparams=None):
72
72
240
13
58
jfut/ganeti
lib/backend.py
Python
GetInstanceInfo
GetInstanceInfo
2,524
2,552
2,524
2,524
040bacd28ec15704c0d0bd4db8cee36e5a236de8
bigcode/the-stack
train
4a8195d3c7b1b42372b180d5
train
function
def _GetVgInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo): """Retrieves information about a LVM volume group. """ # TODO: GetVGInfo supports returning information for multiple VGs at once vginfo = info_fn([name], excl_stor) if vginfo: vg_free = int(round(vginfo[0][0], 0)) vg_size = i...
def _GetVgInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
"""Retrieves information about a LVM volume group. """ # TODO: GetVGInfo supports returning information for multiple VGs at once vginfo = info_fn([name], excl_stor) if vginfo: vg_free = int(round(vginfo[0][0], 0)) vg_size = int(round(vginfo[0][1], 0)) else: vg_free = None vg_size = None ...
should be containing only one for exclusive storage """ excl_stor = _CheckLvmStorageParams(params) return _GetVgInfo(name, excl_stor) def _GetVgInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
64
64
161
25
39
jfut/ganeti
lib/backend.py
Python
_GetVgInfo
_GetVgInfo
639
658
639
640
3a339a00e24516593e2616aaa6c4bde161c65244
bigcode/the-stack
train
28e2cf2eeb672cac3c13f0ad
train
function
def _GetInstReasonFilename(instance_name): """Path of the file containing the reason of the instance status change. @type instance_name: string @param instance_name: The name of the instance @rtype: string @return: The path of the file """ return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_na...
def _GetInstReasonFilename(instance_name):
"""Path of the file containing the reason of the instance status change. @type instance_name: string @param instance_name: The name of the instance @rtype: string @return: The path of the file """ return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
to reduce blockage of noded forks when many #: command requests arrive _RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8 class RPCFail(Exception): """Class denoting RPC failure. Its argument is the error message. """ def _GetInstReasonFilename(instance_name):
63
64
76
9
54
jfut/ganeti
lib/backend.py
Python
_GetInstReasonFilename
_GetInstReasonFilename
136
145
136
136
6337c4b2f9e165d3f4b4931c358a8a80c19cc154
bigcode/the-stack
train
702a6d1a36e727b66c97ccbd
train
function
def BlockdevAssemble(disk, instance, as_primary, idx): """Activate a block device for an instance. This is a wrapper over _RecursiveAssembleBD. @rtype: str or boolean @return: a tuple with the C{/dev/...} path and the created symlink for primary nodes, and (C{True}, C{True}) for secondary nodes """ ...
def BlockdevAssemble(disk, instance, as_primary, idx):
"""Activate a block device for an instance. This is a wrapper over _RecursiveAssembleBD. @rtype: str or boolean @return: a tuple with the C{/dev/...} path and the created symlink for primary nodes, and (C{True}, C{True}) for secondary nodes """ try: result = _RecursiveAssembleBD(disk, instance....
= bdev.Assemble(disk, children) result = r_dev if as_primary or disk.OpenOnSecondary(): r_dev.Open() DevCacheManager.UpdateCache(r_dev.dev_path, owner, as_primary, disk.iv_name) else: result = True return result def BlockdevAssemble(disk, instance, as_primary,...
79
79
266
15
63
jfut/ganeti
lib/backend.py
Python
BlockdevAssemble
BlockdevAssemble
3,656
3,685
3,656
3,656
8ba2eb7505571bebf8e0fc0c27f09f5f3bfed47d
bigcode/the-stack
train
a4033cfdead59757bb7902ee
train
function
def StartInstance(instance, startup_paused, reason, store_reason=True): """Start an instance. @type instance: L{objects.Instance} @param instance: the instance object @type startup_paused: bool @param instance: pause instance at startup? @type reason: list of reasons @param reason: the reason trail for t...
def StartInstance(instance, startup_paused, reason, store_reason=True):
"""Start an instance. @type instance: L{objects.Instance} @param instance: the instance object @type startup_paused: bool @param instance: pause instance at startup? @type reason: list of reasons @param reason: the reason trail for this startup @type store_reason: boolean @param store_reason: whether...
)) 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): """Helper function L{GetInstanceInfo}""" return GetInstanceInfo(instance.name, ins...
99
99
333
15
84
jfut/ganeti
lib/backend.py
Python
StartInstance
StartInstance
2,892
2,928
2,892
2,892
4747d1777c128a916111e9e9de195bce383da906
bigcode/the-stack
train
8a9ef09a471fc4b1be1c522c
train
function
def BlockdevGetdimensions(disks): """Computes the size of the given disks. If a disk is not found, returns None instead. @type disks: list of L{objects.Disk} @param disks: the list of disk to compute the size for @rtype: list @return: list with elements None if the disk cannot be found, otherwise th...
def BlockdevGetdimensions(disks):
"""Computes the size of the given disks. If a disk is not found, returns None instead. @type disks: list of L{objects.Disk} @param disks: the list of disk to compute the size for @rtype: list @return: list with elements None if the disk cannot be found, otherwise the pair (size, spindles), where spi...
rbd = _RecursiveFindBD(disk) except errors.BlockDeviceError as err: _Fail("Failed to find device: %s", err, exc=True) if rbd is None: return None return rbd.GetSyncStatus() def BlockdevGetdimensions(disks):
64
64
174
8
56
jfut/ganeti
lib/backend.py
Python
BlockdevGetdimensions
BlockdevGetdimensions
3,906
3,930
3,906
3,906
3fc2636348546ba38c38d38cc0946b30fcc5c7e0
bigcode/the-stack
train
bb1281275ea9cc426bbf0d2f
train
function
def _ReplaceMasterKeyOnMaster(root_keyfiles): number_of_moves = 0 for (_, (private_key_file, public_key_file)) in root_keyfiles.items(): key_dir = os.path.dirname(public_key_file) private_key_file_tmp = \ os.path.basename(private_key_file) + constants.SSHS_MASTER_SUFFIX public_key_file_tmp = priva...
def _ReplaceMasterKeyOnMaster(root_keyfiles):
number_of_moves = 0 for (_, (private_key_file, public_key_file)) in root_keyfiles.items(): key_dir = os.path.dirname(public_key_file) private_key_file_tmp = \ os.path.basename(private_key_file) + constants.SSHS_MASTER_SUFFIX public_key_file_tmp = private_key_file_tmp + ".pub" private_key_path_...
# for some key types, there might not be any keys key = utils.ReadFile(public_key_path_tmp) new_master_keys.append(key) if not new_master_keys: raise errors.SshUpdateError("Cannot find any type of temporary SSH key.") return {master_node_uuid: new_master_keys} def _ReplaceMasterKeyOnMaster(roo...
78
78
263
11
67
jfut/ganeti
lib/backend.py
Python
_ReplaceMasterKeyOnMaster
_ReplaceMasterKeyOnMaster
2,070
2,094
2,070
2,070
dc3377b9a496828d38bd749f9c1402bf54ccc575
bigcode/the-stack
train
7d03844ed38185385f851e6c
train
function
def FinalizeMigrationSource(instance, success, live): """Finalize the instance migration on the source node. @type instance: L{objects.Instance} @param instance: the instance definition of the migrated instance @type success: bool @param success: whether the migration succeeded or not @type live: bool @p...
def FinalizeMigrationSource(instance, success, live):
"""Finalize the instance migration on the source node. @type instance: L{objects.Instance} @param instance: the instance definition of the migrated instance @type success: bool @param success: whether the migration succeeded or not @type live: bool @param live: whether the user requested a live migration...
hypervisor.GetHypervisor(instance.hypervisor) try: hyper.MigrateInstance(cluster_name, instance, target, live) except errors.HypervisorError as err: _Fail("Failed to migrate instance: %s", err, exc=True) def FinalizeMigrationSource(instance, success, live):
64
64
167
11
53
jfut/ganeti
lib/backend.py
Python
FinalizeMigrationSource
FinalizeMigrationSource
3,143
3,161
3,143
3,143
06bdafaaceede45a83d223613d1ce6b997d51117
bigcode/the-stack
train
595b6cb9dc2ca664bde2eb2c
train
function
def InstanceBalloonMemory(instance, memory): """Resize an instance's memory. @type instance: L{objects.Instance} @param instance: the instance object @type memory: int @param memory: new memory amount in MB @rtype: None """ hyper = hypervisor.GetHypervisor(instance.hypervisor) running = hyper.ListIn...
def InstanceBalloonMemory(instance, memory):
"""Resize an instance's memory. @type instance: L{objects.Instance} @param instance: the instance object @type memory: int @param memory: new memory amount in MB @rtype: None """ hyper = hypervisor.GetHypervisor(instance.hypervisor) running = hyper.ListInstances(hvparams=instance.hvparams) if inst...
ReasonTrail(instance.name, reason) except errors.HypervisorError as err: _Fail("Failed to hard reboot instance '%s': %s", instance.name, err) else: _Fail("Invalid reboot_type received: '%s'", reboot_type) def InstanceBalloonMemory(instance, memory):
64
64
159
9
55
jfut/ganeti
lib/backend.py
Python
InstanceBalloonMemory
InstanceBalloonMemory
3,048
3,066
3,048
3,048
46249ec4994265235dcfaf86327738f2f75e2be5
bigcode/the-stack
train
9fc7c58550f44905fcfeeb04
train
function
def GetNodeInfo(storage_units, hv_specs): """Gives back a hash with different information about the node. @type storage_units: list of tuples (string, string, list) @param storage_units: List of tuples (storage unit, identifier, parameters) to ask for disk space information. In case of lvm-vg, the identifier...
def GetNodeInfo(storage_units, hv_specs):
"""Gives back a hash with different information about the node. @type storage_units: list of tuples (string, string, list) @param storage_units: List of tuples (storage unit, identifier, parameters) to ask for disk space information. In case of lvm-vg, the identifier is the VG name. The parameters can co...
return result 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 GetNodeInfo(storage_units, hv_specs):
81
81
272
10
71
jfut/ganeti
lib/backend.py
Python
GetNodeInfo
GetNodeInfo
746
769
746
746
b0f8ab4c7ddd36ae150f4984d271fc449147fec4
bigcode/the-stack
train
f002302a299e73d27b07104b
train
function
def GetMigrationStatus(instance): """Get the migration status @type instance: L{objects.Instance} @param instance: the instance that is being migrated @rtype: L{objects.MigrationStatus} @return: the status of the current migration (one of L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additio...
def GetMigrationStatus(instance):
"""Get the migration status @type instance: L{objects.Instance} @param instance: the instance that is being migrated @rtype: L{objects.MigrationStatus} @return: the status of the current migration (one of L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional progress info that ...
visor(instance.hypervisor) try: hyper.FinalizeMigrationSource(instance, success, live) except Exception as err: # pylint: disable=W0703 _Fail("Failed to finalize the migration on the source node: %s", err, exc=True) def GetMigrationStatus(instance):
64
64
161
6
58
jfut/ganeti
lib/backend.py
Python
GetMigrationStatus
GetMigrationStatus
3,164
3,180
3,164
3,164
ad0baff94e15c3b22f649e6c5be7114ae79a8eda
bigcode/the-stack
train
5cca574bb1ae95bddf20f5a4
train
function
def ExportOS(instance, override_env): """Creates a GZIPed tarball with an OS definition and environment. The archive contains a file with the environment variables needed by the OS scripts. @type instance: L{objects.Instance} @param instance: instance for which the OS definition is exported @type overrid...
def ExportOS(instance, override_env):
"""Creates a GZIPed tarball with an OS definition and environment. The archive contains a file with the environment variables needed by the OS scripts. @type instance: L{objects.Instance} @param instance: instance for which the OS definition is exported @type override_env: dict of string to string @par...
(tbv, list(osparams)) validate_env = OSCoreEnv(osname, tbv, osparams) result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env, cwd=tbv.path, reset_env=True) if result.failed: logging.error("os validate command '%s' returned error: %s output: %s", result....
129
129
433
8
120
jfut/ganeti
lib/backend.py
Python
ExportOS
ExportOS
5,015
5,067
5,015
5,015
c17d6b3bf46be85a69cc08e9e860c2c4cb6cbacb
bigcode/the-stack
train
41a2a32bf51e51a0eb8b3969
train
function
def EnsureDaemon(daemon_name, run): """Ensures the given daemon is running or stopped. @type daemon_name: string @param daemon_name: name of the daemon (e.g., constants.KVMD) @type run: bool @param run: whether to start or stop the daemon @rtype: bool @return: 'True' if daemon successfully started/stop...
def EnsureDaemon(daemon_name, run):
"""Ensures the given daemon is running or stopped. @type daemon_name: string @param daemon_name: name of the daemon (e.g., constants.KVMD) @type run: bool @param run: whether to start or stop the daemon @rtype: bool @return: 'True' if daemon successfully started/stopped, 'False' otherwise ...
constants.CRYPTO_ACTIONS: raise errors.ProgrammerError("Action '%s' is not supported." % action) if token_type == constants.CRYPTO_TYPE_SSL_DIGEST: tokens.append((token_type, utils.GetCertificateDigest())) return tokens def EnsureDaemon(daemon_n...
64
64
153
9
54
jfut/ganeti
lib/backend.py
Python
EnsureDaemon
EnsureDaemon
1,429
1,452
1,429
1,429
5bf4e32b1104504a3ac8f8146919d8c3c4700716
bigcode/the-stack
train
c303337c81b25e9e6cd8d1a1
train
function
def BlockdevRemovechildren(parent_cdev, new_cdevs): """Shrink a mirrored block device. @type parent_cdev: L{objects.Disk} @param parent_cdev: the disk from which we should remove children @type new_cdevs: list of L{objects.Disk} @param new_cdevs: the list of children which we should remove @rtype: None ...
def BlockdevRemovechildren(parent_cdev, new_cdevs):
"""Shrink a mirrored block device. @type parent_cdev: L{objects.Disk} @param parent_cdev: the disk from which we should remove children @type new_cdevs: list of L{objects.Disk} @param new_cdevs: the list of children which we should remove @rtype: None """ parent_bdev = _RecursiveFindBD(parent_cdev) ...
isk) for disk in new_cdevs] if new_bdevs.count(None) > 0: _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs) parent_bdev.AddChildren(new_bdevs) def BlockdevRemovechildren(parent_cdev, new_cdevs):
76
76
254
14
62
jfut/ganeti
lib/backend.py
Python
BlockdevRemovechildren
BlockdevRemovechildren
3,745
3,771
3,745
3,745
19eef4beb0570e38e14459a331e9ff0e75272324
bigcode/the-stack
train
b0661eb25ee4ffe8c815b50b
train
function
def RunRestrictedCmd(cmd, _lock_timeout=_RCMD_LOCK_TIMEOUT, _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE, _path=pathutils.RESTRICTED_COMMANDS_DIR, _sleep_fn=time.sleep, _prepare_fn=_PrepareRestrictedCmd, ...
def RunRestrictedCmd(cmd, _lock_timeout=_RCMD_LOCK_TIMEOUT, _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE, _path=pathutils.RESTRICTED_COMMANDS_DIR, _sleep_fn=time.sleep, _prepare_fn=_PrepareRestrictedCmd, ...
"""Executes a restricted command after performing strict tests. @type cmd: string @param cmd: Command name @rtype: string @return: Command output @raise RPCFail: In case of an error """ logging.info("Preparing to run restricted command '%s'", cmd) if not _enabled: _Fail("Restricted commands dis...
command if everything was alright (status, msg) = _verify_name(cmd) if not status: return (False, msg) # Check actual executable return _verify_cmd(path, cmd) def RunRestrictedCmd(cmd, _lock_timeout=_RCMD_LOCK_TIMEOUT, _lock_file=pathutils.RESTRICTED_COMMANDS_L...
129
129
433
84
45
jfut/ganeti
lib/backend.py
Python
RunRestrictedCmd
RunRestrictedCmd
5,778
5,834
5,778
5,785
d9503a03353d53c591c1a9a914d01d5251c7e36a
bigcode/the-stack
train
c1dac729791f6efed3927afd
train
function
def AbortImportExport(name): """Sends SIGTERM to a running import/export daemon. """ logging.info("Abort import/export %s", name) status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name) pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE)) if pid: logging.info("Import/export...
def AbortImportExport(name):
"""Sends SIGTERM to a running import/export daemon. """ logging.info("Abort import/export %s", name) status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name) pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE)) if pid: logging.info("Import/export %s is running with PID %s, s...
= utils.ReadFile(status_file) except EnvironmentError as err: if err.errno != errno.ENOENT: raise data = None if not data: result.append(None) continue result.append(serializer.LoadJson(data)) return result def AbortImportExport(name):
64
64
112
6
57
jfut/ganeti
lib/backend.py
Python
AbortImportExport
AbortImportExport
5,439
5,451
5,439
5,439
3fd032279602f4a0b72e00b3cb6e317d79b2cd8f
bigcode/the-stack
train
ee4e1f22957879c347956e12
train
function
def _GetSshRunner(cluster_name): """Simple wrapper to return an SshRunner. @type cluster_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 _GetSshRunner(cluster_name):
"""Simple wrapper to return an SshRunner. @type cluster_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)
logging.error(msg) raise RPCFail(msg) def _GetConfig(): """Simple wrapper to return a SimpleStore. @rtype: L{ssconf.SimpleStore} @return: a SimpleStore instance """ return ssconf.SimpleStore() def _GetSshRunner(cluster_name):
64
64
82
9
55
jfut/ganeti
lib/backend.py
Python
_GetSshRunner
_GetSshRunner
201
211
201
201
4bf742f44bdff3964ebe9c90297d0a2794d55e0c
bigcode/the-stack
train
e571f0c1b9b747cde41590b2
train
function
def CreateFileStorageDir(file_storage_dir): """Create file storage directory. @type file_storage_dir: str @param file_storage_dir: directory to create @rtype: tuple @return: tuple with first element a boolean indicating wheter dir creation was successful or not """ file_storage_dir = _TransformFi...
def CreateFileStorageDir(file_storage_dir):
"""Create file storage directory. @type file_storage_dir: str @param file_storage_dir: directory to create @rtype: tuple @return: tuple with first element a boolean indicating wheter dir creation was successful or not """ file_storage_dir = _TransformFileStorageDir(file_storage_dir) if os.path....
. @type fs_dir: str @param fs_dir: the path to check @return: the normalized path if valid, None otherwise """ filestorage.CheckFileStoragePath(fs_dir) return os.path.normpath(fs_dir) def CreateFileStorageDir(file_storage_dir):
64
64
169
9
55
jfut/ganeti
lib/backend.py
Python
CreateFileStorageDir
CreateFileStorageDir
4,698
4,719
4,698
4,698
973b8974c8d5d0dd692a258faa803844c9139cab
bigcode/the-stack
train
312855202b922d049a66d455
train
function
def _CreateImportExportStatusDir(prefix): """Creates status directory for import/export. """ return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR, prefix=("%s-%s-" % (prefix, utils.TimestampForFilename())))
def _CreateImportExportStatusDir(prefix):
"""Creates status directory for import/export. """ return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR, prefix=("%s-%s-" % (prefix, utils.TimestampForFilename())))
" % script_cmd # Let script predict size exp_size = constants.IE_CUSTOM_SIZE else: _Fail("Invalid %s I/O mode %r", mode, ieio) return (env, prefix, suffix, exp_size) def _CreateImportExportStatusDir(prefix):
64
64
53
9
55
jfut/ganeti
lib/backend.py
Python
_CreateImportExportStatusDir
_CreateImportExportStatusDir
5,265
5,271
5,265
5,265
0ce83e859ca986ec2f9f78e7dc1aea042078258e
bigcode/the-stack
train
bdba6e5337793d47027c70b2
train
function
def RemoveFileStorageDir(file_storage_dir): """Remove file storage directory. Remove it only if it's empty. If not log an error and return. @type file_storage_dir: str @param file_storage_dir: the directory we should cleanup @rtype: tuple (success,) @return: tuple of one element, C{success}, denoting ...
def RemoveFileStorageDir(file_storage_dir):
"""Remove file storage directory. Remove it only if it's empty. If not log an error and return. @type file_storage_dir: str @param file_storage_dir: the directory we should cleanup @rtype: tuple (success,) @return: tuple of one element, C{success}, denoting whether the operation was successful ""...
file_storage_dir) else: try: os.makedirs(file_storage_dir, 0o750) except OSError as err: _Fail("Cannot create file storage directory '%s': %s", file_storage_dir, err, exc=True) def RemoveFileStorageDir(file_storage_dir):
64
64
197
9
55
jfut/ganeti
lib/backend.py
Python
RemoveFileStorageDir
RemoveFileStorageDir
4,722
4,744
4,722
4,722
1f4be9fb8a359ccf68af90d468d758bc5ac91c5c
bigcode/the-stack
train
08af7152064b23713fb6fab8
train
function
def AddNodeSshKey(node_uuid, node_name, potential_master_candidates, to_authorized_keys=False, to_public_keys=False, get_public_keys=False, pub_key_file=pathutils.SSH_PUB_KEYS, ssconf_store=None, ...
def AddNodeSshKey(node_uuid, node_name, potential_master_candidates, to_authorized_keys=False, to_public_keys=False, get_public_keys=False, pub_key_file=pathutils.SSH_PUB_KEYS, ssconf_store=None, ...
"""Distributes a node's public SSH key across the cluster. Note that this function should only be executed on the master node, which then will copy the new node's key to all nodes in the cluster via SSH. Also note: at least one of the flags C{to_authorized_keys}, C{to_public_keys}, and C{get_public_keys} ha...
= \ 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 AddNodeSshKey(node_uuid, node_name, potential_master_candidates, ...
143
143
477
82
60
jfut/ganeti
lib/backend.py
Python
AddNodeSshKey
AddNodeSshKey
1,464
1,508
1,464
1,472
156f730bc4d1477a47c05e9dffa8916315bc2ed3
bigcode/the-stack
train
f53721a684cbda97f7731cf2
train
function
def DrbdWaitSync(disks): """Wait until DRBDs have synchronized. """ def _helper(rd): stats = rd.GetProcStatus() if not (stats.is_connected or stats.is_in_resync): raise utils.RetryAgain() return stats bdevs = _FindDisks(disks) min_resync = 100 alldone = True for rd in bdevs: try: ...
def DrbdWaitSync(disks):
"""Wait until DRBDs have synchronized. """ def _helper(rd): stats = rd.GetProcStatus() if not (stats.is_connected or stats.is_in_resync): raise utils.RetryAgain() return stats bdevs = _FindDisks(disks) min_resync = 100 alldone = True for rd in bdevs: try: # poll each second ...
with a delay of 100 miliseconds and go up to 5 seconds utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60) except utils.RetryTimeout: _Fail("Timeout in disk reconnecting") def DrbdWaitSync(disks):
69
69
230
8
61
jfut/ganeti
lib/backend.py
Python
DrbdWaitSync
DrbdWaitSync
5,570
5,597
5,570
5,570
70be3e4ecfa3445f3b1dfff8c45abfe01298ae8c
bigcode/the-stack
train
57a837252f04a4a35ea220ed
train
function
def _CheckStorageParams(params, num_params): """Performs sanity checks for storage parameters. @type params: list @param params: list of storage parameters @type num_params: int @param num_params: expected number of parameters """ if params is None: raise errors.ProgrammerError("No storage parameter...
def _CheckStorageParams(params, num_params):
"""Performs sanity checks for storage parameters. @type params: list @param params: list of storage parameters @type num_params: int @param num_params: expected number of parameters """ if params is None: raise errors.ProgrammerError("No storage parameters for storage" ...
") utils.StopDaemon(constants.CONFD) utils.StopDaemon(constants.MOND) utils.StopDaemon(constants.KVMD) # Raise a custom exception (handled in ganeti-noded) raise errors.QuitGanetiException(True, "Shutdown scheduled") def _CheckStorageParams(params, num_params):
64
64
164
10
54
jfut/ganeti
lib/backend.py
Python
_CheckStorageParams
_CheckStorageParams
590
608
590
590
0460d2f53b9f65e1ccca8173d5e49b26dcfc2473
bigcode/the-stack
train
afe76561a30963e03deaf1fe
train
function
def GetInstanceMigratable(instance): """Computes whether an instance can be migrated. @type instance: L{objects.Instance} @param instance: object representing the instance to be checked. @rtype: tuple @return: tuple of (result, description) where: - result: whether the instance can be migrated or not ...
def GetInstanceMigratable(instance):
"""Computes whether an instance can be migrated. @type instance: L{objects.Instance} @param instance: object representing the instance to be checked. @rtype: tuple @return: tuple of (result, description) where: - result: whether the instance can be migrated or not - description: a description of...
if iinfo is not None: output["memory"] = iinfo[2] output["vcpus"] = iinfo[3] output["state"] = iinfo[4] output["time"] = iinfo[5] return output def GetInstanceMigratable(instance):
64
64
203
7
56
jfut/ganeti
lib/backend.py
Python
GetInstanceMigratable
GetInstanceMigratable
2,555
2,576
2,555
2,555
0d355dfec3b4f67feb1503357dc254f35c70182a
bigcode/the-stack
train
1aad0613c4e6365ed05ed8d4
train
function
def BlockdevGetmirrorstatusMulti(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 tuples, (bool, status), one for each disk; bool denotes success/failure, status is L{objects....
def BlockdevGetmirrorstatusMulti(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 tuples, (bool, status), one for each disk; bool denotes success/failure, status is L{objects.BlockDevStatus} on success, string ot...
: if any of the disks cannot be found """ stats = [] for dsk in disks: rbd = _RecursiveFindBD(dsk) if rbd is None: _Fail("Can't find device %s", dsk) stats.append(rbd.CombinedSyncStatus()) return stats def BlockdevGetmirrorstatusMulti(disks):
80
80
269
10
69
jfut/ganeti
lib/backend.py
Python
BlockdevGetmirrorstatusMulti
BlockdevGetmirrorstatusMulti
3,796
3,828
3,796
3,796
57ca5d18f1a8abd00e92b62786fb3b5dd88a04e2
bigcode/the-stack
train
006082091bc750ab019dec45
train
function
def _VerifyInstanceList(what, vm_capable, result, all_hvparams): """Verifies the instance 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...
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
"""Verifies the instance 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 verifications in this function will ...
_hv_fn(hv_name).ValidateParameters(hvparms) except errors.HypervisorError as err: result[constants.NV_HVPARAMS].append((source, hv_name, str(err))) def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
64
65
217
19
45
jfut/ganeti
lib/backend.py
Python
_VerifyInstanceList
_VerifyInstanceList
903
924
903
903
170b6e2fcb4ef0ef0100a2bbd0002f71f8fbf0e4
bigcode/the-stack
train
b978e3fea7d1d9e805af168d
train
function
def _GetNewMasterKey(root_keyfiles, master_node_uuid): new_master_keys = [] for (_, (_, public_key_file)) in root_keyfiles.items(): public_key_dir = os.path.dirname(public_key_file) public_key_file_tmp_filename = \ os.path.splitext(os.path.basename(public_key_file))[0] \ + constants.SSHS_MAS...
def _GetNewMasterKey(root_keyfiles, master_node_uuid):
new_master_keys = [] for (_, (_, public_key_file)) in root_keyfiles.items(): public_key_dir = os.path.dirname(public_key_file) public_key_file_tmp_filename = \ os.path.splitext(os.path.basename(public_key_file))[0] \ + constants.SSHS_MASTER_SUFFIX + ".pub" public_key_path_tmp = os.path.j...
_master_keys_by_uuid: raise errors.SshUpdateError("No public key of the master node (UUID '%s')" " found, not generating a new key." % master_node_uuid) return old_master_keys_by_uuid def _GetNewMasterKey(root_keyfiles, master_node_uuid):
64
64
177
14
49
jfut/ganeti
lib/backend.py
Python
_GetNewMasterKey
_GetNewMasterKey
2,052
2,067
2,052
2,052
f5fa2a677df4c79bdb37c0fa544fa8826d0afd53
bigcode/the-stack
train
143e8488a6ee379e69db5364
train
function
def BlockdevShutdown(disk): """Shut down a block device. First, if the device is assembled (Attach() is successful), then the device is shutdown. Then the children of the device are shutdown. This function is called recursively. Note that we don't cache the children or such, as oppossed to assemble, shutd...
def BlockdevShutdown(disk):
"""Shut down a block device. First, if the device is assembled (Attach() is successful), then the device is shutdown. Then the children of the device are shutdown. This function is called recursively. Note that we don't cache the children or such, as oppossed to assemble, shutdown of different devices d...
BD") except errors.BlockDeviceError as err: _Fail("Error while assembling disk: %s", err, exc=True) except OSError as err: _Fail("Error while symlinking disk: %s", err, exc=True) return dev_path, link_name, uri def BlockdevShutdown(disk):
71
71
237
7
63
jfut/ganeti
lib/backend.py
Python
BlockdevShutdown
BlockdevShutdown
3,688
3,723
3,688
3,688
594b1e1e8d567777c952d39d55963f6ca08a6171
bigcode/the-stack
train
6dfbe5b3c3f3f55dc7c3e1b5
train
function
def _IsInstanceUserDown(instance_info): return instance_info and \ "state" in instance_info and \ hv_base.HvInstanceState.IsShutdown(instance_info["state"])
def _IsInstanceUserDown(instance_info):
return instance_info and \ "state" in instance_info and \ hv_base.HvInstanceState.IsShutdown(instance_info["state"])
e: raise errors.BlockDeviceError("Cannot create block device symlink: %s" % e.strerror) uri = _CalculateDeviceURI(instance, disk, device) block_devices.append((disk, link_name, uri)) return block_devices def _IsInstanceUserDown(instance_info):
64
64
38
9
54
jfut/ganeti
lib/backend.py
Python
_IsInstanceUserDown
_IsInstanceUserDown
2,880
2,883
2,880
2,880
15d5a195eaa822036f57cd59ebb3a2313cd508df
bigcode/the-stack
train
40da8fce72dd0d496506a09b
train
function
def _PrepareRestrictedCmd(path, cmd, _verify_dir=_VerifyRestrictedCmdDirectory, _verify_name=_VerifyRestrictedCmdName, _verify_cmd=_VerifyRestrictedCmd): """Performs a number of tests on a restricted command. @type path: string @param ...
def _PrepareRestrictedCmd(path, cmd, _verify_dir=_VerifyRestrictedCmdDirectory, _verify_name=_VerifyRestrictedCmdName, _verify_cmd=_VerifyRestrictedCmd):
"""Performs a number of tests on a restricted command. @type path: string @param path: Directory containing restricted commands @type cmd: string @param cmd: Command name @return: Same as L{_VerifyRestrictedCmd} """ # Verify the directory first (status, msg) = _verify_dir(path) if status: # Ch...
(False, "access(2) thinks '%s' can't be executed" % executable) return (True, executable) def _PrepareRestrictedCmd(path, cmd, _verify_dir=_VerifyRestrictedCmdDirectory, _verify_name=_VerifyRestrictedCmdName, _verify_cmd=_VerifyRestricted...
64
64
169
38
26
jfut/ganeti
lib/backend.py
Python
_PrepareRestrictedCmd
_PrepareRestrictedCmd
5,752
5,775
5,752
5,755
8ec0d99899c79bc569dc3d7e5c22b03ef89b90f2
bigcode/the-stack
train
ac85d4a1604009851662babe
train
function
def BlockdevAddchildren(parent_cdev, new_cdevs): """Extend a mirrored block device. @type parent_cdev: L{objects.Disk} @param parent_cdev: the disk to which we should add children @type new_cdevs: list of L{objects.Disk} @param new_cdevs: the list of children which we should add @rtype: None """ paren...
def BlockdevAddchildren(parent_cdev, new_cdevs):
"""Extend a mirrored block device. @type parent_cdev: L{objects.Disk} @param parent_cdev: the disk to which we should add children @type new_cdevs: list of L{objects.Disk} @param new_cdevs: the list of children which we should add @rtype: None """ parent_bdev = _RecursiveFindBD(parent_cdev) if paren...
(str(err)) if disk.children: for child in disk.children: try: BlockdevShutdown(child) except RPCFail as err: msgs.append(str(err)) if msgs: _Fail("; ".join(msgs)) def BlockdevAddchildren(parent_cdev, new_cdevs):
64
64
205
14
50
jfut/ganeti
lib/backend.py
Python
BlockdevAddchildren
BlockdevAddchildren
3,726
3,742
3,726
3,726
e33c02b6456054de6137f7a31e37a40d376d627d
bigcode/the-stack
train
c02deecaea36a3e6df690330
train
function
def GetFileInfo(file_path): """ Checks if a file exists and returns information related to it. Currently returned information: - file size: int, size in bytes @type file_path: string @param file_path: Name of file to examine. @rtype: tuple of bool, dict @return: Whether the file exists, and a diction...
def GetFileInfo(file_path):
""" Checks if a file exists and returns information related to it. Currently returned information: - file size: int, size in bytes @type file_path: string @param file_path: Name of file to examine. @rtype: tuple of bool, dict @return: Whether the file exists, and a dictionary of information about the...
_name, ovs_link]) if result.failed: _Fail("Failed to connect openvswitch to interface %s. Script return" " value: %s, output: '%s'" % (ovs_link, result.exit_code, result.output), log=True) def GetFileInfo(file_path):
64
64
139
7
57
jfut/ganeti
lib/backend.py
Python
GetFileInfo
GetFileInfo
5,884
5,905
5,884
5,884
25714a510c601ba68d7d52f7effaa7698e7d159d
bigcode/the-stack
train
9cfd126e6340cf15e2638b36
train
function
def AddNodeSshKeyBulk(node_list, potential_master_candidates, pub_key_file=pathutils.SSH_PUB_KEYS, ssconf_store=None, noded_cert_file=pathutils.NODED_CERT_FILE, run_cmd_fn=ssh.RunSshCmdWithStdin): """Distribu...
def AddNodeSshKeyBulk(node_list, potential_master_candidates, pub_key_file=pathutils.SSH_PUB_KEYS, ssconf_store=None, noded_cert_file=pathutils.NODED_CERT_FILE, run_cmd_fn=ssh.RunSshCmdWithStdin):
"""Distributes a node's public SSH key across the cluster. Note that this function should only be executed on the master node, which then will copy the new node's key to all nodes in the cluster via SSH. Also note: at least one of the flags C{to_authorized_keys}, C{to_public_keys}, and C{get_public_keys} ha...
boolean @param get_public_keys: whether the node should add the clusters' public keys to its {ganeti_pub_keys} file """ node_list = [SshAddNodeInfo(name=node_name, uuid=node_uuid, to_authorized_keys=to_authorized_keys, to_public_keys=to_public_keys...
255
256
1,524
61
194
jfut/ganeti
lib/backend.py
Python
AddNodeSshKeyBulk
AddNodeSshKeyBulk
1,521
1,675
1,521
1,526
ea13a785ca2b211df5c61eb4a9f3fe1ad11324c8
bigcode/the-stack
train
8312dacabd47658d3f20ba1d
train
function
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR): """Removes a X509 certificate. @type name: string @param name: Certificate name """ (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name) utils.RemoveFile(key_file) utils.RemoveFile(cert_file) try: os.rmdir(cert...
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
"""Removes a X509 certificate. @type name: string @param name: Certificate name """ (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name) utils.RemoveFile(key_file) utils.RemoveFile(cert_file) try: os.rmdir(cert_dir) except EnvironmentError as err: _Fail("Cannot remove certi...
data=cert_pem) # Never return private key as it shouldn't leave the node return (name, cert_pem) except Exception: shutil.rmtree(cert_dir, ignore_errors=True) raise def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
64
64
120
18
45
jfut/ganeti
lib/backend.py
Python
RemoveX509Certificate
RemoveX509Certificate
5,135
5,151
5,135
5,135
1ca66b253ef337fef1ce3f034666c4240f7cd41a
bigcode/the-stack
train
309295f801798675fefe6f1c
train
function
def BridgesExist(bridges_list): """Check if a list of bridges exist on the current node. @rtype: boolean @return: C{True} if all of them exist, C{False} otherwise """ missing = [] for bridge in bridges_list: if not utils.BridgeExists(bridge): missing.append(bridge) if missing: _Fail("Miss...
def BridgesExist(bridges_list):
"""Check if a list of bridges exist on the current node. @rtype: boolean @return: C{True} if all of them exist, C{False} otherwise """ missing = [] for bridge in bridges_list: if not utils.BridgeExists(bridge): missing.append(bridge) if missing: _Fail("Missing bridges %s", utils.CommaJoin...
line in result.stdout.splitlines(): if line.count("|") >= 3: all_devs.extend(map_line(line.split("|"))) else: logging.warning("Strange line in the output from lvs: '%s'", line) return all_devs def BridgesExist(bridges_list):
64
64
97
8
55
jfut/ganeti
lib/backend.py
Python
BridgesExist
BridgesExist
2,456
2,469
2,456
2,456
c6a95c89acd910da31d4e16280cf2dff8e338d2f
bigcode/the-stack
train
d6575d04c2cc266cd70c0d64
train
function
def _RunMasterSetupScript(master_params, action, use_external_mip_script): """Execute the master IP address setup script. @type master_params: L{objects.MasterNetworkParameters} @param master_params: network parameters of the master @type action: string @param action: action to pass to the script. Must be on...
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
"""Execute the master IP address setup script. @type master_params: L{objects.MasterNetworkParameters} @param master_params: network parameters of the master @type action: string @param action: action to pass to the script. Must be one of L{backend._MASTER_START} or L{backend._MASTER_STOP} @type use_ex...
FromAddressFamily(master_params.ip_family) env = { "MASTER_NETDEV": master_params.netdev, "MASTER_IP": master_params.ip, "MASTER_NETMASK": str(master_params.netmask), "CLUSTER_IP_VERSION": str(ver), } return env def _RunMasterSetupScript(master_params, action, use_external_mip_script):
77
77
257
17
59
jfut/ganeti
lib/backend.py
Python
_RunMasterSetupScript
_RunMasterSetupScript
380
406
380
380
d115e3810f9438c57c35f61345e5c57a4cee2ffc
bigcode/the-stack
train
efa9909f344c5ab5c21b030f
train
function
def JobQueueUpdate(file_name, content): """Updates a file in the queue directory. This is just a wrapper over L{utils.io.WriteFile}, with proper checking. @type file_name: str @param file_name: the job file name @type content: str @param content: the new job contents @rtype: boolean @return: the suc...
def JobQueueUpdate(file_name, content):
"""Updates a file in the queue directory. This is just a wrapper over L{utils.io.WriteFile}, with proper checking. @type file_name: str @param file_name: the job file name @type content: str @param content: the new job contents @rtype: boolean @return: the success of the operation """ file_name...
is not valid """ if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name): _Fail("Passed job queue file '%s' does not belong to" " the queue directory '%s'", file_name, pathutils.QUEUE_DIR) def JobQueueUpdate(file_name, content):
64
64
172
9
55
jfut/ganeti
lib/backend.py
Python
JobQueueUpdate
JobQueueUpdate
4,791
4,812
4,791
4,791
42447099f668238002f207c1dfea20d62026e82d
bigcode/the-stack
train
6e8954110f3322ae3a1bc38a
train
function
def VerifyNode(what, cluster_name, all_hvparams): """Verify the status of the local node. Based on the input L{what} parameter, various checks are done on the local node. If the I{filelist} key is present, this list of files is checksummed and the file/checksum pairs are returned. If the I{nodelist} key ...
def VerifyNode(what, cluster_name, all_hvparams):
"""Verify the status of the local node. Based on the input L{what} parameter, various checks are done on the local node. If the I{filelist} key is present, this list of files is checksummed and the file/checksum pairs are returned. If the I{nodelist} key is present, we check that we have connectivity v...
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): """Verify master IP is reachable. @type my_name...
256
256
2,044
14
242
jfut/ganeti
lib/backend.py
Python
VerifyNode
VerifyNode
1,182
1,392
1,182
1,182
3a37a41eb8aadaf9dfa9ee282a5c0bf2d82e6643
bigcode/the-stack
train
83a9061e823ee9fa6787ceca
train
class
class HooksRunner(object): """Hook runner. This class is instantiated on the node side (ganeti-noded) and not on the master side. """ def __init__(self, hooks_base_dir=None): """Constructor for hooks runner. @type hooks_base_dir: str or None @param hooks_base_dir: if not None, this overrides th...
class HooksRunner(object):
"""Hook runner. This class is instantiated on the node side (ganeti-noded) and not on the master side. """ def __init__(self, hooks_base_dir=None): """Constructor for hooks runner. @type hooks_base_dir: str or None @param hooks_base_dir: if not None, this overrides the L{pathutils.HOOKS...
.RunCmd(["ovs-vsctl", "--may-exist", "add-port", ovs_name, ovs_link]) if result.failed: _Fail("Failed to connect openvswitch to interface %s. Script return" " value: %s, output: '%s'" % (ovs_link, result.exit_code, result.output), log=True) def GetFileInfo...
220
221
737
5
215
jfut/ganeti
lib/backend.py
Python
HooksRunner
HooksRunner
5,908
5,999
5,908
5,908
f27f3b31b71af4bc8f13a2332409c025bf57e741
bigcode/the-stack
train
670cac5572527d8493587256
train
function
def FinalizeMigrationDst(instance, info, success): """Finalize any preparation 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 success: boolean @param succes...
def FinalizeMigrationDst(instance, info, success):
"""Finalize any preparation 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 success: boolean @param success: whether the migration was a success or a failure...
""" hyper = hypervisor.GetHypervisor(instance.hypervisor) try: hyper.AcceptInstance(instance, info, target) except errors.HypervisorError as err: _Fail("Failed to accept instance: %s", err, exc=True) def FinalizeMigrationDst(instance, info, success):
64
64
145
11
53
jfut/ganeti
lib/backend.py
Python
FinalizeMigrationDst
FinalizeMigrationDst
3,102
3,117
3,102
3,102
7cb9f7cacb0c84bf645b69879267caf0e5345d75
bigcode/the-stack
train
1eeb01e9890d7819711ab368
train
function
def _StoreInstReasonTrail(instance_name, trail): """Serialize a reason trail related to an instance change of state to file. The exact location of the file depends on the name of the instance and on the configuration of the Ganeti cluster defined at deploy time. @type instance_name: string @param instance_n...
def _StoreInstReasonTrail(instance_name, trail):
"""Serialize a reason trail related to an instance change of state to file. The exact location of the file depends on the name of the instance and on the configuration of the Ganeti cluster defined at deploy time. @type instance_name: string @param instance_name: The name of the instance @type trail: lis...
. @type instance_name: string @param instance_name: The name of the instance @rtype: string @return: The path of the file """ return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name) def _StoreInstReasonTrail(instance_name, trail):
64
64
132
11
53
jfut/ganeti
lib/backend.py
Python
_StoreInstReasonTrail
_StoreInstReasonTrail
148
165
148
148
cdd9cacc2247823388ed6652e11f1f1ada4fd0ef
bigcode/the-stack
train
b862e1c5de5bcdc747109313
train
function
def InstanceShutdown(instance, timeout, reason, store_reason=True): """Shut an instance down. @note: this functions uses polling with a hardcoded timeout. @type instance: L{objects.Instance} @param instance: the instance object @type timeout: integer @param timeout: maximum timeout for soft shutdown @ty...
def InstanceShutdown(instance, timeout, reason, store_reason=True):
"""Shut an instance down. @note: this functions uses polling with a hardcoded timeout. @type instance: L{objects.Instance} @param instance: the instance object @type timeout: integer @param timeout: maximum timeout for soft shutdown @type reason: list of reasons @param reason: the reason trail for thi...
return logging.info("Instance '%s' hypervisor config out of date. Restoring.", instance.name) block_devices = _GatherAndLinkBlockDevs(instance) hyper.RestoreInstance(instance, block_devices) return block_devices = _GatherAndLinkBlockDevs(instance) hyper.StartI...
171
171
573
13
158
jfut/ganeti
lib/backend.py
Python
InstanceShutdown
InstanceShutdown
2,931
2,999
2,931
2,931
0ce99eb08d00d6a5be479c1fdbfacbb4f9b6cd38
bigcode/the-stack
train
d26bd924962639e9f86b0eea
train
function
def RunRenameInstance(instance, old_name, debug): """Run the OS rename script for an instance. @type instance: L{objects.Instance} @param instance: Instance whose OS is to be installed @type old_name: string @param old_name: previous instance name @type debug: integer @param debug: debug level, passed to...
def RunRenameInstance(instance, old_name, debug):
"""Run the OS rename script for an instance. @type instance: L{objects.Instance} @param instance: Instance whose OS is to be installed @type old_name: string @param old_name: previous instance name @type debug: integer @param debug: debug level, passed to the OS scripts @rtype: boolean @return: the s...
: %s", result.cmd, result.fail_reason, logfile, result.output) lines = [utils.SafeEncode(val) for val in utils.TailFile(logfile, lines=20)] _Fail("OS create script failed (%s), last lines in the" " log file:\n%s", result.fail_reason, "\n".join(lines), log=False) def RunR...
89
89
298
11
78
jfut/ganeti
lib/backend.py
Python
RunRenameInstance
RunRenameInstance
2,737
2,767
2,737
2,737
b2408198c36672f10c9e6d7b1f665e9eada9d868
bigcode/the-stack
train
829003509037a0f49a3c8769
train
function
def ListVolumeGroups(): """List the volume groups and their size. @rtype: dict @return: dictionary with keys volume name and values the size of the volume """ return utils.ListVolumeGroups()
def ListVolumeGroups():
"""List the volume groups and their size. @rtype: dict @return: dictionary with keys volume name and values the size of the volume """ return utils.ListVolumeGroups()
0] == "v" 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():
64
64
49
5
58
jfut/ganeti
lib/backend.py
Python
ListVolumeGroups
ListVolumeGroups
2,399
2,407
2,399
2,399
f31769748eba70a8264b80d1af0c2af242235992
bigcode/the-stack
train
4a95bc64e51ccec448da0b8b
train
function
def _VerifyRestrictedCmd(path, cmd, _owner=None): """Verifies a whole restricted command and returns its executable filename. @type path: string @param path: Directory containing restricted commands @type cmd: string @param cmd: Command name @rtype: tuple; (boolean, string) @return: The tuple's first ele...
def _VerifyRestrictedCmd(path, cmd, _owner=None):
"""Verifies a whole restricted command and returns its executable filename. @type path: string @param path: Directory containing restricted commands @type cmd: string @param cmd: Command name @rtype: tuple; (boolean, string) @return: The tuple's first element is the status; if C{False}, the second el...
_owner) if not status: return (False, value) if not stat.S_ISDIR(value.st_mode): return (False, "Path '%s' is not a directory" % path) return (True, None) def _VerifyRestrictedCmd(path, cmd, _owner=None):
64
64
192
13
51
jfut/ganeti
lib/backend.py
Python
_VerifyRestrictedCmd
_VerifyRestrictedCmd
5,726
5,749
5,726
5,726
f264498252a1e9f5e62af6816b5799e48855f29f
bigcode/the-stack
train
580178789516e3bb0731f4b9
train
function
def BlockdevSnapshot(disk, snap_name, snap_size): """Create a snapshot copy of a block device. This function is called recursively, and the snapshot is actually created just for the leaf lvm backend device. @type disk: L{objects.Disk} @param disk: the disk to be snapshotted @type snap_name: string @para...
def BlockdevSnapshot(disk, snap_name, snap_size):
"""Create a snapshot copy of a block device. This function is called recursively, and the snapshot is actually created just for the leaf lvm backend device. @type disk: L{objects.Disk} @param disk: the disk to be snapshotted @type snap_name: string @param snap_name: the name of the snapshot @type snap...
""" r_dev = _RecursiveFindBD(disk) if r_dev is None: _Fail("Cannot find block device %s", disk) try: r_dev.Grow(amount, dryrun, backingstore, excl_stor) except errors.BlockDeviceError as err: _Fail("Failed to grow block device: %s", err, exc=True) def BlockdevSnapshot(disk, snap_name, snap_size...
94
94
315
13
81
jfut/ganeti
lib/backend.py
Python
BlockdevSnapshot
BlockdevSnapshot
4,430
4,463
4,430
4,430
bfd73dca3b573ad14c850c8c9ed96c09003d3d0a
bigcode/the-stack
train
03b71fe0f4aaeb055b401f54
train
function
def _GetLvmVgSpaceInfo(name, params): """Wrapper around C{_GetVgInfo} which checks the storage parameters. @type name: string @param name: name of the volume group @type params: list @param params: list of storage parameters, which in this case should be containing only one for exclusive storage """ ...
def _GetLvmVgSpaceInfo(name, params):
"""Wrapper around C{_GetVgInfo} which checks the storage parameters. @type name: string @param name: name of the volume group @type params: list @param params: list of storage parameters, which in this case should be containing only one for exclusive storage """ excl_stor = _CheckLvmStorageParams(pa...
excl_stor = params[0] if not isinstance(params[0], bool): raise errors.ProgrammerError("Exclusive storage parameter is not" " boolean: '%s'." % excl_stor) return excl_stor def _GetLvmVgSpaceInfo(name, params):
64
64
109
13
50
jfut/ganeti
lib/backend.py
Python
_GetLvmVgSpaceInfo
_GetLvmVgSpaceInfo
625
636
625
625
37487e9fa35a67bcd6b9263c55504d2e422a0e80
bigcode/the-stack
train
60043134b413e686f750229b
train
function
def _SymlinkBlockDev(instance_name, device_path, idx): """Set up symlinks to a instance's block device. This is an auxiliary function run when an instance is start (on the primary node) or when an instance is migrated (on the target node). @param instance_name: the name of the target instance @param device...
def _SymlinkBlockDev(instance_name, device_path, idx):
"""Set up symlinks to a instance's block device. This is an auxiliary function run when an instance is start (on the primary node) or when an instance is migrated (on the target node). @param instance_name: the name of the target instance @param device_path: path of the physical block device, on the node ...
"""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 _SymlinkBlockDev(instance_name, device_path, idx):
71
72
240
14
57
jfut/ganeti
lib/backend.py
Python
_SymlinkBlockDev
_SymlinkBlockDev
2,782
2,811
2,782
2,782
ad5f68424e8b0f6e93c2cfae7d184ac95abe1d3b
bigcode/the-stack
train
07fb8ef535ee8ecfcc02a443
train
function
def _CheckOSPList(os_obj, parameters): """Check whether a list of parameters is supported by the OS. @type os_obj: L{objects.OS} @param os_obj: OS object to check @type parameters: list @param parameters: the list of parameters to check """ supported = [v[0] for v in os_obj.supported_parameters] delta...
def _CheckOSPList(os_obj, parameters):
"""Check whether a list of parameters is supported by the OS. @type os_obj: L{objects.OS} @param os_obj: OS object to check @type parameters: list @param parameters: the list of parameters to check """ supported = [v[0] for v in os_obj.supported_parameters] delta = frozenset(parameters).difference(sup...
validated @rtype: None """ try: hv_type = hypervisor.GetHypervisor(hvname) hv_type.ValidateParameters(hvparams) except errors.HypervisorError as err: _Fail(str(err), log=False) def _CheckOSPList(os_obj, parameters):
64
64
134
10
54
jfut/ganeti
lib/backend.py
Python
_CheckOSPList
_CheckOSPList
4,917
4,930
4,917
4,917
e860b80544eb676cc09f16394ab3e3ac5e21c656
bigcode/the-stack
train
c521a2cad4fe51e5b6ad1b7c
train
function
def BlockdevConvert(src_disk, target_disk): """Copies data from source block device to target. This function gets the export and import commands from the source and target devices respectively, and then concatenates them to a single command using a pipe ("|"). Finally, executes the unified command that will ...
def BlockdevConvert(src_disk, target_disk):
"""Copies data from source block device to target. This function gets the export and import commands from the source and target devices respectively, and then concatenates them to a single command using a pipe ("|"). Finally, executes the unified command that will transfer the data between the devices during...
.USERAGENT, http.HTTP_GANETI_VERSION) curl.setopt(pycurl.URL, source_url) curl.setopt(pycurl.WRITEFUNCTION, lambda out: dd_write(ddparams, out)) try: curl.perform() except pycurl.error: if ddparams.image_size_error: _Fail("Disk image larger than the disk") else: raise target_file.clo...
97
97
326
10
87
jfut/ganeti
lib/backend.py
Python
BlockdevConvert
BlockdevConvert
3,415
3,450
3,415
3,415
6038b6454ceb9530efb3299f63a866a875eb0590
bigcode/the-stack
train
c6c9e44b73579aa8d188748a
train
function
def BlockdevFind(disk): """Check if a device is activated. If it is, return information about the real device. @type disk: L{objects.Disk} @param disk: the disk to find @rtype: None or objects.BlockDevStatus @return: None if the disk cannot be found, otherwise a the current information """ ...
def BlockdevFind(disk):
"""Check if a device is activated. If it is, return information about the real device. @type disk: L{objects.Disk} @param disk: the disk to find @rtype: None or objects.BlockDevStatus @return: None if the disk cannot be found, otherwise a the current information """ try: rbd = _Recursi...
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 BlockdevFind(disk):
64
64
141
7
56
jfut/ganeti
lib/backend.py
Python
BlockdevFind
BlockdevFind
3,883
3,903
3,883
3,883
f33620777fa4acb5ec74212da04d3d075b21a3f3
bigcode/the-stack
train
420ca1dbbf66b2d603a2b4ca
train
function
def GetAllInstancesInfo(hypervisor_list, all_hvparams): """Gather data about all instances. This is the equivalent of L{GetInstanceInfo}, except that it computes data for all instances at once, thus being faster if one needs data about more than one instance. @type hypervisor_list: list @param hypervisor_...
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
"""Gather data about all instances. This is the equivalent of L{GetInstanceInfo}, except that it computes data for all instances at once, thus being faster if one needs data about more than one instance. @type hypervisor_list: list @param hypervisor_list: list of hypervisors to query for instance data @...
iname = instance.name if iname not in hyper.ListInstances(hvparams=instance.hvparams): _Fail("Instance %s is not running", iname) for idx in range(len(instance.disks_info)): link_name = _GetBlockDevSymlinkPath(iname, idx) if not os.path.islink(link_name): logging.warning("Instance %s is missing ...
117
117
391
15
102
jfut/ganeti
lib/backend.py
Python
GetAllInstancesInfo
GetAllInstancesInfo
2,579
2,621
2,579
2,579
2f002b9cd921dbe632bab9864b1d25832b84c040
bigcode/the-stack
train
e456d29386526ee5a75d5808
train
function
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev): """Change the netmask of the master IP. @param old_netmask: the old value of the netmask @param netmask: the new value of the netmask @param master_ip: the master IP @param master_netdev: the master network device """ if old_netmas...
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
"""Change the netmask of the master IP. @param old_netmask: the old value of the netmask @param netmask: the new value of the netmask @param master_ip: the master IP @param master_netdev: the master network device """ if old_netmask == netmask: return if not netutils.IPAddress.Own(master_ip): ...
the RPC for this result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"]) if result.failed: logging.error("Could not stop Ganeti master, command %s had exitcode %s" " and error %s", result.cmd, result.exit_code, result.output) def ChangeMasterNetmask(old_netmask, netma...
85
85
284
19
66
jfut/ganeti
lib/backend.py
Python
ChangeMasterNetmask
ChangeMasterNetmask
490
518
490
490
f115a6229830396f6a7565b48115a13a023d706c
bigcode/the-stack
train
4755801ce7779f02d6e6cf84
train
function
def GetBlockDevSizes(devices): """Return the size of the given block devices @type devices: list @param devices: list of block device nodes to query @rtype: dict @return: dictionary of all block devices under /dev (key). The value is their size in MiB. {'/dev/disk/by-uuid/123456-12321231-312312-...
def GetBlockDevSizes(devices):
"""Return the size of the given block devices @type devices: list @param devices: list of block device nodes to query @rtype: dict @return: dictionary of all block devices under /dev (key). The value is their size in MiB. {'/dev/disk/by-uuid/123456-12321231-312312-312': 124} """ DEV_PREFIX ...
_node_uuid, master_node_name, master_candidate_uuids, potential_master_candidates, keys_to_remove=old_master_keys_by_uuid, from_authorized_keys=True, from_public_keys=False, clear_authorized_keys=False, clear_public_keys=False) if node_errors: all_node_errors = all_node_errors + node_error...
84
84
282
8
75
jfut/ganeti
lib/backend.py
Python
GetBlockDevSizes
GetBlockDevSizes
2,315
2,350
2,315
2,315
a4e7356d47e32f2557e427e0b9db450b5c850281
bigcode/the-stack
train
43bab3d2ab0a40ff11359a40
train
function
def VerifyNodeNetTest(my_name, test_config): """Verify nodes are reachable. @type my_name: string @param my_name: name of the node this test is running on @type test_config: tuple (node_list, master_candidate_list) @param test_config: configuration for test as passed from LUClusterVerify() in what[con...
def VerifyNodeNetTest(my_name, test_config):
"""Verify nodes are reachable. @type my_name: string @param my_name: name of the node this test is running on @type test_config: tuple (node_list, master_candidate_list) @param test_config: configuration for test as passed from LUClusterVerify() in what[constants.NV_NODENETTEST] @rtype: dict @ret...
be" \ " due to an unsuccessful operation which cluttered up the" \ " 'authorized_keys' file. We recommend to clean this up manually. " \ % my_name for host, occ in multiple_occurrences.items(): msg += "Entry for '%s' in lines %s. " % (host, utils.CommaJoin(occ)) result.appen...
97
97
325
11
85
jfut/ganeti
lib/backend.py
Python
VerifyNodeNetTest
VerifyNodeNetTest
1,114
1,154
1,114
1,114
35a6b9b18f3bf3a90bc0c3920d1c35bcbb7fbba7
bigcode/the-stack
train
91b326b0805245d8a46e6347
train
function
def _RemoveBlockDevLinks(instance_name, disks): """Remove the block device symlinks belonging to the given instance. """ for idx, _ in enumerate(disks): link_name = _GetBlockDevSymlinkPath(instance_name, idx) if os.path.islink(link_name): try: os.remove(link_name) except OSError: ...
def _RemoveBlockDevLinks(instance_name, disks):
"""Remove the block device symlinks belonging to the given instance. """ for idx, _ in enumerate(disks): link_name = _GetBlockDevSymlinkPath(instance_name, idx) if os.path.islink(link_name): try: os.remove(link_name) except OSError: logging.exception("Can't remove symlink '%s'...
IST: if (not os.path.islink(link_name) or os.readlink(link_name) != device_path): os.remove(link_name) os.symlink(device_path, link_name) else: raise return link_name def _RemoveBlockDevLinks(instance_name, disks):
64
64
91
11
52
jfut/ganeti
lib/backend.py
Python
_RemoveBlockDevLinks
_RemoveBlockDevLinks
2,814
2,824
2,814
2,814
96a391d845fdb58eda525bc7048eeb7db73a5751
bigcode/the-stack
train
d1b43ec178a5fc9633abadbb
train
function
def _GatherAndLinkBlockDevs(instance): """Set up an instance's block device(s). This is run on the primary node at instance startup. The block devices must be already assembled. @type instance: L{objects.Instance} @param instance: the instance whose disks we should assemble @rtype: list @return: list of...
def _GatherAndLinkBlockDevs(instance):
"""Set up an instance's block device(s). This is run on the primary node at instance startup. The block devices must be already assembled. @type instance: L{objects.Instance} @param instance: the instance whose disks we should assemble @rtype: list @return: list of (disk_object, link_name, drive_uri) ...
access_mode = disk.params.get(constants.LDP_ACCESS, constants.DISK_KERNELSPACE) if access_mode == constants.DISK_USERSPACE: # This can raise errors.BlockDeviceError return device.GetUserspaceAccessUri(instance.hypervisor) else: return None def _GatherAndLinkBlockDevs(in...
69
69
231
10
58
jfut/ganeti
lib/backend.py
Python
_GatherAndLinkBlockDevs
_GatherAndLinkBlockDevs
2,849
2,877
2,849
2,849
890d592e2bd60711122a8f31ead7e2898ee9a678
bigcode/the-stack
train
1120bb32534eb6237e0b893c
train
function
def DrbdDisconnectNet(disks): """Disconnects the network on a list of drbd devices. """ bdevs = _FindDisks(disks) # disconnect disks for rd in bdevs: try: rd.DisconnectNet() except errors.BlockDeviceError as err: _Fail("Can't change network configuration to standalone mode: %s", ...
def DrbdDisconnectNet(disks):
"""Disconnects the network on a list of drbd devices. """ bdevs = _FindDisks(disks) # disconnect disks for rd in bdevs: try: rd.DisconnectNet() except errors.BlockDeviceError as err: _Fail("Can't change network configuration to standalone mode: %s", err, exc=True)
. """ 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):
64
64
88
8
55
jfut/ganeti
lib/backend.py
Python
DrbdDisconnectNet
DrbdDisconnectNet
5,495
5,507
5,495
5,495
3c03e8b18eea1e743dc67c01e53dc2441e8ca6eb
bigcode/the-stack
train
37f3d6b3515ed001b115420b
train
function
def _VerifyRestrictedCmdDirectory(path, _owner=None): """Verifies restricted command directory. @type path: string @param path: Path to check @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...
def _VerifyRestrictedCmdDirectory(path, _owner=None):
"""Verifies restricted command directory. @type path: string @param path: Path to check @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} """ (status, value) = _CommonRestricte...
.st_gid) != owner: (owner_uid, owner_gid) = owner return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid)) return (True, st) def _VerifyRestrictedCmdDirectory(path, _owner=None):
64
64
151
12
52
jfut/ganeti
lib/backend.py
Python
_VerifyRestrictedCmdDirectory
_VerifyRestrictedCmdDirectory
5,705
5,723
5,705
5,705
5b9ab974aa2f20b729e7aa77f72257efa82a6f64
bigcode/the-stack
train
7b22a1be5692a96b009987c9
train
function
def GetMasterNodeName(): """Returns 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 GetMasterNodeName():
"""Returns 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)
Removes job queue files and archived jobs. @rtype: tuple @return: True, None """ _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE]) _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR) def GetMasterNodeName():
64
64
80
6
58
jfut/ganeti
lib/backend.py
Python
GetMasterNodeName
GetMasterNodeName
307
318
307
307
f7454aedb6ab7e81ad00673cbfd015d13397acdc
bigcode/the-stack
train
415b7987b1f4b758685d91cd
train
function
def BlockdevImage(disk, image, size): """Images a block device either by dumping a local file or downloading a URL. @type disk: L{objects.Disk} @param disk: the disk object we want to image @type image: string @param image: file path to the disk image be dumped @type size: int @param size: The size i...
def BlockdevImage(disk, image, size):
"""Images a block device either by dumping a local file or downloading a URL. @type disk: L{objects.Disk} @param disk: the disk object we want to image @type image: string @param image: file path to the disk image be dumped @type size: int @param size: The size in MiB to write @rtype: NoneType @...
("Negative size") if offset > rdev.size: _Fail("Wipe offset is bigger than device size") if (offset + size) > rdev.size: _Fail("Wipe offset and size are bigger than device size") _DumpDevice("/dev/zero", rdev.dev_path, offset, size, True) def BlockdevImage(disk, image, size):
83
83
277
11
72
jfut/ganeti
lib/backend.py
Python
BlockdevImage
BlockdevImage
3,483
3,519
3,483
3,483
30e682948600b7ad02ef3c9f6cf59714e55b747d
bigcode/the-stack
train
b12039d459c319ace941c027
train
function
def ListExports(): """Return a list of 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 ListExports():
"""Return a list of 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")
) config = objects.SerializableConfigParser() config.read(cff) if (not config.has_section(constants.INISECT_EXP) or not config.has_section(constants.INISECT_INS)): _Fail("Export info file doesn't have the required fields") return config.Dumps() def ListExports():
64
64
69
4
60
jfut/ganeti
lib/backend.py
Python
ListExports
ListExports
4,612
4,622
4,612
4,612
00e7d31e4dedbc5cc2af4d4586c35c0f026ef92e
bigcode/the-stack
train
0fa9d3fda0fe02538dceba85
train
function
def _CalculateDeviceURI(instance, disk, device): """Get the URI for the device. @type instance: L{objects.Instance} @param instance: the instance which disk belongs to @type disk: L{objects.Disk} @param disk: the target disk object @type device: L{bdev.BlockDev} @param device: the corresponding BlockDevi...
def _CalculateDeviceURI(instance, disk, device):
"""Get the URI for the device. @type instance: L{objects.Instance} @param instance: the instance which disk belongs to @type disk: L{objects.Disk} @param disk: the target disk object @type device: L{bdev.BlockDev} @param device: the corresponding BlockDevice @rtype: string @return: the device uri if ...
link_name = _GetBlockDevSymlinkPath(instance_name, idx) if os.path.islink(link_name): try: os.remove(link_name) except OSError: logging.exception("Can't remove symlink '%s'", link_name) def _CalculateDeviceURI(instance, disk, device):
64
64
164
11
53
jfut/ganeti
lib/backend.py
Python
_CalculateDeviceURI
_CalculateDeviceURI
2,827
2,846
2,827
2,827
1195c41063632d583349eb2003d8bc9438c64e38
bigcode/the-stack
train
6ab40c250df5777b4e6a68e3
train
function
def _TransformFileStorageDir(fs_dir): """Checks whether given file_storage_dir is valid. Checks wheter the given fs_dir is within the cluster-wide default file_storage_dir or the shared_file_storage_dir, which are stored in SimpleStore. Only paths under those directories are allowed. @type fs_dir: str @pa...
def _TransformFileStorageDir(fs_dir):
"""Checks whether given file_storage_dir is valid. Checks wheter the given fs_dir is within the cluster-wide default file_storage_dir or the shared_file_storage_dir, which are stored in SimpleStore. Only paths under those directories are allowed. @type fs_dir: str @param fs_dir: the path to check @retu...
to '%s': %s" % (dev, unique_id, err)) logging.exception("Can't rename device '%s' to '%s'", dev, unique_id) result = False if not result: _Fail("; ".join(msgs)) def _TransformFileStorageDir(fs_dir):
64
64
117
9
55
jfut/ganeti
lib/backend.py
Python
_TransformFileStorageDir
_TransformFileStorageDir
4,680
4,695
4,680
4,680
5eb7143c33d4da03719266c255b1a9c317ee2cb2
bigcode/the-stack
train
025624f3ef5316ccc70968c1
train
function
def JobQueueRename(old, new): """Renames a job queue file. This is just a wrapper over os.rename with proper checking. @type old: str @param old: the old (actual) file name @type new: str @param new: the desired file name @rtype: tuple @return: the success of the operation and payload """ old = v...
def JobQueueRename(old, new):
"""Renames a job queue file. This is just a wrapper over os.rename with proper checking. @type old: str @param old: the old (actual) file name @type new: str @param new: the desired file name @rtype: tuple @return: the success of the operation and payload """ old = vcluster.LocalizeVirtualPath(ol...
getents = runtime.GetEnts() # Write and replace the file atomically utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid, gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS) def JobQueueRename(old, new):
64
64
170
8
56
jfut/ganeti
lib/backend.py
Python
JobQueueRename
JobQueueRename
4,815
4,837
4,815
4,815
fb549106e167a7023dff9a810717e0aeed91ca0e
bigcode/the-stack
train
9247b1011f62e3949a3e9439
train
function
def BlockdevSetInfo(disk, info): """Sets 'metadata' information on block devices. This function sets 'info' metadata on block devices. Initial information is set at device creation; this function should be used for example after renames. @type disk: L{objects.Disk} @param disk: the disk to be grown @typ...
def BlockdevSetInfo(disk, info):
"""Sets 'metadata' information on block devices. This function sets 'info' metadata on block devices. Initial information is set at device creation; this function should be used for example after renames. @type disk: L{objects.Disk} @param disk: the disk to be grown @type info: string @param info: new...
[0], snap_name, snap_size) else: 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):
64
64
205
10
54
jfut/ganeti
lib/backend.py
Python
BlockdevSetInfo
BlockdevSetInfo
4,466
4,489
4,466
4,466
26535899d36efb94e5c4c36a5d3e934e3f2ab113
bigcode/the-stack
train
74d9427672ae613d05757f8a
train
function
def EtcHostsModify(mode, host, ip): """Modify a host entry in /etc/hosts. @param mode: The mode to operate. Either add or remove entry @param host: The host to operate on @param ip: The ip associated with the entry """ if mode == constants.ETC_HOSTS_ADD: if not ip: RPCFail("Mode 'add' needs 'ip'...
def EtcHostsModify(mode, host, ip):
"""Modify a host entry in /etc/hosts. @param mode: The mode to operate. Either add or remove entry @param host: The host to operate on @param ip: The ip associated with the entry """ if mode == constants.ETC_HOSTS_ADD: if not ip: RPCFail("Mode 'add' needs 'ip' parameter, but parameter not" ...
% (master_ip, old_netmask), "dev", master_netdev, "label", "%s:0" % master_netdev]) if result.failed: _Fail("Could not bring down the master IP address with the old netmask") def EtcHostsModify(mode, host, ip):
64
64
175
10
54
jfut/ganeti
lib/backend.py
Python
EtcHostsModify
EtcHostsModify
521
540
521
521
5c07fa119250e72c66cd060eb2281e7c8a7f8c93
bigcode/the-stack
train
2643ec388bf25ddcdf9c5429
train
function
def DiagnoseExtStorage(top_dirs=None): """Compute the validity for all ExtStorage Providers. @type top_dirs: list @param top_dirs: the list of directories in which to search (if not given defaults to L{pathutils.ES_SEARCH_PATH}) @rtype: list of L{objects.ExtStorage} @return: a list of tuples (nam...
def DiagnoseExtStorage(top_dirs=None):
"""Compute the validity for all ExtStorage Providers. @type top_dirs: list @param top_dirs: the list of directories in which to search (if not given defaults to L{pathutils.ES_SEARCH_PATH}) @rtype: list of L{objects.ExtStorage} @return: a list of tuples (name, path, status, diagnose, parameters) ...
IC_TYPE in instance.hvparams: result["NIC_%d_FRONTEND_TYPE" % idx] = \ instance.hvparams[constants.HV_NIC_TYPE] # HV/BE params for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]: for key, value in source.items(): result["INSTANCE_%s_%s" % (kind, key)] = str(value) ...
107
107
358
8
98
jfut/ganeti
lib/backend.py
Python
DiagnoseExtStorage
DiagnoseExtStorage
4,352
4,394
4,352
4,352
aef39aea1fa1e8d89779aab081df4bc74623bc58
bigcode/the-stack
train
5893802f68da9f576a3bd60f
train
function
def GetInstanceListForHypervisor(hname, hvparams=None, get_hv_fn=hypervisor.GetHypervisor): """Provides a list of instances of the given hypervisor. @type hname: string @param hname: name of the hypervisor @type hvparams: dict of strings @param hvparams: hypervisor parameters...
def GetInstanceListForHypervisor(hname, hvparams=None, get_hv_fn=hypervisor.GetHypervisor):
"""Provides a list of instances of the given hypervisor. @type hname: string @param hname: name of the hypervisor @type hvparams: dict of strings @param hvparams: hypervisor parameters for the given hypervisor @type get_hv_fn: function @param get_hv_fn: function that returns a hypervisor for the given hy...
bridges_list: if not utils.BridgeExists(bridge): missing.append(bridge) if missing: _Fail("Missing bridges %s", utils.CommaJoin(missing)) def GetInstanceListForHypervisor(hname, hvparams=None, get_hv_fn=hypervisor.GetHypervisor):
65
65
218
26
39
jfut/ganeti
lib/backend.py
Python
GetInstanceListForHypervisor
GetInstanceListForHypervisor
2,472
2,494
2,472
2,473
10c3d2c37cb6fc759ebefad7a5ea3c2efc2e73fb
bigcode/the-stack
train
44508a41c84c80567ca8e870
train
function
def RemoveNodeSshKeyBulk(node_list, master_candidate_uuids, potential_master_candidates, master_uuid=None, keys_to_remove=None, pub_key_file=pathutils.SSH_PUB_KEYS, sscon...
def RemoveNodeSshKeyBulk(node_list, master_candidate_uuids, potential_master_candidates, master_uuid=None, keys_to_remove=None, pub_key_file=pathutils.SSH_PUB_KEYS, sscon...
"""Removes the node's SSH keys from the key files and distributes those. Note that at least one of the flags C{from_authorized_keys}, C{from_public_keys}, C{clear_authorized_keys}, and C{clear_public_keys} of at least one node has to be set to C{True} for the function to perform any action at all. Not doing ...
clear_authorized_keys=clear_authorized_keys, clear_public_keys=clear_public_keys)] return RemoveNodeSshKeyBulk(node_list, master_candidate_uuids, potential_master_candidates, ...
255
256
2,273
84
171
jfut/ganeti
lib/backend.py
Python
RemoveNodeSshKeyBulk
RemoveNodeSshKeyBulk
1,759
1,988
1,759
1,768
9a755aa8b0f2cbe2ef4b9ea6454c143db59fbd1a
bigcode/the-stack
train
b380bf3f3591c1c51629787f
train
function
def _GetImportExportIoCommand(instance, mode, ieio, ieargs): """Returns the command for the requested input/output. @type instance: L{objects.Instance} @param instance: The instance object @param mode: Import/export mode @param ieio: Input/output type @param ieargs: Input/output arguments """ assert m...
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
"""Returns the command for the requested input/output. @type instance: L{objects.Instance} @param instance: The instance object @param mode: Import/export mode @param ieio: Input/output type @param ieargs: Input/output arguments """ assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT) env = ...
name = os.path.basename(cert_dir) assert len(name) > 5 (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name) utils.WriteFile(key_file, mode=0o400, data=key_pem) utils.WriteFile(cert_file, mode=0o400, data=cert_pem) # Never return private key as it shouldn't leave the node return (nam...
254
254
847
17
237
jfut/ganeti
lib/backend.py
Python
_GetImportExportIoCommand
_GetImportExportIoCommand
5,154
5,262
5,154
5,154
b82a73901f9af869c59ff6311a226a575b8f3429
bigcode/the-stack
train
6f4b12bdc91cfc15097b8b85
train
function
def _FindDisks(disks): """Finds attached L{BlockDev}s for the given disks. @type disks: list of L{objects.Disk} @param disks: the disk objects we need to find @return: list of L{BlockDev} objects or C{None} if a given disk was not found or was no attached. """ bdevs = [] for disk in disks: ...
def _FindDisks(disks):
"""Finds attached L{BlockDev}s for the given disks. @type disks: list of L{objects.Disk} @param disks: the disk objects we need to find @return: list of L{BlockDev} objects or C{None} if a given disk was not found or was no attached. """ bdevs = [] for disk in disks: rd = _RecursiveFind...
Join(status_dir, _IES_PID_FILE)) if pid: logging.info("Import/export %s is still running with PID %s", name, pid) utils.KillProcess(pid, waitpid=False) shutil.rmtree(status_dir, ignore_errors=True) def _FindDisks(disks):
64
64
135
8
56
jfut/ganeti
lib/backend.py
Python
_FindDisks
_FindDisks
5,475
5,492
5,475
5,475
668f50fdf0720dd34049e2bbeaa31a1ecb864016
bigcode/the-stack
train
0f297f8e9fe87dd11c77e97b
train
function
def _GetFileStorageSpaceInfo(path, params): """Wrapper around filestorage.GetSpaceInfo. The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo and ignore the *args parameter to not leak it into the filestorage module's code. @see: C{filestorage.GetFileStorageSpaceInfo} for description of...
def _GetFileStorageSpaceInfo(path, params):
"""Wrapper around filestorage.GetSpaceInfo. The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo and ignore the *args parameter to not leak it into the filestorage module's code. @see: C{filestorage.GetFileStorageSpaceInfo} for description of the parameters. """ _CheckStorageP...
_params: _ApplyStorageInfoFunction(type_key_params[0], type_key_params[1], type_key_params[2]))) hv_info = _GetHvInfoAll(hv_specs) return (bootid, storage_info, hv_info) def _GetFileStorageSpaceInfo(path, params):
64
64
109
11
53
jfut/ganeti
lib/backend.py
Python
_GetFileStorageSpaceInfo
_GetFileStorageSpaceInfo
772
784
772
772
79f63dde94018f3bc778d3d5c2bc9ecf80c2a2a1
bigcode/the-stack
train
036e77b2d2af5e89289e6ce5
train
function
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor): """Grow a stack of block devices. This function is called recursively, with the childrens being the first ones to resize. @type disk: L{objects.Disk} @param disk: the disk to be grown @type amount: integer @param amount: the amount (in meb...
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
"""Grow a stack of block devices. This function is called recursively, with the childrens being the first ones to resize. @type disk: L{objects.Disk} @param disk: the disk to be grown @type amount: integer @param amount: the amount (in mebibytes) to grow with @type dryrun: boolean @param dryrun: whe...
(dir_name, name) status, es_inst = extstorage.ExtStorageFromDisk(name, base_dir=dir_name) if status: diagnose = "" parameters = es_inst.supported_parameters else: diagnose = es_inst parameters = [] result.append((name, es_path, status, diagnose, pa...
93
93
313
19
73
jfut/ganeti
lib/backend.py
Python
BlockdevGrow
BlockdevGrow
4,397
4,427
4,397
4,397
e5d4dc297bab9fc6eb47ab181351371865305eea
bigcode/the-stack
train
4e0b0bc5a1059c7d02d87e3b
train
function
def JobQueuePurge(): """Removes job queue files and archived jobs. @rtype: tuple @return: True, None """ _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE]) _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
def JobQueuePurge():
"""Removes job queue files and archived jobs. @rtype: tuple @return: True, None """ _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE]) _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
.update(hv_class.GetAncillaryFiles()[0]) assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \ "Allowed file storage paths should never be uploaded via RPC" return frozenset(allowed_files) _ALLOWED_UPLOAD_FILES = _BuildUploadFileList() def JobQueuePurge():
64
64
66
6
58
jfut/ganeti
lib/backend.py
Python
JobQueuePurge
JobQueuePurge
296
304
296
296
babc9b1c2dc69c11bc2e86600bfffb7350ecd4c9
bigcode/the-stack
train
f288847925330b90bfbb905d
train
function
def RemoveNodeSshKey(node_uuid, node_name, master_candidate_uuids, potential_master_candidates, master_uuid=None, keys_to_remove=None, from_authorized_keys=False, from_public_keys=False, ...
def RemoveNodeSshKey(node_uuid, node_name, master_candidate_uuids, potential_master_candidates, master_uuid=None, keys_to_remove=None, from_authorized_keys=False, from_public_keys=False, ...
"""Removes the node's SSH keys from the key files and distributes those. Note that at least one of the flags C{from_authorized_keys}, C{from_public_keys}, C{clear_authorized_keys}, and C{clear_public_keys} has to be set to C{True} for the function to perform any action at all. Not doing so will trigger an as...
((node, error_msg)) # We only log the error and don't throw an exception, because # one unreachable node shall not abort the entire procedure. logging.error(error_msg) else: if to_authorized_keys: run_cmd_fn(cluster_name, node, pathutils.SSH_UPDATE, ssh_port...
213
213
710
112
100
jfut/ganeti
lib/backend.py
Python
RemoveNodeSshKey
RemoveNodeSshKey
1,678
1,745
1,678
1,691
2fb3b832318ddfa389ff407fa072b11a5d5eff02
bigcode/the-stack
train
63c6906779840f4a9721c028
train
function
def _CleanDirectory(path, exclude=None): """Removes all regular files in a directory. @type path: str @param path: the directory to clean @type exclude: list @param exclude: list of files to be excluded, defaults to the empty list """ if path not in _ALLOWED_CLEAN_DIRS: _Fail("Path passed to _...
def _CleanDirectory(path, exclude=None):
"""Removes all regular files in a directory. @type path: str @param path: the directory to clean @type exclude: list @param exclude: list of files to be excluded, defaults to the empty list """ if path not in _ALLOWED_CLEAN_DIRS: _Fail("Path passed to _CleanDirectory not in allowed clean targe...
= data if encoding == constants.RPC_ENCODING_NONE: return content elif encoding == constants.RPC_ENCODING_ZLIB_BASE64: return zlib.decompress(base64.b64decode(content)) else: raise AssertionError("Unknown data encoding") def _CleanDirectory(path, exclude=None):
64
64
203
9
55
jfut/ganeti
lib/backend.py
Python
_CleanDirectory
_CleanDirectory
234
261
234
234
e1623b6cdf962f98079b5de7f08b1e448a2a5b1b
bigcode/the-stack
train
89669b5c96e22d930ab885db
train
function
def DiagnoseOS(top_dirs=None): """Compute the validity for all OSes. @type top_dirs: list @param top_dirs: the list of directories in which to search (if not given defaults to L{pathutils.OS_SEARCH_PATH}) @rtype: list of L{objects.OS} @return: a list of tuples (name, path, status, diagnose, varia...
def DiagnoseOS(top_dirs=None):
"""Compute the validity for all OSes. @type top_dirs: list @param top_dirs: the list of directories in which to search (if not given defaults to L{pathutils.OS_SEARCH_PATH}) @rtype: list of L{objects.OS} @return: a list of tuples (name, path, status, diagnose, variants, parameters, api_vers...
_FILE, os_dir)) try: api_versions = utils.ReadFile(api_file).splitlines() except EnvironmentError as err: return False, ("Error while reading the API version file at %s: %s" % (api_file, utils.ErrnoOrStr(err))) try: api_versions = [int(version.strip()) for version in api_versions]...
127
127
424
7
119
jfut/ganeti
lib/backend.py
Python
DiagnoseOS
DiagnoseOS
4,040
4,087
4,040
4,040
e026b2be3d0d97eb4fbc8a86bcd968a812f44207
bigcode/the-stack
train
042498b734eb5e076f075524
train
function
def _VerifyHvparams(what, vm_capable, result, get_hv_fn=hypervisor.GetHypervisor): """Verifies the hvparams. 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...
def _VerifyHvparams(what, vm_capable, result, get_hv_fn=hypervisor.GetHypervisor):
"""Verifies the hvparams. 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 ...
_fn(hv_name).Verify(hvparams=hvparams) except errors.HypervisorError as err: val = "Error while checking hypervisor: %s" % str(err) result[constants.NV_HYPERVISOR][hv_name] = val def _VerifyHvparams(what, vm_capable, result, get_hv_fn=hypervisor.GetHypervisor):
84
84
281
26
57
jfut/ganeti
lib/backend.py
Python
_VerifyHvparams
_VerifyHvparams
875
900
875
876
9cfe2699901913631f80cb0a4e9dc4934743d2a2
bigcode/the-stack
train
8dd0e9551f8a59ae795564df
train
function
def ConfigureOVS(ovs_name, ovs_link): """Creates a OpenvSwitch on the node. This function sets up a OpenvSwitch on the node with given name nad connects it via a given eth device. @type ovs_name: string @param ovs_name: Name of the OpenvSwitch to create. @type ovs_link: None or string @param ovs_link: E...
def ConfigureOVS(ovs_name, ovs_link):
"""Creates a OpenvSwitch on the node. This function sets up a OpenvSwitch on the node with given name nad connects it via a given eth device. @type ovs_name: string @param ovs_name: Name of the OpenvSwitch to create. @type ovs_link: None or string @param ovs_link: Ethernet device for outside connection ...
longer pause watcher") utils.RemoveFile(_filename) else: logging.info("Received request to pause watcher until %s", until) if not ht.TNumber(until): _Fail("Duration must be numeric") utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0o644) def ConfigureOVS(ovs_name, ovs_link):
81
81
270
11
70
jfut/ganeti
lib/backend.py
Python
ConfigureOVS
ConfigureOVS
5,856
5,881
5,856
5,856
6c1b6479fc17177e430f7b411f32e891fb778642
bigcode/the-stack
train
2100c3f0cd831f959b2c2d29
train
function
def _RecursiveAssembleBD(disk, owner, as_primary): """Activate a block device for an instance. This is run on the primary and secondary nodes for an instance. @note: this function is called recursively. @type disk: L{objects.Disk} @param disk: the disk we try to assemble @type owner: str @param owner: ...
def _RecursiveAssembleBD(disk, owner, as_primary):
"""Activate a block device for an instance. This is run on the primary and secondary nodes for an instance. @note: this function is called recursively. @type disk: L{objects.Disk} @param disk: the disk we try to assemble @type owner: str @param owner: the name of the instance which owns the disk @typ...
errors.BlockDeviceError as err: return [str(err)] msgs.extend(utils.SimpleRetry([], _TryRemove, constants.DISK_REMOVE_RETRY_INTERVAL, constants.DISK_REMOVE_RETRY_TIMEOUT)) if not msgs: DevCacheManager.RemoveCache(r_path) if ...
117
117
391
14
103
jfut/ganeti
lib/backend.py
Python
_RecursiveAssembleBD
_RecursiveAssembleBD
3,603
3,653
3,603
3,603
ddc996eaa746a70ddf446328afb0293d858e3df4
bigcode/the-stack
train
7c2dd5b6467e1940f13d5e05
train
function
def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE): """Verify the existance and validity of the client SSL certificate. Also, verify that the client certificate is not self-signed. Self- signed client certificates stem from Ganeti versions 2.12.0 - 2.12.4 and should be replaced by client ...
def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE):
"""Verify the existance and validity of the client SSL certificate. Also, verify that the client certificate is 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...
_capable: hvname = what[constants.NV_HVINFO] hyper = hypervisor.GetHypervisor(hvname) hvparams = all_hvparams[hvname] result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams) def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE):
78
78
263
16
62
jfut/ganeti
lib/backend.py
Python
_VerifyClientCertificate
_VerifyClientCertificate
948
973
948
948
48fb2eef1ee80d74f625c263257f56bf200e3ec2
bigcode/the-stack
train
40a42d5ccc779a1235e38abc
train
function
def LeaveCluster(modify_ssh_setup): """Cleans up and remove the current node. This function cleans up and prepares the current node to be removed from the cluster. If processing is successful, then it raises an L{errors.QuitGanetiException} which is used as a special case to shutdown the node daemon. @...
def LeaveCluster(modify_ssh_setup):
"""Cleans up and remove the current node. This function cleans up and prepares the current node to be removed from the cluster. If processing is successful, then it raises an L{errors.QuitGanetiException} which is used as a special case to shutdown the node daemon. @param modify_ssh_setup: boolean "...
Fail("Mode 'add' needs 'ip' parameter, but parameter not" " present") utils.AddHostToEtcHosts(host, ip) elif mode == constants.ETC_HOSTS_REMOVE: if ip: RPCFail("Mode 'remove' does not allow 'ip' parameter, but" " parameter is present") utils.RemoveHostFromEtcHosts(host) ...
102
102
340
9
93
jfut/ganeti
lib/backend.py
Python
LeaveCluster
LeaveCluster
543
587
543
543
f8b592675e82c02aa42d030f54c51e8c9966034c
bigcode/the-stack
train
3300108532c39adc63156b63
train
function
def _GetVgSpindlesInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo): """Retrieves information about spindles in an LVM volume group. @type name: string @param name: VG name @type excl_stor: bool @param excl_stor: exclusive storage @rtype: dict @return: dictionary whose keys are "na...
def _GetVgSpindlesInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
"""Retrieves information about spindles in an LVM volume group. @type name: string @param name: VG name @type excl_stor: bool @param excl_stor: exclusive storage @rtype: dict @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name, free spindles, total spindles respectively "...
} """ excl_stor = _CheckLvmStorageParams(params) return _GetVgSpindlesInfo(name, excl_stor) def _GetVgSpindlesInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
64
64
199
32
32
jfut/ganeti
lib/backend.py
Python
_GetVgSpindlesInfo
_GetVgSpindlesInfo
671
694
671
672
7bc551f6550051a67aa30f8fc8ac0f3607b84243
bigcode/the-stack
train
9fb5891e2f53e5c893b651d8
train
function
def GetInstanceConsoleInfo(instance_param_dict, get_hv_fn=hypervisor.GetHypervisor): """Gather data about the console access of a set of instances of this node. This function assumes that the caller already knows which instances are on this node, by calling a function such as L{GetAllI...
def GetInstanceConsoleInfo(instance_param_dict, get_hv_fn=hypervisor.GetHypervisor):
"""Gather data about the console access of a set of instances of this node. This function assumes that the caller already knows which instances are on this node, by calling a function such as L{GetAllInstancesInfo} or L{GetInstanceList}. For every instance, a large amount of configuration data needs to be ...
"vcpus": vcpus, "state": state, "time": times, } if name in output: # we only check static parameters, like memory and vcpus, # and not state and time which can change between the # invocations of the different hypervisors for key in "memory...
142
142
474
21
120
jfut/ganeti
lib/backend.py
Python
GetInstanceConsoleInfo
GetInstanceConsoleInfo
2,624
2,674
2,624
2,625
d046416889beec0a3740e26a96035a126fd52695
bigcode/the-stack
train
e2df6289644d072191e8a618
train
function
def _Fail(msg, *args, **kwargs): """Log an error and the raise an RPCFail exception. This exception is then handled specially in the ganeti daemon and turned into a 'failed' return type. As such, this function is a useful shortcut for logging the error and returning it to the master daemon. @type msg: str...
def _Fail(msg, *args, **kwargs):
"""Log an error and the raise an RPCFail exception. This exception is then handled specially in the ganeti daemon and turned into a 'failed' return type. As such, this function is a useful shortcut for logging the error and returning it to the master daemon. @type msg: string @param msg: the text of the...
type trail: list of reasons @param trail: reason trail @rtype: None """ json = serializer.DumpJson(trail) filename = _GetInstReasonFilename(instance_name) utils.WriteFile(filename, data=json) def _Fail(msg, *args, **kwargs):
64
64
162
11
53
jfut/ganeti
lib/backend.py
Python
_Fail
_Fail
168
188
168
168
e2b9f80c30e43f69873b7fc97320f175213f7277
bigcode/the-stack
train