text
stringlengths
18
773k
def _get_source_device_path(self, fcp, target_wwpn, target_lun): """rhel""" device = '0.0.%s' % fcp data = {'device': device, 'wwpn': target_wwpn, 'lun': target_lun} var_source_device = ('SourceDevice="/dev/disk/by-path/ccw-%(device)s-' 'zfcp-%(wwpn)s:%(lun)s...
def _set_sysfs(self, fcp, target_wwpn, target_lun): """rhel6 set WWPN and LUN in sysfs""" device = '0.0.%s' % fcp port_add = "echo '%s' > " % target_wwpn port_add += "/sys/bus/ccw/drivers/zfcp/%s/port_add" % device unit_add = "echo '%s' > " % target_lun unit_add += "/sys/...
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun): """rhel6 set WWPN and LUN in configuration files""" device = '0.0.%s' % fcp set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf'\ % {'device': device, 'wwpn': target_wwpn, ...
def _set_sysfs(self, fcp, target_wwpn, target_lun): """rhel7 set WWPN and LUN in sysfs""" device = '0.0.%s' % fcp unit_add = "echo '%s' > " % target_lun unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\ % {'device': device, 'wwpn': target_wwpn} ...
def _get_udev_rules(self, channel_read, channel_write, channel_data): """construct udev rules info.""" sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { 'read': channel_read, 'read': channel_read, ...
def _delete_vdev_info(self, vdev): """handle udev rules file.""" vdev = vdev.lower() rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev cmd = 'rm -f %s\n' % rules_file_name address = '0.0.%s' % str(vdev).zfill(4) udev_file_name = '/etc/udev/rules.d/70-pers...
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun): """sles set WWPN and LUN in configuration files""" device = '0.0.%s' % fcp # host config host_config = '/sbin/zfcp_host_configure %s 1' % device # disk config disk_config = '/sbin/zfcp_disk_configure ' +\ ...
def _set_zfcp_multipath(self): """sles""" # modprobe DM multipath kernel module modprobe = 'modprobe dm_multipath' conf_file = '#blacklist {\n' conf_file += '#\tdevnode \\"*\\"\n' conf_file += '#}\n' conf_cmd = 'echo -e "%s" > /etc/multipath.conf' % conf_file ...
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath): """sles offline zfcp. sampe to all rhel distro.""" device = '0.0.%s' % fcp # disk config disk_config = '/sbin/zfcp_disk_configure ' +\ '%(device)s %(wwpn)s %(lun)s 0' %\ {'...
def create_network_configuration_files(self, file_path, guest_networks, first, active=False): """Generate network configuration files for guest vm :param list guest_networks: a list of network info for the guest. It has one dictionary that conta...
def _delete_vdev_info(self, vdev): """handle vdev related info.""" vdev = vdev.lower() network_config_file_name = self._get_network_file() device = self._get_device_name(vdev) cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device, ...
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun): """ubuntu zfcp configuration """ host_config = '/sbin/chzdev zfcp-host %s -e' % fcp device = '0.0.%s' % fcp target = '%s:%s:%s' % (device, target_wwpn, target_lun) disk_config = '/sbin/chzdev zfcp-lun %s -e\n' % tar...
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath): """ubuntu offline zfcp.""" device = '0.0.%s' % fcp target = '%s:%s:%s' % (device, target_wwpn, target_lun) disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target host_offline = '/sbin/chzdev zfcp-host %s -d' %...
def parse_dist(self, os_version): """Separate os and version from os_version. Possible return value are only: ('rhel', x.y) and ('sles', x.y) where x.y may not be digits """ supported = {'rhel': ['rhel', 'redhat', 'red hat'], 'sles': ['suse', 'sles'], ...
def getStatus(rh): """ Get status of a VMRelocate request. Input: Request Handle with the following properties: function - 'MIGRATEVM' subfunction - 'STATUS' userid - userid of the virtual machine parms['all'] - If present, set status_target to A...
def driveFunction(self): """ Drive the function/subfunction call. Input: Self with request filled in. Output: Request Handle updated with the results. Overall return code - 0: successful, non-zero: error """ if self.function == 'HELP': ...
def parseCmdline(self, requestData): """ Parse the request command string. Input: Self with request filled in. Output: Request Handle updated with the parsed information so that it is accessible via key/value pairs for later processing. Re...
def printLn(self, respType, respString): """ Add one or lines of output to the response list. Input: Response type: One or more characters indicate type of response. E - Error message N - Normal message S - Output should be logged ...
def printSysLog(self, logString): """ Log one or more lines. Optionally, add them to logEntries list. Input: Strings to be logged. """ if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG: # print log only when debug is enabled if self.daemon =...
def updateResults(self, newResults, **kwArgs): """ Update the results related to this request excluding the 'response' and 'logEntries' values. We specifically update (if present): overallRC, rc, rs, errno. Input: Dictionary containing the results to be upd...
def filter(self, field, operator, value): """ Add a query filter to be applied to the next API list call for this resource. :param field: Field name to filter by :type field: str :param operator: Operator value :type operator: str :param value: Value o...
def resultsperpage(self, value): """ Set the number of results that will be retrieved by the request. :param value: 'resultsperpage' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object ...
def page(self, value): """ Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object """ instance = copy(self) ins...
def filters(self): """ Returns a merged dictionary of filters. """ params = {} for _filter in self._filters: params.update(_filter) return params
def json_error_formatter(body, status, title, environ): """A json_formatter for webob exceptions.""" body = webob.exc.strip_tags(body) status_code = int(status.split(None, 1)[0]) error_dict = { 'status': status_code, 'title': title, 'detail': body } return {'errors': [err...
def call_func(self, req, *args, **kwargs): """Add json_error_formatter to any webob HTTPExceptions.""" try: return super(SdkWsgify, self).call_func(req, *args, **kwargs) except webob.exc.HTTPException as exc: msg = ('encounter %(error)s error') % {'error': exc} ...
def _load_GeoTransform(self): """Calculate latitude and longitude variable calculated from the gdal.Open.GetGeoTransform method""" def load_lon(): return arange(ds.RasterXSize)*b[1]+b[0] def load_lat(): return arange(ds.RasterYSize)*b[5]+b[3] ds = self.ds...
def psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml', if_exists=True): """ Get the location of the config file. The file location is determined in the following order - `$PWD/psyplotrc.yml` - environment variable `PSYPLOTRC` (pointing to the file location or a dire...
def validate_path_exists(s): """If s is a path, return s, else False""" if s is None: return None if os.path.exists(s): return s else: raise ValueError('"%s" should be a path but it does not exist' % s)
def validate_dict(d): """Validate a dictionary Parameters ---------- d: dict or str If str, it must be a path to a yaml file Returns ------- dict Raises ------ ValueError""" try: return dict(d) except TypeError: d = validate_path_exists(d) ...
def validate_bool_maybe_none(b): 'Convert b to a boolean or raise' if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'none': return None return validate_bool(b)
def validate_bool(b): """Convert b to a boolean or raise""" if isinstance(b, six.string_types): b = b.lower() if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False else: raise ValueEr...
def validate_str(s): """Validate a string Parameters ---------- s: str Returns ------- str Raises ------ ValueError""" if not isinstance(s, six.string_types): raise ValueError("Did not found string!") return six.text_type(s)
def validate_stringlist(s): """Validate a list of strings Parameters ---------- val: iterable of strings Returns ------- list list of str Raises ------ ValueError""" if isinstance(s, six.string_types): return [six.text_type(v.strip()) for v in s.split(',') ...
def add_base_str(self, base_str, pattern='.+', pattern_base=None, append=True): """ Add further base string to this instance Parameters ---------- base_str: str or list of str Strings that are used as to look for keys to get and set keys in ...
def iterkeys(self): """Unsorted iterator over keys""" patterns = self.patterns replace = self.replace seen = set() for key in six.iterkeys(self.base): for pattern in patterns: m = pattern.match(key) if m: ret = m.gro...
def validate(self): """Dictionary with validation methods as values""" depr = self._all_deprecated return dict((key, val[1]) for key, val in six.iteritems(self.defaultParams) if key not in depr)
def descriptions(self): """The description of each keyword in the rcParams dictionary""" return {key: val[2] for key, val in six.iteritems(self.defaultParams) if len(val) >= 3}
def connect(self, key, func): """Connect a function to the given formatoption Parameters ---------- key: str The rcParams key func: function The function that shall be called when the rcParams key changes. It must accept a single value that is...
def disconnect(self, key=None, func=None): """Disconnect the connections to the an rcParams key Parameters ---------- key: str The rcParams key. If None, all keys are used func: function The function that is connected. If None, all functions are ...
def update_from_defaultParams(self, defaultParams=None, plotters=True): """Update from the a dictionary like the :attr:`defaultParams` Parameters ---------- defaultParams: dict The :attr:`defaultParams` like dictionary. If None, the ...
def keys(self): """ Return sorted list of keys. """ k = list(dict.keys(self)) k.sort() return k
def find_all(self, pattern): """ Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. Parameters ---------- pattern: str pattern as suitable for re.compile Returns ------- RcP...
def load_from_file(self, fname=None): """Update rcParams from user-defined settings This function updates the instance with what is found in `fname` Parameters ---------- fname: str Path to the yaml configuration file. Possible keys of the dictionary are...
def dump(self, fname=None, overwrite=True, include_keys=None, exclude_keys=['project.plotters'], include_descriptions=True, **kwargs): """Dump this instance to a yaml file Parameters ---------- fname: str or None file name to write to. If None, the ...
def _load_plugin_entrypoints(self): """Load the modules for the psyplot plugins Yields ------ pkg_resources.EntryPoint The entry point for the psyplot plugin module""" from pkg_resources import iter_entry_points def load_plugin(ep): if plugins_en...
def load_plugins(self, raise_error=False): """ Load the plotters and defaultParams from the plugins This method loads the `plotters` attribute and `defaultParams` attribute from the plugins that use the entry point specified by `group`. Entry points must be objects (or modules) ...
def deploy(project_name): """Assemble the middleware pipeline""" request_log = requestlog.RequestLog header_addon = HeaderControl fault_wrapper = FaultWrapper application = handler.SdkHandler() # currently we have 3 middleware for middleware in (header_addon, fault_wr...
def guest_start(self, userid): """"Power on z/VM instance.""" LOG.info("Begin to power on vm %s", userid) self._smtclient.guest_start(userid) LOG.info("Complete power on vm %s", userid)
def guest_reboot(self, userid): """Reboot a guest vm.""" LOG.info("Begin to reboot vm %s", userid) self._smtclient.guest_reboot(userid) LOG.info("Complete reboot vm %s", userid)
def guest_reset(self, userid): """Reset z/VM instance.""" LOG.info("Begin to reset vm %s", userid) self._smtclient.guest_reset(userid) LOG.info("Complete reset vm %s", userid)
def live_migrate_vm(self, userid, destination, parms, action): """Move an eligible, running z/VM(R) virtual machine transparently from one z/VM system to another within an SSI cluster.""" # Check guest state is 'on' state = self.get_power_state(userid) if state != 'on': ...
def create_vm(self, userid, cpu, memory, disk_list, user_profile, max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam): """Create z/VM userid into user directory for a z/VM instance.""" LOG.info("Creating the user directory for vm %s", userid) info = self._s...
def delete_vm(self, userid): """Delete z/VM userid for the instance.""" LOG.info("Begin to delete vm %s", userid) self._smtclient.delete_vm(userid) # remove userid from smapi namelist self._smtclient.namelist_remove(self._namelist, userid) LOG.info("Complete delete vm %s...
def execute_cmd(self, userid, cmdStr): """Execute commands on the guest vm.""" LOG.debug("executing cmd: %s", cmdStr) return self._smtclient.execute_cmd(userid, cmdStr)
def set_hostname(self, userid, hostname, os_version): """Punch a script that used to set the hostname of the guest. :param str guest: the user id of the guest :param str hostname: the hostname of the guest :param str os_version: version of guest operation system """ tmp_...
def cvtToBlocks(rh, diskSize): """ Convert a disk storage value to a number of blocks. Input: Request Handle Size of disk in bytes Output: Results structure: overallRC - Overall return code for the function: 0 - Everything went ok ...
def cvtToMag(rh, size): """ Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude """ rh.printSysLog("Enter generalUtils.cvtToMag") mSize = '' size = size / (1024 * 1024) if size...
def getSizeFromPage(rh, page): """ Convert a size value from page to a number with a magnitude appended. Input: Request Handle Size in page Output: Converted value with a magnitude """ rh.printSysLog("Enter generalUtils.getSizeFromPage") bSize = float(page) * 4096 ...
def parseCmdline(rh, posOpsList, keyOpsList): """ Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. ...
def default_52xhandler(response, resource, url, params): """ Default 52x handler that loops every second until a non 52x response is received. :param response: The response of the last executed api request. :param resource: The resource of the last executed api request. :param url: The url of the la...
def validate(self): """ Perform validation check on properties. """ if not self.api_token or not self.api_token_secret: raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.") if self.response_type not in ["json", "pson", "xm...
def execute(self, url, params): """ Executes a call to the API. :param url: The full url for the api call. :param params: Query parameters encoded in the request. """ response = requests.get(url, params=params, **self.config.requests_kwargs) if 520 <= response.st...
def _create_invokeScript(self, network_file_path, commands, files_map): """invokeScript: Configure zLinux os network invokeScript is included in the network.doscript, it is used to put the network configuration file to the directory where it belongs and call...
def _create_network_doscript(self, network_file_path): """doscript: contains a invokeScript.sh which will do the special work The network.doscript contains network configuration files and it will be used by zvmguestconfigure to configure zLinux os network when it starts up """ ...
def R(X, destination, a1, a2, b): """A single Salsa20 row operation""" a = (X[a1] + X[a2]) & 0xffffffff X[destination] ^= ((a << b) | (a >> (32 - b)))
def salsa20_8(B, x, src, s_start, dest, d_start): """Salsa20/8 http://en.wikipedia.org/wiki/Salsa20""" # Merged blockxor for speed for i in xrange(16): x[i] = B[i] = B[i] ^ src[s_start + i] # This is the actual Salsa 20/8: four identical double rounds for i in xrange(4): R(x, 4, 0,...
def fileChunkIter(file_object, file_chunk_size=65536): """ Return an iterator to a file-like object that yields fixed size chunks :param file_object: a file-like object :param file_chunk_size: maximum size of chunk """ while True: chunk = file_object.read(file_chunk_size) if chu...
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64): """Returns a key derived using the scrypt key-derivarion function N must be a power of two larger than 1 but no larger than 2 ** 63 (insane) r and p must be positive numbers such that r * p < 2 ** 30 The default values are: N...
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): """Derives a Modular Crypt Format hash using the scrypt KDF Parameter space is smaller than for scrypt(): N must be a power of two larger than 1 but no larger than 2 ** 31 r and p m...
def scrypt_mcf_check(mcf, password): """Returns True if the password matches the given MCF hash""" if not isinstance(mcf, bytes): raise TypeError('MCF must be a byte string') if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): ...
def parse_mixed_delim_str(line): """Turns .obj face index string line into [verts, texcoords, normals] numeric tuples.""" arrs = [[], [], []] for group in line.split(' '): for col, coord in enumerate(group.split('/')): if coord: arrs[col].append(int(coord)) return [t...
def read_objfile(fname): """Takes .obj filename and returns dict of object properties for each object in file.""" verts = defaultdict(list) obj_props = [] with open(fname) as f: lines = f.read().splitlines() for line in lines: if line: split_line = line.strip().split(' '...
def read_wavefront(fname_obj): """Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file.""" fname_mtl = '' geoms = read_objfile(fname_obj) for line in open(fname_obj): if line: split_line = line.strip().split(' ', 1) if len(...
def disableEnableDisk(rh, userid, vaddr, option): """ Disable or enable a disk. Input: Request Handle: owning userid virtual address option ('-e': enable, '-d': disable) Output: Dictionary containing the following: overallRC - overall return code, ...
def execCmdThruIUCV(rh, userid, strCmd, hideInLog=[]): """ Send a command to a virtual machine using IUCV. Input: Request Handle Userid of the target virtual machine Command string to send (Optional) List of strCmd words (by index) to hide in sysLog by replacing the wo...
def getPerfInfo(rh, useridlist): """ Get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure ...
def installFS(rh, vaddr, mode, fileSystem, diskType): """ Install a filesystem on a virtual machine's dasd. Input: Request Handle: userid - Userid that owns the disk Virtual address as known to the owning system. Access mode to use to get the disk. Disk Type - 3390 or ...
def invokeSMCLI(rh, api, parms, hideInLog=[]): """ Invoke SMCLI and parse the results. Input: Request Handle API name, SMCLI parms as an array (Optional) List of parms (by index) to hide in sysLog by replacing the parm with "<hidden>". Output: Dictionary co...
def isLoggedOn(rh, userid): """ Determine whether a virtual machine is logged on. Input: Request Handle: userid being queried Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - 0: if we got...
def punch2reader(rh, userid, fileLoc, spoolClass): """ Punch a file to a virtual reader of the specified virtual machine. Input: Request Handle - for general use and to hold the results userid - userid of the virtual machine fileLoc - File to send spoolClass -...
def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): """ Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired st...
def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): """ Wait for the virtual machine to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'on' or 'off', case sensitive Maximum attempts to wait for desire...
def match(self, context, line): """Match lines prefixed with a hash ("#") mark that don't look like text.""" stripped = line.stripped return stripped.startswith('#') and not stripped.startswith('#{')
def stream(input, encoding=None, errors='strict'): """Safely iterate a template generator, ignoring ``None`` values and optionally stream encoding. Used internally by ``cinje.flatten``, this allows for easy use of a template generator as a WSGI body. """ input = (i for i in input if i) # Omits `None` (empty wr...
def flatten(input, file=None, encoding=None, errors='strict'): """Return a flattened representation of a cinje chunk stream. This has several modes of operation. If no `file` argument is given, output will be returned as a string. The type of string will be determined by the presence of an `encoding`; if one is g...
def fragment(string, name="anonymous", **context): """Translate a template fragment into a callable function. **Note:** Use of this function is discouraged everywhere except tests, as no caching is implemented at this time. Only one function may be declared, either manually, or automatically. If automatic defint...
def iterate(obj): """Loop over an iterable and track progress, including first and last state. On each iteration yield an Iteration named tuple with the first and last flags, current element index, total iterable length (if possible to acquire), and value, in that order. for iteration in iterate(something): ...
def chunk(line, mapping={None: 'text', '${': 'escape', '#{': 'bless', '&{': 'args', '%{': 'format', '@{': 'json'}): """Chunkify and "tag" a block of text into plain text and code sections. The first delimeter is blank to represent text sections, and keep the indexes aligned with the tags. Values are yielded in t...
def prepare(self): """Prepare the ordered list of transformers and reset context state to initial.""" self.scope = 0 self.mapping = deque([0]) self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)]
def stream(self): """The workhorse of cinje: transform input lines and emit output lines. After constructing an instance with a set of input lines iterate this property to generate the template. """ if 'init' not in self.flag: root = True self.prepare() else: root = False # Track which lin...
def classify(self, line): """Identify the correct handler for a given line of input.""" for handler in self._handler: if handler.match(self, line): return handler
def red(numbers): """Encode the deltas to reduce entropy.""" line = 0 deltas = [] for value in numbers: deltas.append(value - line) line = value return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1')
def match(self, context, line): """Match code lines prefixed with a variety of keywords.""" return line.kind == 'code' and line.partitioned[0] in self._both
def _get_field_by_name(model_class, field_name): """ Compatible with old API of model_class._meta.get_field_by_name(field_name) """ field = model_class._meta.get_field(field_name) return ( field, # field field.model, ...
def _get_remote_field(field): """ Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') """ if hasattr(field, 'remote_field'): return field.remote_field elif hasattr(field, 'related'): return field.related else: return None
def _get_all_field_names(model): """ 100% compatible version of the old API of model._meta.get_all_field_names() From: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api """ return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'att...
def get_relation_fields_from_model(model_class): """ Get related fields (m2m, FK, and reverse FK) """ relation_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: field, model, direct, m2m = _get_field_by_name(model_class, field_name) # ge...
def get_direct_fields_from_model(model_class): """ Direct, not m2m, not FK """ direct_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: field, model, direct, m2m = _get_field_by_name(model_class, field_name) if direct and not m2m and not...
def get_model_from_path_string(root_model, path): """ Return a model class for a related model root_model is the class of the initial model path is like foo__bar where bar is related to foo """ for path_section in path.split('__'): if path_section: try: field, mod...