desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'replace the current object with oc replace'
| def _replace(self, fname, force=False):
| yed = Yedit(fname)
results = yed.delete('metadata.resourceVersion')
if results[0]:
yed.write()
cmd = ['replace', '-f', fname]
if force:
cmd.append('--force')
return self.openshift_cmd(cmd)
|
'create a temporary file and then call oc create on it'
| def _create_from_content(self, rname, content):
| fname = Utils.create_tmpfile((rname + '-'))
yed = Yedit(fname, content=content)
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._create(fname)
|
'call oc create on a filename'
| def _create(self, fname):
| return self.openshift_cmd(['create', '-f', fname])
|
'call oc delete on a resource'
| def _delete(self, resource, name=None, selector=None):
| cmd = ['delete', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift... |
'process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template\'s data; instead of a file'
| def _process(self, template_name, create=False, params=None, template_data=None):
| cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ['{}={}'.format(key, str(value).replace("'", '"')) for (key, value) in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.open... |
'return a resource by name'
| def _get(self, resource, name=None, selector=None):
| cmd = ['get', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
if ('items' in rval):
rval['results'] = rval['items']
elif ... |
'perform oadm manage-node scheduable'
| def _schedulable(self, node=None, selector=None, schedulable=True):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
'perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided'
| def _list_pods(self, node=None, selector=None, pod_selector=None):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output... |
'perform oadm manage-node evacuate'
| def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.for... |
'return the openshift version'
| def _version(self):
| return self.openshift_cmd(['version'], output=True, output_type='raw')
|
'perform image import'
| def _import_image(self, url=None, name=None, tag=None):
| cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
|
'Actually executes the command. This makes mocking easier.'
| def _run(self, cmds, input_data):
| curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env)
(stdout, stderr) = proc.communicate(input_data)
return (proc.returncode, stdout.decode('utf-8'), stderr.dec... |
'Base command for oc'
| def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
| cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif ((self.namespace is not None) and (self.namespace.lower() not in ['none', 'emtpy'])):
cmds.extend(['-n', self.namespace])
if self.verbose:
... |
'Actually write the file contents to disk. This helps with mocking.'
| @staticmethod
def _write(filename, contents):
| with open(filename, 'w') as sfd:
sfd.write(contents)
|
'create a file in tmp with name and contents'
| @staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
| tmp = Utils.create_tmpfile(prefix=rname)
if (ftype == 'yaml'):
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif (ftype == 'json'):
... |
'create a temporary copy of a file'
| @staticmethod
def create_tmpfile_copy(inc_file):
| tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
|
'Generates and returns a temporary file name'
| @staticmethod
def create_tmpfile(prefix='tmp'):
| with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
|
'Turn an array of dict: filename, content into a files array'
| @staticmethod
def create_tmp_files_from_contents(content, content_type=None):
| if (not isinstance(content, list)):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents((item['path'] + '-'), item['data'], ftype=content_type)
files.append({'name': os.path.basename(item['path']), 'path': path})
return files
|
'Clean up on exit'
| @staticmethod
def cleanup(files):
| for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
|
'Check to see if the results include the name'
| @staticmethod
def exists(results, _name):
| if (not results):
return False
if Utils.find_result(results, _name):
return True
return False
|
'Find the specified result by name'
| @staticmethod
def find_result(results, _name):
| rval = None
for result in results:
if (('metadata' in result) and (result['metadata']['name'] == _name)):
rval = result
break
return rval
|
'return the service file'
| @staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
| contents = None
with open(sfile) as sfd:
contents = sfd.read()
if (sfile_type == 'yaml'):
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif (sfile_type == 'json'):
... |
'filter the oc version output'
| @staticmethod
def filter_versions(stdout):
| version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if (not line):
continue
if line.startswith(term):
version_dict[term] = line.split()[(-1)]
if ('openshif... |
'create custom versions strings'
| @staticmethod
def add_custom_versions(versions):
| versions_dict = {}
for (tech, version) in versions.items():
if ('-' in version):
version = version.split('-')[0]
if version.startswith('v'):
versions_dict[(tech + '_numeric')] = version[1:].split('+')[0]
versions_dict[(tech + '_short')] = version[1:4]
retu... |
'check if openshift is installed'
| @staticmethod
def openshift_installed():
| import yum
yum_base = yum.YumBase()
if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
return True
return False
|
'Given a user defined definition, compare it with the results given back by our query.'
| @staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
| skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for (key, value) in result_def.items():
if (key in skip):
continue
if isinstance(value, list):
if (key not in user_def):
if debug:
print(('User data do... |
'return config options'
| @property
def config_options(self):
| return self._options
|
'return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'
| def to_option_list(self, ascommalist=''):
| return self.stringify(ascommalist)
|
'return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'
| def stringify(self, ascommalist=''):
| rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if (data['include'] and (data['value'] or isinstance(data['value'], int))):
if (key == ascommalist):
val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].it... |
'Constructor for OpenshiftOC'
| def __init__(self, kind, namespace, name=None, selector=None, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False):
| super(OCObject, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose, all_namespaces=all_namespaces)
self.kind = kind
self.name = name
self.selector = selector
|
'return a kind by name'
| def get(self):
| results = self._get(self.kind, name=self.name, selector=self.selector)
if ((results['returncode'] != 0) and ('stderr' in results) and ('"{}" not found'.format(self.name) in results['stderr'])):
results['returncode'] = 0
return results
|
'delete the object'
| def delete(self):
| results = self._delete(self.kind, name=self.name, selector=self.selector)
if ((results['returncode'] != 0) and ('stderr' in results) and ('"{}" not found'.format(self.name) in results['stderr'])):
results['returncode'] = 0
return results
|
'Create a config
NOTE: This creates the first file OR the first conent.
TODO: Handle all files and content passed in'
| def create(self, files=None, content=None):
| if files:
return self._create(files[0])
content['data'] = yaml.dump(content['data'])
content_file = Utils.create_tmp_files_from_contents(content)[0]
return self._create(content_file['path'])
|
'update a current openshift object
This receives a list of file names or content
and takes the first and calls replace.
TODO: take an entire list'
| def update(self, files=None, content=None, force=False):
| if files:
return self._replace(files[0], force)
if (content and ('data' in content)):
content = content['data']
return self.update_content(content, force)
|
'update an object through using the content param'
| def update_content(self, content, force=False):
| return self._replace_content(self.kind, self.name, content, force=force)
|
'check to see if we need to update'
| def needs_update(self, files=None, content=None, content_type='yaml'):
| objects = self.get()
if (objects['returncode'] != 0):
return objects
data = None
if files:
data = Utils.get_resource_file(files[0], content_type)
elif (content and ('data' in content)):
data = content['data']
else:
data = content
return (not Utils.check_def_eq... |
'perform the ansible idempotent code'
| @staticmethod
def run_ansible(params, check_mode=False):
| ocobj = OCObject(params['kind'], params['namespace'], params['name'], params['selector'], kubeconfig=params['kubeconfig'], verbose=params['debug'], all_namespaces=params['all_namespaces'])
state = params['state']
api_rval = ocobj.get()
if (state == 'list'):
return {'changed': False, 'results': a... |
'getter method for separator'
| @property
def separator(self):
| return self._separator
|
'setter method for separator'
| @separator.setter
def separator(self, inc_sep):
| self._separator = inc_sep
|
'getter method for yaml_dict'
| @property
def yaml_dict(self):
| return self.__yaml_dict
|
'setter method for yaml_dict'
| @yaml_dict.setter
def yaml_dict(self, value):
| self.__yaml_dict = value
|
'parse the key allowing the appropriate separator'
| @staticmethod
def parse_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
|
'validate the incoming key'
| @staticmethod
def valid_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
if (not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key)):
return False
return True
|
'remove data at location key'
| @staticmethod
def remove_entry(data, key, sep='.'):
| if ((key == '') and isinstance(data, dict)):
data.clear()
return True
elif ((key == '') and isinstance(data, list)):
del data[:]
return True
if ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_ke... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a#b
return c'
| @staticmethod
def add_entry(data, key, item=None, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes[:(-1)]:
if dict_key:
if (isinstance(data, dict) and (dict_key in data) ... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a.b
return c'
| @staticmethod
def get_entry(data, key, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes:
if (dict_key and isinstance(data, dict)):
data = data.get(dict_key)
... |
'Actually write the file contents to disk. This helps with mocking.'
| @staticmethod
def _write(filename, contents):
| tmp_filename = (filename + '.yedit')
with open(tmp_filename, 'w') as yfd:
yfd.write(contents)
os.rename(tmp_filename, filename)
|
'write to file'
| def write(self):
| if (not self.filename):
raise YeditException('Please specify a filename.')
if (self.backup and self.file_exists()):
shutil.copy(self.filename, (self.filename + '.orig'))
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
try:
Yedit._... |
'read from file'
| def read(self):
| if ((self.filename is None) or (not self.file_exists())):
return None
contents = None
with open(self.filename) as yfd:
contents = yfd.read()
return contents
|
'return whether file exists'
| def file_exists(self):
| if os.path.exists(self.filename):
return True
return False
|
'return yaml file'
| def load(self, content_type='yaml'):
| contents = self.read()
if ((not contents) and (not self.content)):
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
t... |
'get a specified key'
| def get(self, key):
| try:
entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
except KeyError:
entry = None
return entry
|
'remove a key, value pair from a dict or an item for a list'
| def pop(self, path, key_or_item):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
if isinstance(entry, dict):
if (key_or_item in entry):
entry.pop(key_or_item)
return (True, self.yam... |
'remove path from a dict'
| def delete(self, path):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
if (not result):
return (False, self.yaml_dict)
re... |
'check if value exists at path'
| def exists(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, list):
if (value in entry):
return True
return False
elif isinstance(entry, dict):
if isinstance(value, dict):
rval = Fals... |
'append value to a list'
| def append(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if (not isinstance(entry, list)):
return (False, self.yaml_dict)
... |
'put path, value into a dict'
| def update(self, path, value, index=None, curr_value=None):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
if (not isinstance(value, dict)):
raise YeditException(('Cannot replace key, value entry in dict with non-dict type. ... |
'put path, value into a dict'
| def put(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry == value):
return (False, self.yaml_dict)
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except ... |
'create a yaml file'
| def create(self, path, value):
| if (not self.file_exists()):
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
try:
tmp_copy.fa.set_block_style()
except A... |
'return the current value'
| @staticmethod
def get_curr_value(invalue, val_type):
| if (invalue is None):
return None
curr_value = invalue
if (val_type == 'yaml'):
curr_value = yaml.load(invalue)
elif (val_type == 'json'):
curr_value = json.loads(invalue)
return curr_value
|
'determine value type passed'
| @staticmethod
def parse_value(inc_value, vtype=''):
| true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON']
false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF']
if (isinstance(inc_value, str) and ('bool' in vtype)):
if ((inc_value not in true_bools) and (inc_value not in false_bools... |
'run through a list of edits and process them one-by-one'
| @staticmethod
def process_edits(edits, yamlfile):
| results = []
for edit in edits:
value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
if (edit.get('action') == 'update'):
curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format'))
rval = yamlfile.update(edi... |
'perform the idempotent crud operations'
| @staticmethod
def run_ansible(params):
| yamlfile = Yedit(filename=params['src'], backup=params['backup'], separator=params['separator'])
state = params['state']
if params['src']:
rval = yamlfile.load()
if ((yamlfile.yaml_dict is None) and (state != 'present')):
return {'failed': True, 'msg': ('Error opening file ... |
'Constructor for OpenshiftCLI'
| def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False):
| self.namespace = namespace
self.verbose = verbose
self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
self.oc_binary = locate_oc_binary()
|
'replace the current object with the content'
| def _replace_content(self, resource, rname, content, force=False, sep='.'):
| res = self._get(resource, rname)
if (not res['results']):
return res
fname = Utils.create_tmpfile((rname + '-'))
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for (key, value) in content.items():
changes.append(yed.put(key, value))
if any([change[0] for ch... |
'replace the current object with oc replace'
| def _replace(self, fname, force=False):
| yed = Yedit(fname)
results = yed.delete('metadata.resourceVersion')
if results[0]:
yed.write()
cmd = ['replace', '-f', fname]
if force:
cmd.append('--force')
return self.openshift_cmd(cmd)
|
'create a temporary file and then call oc create on it'
| def _create_from_content(self, rname, content):
| fname = Utils.create_tmpfile((rname + '-'))
yed = Yedit(fname, content=content)
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._create(fname)
|
'call oc create on a filename'
| def _create(self, fname):
| return self.openshift_cmd(['create', '-f', fname])
|
'call oc delete on a resource'
| def _delete(self, resource, name=None, selector=None):
| cmd = ['delete', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift... |
'process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template\'s data; instead of a file'
| def _process(self, template_name, create=False, params=None, template_data=None):
| cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ['{}={}'.format(key, str(value).replace("'", '"')) for (key, value) in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.open... |
'return a resource by name'
| def _get(self, resource, name=None, selector=None):
| cmd = ['get', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
if ('items' in rval):
rval['results'] = rval['items']
elif ... |
'perform oadm manage-node scheduable'
| def _schedulable(self, node=None, selector=None, schedulable=True):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
'perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided'
| def _list_pods(self, node=None, selector=None, pod_selector=None):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output... |
'perform oadm manage-node evacuate'
| def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
| cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.for... |
'return the openshift version'
| def _version(self):
| return self.openshift_cmd(['version'], output=True, output_type='raw')
|
'perform image import'
| def _import_image(self, url=None, name=None, tag=None):
| cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
|
'Actually executes the command. This makes mocking easier.'
| def _run(self, cmds, input_data):
| curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env)
(stdout, stderr) = proc.communicate(input_data)
return (proc.returncode, stdout.decode('utf-8'), stderr.dec... |
'Base command for oc'
| def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
| cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif ((self.namespace is not None) and (self.namespace.lower() not in ['none', 'emtpy'])):
cmds.extend(['-n', self.namespace])
if self.verbose:
... |
'Actually write the file contents to disk. This helps with mocking.'
| @staticmethod
def _write(filename, contents):
| with open(filename, 'w') as sfd:
sfd.write(contents)
|
'create a file in tmp with name and contents'
| @staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
| tmp = Utils.create_tmpfile(prefix=rname)
if (ftype == 'yaml'):
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif (ftype == 'json'):
... |
'create a temporary copy of a file'
| @staticmethod
def create_tmpfile_copy(inc_file):
| tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
|
'Generates and returns a temporary file name'
| @staticmethod
def create_tmpfile(prefix='tmp'):
| with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
|
'Turn an array of dict: filename, content into a files array'
| @staticmethod
def create_tmp_files_from_contents(content, content_type=None):
| if (not isinstance(content, list)):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents((item['path'] + '-'), item['data'], ftype=content_type)
files.append({'name': os.path.basename(item['path']), 'path': path})
return files
|
'Clean up on exit'
| @staticmethod
def cleanup(files):
| for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
|
'Check to see if the results include the name'
| @staticmethod
def exists(results, _name):
| if (not results):
return False
if Utils.find_result(results, _name):
return True
return False
|
'Find the specified result by name'
| @staticmethod
def find_result(results, _name):
| rval = None
for result in results:
if (('metadata' in result) and (result['metadata']['name'] == _name)):
rval = result
break
return rval
|
'return the service file'
| @staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
| contents = None
with open(sfile) as sfd:
contents = sfd.read()
if (sfile_type == 'yaml'):
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif (sfile_type == 'json'):
... |
'filter the oc version output'
| @staticmethod
def filter_versions(stdout):
| version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if (not line):
continue
if line.startswith(term):
version_dict[term] = line.split()[(-1)]
if ('openshif... |
'create custom versions strings'
| @staticmethod
def add_custom_versions(versions):
| versions_dict = {}
for (tech, version) in versions.items():
if ('-' in version):
version = version.split('-')[0]
if version.startswith('v'):
versions_dict[(tech + '_numeric')] = version[1:].split('+')[0]
versions_dict[(tech + '_short')] = version[1:4]
retu... |
'check if openshift is installed'
| @staticmethod
def openshift_installed():
| import yum
yum_base = yum.YumBase()
if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
return True
return False
|
'Given a user defined definition, compare it with the results given back by our query.'
| @staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
| skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for (key, value) in result_def.items():
if (key in skip):
continue
if isinstance(value, list):
if (key not in user_def):
if debug:
print(('User data do... |
'return config options'
| @property
def config_options(self):
| return self._options
|
'return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'
| def to_option_list(self, ascommalist=''):
| return self.stringify(ascommalist)
|
'return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'
| def stringify(self, ascommalist=''):
| rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if (data['include'] and (data['value'] or isinstance(data['value'], int))):
if (key == ascommalist):
val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].it... |
'constructor for handling service options'
| def __init__(self, sname, namespace, ports, selector=None, labels=None, cluster_ip=None, portal_ip=None, session_affinity=None, service_type=None, external_ips=None):
| self.name = sname
self.namespace = namespace
self.ports = ports
self.selector = selector
self.labels = labels
self.cluster_ip = cluster_ip
self.portal_ip = portal_ip
self.session_affinity = session_affinity
self.service_type = service_type
self.external_ips = external_ips
sel... |
'instantiates a service dict'
| def create_dict(self):
| self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Service'
self.data['metadata'] = {}
self.data['metadata']['name'] = self.name
self.data['metadata']['namespace'] = self.namespace
if self.labels:
self.data['metadata']['labels'] = {}
for (lab, lab_value) in self.labels.items():
... |
'Service constructor'
| def __init__(self, content):
| super(Service, self).__init__(content=content)
|
'get a list of ports'
| def get_ports(self):
| return (self.get(Service.port_path) or [])
|
'get the service selector'
| def get_selector(self):
| return (self.get(Service.selector_path) or {})
|
'add a port object to the ports list'
| def add_ports(self, inc_ports):
| if (not isinstance(inc_ports, list)):
inc_ports = [inc_ports]
ports = self.get_ports()
if (not ports):
self.put(Service.port_path, inc_ports)
else:
ports.extend(inc_ports)
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.