docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
An internal method to open an existing ISO for inspection and modification. Note that the file object passed in here must stay open for the lifetime of this object, as the PyCdlib class uses it internally to do writing and reading operations. Parameters: fp - The file object c...
def _open_fp(self, fp): # type: (BinaryIO) -> None if hasattr(fp, 'mode') and 'b' not in fp.mode: raise pycdlibexception.PyCdlibInvalidInput("The file to open must be in binary mode (add 'b' to the open flags)") self._cdfp = fp # Get the Primary Volume Descriptor (...
511,281
An internal method to fetch a single file from the ISO and write it out to the file object. Parameters: iso_path - The absolute path to the file to get data from. outfp - The file object to write data to. blocksize - The blocksize to use when copying data. Returns: ...
def _get_and_write_fp(self, iso_path, outfp, blocksize): # type: (bytes, BinaryIO, int) -> None try: return self._get_file_from_iso_fp(outfp, blocksize, None, None, iso_path) except pycdlibexception.PyCdlibException: pass try: return self._ge...
511,282
An internal method to fetch a single UDF file from the ISO and write it out to the file object. Parameters: outfp - The file object to write data to. blocksize - The number of bytes in each transfer. udf_path - The absolute UDF path to lookup on the ISO. Returns: ...
def _udf_get_file_from_iso_fp(self, outfp, blocksize, udf_path): # type: (BinaryIO, int, bytes) -> None if self.udf_root is None: raise pycdlibexception.PyCdlibInvalidInput('Cannot fetch a udf_path from a non-UDF ISO') (ident_unused, found_file_entry) = self._find_udf_recor...
511,283
Internal method to write data out to the output file descriptor, ensuring that it doesn't go beyond the bounds of the ISO. Parameters: outfp - The file object to write to. data - The actual data to write. enable_overwrite_check - Whether to do overwrite checking if it is enab...
def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True): # type: (BinaryIO, bytes, bool) -> None start = outfp.tell() outfp.write(data) if self._track_writes: # After the write, double check that we didn't write beyond the # boundary o...
511,285
Internal method to write a directory record entry out. Parameters: outfp - The file object to write the data to. blocksize - The blocksize to use when writing the data out. ino - The Inode to write. Returns: The total number of bytes written out.
def _output_file_data(self, outfp, blocksize, ino): # type: (BinaryIO, int, inode.Inode) -> int log_block_size = self.pvd.logical_block_size() outfp.seek(ino.extent_location() * log_block_size) tmp_start = outfp.tell() with inode.InodeOpenData(ino, log_block_size) as (d...
511,286
An internal method to write out the directory records from a particular Volume Descriptor. Parameters: vd - The Volume Descriptor to write the Directory Records from. outfp - The file object to write data to. progress - The _Progress object to use for outputting progress. ...
def _write_directory_records(self, vd, outfp, progress): # type: (headervd.PrimaryOrSupplementaryVD, BinaryIO, PyCdlib._Progress) -> None log_block_size = vd.logical_block_size() le_ptr_offset = 0 be_ptr_offset = 0 dirs = collections.deque([vd.root_directory_record()]) ...
511,287
An internal method to write out a UDF Descriptor sequence. Parameters: descs - The UDF Descriptors object to write out. outfp - The output file descriptor to use for writing. progress - The _Progress object to use for updating progress. Returns: Nothing.
def _write_udf_descs(self, descs, outfp, progress): # type: (PyCdlib._UDFDescriptors, BinaryIO, PyCdlib._Progress) -> None log_block_size = self.pvd.logical_block_size() outfp.seek(descs.pvd.extent_location() * log_block_size) rec = descs.pvd.record() self._outfp_write_...
511,288
An internal method to update the Rock Ridge CE entry for the given record. Parameters: rec - The record to update the Rock Ridge CE entry for (if it exists). Returns: The number of additional bytes needed for this Rock Ridge CE entry.
def _update_rr_ce_entry(self, rec): # type: (dr.DirectoryRecord) -> int if rec.rock_ridge is not None and rec.rock_ridge.dr_entries.ce_record is not None: celen = rec.rock_ridge.dr_entries.ce_record.len_cont_area added_block, block, offset = self.pvd.add_rr_ce_entry(cele...
511,290
An internal method to do all of the accounting needed whenever something is added to the ISO. This method should only be called by public API implementations. Parameters: num_bytes_to_add - The number of additional bytes to add to all descriptors. ...
def _finish_add(self, num_bytes_to_add, num_partition_bytes_to_add): # type: (int, int) -> None for pvd in self.pvds: pvd.add_to_space_size(num_bytes_to_add + num_partition_bytes_to_add) if self.joliet_vd is not None: self.joliet_vd.add_to_space_size(num_bytes_to...
511,291
An internal method to do all of the accounting needed whenever something is removed from the ISO. This method should only be called by public API implementations. Parameters: num_bytes_to_remove - The number of additional bytes to remove from the descriptors. is_partition - W...
def _finish_remove(self, num_bytes_to_remove, is_partition): # type: (int, bool) -> None for pvd in self.pvds: pvd.remove_from_space_size(num_bytes_to_remove) if self.joliet_vd is not None: self.joliet_vd.remove_from_space_size(num_bytes_to_remove) if se...
511,292
An internal method to remove a Directory Record link given the record. Parameters: rec - The Directory Record to remove. Returns: The number of bytes to remove from the ISO.
def _rm_dr_link(self, rec): # type: (dr.DirectoryRecord) -> int if not rec.is_file(): raise pycdlibexception.PyCdlibInvalidInput('Cannot remove a directory with rm_hard_link (try rm_directory instead)') num_bytes_to_remove = 0 logical_block_size = rec.vd.logical_bl...
511,295
An internal method to remove a UDF File Identifier from the parent and remove any space from the Logical Volume as necessary. Parameters: parent - The parent entry to remove the UDF File Identifier from. fi - The file identifier to remove. Returns: The number of bytes...
def _rm_udf_file_ident(self, parent, fi): # type: (udfmod.UDFFileEntry, bytes) -> int logical_block_size = self.pvd.logical_block_size() num_extents_to_remove = parent.remove_file_ident_desc_by_name(fi, logical_block_...
511,296
An internal method to remove a UDF File Entry link. Parameters: rec - The UDF File Entry to remove. Returns: The number of bytes to remove from the ISO.
def _rm_udf_link(self, rec): # type: (udfmod.UDFFileEntry) -> int if not rec.is_file() and not rec.is_symlink(): raise pycdlibexception.PyCdlibInvalidInput('Cannot remove a directory with rm_hard_link (try rm_directory instead)') # To remove something from UDF, we have to: ...
511,297
An internal method to add a joliet directory to the ISO. Parameters: joliet_path - The path to add to the Joliet portion of the ISO. Returns: The number of additional bytes needed on the ISO to fit this directory.
def _add_joliet_dir(self, joliet_path): # type: (bytes) -> int if self.joliet_vd is None: raise pycdlibexception.PyCdlibInternalError('Tried to add joliet dir to non-Joliet ISO') (joliet_name, joliet_parent) = self._joliet_name_and_parent_from_path(joliet_path) lo...
511,298
An internal method to remove a directory from the Joliet portion of the ISO. Parameters: joliet_path - The Joliet directory to remove. Returns: The number of bytes to remove from the ISO for this Joliet directory.
def _rm_joliet_dir(self, joliet_path): # type: (bytes) -> int if self.joliet_vd is None: raise pycdlibexception.PyCdlibInternalError('Tried to remove joliet dir from non-Joliet ISO') log_block_size = self.joliet_vd.logical_block_size() joliet_child = self._find_joli...
511,299
Internal method to get the directory record for a particular path. Parameters: iso_path - The path on the ISO filesystem to look up the record for. rr_path - The Rock Ridge path on the ISO filesystem to look up the record for. joliet_path - The path on the Joliet f...
def _get_entry(self, iso_path, rr_path, joliet_path): # type: (Optional[bytes], Optional[bytes], Optional[bytes]) -> dr.DirectoryRecord if self._needs_reshuffle: self._reshuffle_extents() rec = None if joliet_path is not None: rec = self._find_joliet_re...
511,300
Internal method to get the UDF File Entry for a particular path. Parameters: udf_path - The path on the UDF filesystem to look up the record for. Returns: A udfmod.UDFFileEntry object representing the path.
def _get_udf_entry(self, udf_path): # type: (str) -> udfmod.UDFFileEntry if self._needs_reshuffle: self._reshuffle_extents() (ident_unused, rec) = self._find_udf_record(utils.normpath(udf_path)) if rec is None: raise pycdlibexception.PyCdlibInvalidInput(...
511,301
Open up an existing ISO for inspection and modification. Parameters: filename - The filename containing the ISO to open up. Returns: Nothing.
def open(self, filename): # type: (str) -> None if self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object already has an ISO; either close it or create a new object') fp = open(filename, 'r+b') self._managing_fp = True try: se...
511,306
Open up an existing ISO for inspection and modification. Note that the file object passed in here must stay open for the lifetime of this object, as the PyCdlib class uses it internally to do writing and reading operations. If you want PyCdlib to manage this for you, use 'open' instead...
def open_fp(self, fp): # type: (BinaryIO) -> None if self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object already has an ISO; either close it or create a new object') self._open_fp(fp)
511,307
Remove a file from the ISO. Parameters: iso_path - The path to the file to remove. rr_name - The Rock Ridge name of the file to remove. joliet_path - The Joliet path to the file to remove. udf_path - The UDF path to the file to remove. Returns: Nothing.
def rm_file(self, iso_path, rr_name=None, joliet_path=None, udf_path=None): # pylint: disable=unused-argument # type: (str, Optional[str], Optional[str], Optional[str]) -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized...
511,320
Remove a directory from the ISO. Parameters: iso_path - The path to the directory to remove. rr_name - The Rock Ridge name of the directory to remove. joliet_path - The Joliet path to the directory to remove. udf_path - The UDF absolute path to the directory to remove. ...
def rm_directory(self, iso_path=None, rr_name=None, joliet_path=None, udf_path=None): # type: (Optional[str], Optional[str], Optional[str], Optional[str]) -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either op...
511,321
Remove the El Torito boot record (and Boot Catalog) from the ISO. Parameters: None. Returns: Nothing.
def rm_eltorito(self): # type: () -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') if self.eltorito_boot_catalog is None: raise pycdlibexception.PyCdl...
511,323
(deprecated) Generate a list of all of the file/directory objects in the specified location on the ISO. It is recommended to use the 'list_children' API instead. Parameters: iso_path - The path on the ISO to look up information for. joliet - Whether to look for the path in th...
def list_dir(self, iso_path, joliet=False): # type: (str, bool) -> Generator if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') if joliet: rec = self._get_entry...
511,325
(deprecated) Get the directory record for a particular path. It is recommended to use the 'get_record' API instead. Parameters: iso_path - The path on the ISO to look up information for. joliet - Whether to look for the path in the Joliet portion of the ISO. Returns: ...
def get_entry(self, iso_path, joliet=False): # type: (str, bool) -> dr.DirectoryRecord if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') if joliet: return self...
511,327
A method to get the absolute path of a directory record. Parameters: rec - The directory record to get the full path for. rockridge - Whether to get the rock ridge full path. Returns: A string representing the absolute path to the file on the ISO.
def full_path_from_dirrecord(self, rec, rockridge=False): # type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') ...
511,330
A method to add a duplicate PVD to the ISO. This is a mostly useless feature allowed by Ecma-119 to have duplicate PVDs to avoid possible corruption. Parameters: None. Returns: Nothing.
def duplicate_pvd(self): # type: () -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') pvd = headervd.PrimaryOrSupplementaryVD(headervd.VOLUME_DESCRIPTOR_TYPE_PRIMA...
511,331
Set the name of the relocated directory on a Rock Ridge ISO. The ISO must be a Rock Ridge one, and must not have previously had the relocated name set. Parameters: name - The name for a relocated directory. rr_name - The Rock Ridge name for a relocated directory. Retu...
def set_relocated_name(self, name, rr_name): # type: (str, str) -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') if not self.rock_ridge: raise pycdlib...
511,333
Close the PyCdlib object, and re-initialize the object to the defaults. The object can then be re-used for manipulation of another ISO. Parameters: None. Returns: Nothing.
def close(self): # type: () -> None if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO') if self._managing_fp: # In this case, we are managing self._cdfp, so we n...
511,336
Update BIRD configuration. It adds to or removes IP prefix from BIRD configuration. It also updates generation time stamp in the configuration file. Main program will exit if configuration file cant be read/written. Arguments: operation (obj): Either an AddOperation or Del...
def _update_bird_conf_file(self, operation): conf_updated = False prefixes = [] ip_version = operation.ip_version config_file = self.bird_configuration[ip_version]['config_file'] variable_name = self.bird_configuration[ip_version]['variable_name'] changes_counter...
511,341
Perform a sanity check on ip_prefix. Arguments: ip_prefix (str): The IP-Prefix to validate Returns: True if ip_prefix is a valid IPv4 address with prefix length 32 or a valid IPv6 address with prefix length 128, otherwise False
def valid_ip_prefix(ip_prefix): try: ip_prefix = ipaddress.ip_network(ip_prefix) except ValueError: return False else: if ip_prefix.version == 4 and ip_prefix.max_prefixlen != 32: return False if ip_prefix.version == 6 and ip_prefix.max_prefixlen != 128: ...
511,343
Build a set of IP prefixes found in service configuration files. Arguments: config (obg): A configparser object which holds our configuration. services (list): A list of section names which are the name of the service checks. ip_version (int): IP protocol version Returns: ...
def get_ip_prefixes_from_config(config, services, ip_version): ip_prefixes = set() for service in services: ip_prefix = ipaddress.ip_network(config.get(service, 'ip_prefix')) if ip_prefix.version == ip_version: ip_prefixes.add(ip_prefix.with_prefixlen) return ip_prefixes
511,344
Sanity check on IP prefixes. Arguments: config (obg): A configparser object which holds our configuration. bird_configuration (dict): A dictionary, which holds Bird configuration per IP protocol version.
def ip_prefixes_sanity_check(config, bird_configuration): for ip_version in bird_configuration: modify_ip_prefixes(config, bird_configuration[ip_version]['config_file'], bird_configuration[ip_version]['variable_name'], bir...
511,345
Perform a sanity check on configuration. First it performs a sanity check against settings for daemon and then against settings for each service check. Arguments: config (obj): A configparser object which holds our configuration. Returns: None if all checks are successfully passed oth...
def configuration_check(config): log_level = config.get('daemon', 'loglevel') num_level = getattr(logging, log_level.upper(), None) pidfile = config.get('daemon', 'pidfile') # Catch the case where the directory, under which we store the pid file, is # missing. if not os.path.isdir(os.path....
511,348
Perform a sanity check against options for each service check. Arguments: config (obj): A configparser object which holds our configuration. Returns: None if all sanity checks are successfully passed otherwise raises a ValueError exception.
def service_configuration_check(config): ipv4_enabled = config.getboolean('daemon', 'ipv4') ipv6_enabled = config.getboolean('daemon', 'ipv6') services = config.sections() # we don't need it during sanity check for services check services.remove('daemon') ip_prefixes = [] for service i...
511,349
Build bird configuration structure. First it performs a sanity check against bird settings and then builds a dictionary structure with bird configuration per IP version. Arguments: config (obj): A configparser object which holds our configuration. Returns: A dictionary Raises: ...
def build_bird_configuration(config): bird_configuration = {} if config.getboolean('daemon', 'ipv4'): if os.path.islink(config.get('daemon', 'bird_conf')): config_file = os.path.realpath(config.get('daemon', 'bird_conf')) print("'bird_conf' is set to a symbolic link ({s} ->...
511,350
Return the variable name set in Bird configuration. The variable name in Bird configuration is set with the keyword 'define', here is an example: define ACAST_PS_ADVERTISE = and we exract the string between the word 'define' and the equals sign. Arguments: bird_conf (str): The absolu...
def get_variable_name_from_bird(bird_conf): bird_variable_pattern = re.compile( r, re.VERBOSE ) with open(bird_conf, 'r') as content: for line in content.readlines(): variable_match = bird_variable_pattern.search(line) if variable_match: return v...
511,351
Create bird configuration files per IP version. Creates bird configuration files if they don't exist. It also creates the directories where we store the history of changes, if this functionality is enabled. Arguments: bird_configuration (dict): A dictionary with settings for bird. Returns...
def create_bird_config_files(bird_configuration): for ip_version in bird_configuration: # This creates the file if it doesn't exist. config_file = bird_configuration[ip_version]['config_file'] try: touch(config_file) except OSError as exc: raise ValueErro...
511,352
Check the validity of a process ID. Arguments: processid (int): Process ID number. Returns: True if process ID is found otherwise False.
def running(processid): try: # From kill(2) # If sig is 0 (the null signal), error checking is performed but no # signal is actually sent. The null signal can be used to check the # validity of pid os.kill(processid, 0) except OverflowError as exc: prin...
511,353
Build a list of IP prefixes found in Bird configuration. Arguments: filename (str): The absolute path of the Bird configuration file. Notes: It can only parse a file with the following format define ACAST_PS_ADVERTISE = [ 10.189.200.155/32, ...
def get_ip_prefixes_from_bird(filename): prefixes = [] with open(filename, 'r') as bird_conf: lines = bird_conf.read() for line in lines.splitlines(): line = line.strip(', ') if valid_ip_prefix(line): prefixes.append(line) return prefixes
511,354
Write in a temporary file the list of IP-Prefixes. A failure to create and write the temporary file will exit main program. Arguments: dummy_ip_prefix (str): The dummy IP prefix, which must be always config_file (str): The file name of bird configuration variable_name (str): The name o...
def write_temp_bird_conf(dummy_ip_prefix, config_file, variable_name, prefixes): log = logging.getLogger(PROGRAM_NAME) comment = ("# {i} is a dummy IP Prefix. It should NOT be used and " "REMOVED from the constant.".f...
511,356
Keep a history of Bird configuration files. Arguments: config_file (str): file name of bird configuration changes_counter (int): number of configuration files to keep in the history
def archive_bird_conf(config_file, changes_counter): log = logging.getLogger(PROGRAM_NAME) history_dir = os.path.join(os.path.dirname(config_file), 'history') dst = os.path.join(history_dir, str(time.time())) log.debug("coping %s to %s", config_file, dst) history = [x for x in os.listdir(histo...
511,357
Update pidfile. Notice: We should call this function only after we have successfully acquired a lock and never before. It exits main program if it fails to parse and/or write pidfile. Arguments: pidfile (str): pidfile to update
def update_pidfile(pidfile): try: with open(pidfile, mode='r') as _file: pid = _file.read(1024).rstrip() try: pid = int(pid) except ValueError: print("cleaning stale pidfile with invalid data:'{}'".format(pid)) write_pid(pidfile) ...
511,358
Write processID to the pidfile. Notice: It exits main program if it fails to write pidfile. Arguments: pidfile (str): pidfile to update
def write_pid(pidfile): pid = str(os.getpid()) try: with open(pidfile, mode='w') as _file: print("writing processID {p} to pidfile".format(p=pid)) _file.write(pid) except OSError as exc: sys.exit("failed to write pidfile:{e}".format(e=exc))
511,359
Clean up pidfile upon shutdown. Notice: We should register this function as signal handler for the following termination signals: SIGHUP SIGTERM SIGABRT SIGINT Arguments: pidfile (str): pidfile to remove signalnb (int): The ID of ...
def shutdown(pidfile, signalnb=None, frame=None): log = logging.getLogger(PROGRAM_NAME) log.info("received %s at %s", signalnb, frame) log.info("going to remove pidfile %s", pidfile) # no point to catch possible errors when we delete the pid file os.unlink(pidfile) log.info('shutdown is com...
511,360
Reconfigure BIRD daemon by running a custom command. It adds one argument to the command, either "up" or "down". If command times out then we kill it. In order to avoid leaving any orphan processes, that may have been started by the command, we start a new session when we invoke the command and then we...
def run_custom_bird_reconfigure(operation): log = logging.getLogger(PROGRAM_NAME) if isinstance(operation, AddOperation): status = 'up' else: status = 'down' cmd = shlex.split(operation.bird_reconfigure_cmd + " " + status) log.info("reconfiguring BIRD by running custom command %...
511,362
Add a value to the list. Arguments: prefixes(list): A list to add the value
def update(self, prefixes): if self.ip_prefix not in prefixes: prefixes.append(self.ip_prefix) self.log.info("announcing %s for %s", self.ip_prefix, self.name) return True return False
511,364
Return process id of anycast-healthchecker. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. Returns: The process id found in the pid file Raises: ValueError in the following cases - pidfile option is missing from the ...
def get_processid(config): pidfile = config.get('daemon', 'pidfile', fallback=None) if pidfile is None: raise ValueError("Configuration doesn't have pidfile option!") try: with open(pidfile, 'r') as _file: pid = _file.read().rstrip() try: pid = i...
511,381
Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each service check Returns: A number (i...
def parse_services(config, services): enabled = 0 for service in services: check_disabled = config.getboolean(service, 'check_disabled') if not check_disabled: enabled += 1 return enabled
511,382
Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint
def _build_endpoint(self, endpoint_name): endpoint_relative = settings.get('asmaster_endpoints', endpoint_name) return '%s%s' % (self.host, endpoint_relative)
511,485
Handler for `--reset-subscription-since` command. Args: account_id(int): id of the account to reset. datetime_str(str): string representing the datetime used in the next poll to retrieve data since. Returns: (str) json encoded response. NOTE...
def reset_subscription_since(self, account_id, datetime_str): data = { 'account_id': account_id, 'datetime': datetime_str, } return self._perform_post_request(self.reset_subscription_since_endpoint, data, self.token_header)
511,497
Summary audio to listen on web browser. Args: audio (:class:`numpy.ndarray` or :class:`cupy.ndarray` or \ :class:`chainer.Variable`): sampled wave array. sample_rate (int): sampling rate. name (str): name of image. set as column name. when not setting, ...
def audio(self, audio, sample_rate, name=None, subdir=''): from chainerui.report.audio_report import check_available if not check_available(): return from chainerui.report.audio_report import report as _audio col_name = self.get_col_name(name, 'audio') out_...
515,410
Add training log. Args: stats (dict): Training log values. The object must be key-value style and values type must be `float` or `int`. When the object does not have 'elapsed_time' key, the function set the time automatically. The measurement starts w...
def __call__(self, stats): if 'elapsed_time' not in stats: stats['elapsed_time'] = _get_time() - self._start_at self._log.append(stats) with tempdir(prefix=self._log_name, dir=self._out_path) as tempd: path = os.path.join(tempd, 'log.json') with open...
515,429
A util function to save experiment condition for job table. Args: conditions (:class:`argparse.Namespace` or dict): Experiment conditions to show on a job table. Keys are show as table header and values are show at a job row. out_path (str): Output directory name to save con...
def save_args(conditions, out_path): if isinstance(conditions, argparse.Namespace): args = vars(conditions) else: args = conditions try: os.makedirs(out_path) except OSError: pass with tempdir(prefix='args', dir=out_path) as tempd: path = os.path.join(...
515,489
Checks if two ProtoRPC fields are "equal". Compares the arguments, rather than the id of the elements (which is the default __eq__ behavior) as well as the class of the fields. Args: field: A ProtoRPC message field to be compared. other_field: A ProtoRPC message field to be compared. Returns: Boo...
def _CompareFields(field, other_field): field_attrs = _GetFieldAttributes(field) other_field_attrs = _GetFieldAttributes(other_field) if field_attrs != other_field_attrs: return False return field.__class__ == other_field.__class__
516,569
Copies a (potentially) owned ProtoRPC field instance into a new copy. Args: field: A ProtoRPC message field to be copied. number: An integer for the field to override the number of the field. Defaults to None. Raises: TypeError: If the field is not an instance of messages.Field. Returns: ...
def _CopyField(field, number=None): positional_args, kwargs = _GetFieldAttributes(field) number = number or field.number positional_args.append(number) return field.__class__(*positional_args, **kwargs)
516,570
Adds a ResourceContainer to a cache tying it to a protorpc method. Args: remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding to a method. container: An instance of ResourceContainer. Raises: TypeError: if the container is not an instance of cls. KeyError:...
def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name if not isinstance(container, cls): raise TypeError('%r not an instance of %r, could not be added to cache.' % (container, cls)) if remote_info in cls.__remote_info_cache: raise KeyError('Cache has...
516,573
Gets request message or container from remote info. Args: remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding to a method. Returns: Either an instance of the request type from the remote or the ResourceContainer that was cached with the remote method.
def get_request_message(cls, remote_info): # pylint: disable=g-bad-name if remote_info in cls.__remote_info_cache: return cls.__remote_info_cache[remote_info] else: return remote_info.request_type()
516,574
Get user information from the id_token or oauth token in the request. Used internally by Endpoints to set up environment variables for user authentication. Args: method: The class method that's handling this request. This method should be annotated with @endpoints.method. api_info: An api_config....
def _maybe_set_current_user_vars(method, api_info=None, request=None): if _is_auth_info_available(): return # By default, there's no user. os.environ[_ENV_AUTH_EMAIL] = '' os.environ[_ENV_AUTH_DOMAIN] = '' # Choose settings on the method, if specified. Otherwise, choose settings # from the API. S...
516,577
Get the auth token for this request. Auth token may be specified in either the Authorization header or as a query param (either access_token or bearer_token). We'll check in this order: 1. Authorization header. 2. bearer_token query param. 3. access_token query param. Args: request: The curre...
def _get_token( request=None, allowed_auth_schemes=('OAuth', 'Bearer'), allowed_query_keys=('bearer_token', 'access_token')): allowed_auth_schemes = _listlike_guard( allowed_auth_schemes, 'allowed_auth_schemes', iterable_only=True) # Check if the token is in the Authorization header. auth_header ...
516,578
Get a User for the given id token, if the token is valid. Args: token: The id_token to check. issuers: dict of Issuers audiences: List of audiences that are acceptable. allowed_client_ids: List of client IDs that are acceptable. time_now: The current time as a long (eg. long(time.time())). ca...
def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache): # Verify that the token is valid before we try to extract anything from it. # This verifies the signature and some of the basic info in the token. for issuer_key, issuer in issuers.items(): issuer_cert_uri = convert_jwk...
516,579
Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from _process_scopes
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes): for sufficient_scope_set in sufficient_scopes: if sufficient_scope_set.issubset(authorized_scopes): return True return False
516,582
Validate the oauth bearer token and set endpoints auth user variables. If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This provides enough information that our endpoints.get_current_user() function can get the user. Args: allowed_client_ids: List of client IDs that are acceptable. ...
def _set_bearer_user_vars(allowed_client_ids, scopes): all_scopes, sufficient_scopes = _process_scopes(scopes) try: authorized_scopes = oauth.get_authorized_scopes(sorted(all_scopes)) except oauth.Error: _logger.debug('Unable to get authorized scopes.', exc_info=True) return if not _are_scopes_su...
516,583
Validate the oauth bearer token on the dev server. Since the functions in the oauth module return only example results in local development, this hits the tokeninfo endpoint and attempts to validate the token. If it's valid, we'll set _ENV_AUTH_EMAIL and _ENV_AUTH_DOMAIN so we can get the user from the token....
def _set_bearer_user_vars_local(token, allowed_client_ids, scopes): # Get token info from the tokeninfo endpoint. result = urlfetch.fetch( '%s?%s' % (_TOKENINFO_URL, urllib.urlencode({'access_token': token}))) if result.status_code != 200: try: error_description = json.loads(result.content)['er...
516,584
Verify a parsed user ID token. Args: parsed_token: The parsed token information. issuers: A list of allowed issuers audiences: The allowed audiences. allowed_client_ids: The allowed client IDs. Returns: True if the token is verified, False otherwise.
def _verify_parsed_token(parsed_token, issuers, audiences, allowed_client_ids, is_legacy_google_auth=True): # Verify the issuer. if parsed_token.get('iss') not in issuers: _logger.warning('Issuer was not valid: %s', parsed_token.get('iss')) return False # Check audiences. aud = parsed_token.get('aud...
516,585
Get the expiration time for a cert, given the response headers. Get expiration time from the headers in the result. If we can't get a time from the headers, this returns 0, indicating that the cert shouldn't be cached. Args: headers: A dict containing the response headers from the request to get ce...
def _get_cert_expiration_time(headers): # Check the max age of the cert. cache_control = headers.get('Cache-Control', '') # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 indicates only # a comma-separated header is valid, so it should be fine to split this on # commas. for entry in cache_c...
516,587
Get certs from cache if present; otherwise, gets from URI and caches them. Args: cert_uri: URI from which to retrieve certs if cache is stale or empty. cache: Cache of pre-fetched certs. Returns: The retrieved certs.
def _get_cached_certs(cert_uri, cache): certs = cache.get(cert_uri, namespace=_CERT_NAMESPACE) if certs is None: _logger.debug('Cert cache miss for %s', cert_uri) try: result = urlfetch.fetch(cert_uri) except AssertionError: # This happens in unit tests. Act as if we couldn't get any cer...
516,588
Builds an item descriptor for a service configuration. Args: config: A dictionary containing the service configuration to describe. Returns: A dictionary that describes the service configuration.
def __item_descriptor(self, config): descriptor = { 'kind': 'discovery#directoryItem', 'icons': { 'x16': 'https://www.gstatic.com/images/branding/product/1x/' 'googleg_16dp.png', 'x32': 'https://www.gstatic.com/images/branding/product/1x/' ...
516,595
Builds a directory list for an API. Args: configs: List of dicts containing the service configurations to list. Returns: A dictionary that can be deserialized into JSON in discovery list format. Raises: ApiConfigurationError: If there's something wrong with the API configuration...
def __directory_list_descriptor(self, configs): descriptor = { 'kind': 'discovery#directoryList', 'discoveryVersion': 'v1', } items = [] for config in configs: item_descriptor = self.__item_descriptor(config) if item_descriptor: items.append(item_descriptor) ...
516,596
JSON dict description of a protorpc.remote.Service in list format. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: dict, The directory list document as a JSON dict.
def get_directory_list_doc(self, configs): if not isinstance(configs, (tuple, list)): configs = [configs] util.check_list_type(configs, dict, 'configs', allow_none=False) return self.__directory_list_descriptor(configs)
516,597
JSON string description of a protorpc.remote.Service in a discovery doc. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: string, The directory list document as a JSON string.
def pretty_print_config_to_json(self, configs): descriptor = self.get_directory_list_doc(configs) return json.dumps(descriptor, sort_keys=True, indent=2, separators=(',', ': '))
516,598
Format this error into a JSON response. Args: error_list_tag: A string specifying the name of the tag to use for the error list. Returns: A dict containing the reformatted JSON error response.
def __format_error(self, error_list_tag): error = {'domain': self.domain(), 'reason': self.reason(), 'message': self.message()} error.update(self.extra_fields() or {}) return {'error': {error_list_tag: [error], 'code': self.status_code(), ...
516,599
Constructor for InvalidParameterError. Args: parameter_name: String; the name of the parameter which had a value rejected. value: The actual value passed in for the parameter. Usually string.
def __init__(self, parameter_name, value): super(InvalidParameterError, self).__init__() self.parameter_name = parameter_name self.value = value
516,601
Constructor for BasicTypeParameterError. Args: parameter_name: String; the name of the parameter which had a value rejected. value: The actual value passed in for the enum. Usually string. type_name: Descriptive name of the data type expected.
def __init__(self, parameter_name, value, type_name): super(BasicTypeParameterError, self).__init__(parameter_name, value) self.type_name = type_name
516,602
Constructor for EnumRejectionError. Args: parameter_name: String; the name of the enum parameter which had a value rejected. value: The actual value passed in for the enum. Usually string. allowed_values: List of strings allowed for the enum.
def __init__(self, parameter_name, value, allowed_values): super(EnumRejectionError, self).__init__(parameter_name, value) self.allowed_values = allowed_values
516,603
Get the HTTP status code from an HTTP status string. Args: http_status: A string containing a HTTP status code and reason. Returns: An integer with the status code number from http_status.
def _get_status_code(self, http_status): try: return int(http_status.split(' ', 1)[0]) except TypeError: _logger.warning('Unable to find status code in HTTP status %r.', http_status) return 500
516,605
Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response.
def process_api_config_response(self, config_json): with self._config_lock: self._add_discovery_config() for config in config_json.get('items', []): lookup_key = config.get('name', ''), config.get('version', '') self._configs[lookup_key] = config for config in self._configs.i...
516,608
Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server.
def _get_sorted_methods(self, methods): if not methods: return methods # Comparison function we'll use to sort the methods: def _sorted_methods_comparison(method_info1, method_info2): def _score_path(path): score = 0 parts = path.split('/') for part...
516,609
Gets path parameters from a regular expression match. Args: match: A regular expression Match object for a path. Returns: A dictionary containing the variable names converted from base64.
def _get_path_params(match): result = {} for var_name, value in match.groupdict().iteritems(): actual_var_name = ApiConfigManager._from_safe_path_param_name(var_name) result[actual_var_name] = urllib.unquote_plus(value) return result
516,610
Save a configuration to the cache of configs. Args: lookup_key: A string containing the cache lookup key. config: The dict containing the configuration to save to the cache.
def save_config(self, lookup_key, config): with self._config_lock: self._configs[lookup_key] = config
516,613
Takes a safe regex group name and converts it back to the original value. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter:...
def _from_safe_path_param_name(safe_parameter): assert safe_parameter.startswith('_') safe_parameter_as_base32 = safe_parameter[1:] padding_length = - len(safe_parameter_as_base32) % 8 padding = '=' * padding_length return base64.b32decode(safe_parameter_as_base32 + padding)
516,614
r"""Generates a compiled regex pattern for a path pattern. e.g. '/MyApi/v1/notes/{id}' returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)') Args: pattern: A string, the parameterized path pattern to be checked. Returns: A compiled regex object to match this path pattern.
def _compile_path_pattern(pattern): r def replace_variable(match): if match.lastindex > 1: var_name = ApiConfigManager._to_safe_path_param_name(match.group(2)) return '%s(?P<%s>%s)' % (match.group(1), var_name, _PATH_VALUE_PATTERN) return matc...
516,615
Register a single API and its config contents. Args: config_contents: Dict containing API configuration.
def register_backend(self, config_contents): if config_contents is None: return self.__register_class(config_contents) self.__api_configs.append(config_contents) self.__register_methods(config_contents)
516,618
Register the class implementing this config, so we only add it once. Args: parsed_config: The JSON object with the API configuration being added. Raises: ApiConfigurationError: If the class has already been registered.
def __register_class(self, parsed_config): methods = parsed_config.get('methods') if not methods: return # Determine the name of the class that implements this configuration. service_classes = set() for method in methods.itervalues(): rosy_method = method.get('rosyMethod') if...
516,619
Register all methods from the given api config file. Methods are stored in a map from method_name to rosyMethod, the name of the ProtoRPC method to be called on the backend. If no rosyMethod was specified the value will be None. Args: parsed_config: The JSON object with the API configuration bei...
def __register_methods(self, parsed_config): methods = parsed_config.get('methods') if not methods: return for method_name, method in methods.iteritems(): self.__api_methods[method_name] = method.get('rosyMethod')
516,620
Determine if response is an error. Args: status: HTTP status code. headers: Dictionary of (lowercase) header name to value. Returns: True if the response was an error, else False.
def __is_json_error(self, status, headers): content_header = headers.get('content-type', '') content_type, unused_params = cgi.parse_header(content_header) return (status.startswith('400') and content_type.lower() in _ALL_JSON_CONTENT_TYPES)
516,624
Return the HTTP status line and body for a given error code and message. Args: status_code: HTTP status code to be returned. error_message: Error message to be returned. Returns: Tuple (http_status, body): http_status: HTTP status line, e.g. 200 OK. body: Body of the HTTP req...
def __write_error(self, status_code, error_message=None): if error_message is None: error_message = httplib.responses[status_code] status = '%d %s' % (status_code, httplib.responses[status_code]) message = EndpointsErrorMessage( state=EndpointsErrorMessage.State.APPLICATION_ERROR, ...
516,625
Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expecte...
def protorpc_to_endpoints_error(self, status, body): try: rpc_error = self.__PROTOJSON.decode_message(remote.RpcStatus, body) except (ValueError, messages.ValidationError): rpc_error = remote.RpcStatus() if rpc_error.state == remote.RpcStatus.State.APPLICATION_ERROR: # Try to map to...
516,626
Wrapper for the Endpoints server app. Args: environ: WSGI request environment. start_response: WSGI start response function. Returns: Response from service_app or appropriately transformed error response.
def __call__(self, environ, start_response): # Call the ProtoRPC App and capture its response with util.StartResponseProxy() as start_response_proxy: body_iter = self.service_app(environ, start_response_proxy.Proxy) status = start_response_proxy.response_status headers = start_response_pr...
516,627
Constructor for EndpointsDispatcherMiddleware. Args: backend_wsgi_app: A WSGI server that serves the app's endpoints. config_manager: An ApiConfigManager instance that allows a caller to set up an existing configuration for testing.
def __init__(self, backend_wsgi_app, config_manager=None): if config_manager is None: config_manager = api_config_manager.ApiConfigManager() self.config_manager = config_manager self._backend = backend_wsgi_app self._dispatchers = [] for base_path in self._backend.base_paths: self....
516,628
Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response bo...
def _add_dispatcher(self, path_regex, dispatch_function): self._dispatchers.append((re.compile(path_regex), dispatch_function))
516,629
Handles dispatch to apiserver handlers. This typically ends up calling start_response and returning the entire body of the response. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string, the body o...
def dispatch(self, request, start_response): # Check if this matches any of our special handlers. dispatched_response = self.dispatch_non_api_requests(request, start_response) if dispatched_response is not None: return dispatched_response ...
516,633
Dispatch this request if this is a request to a reserved URL. If the request matches one of our reserved URLs, this calls start_response and returns the response body. This also handles OPTIONS CORS requests. Args: request: An ApiRequest, the request from the user. start_response: A funct...
def dispatch_non_api_requests(self, request, start_response): for path_regex, dispatch_function in self._dispatchers: if path_regex.match(request.relative_url): return dispatch_function(request, start_response) if request.http_method == 'OPTIONS': cors_handler = self._create_cors_handl...
516,634
Handler for requests to {base_path}/explorer. This calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body (which is empty, i...
def handle_api_explorer_request(self, request, start_response): redirect_url = self._get_explorer_redirect_url( request.server, request.port, request.base_path) return util.send_wsgi_redirect_response(redirect_url, start_response)
516,635
Handler for requests to {base_path}/static/.*. This calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
def handle_api_static_request(self, request, start_response): if request.path == PROXY_PATH: return util.send_wsgi_response('200 OK', [('Content-Type', 'text/html')], PROXY_HTML, start_respons...
516,636
Verifies that a response has the expected status and content type. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string with the acceptable Content-Type header value. None allows any ...
def verify_response(response, status_code, content_type=None): status = int(response.status.split(' ', 1)[0]) if status != status_code: return False if content_type is None: return True for header, value in response.headers: if header.lower() == 'content-type': return va...
516,637
Generate API call (from earlier-saved request). This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
def call_backend(self, orig_request, start_response): method_config, params = self.lookup_rest_method(orig_request) if not method_config: cors_handler = self._create_cors_handler(orig_request) return util.send_wsgi_not_found_response(start_response, ...
516,639
Write an immediate failure response to outfile, no redirect. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with se...
def fail_request(self, orig_request, message, start_response): cors_handler = self._create_cors_handler(orig_request) return util.send_wsgi_error_response( message, start_response, cors_handler=cors_handler)
516,641
Looks up and returns rest method for the currently-pending request. Args: orig_request: An ApiRequest, the original request from the user. Returns: A tuple of (method descriptor, parameters), or (None, None) if no method was found for the current request.
def lookup_rest_method(self, orig_request): method_name, method, params = self.config_manager.lookup_rest_method( orig_request.path, orig_request.request_uri, orig_request.http_method) orig_request.method_name = method_name return method, params
516,642
Updates the dictionary for an API payload with the request body. The values from the body should override those already in the payload, but for nested fields (message objects) the values can be combined recursively. Args: destination: A dictionary containing an API payload parsed from the ...
def _update_from_body(self, destination, source): for key, value in source.iteritems(): destination_value = destination.get(key) if isinstance(value, dict) and isinstance(destination_value, dict): self._update_from_body(destination_value, value) else: destination[key] = value
516,645
Raise an exception if the response from the backend was an error. Args: body: A string containing the backend response body. status: A string containing the backend response status. Raises: BackendError if the response is an error.
def check_error_response(self, body, status): status_code = int(status.split(' ', 1)[0]) if status_code >= 300: raise errors.BackendError(body, status)
516,647