text
stringlengths
81
112k
Implementation of NAPALM method commit_config. def commit_config(self, message=""): """Implementation of NAPALM method commit_config.""" if message: raise NotImplementedError( "Commit message not implemented for this platform" ) commands = [ "...
Implementation of NAPALM method get_bgp_config. def get_bgp_config(self, group="", neighbor=""): """Implementation of NAPALM method get_bgp_config.""" _GROUP_FIELD_MAP_ = { "type": "type", "multipath": "multipath", "apply-groups": "apply_groups", "remove-...
get_network_instances implementation for EOS. def get_network_instances(self, name=""): """get_network_instances implementation for EOS.""" output = self._show_vrf() vrfs = {} all_vrf_interfaces = {} for vrf in output: if ( vrf.get("route_distinguish...
Execute ping on the device and returns a dictionary with the result. Output dictionary has one of following keys: * success * error In case of success, inner dictionary will have the followin keys: * probes_sent (int) * packet_loss (int) * rtt_...
Recursively iterate through values in nested lists. def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
Create documentation for Ansible modules. def build_napalm_ansible_module_docs(app): """Create documentation for Ansible modules.""" # Add script to clone napalm-ansible repo status = subprocess.call( "./build-ansible-module-docs.sh", stdout=sys.stdout, stderr=sys.stderr ) if status != 0:...
Build the getters support matrix. def build_getters_support_matrix(app): """Build the getters support matrix.""" status = subprocess.call("./test.sh", stdout=sys.stdout, stderr=sys.stderr) if status != 0: print("Something bad happened when processing the test reports.") sys.exit(-1) d...
Initial run to figure out what VRF's are available Decided to get this one from Configured-section because bulk-getting all instance-data to do the same could get ridiculously heavy Assuming we're always interested in the DefaultVRF def get_bgp_neighbors(self): def generate_vrf_query(vr...
Check for Netmiko arguments that were passed in as NAPALM optional arguments. Return a dictionary of these optional args that will be passed into the Netmiko ConnectHandler call. def netmiko_args(optional_args): """Check for Netmiko arguments that were passed in as NAPALM optional arguments. Return ...
Decorator that ensures Netmiko connection exists. def ensure_netmiko_conn(func): """Decorator that ensures Netmiko connection exists.""" def wrap_function(self, filename=None, config=None): try: netmiko_object = self._netmiko_device if netmiko_object is None: ra...
The merge diff is not necessarily what needs to be loaded for example under NTP, even though the 'ntp commit' command might be alread configured, it is mandatory to be sent otherwise it won't take the new configuration - see: https://github.com/napalm-automation/napalm-nxos/issues/59 ...
Get a diff between running config and a proposed file. def _get_diff(self): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() diff_out = self._send_command( "show diff rollback-patch file {} file {}".format( "sot_f...
Create Source of Truth file to compare. def _create_sot_file(self): """Create Source of Truth file to compare.""" # Bug on on NX-OS 6.2.16 where overwriting sot_file would take exceptionally long time # (over 12 minutes); so just delete the sot_file try: self._delete_file(f...
Execute ping on the device and returns a dictionary with the result. Output dictionary has one of following keys: * success * error In case of success, inner dictionary will have the followin keys: * probes_sent (int) * packet_loss (int) * rtt_...
IOS implementation of get_lldp_neighbors. def get_lldp_neighbors(self): """IOS implementation of get_lldp_neighbors.""" lldp = {} neighbors_detail = self.get_lldp_neighbors_detail() for intf_name, entries in neighbors_detail.items(): lldp[intf_name] = [] for lldp...
Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. def _send_command(self, command, raw_text=False): """ Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. """ return self.device.show(command, raw_text=raw_tex...
Some fields such `uptime` are returned as: 23week(s) 3day(s) This method will determine the epoch of the event. e.g.: 23week(s) 3day(s) -> 1462248287 def _compute_timestamp(stupid_cisco_output): """ Some fields such `uptime` are returned as: 23week(s) 3day(s) This method will de...
Inconsistent behavior: {'TABLE_intf': [{'ROW_intf': { vs {'TABLE_mac_address': {'ROW_mac_address': [{ vs {'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': { def _get_table_rows(parent_table, table_name, row_name): """ Inconsistent behavior: {'TABLE_intf...
af_name_dict = { 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"} } def get_bgp_neighbors(self): results = {} bgp_state_dict = { "Idle": {"is_up": False, "is_enabled": True}, "Active": {"is_up": ...
get_network_instances implementation for NX-OS def get_network_instances(self, name=""): """ get_network_instances implementation for NX-OS """ # command 'show vrf detail' returns all VRFs with detailed information # format: list of dictionaries with keys such as 'vrf_name' and 'rd' co...
Searches for a class derived form the base NAPALM class NetworkDriver in a specific library. The library name must repect the following pattern: napalm_[DEVICE_OS]. NAPALM community supports a list of devices and provides the corresponding libraries; for full reference please refer to the `Supported Network...
Load a config for the device. def main(config_file): """Load a config for the device.""" if not (os.path.exists(config_file) and os.path.isfile(config_file)): msg = "Missing or invalid config file {0}".format(config_file) raise ValueError(msg) print("Loading config file {0}.".format(confi...
Return wether an OC attribute has been defined or not. def oc_attr_isdefault(o): """Return wether an OC attribute has been defined or not.""" if not o._changed() and not o.default(): return True if o == o.default(): return True return False
Iterates over values of a given column. Args: column_name: A nome of the column to retrieve the values for. Yields: Values of the specified column. Raises: KeyError: If given column is not present in the table. def Column(self, column_name): """Iterates over values of a given colum...
Create n clients to run in a pool. def CreateClientPool(n): """Create n clients to run in a pool.""" clients = [] # Load previously stored clients. try: certificates = [] with open(flags.FLAGS.cert_file, "rb") as fd: # Certificates are base64-encoded, so that we can use new-lines as # sepa...
Checks that the poolclient is not accidentally ran against production. def CheckLocation(): """Checks that the poolclient is not accidentally ran against production.""" for url in (config.CONFIG["Client.server_urls"] + config.CONFIG["Client.control_urls"]): if "staging" in url or "localhost" in u...
Event loop. def Run(self): """Event loop.""" if data_store.RelationalDBEnabled(): data_store.REL_DB.RegisterMessageHandler( self._ProcessMessageHandlerRequests, self.well_known_flow_lease_time, limit=100) data_store.REL_DB.RegisterFlowProcessingHandler(self.ProcessFlow...
Processes message handler requests. def _ProcessMessageHandlerRequests(self, requests): """Processes message handler requests.""" logging.debug("Leased message handler request ids: %s", ",".join(str(r.request_id) for r in requests)) grouped_requests = collection.Group(requests, lambda r: ...
Processes one set of messages from Task Scheduler. The worker processes new jobs from the task master. For each job we retrieve the session from the Task Scheduler. Returns: Total number of messages processed by this call. def RunOnce(self): """Processes one set of messages from Task Schedule...
Processes all the flows in the messages. Precondition: All tasks come from the same queue. Note that the server actually completes the requests in the flow when receiving the messages from the client. We do not really look at the messages here at all any more - we just work from the completed mess...
Processes messages for a given flow. def _ProcessRegularFlowMessages(self, flow_obj, notification): """Processes messages for a given flow.""" session_id = notification.session_id if not isinstance(flow_obj, flow.FlowBase): logging.warning("%s is not a proper flow object (got %s)", session_id, ...
Does the real work with a single flow. def _ProcessMessages(self, notification, queue_manager): """Does the real work with a single flow.""" flow_obj = None session_id = notification.session_id try: # Take a lease on the flow: flow_name = session_id.FlowName() if flow_name in self.we...
The callback for the flow processing queue. def ProcessFlow(self, flow_processing_request): """The callback for the flow processing queue.""" client_id = flow_processing_request.client_id flow_id = flow_processing_request.flow_id data_store.REL_DB.AckFlowProcessingRequests([flow_processing_request]) ...
Wait until the operation is done. Args: timeout: timeout in seconds. None means default timeout (1 hour). 0 means no timeout (wait forever). Returns: Operation object with refreshed target_file. Raises: PollTimeoutError: if timeout is reached. def WaitUntilDone(self, timeo...
Fetch file's data and return proper File object. def Get(self): """Fetch file's data and return proper File object.""" args = vfs_pb2.ApiGetFileDetailsArgs( client_id=self.client_id, file_path=self.path) data = self._context.SendRequest("GetFileDetails", args).file return File(client_id=self.c...
Gets an output plugin index for a plugin with a given id. Historically output plugins descriptors were stored in dicts-like structures with unique identifiers as keys. In REL_DB-based implementation, however, both plugin descriptors and their states are stored in flat lists (see Flow definition in flows.proto)...
Resolve a URN of a flow with this id belonging to a given cron job. def ResolveCronJobFlowURN(self, cron_job_id): """Resolve a URN of a flow with this id belonging to a given cron job.""" if not self._value: raise ValueError("Can't call ResolveCronJobFlowURN on an empty " "client i...
Resolve a URN of a flow with this id belonging to a given client. Note that this may need a roundtrip to the datastore. Resolving algorithm is the following: 1. If the flow id doesn't contain slashes (flow is not nested), we just append it to the <client id>/flows. 2. If the flow id has slash...
Get a simplified description of the args_type for a flow. def _GetArgsDescription(self, args_type): """Get a simplified description of the args_type for a flow.""" args = {} if args_type: for type_descriptor in args_type.type_infos: if not type_descriptor.hidden: args[type_descripto...
Get a description of the calling prototype for this flow class. def _GetCallingPrototypeAsString(self, flow_cls): """Get a description of the calling prototype for this flow class.""" output = [] output.append("flow.StartAFF4Flow(client_id=client_id, ") output.append("flow_name=\"%s\", " % flow_cls.__n...
Get a string description of the calling prototype for this flow. def _GetFlowArgsHelpAsString(self, flow_cls): """Get a string description of the calling prototype for this flow.""" output = [ " Call Spec:", " %s" % self._GetCallingPrototypeAsString(flow_cls), "" ] arg_list = sorted...
Renders list of descriptors for all the flows. def Handle(self, args, token=None): """Renders list of descriptors for all the flows.""" if data_store.RelationalDBEnabled(): flow_iterator = iteritems(registry.FlowRegistry.FLOW_REGISTRY) else: flow_iterator = iteritems(registry.AFF4FlowRegistry....
Allow given user access to a given subject. def AuthorizeUser(self, user, subject): """Allow given user access to a given subject.""" user_set = self.authorized_users.setdefault(subject, set()) user_set.add(user)
Allow given group access to a given subject. def AuthorizeGroup(self, group, subject): """Allow given group access to a given subject.""" # Add the subject to the dict if is isn't present, so it will get checked in # CheckPermissions self.authorized_users.setdefault(subject, set()) self.group_acce...
Checks if a given user has access to a given subject. def CheckPermissions(self, username, subject): """Checks if a given user has access to a given subject.""" if subject in self.authorized_users: return ((username in self.authorized_users[subject]) or self.group_access_manager.MemberOfAu...
Guess windows filenames from a commandline string. def _GetFilePaths(self, path, pathtype, kb): """Guess windows filenames from a commandline string.""" environ_vars = artifact_utils.GetWindowsEnvironmentVariablesMap(kb) path_guesses = path_detection_windows.DetectExecutablePaths([path], ...
Convert persistence collector output to downloadable rdfvalues. def Parse(self, persistence, knowledge_base, download_pathtype): """Convert persistence collector output to downloadable rdfvalues.""" pathspecs = [] if isinstance(persistence, rdf_client.WindowsServiceInformation): if persistence.HasFi...
Hacks to make the filesystem look normal. def FileHacks(self): """Hacks to make the filesystem look normal.""" if sys.platform == "win32": import win32api # pylint: disable=g-import-not-at-top # Make the filesystem look like the topmost level are the drive letters. if self.path == "/": ...
Read from the file. def Read(self, length=None): """Read from the file.""" if self.progress_callback: self.progress_callback() available_to_read = max(0, (self.size or 0) - self.offset) if length is None: to_read = available_to_read else: to_read = min(length, available_to_read)...
Returns stat information of a specific path. Args: path: A unicode string containing the path. ext_attrs: Whether the call should also collect extended attributes. Returns: a StatResponse proto Raises: IOError when call to os.stat() fails def _Stat(self, path, ext_attrs=False): ...
List all files in the dir. def ListFiles(self, ext_attrs=False): """List all files in the dir.""" if not self.IsDirectory(): raise IOError("%s is not a directory." % self.path) for path in self.files: try: filepath = utils.JoinPath(self.path, path) response = self._Stat(filepat...
Call os.statvfs for a given list of rdf_paths. OS X and Linux only. Note that a statvfs call for a network filesystem (e.g. NFS) that is unavailable, e.g. due to no network, will result in the call blocking. Args: path: a Unicode string containing the path or None. If path is None the v...
Walk back from the path to find the mount point. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: path string of the mount point def GetMountPoint(self, path=None): """Walk back from the path to find the mount point. ...
Writes a hunt object to the database. def WriteHuntObject(self, hunt_obj, cursor=None): """Writes a hunt object to the database.""" query = """ INSERT INTO hunts (hunt_id, creator, description, duration_micros, hunt_state, client_rate, client_limit, ...
Updates the hunt object by applying the update function. def UpdateHuntObject(self, hunt_id, duration=None, client_rate=None, client_limit=None, hunt_state=None, hunt_state_comment=...
Deletes a given hunt object. def DeleteHuntObject(self, hunt_id, cursor=None): """Deletes a given hunt object.""" query = "DELETE FROM hunts WHERE hunt_id = %s" hunt_id_int = db_utils.HuntIDToInt(hunt_id) rows_deleted = cursor.execute(query, [hunt_id_int]) if rows_deleted == 0: raise db.Unkn...
Generates a flow object from a database row. def _HuntObjectFromRow(self, row): """Generates a flow object from a database row.""" ( create_time, last_update_time, creator, duration_micros, client_rate, client_limit, hunt_state, hunt_state_comment...
Reads a hunt object from the database. def ReadHuntObject(self, hunt_id, cursor=None): """Reads a hunt object from the database.""" query = ("SELECT {columns} " "FROM hunts WHERE hunt_id = %s".format( columns=_HUNT_COLUMNS_SELECT)) nr_results = cursor.execute(query, [db_utils...
Reads multiple hunt objects from the database. def ReadHuntObjects(self, offset, count, with_creator=None, created_after=None, with_description_match=None, cursor=None): """Reads mult...
Builds OutputPluginState object from a DB row. def _HuntOutputPluginStateFromRow(self, row): """Builds OutputPluginState object from a DB row.""" plugin_name, plugin_args_bytes, plugin_state_bytes = row plugin_descriptor = rdf_output_plugin.OutputPluginDescriptor( plugin_name=plugin_name) if p...
Reads all hunt output plugins states of a given hunt. def ReadHuntOutputPluginsStates(self, hunt_id, cursor=None): """Reads all hunt output plugins states of a given hunt.""" columns = ", ".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS) query = ("SELECT {columns} FROM hunt_output_plugins_states " ...
Writes hunt output plugin states for a given hunt. def WriteHuntOutputPluginsStates(self, hunt_id, states, cursor=None): """Writes hunt output plugin states for a given hunt.""" columns = ", ".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS) placeholders = mysql_utils.Placeholders( 2 + len(_HUNT_OUTPUT_P...
Updates hunt output plugin state for a given output plugin. def UpdateHuntOutputPluginState(self, hunt_id, state_index, update_fn, cursor=None): """Updates hunt output plugin stat...
Reads hunt log entries of a given hunt using given query options. def ReadHuntLogEntries(self, hunt_id, offset, count, with_substring=None, cursor=None): """Reads hunt log entries of a given...
Returns number of hunt log entries of a given hunt. def CountHuntLogEntries(self, hunt_id, cursor=None): """Returns number of hunt log entries of a given hunt.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = ("SELECT COUNT(*) FROM flow_log_entries " "FORCE INDEX(flow_log_entries_by_hun...
Reads hunt results of a given hunt using given query options. def ReadHuntResults(self, hunt_id, offset, count, with_tag=None, with_type=None, with_substring=None, w...
Counts hunt results of a given hunt using given query options. def CountHuntResults(self, hunt_id, with_tag=None, with_type=None, cursor=None): """Counts hunt results of a given hunt using given query options.""" hunt_i...
Counts number of hunts results per type. def CountHuntResultsByType(self, hunt_id, cursor=None): """Counts number of hunts results per type.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = ("SELECT type, COUNT(*) FROM flow_results " "WHERE hunt_id = %s GROUP BY type") cursor.execu...
Builds an SQL condition matching db.HuntFlowsCondition. def _HuntFlowCondition(self, condition): """Builds an SQL condition matching db.HuntFlowsCondition.""" if condition == db.HuntFlowsCondition.UNSET: return "", [] elif condition == db.HuntFlowsCondition.FAILED_FLOWS_ONLY: return ("AND flow_...
Reads hunt flows matching given conditins. def ReadHuntFlows(self, hunt_id, offset, count, filter_condition=db.HuntFlowsCondition.UNSET, cursor=None): """Reads hunt flows matching given conditins.""" hunt_id_int...
Counts hunt flows matching given conditions. def CountHuntFlows(self, hunt_id, filter_condition=db.HuntFlowsCondition.UNSET, cursor=None): """Counts hunt flows matching given conditions.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = (...
Reads hunt counters. def ReadHuntCounters(self, hunt_id, cursor=None): """Reads hunt counters.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = ("SELECT flow_state, COUNT(*) " "FROM flows " "FORCE INDEX(flows_by_hunt) " "WHERE parent_hunt_id = %s AND parent_flo...
Builds an SQL query part to fetch counts corresponding to given bins. def _BinsToQuery(self, bins, column_name): """Builds an SQL query part to fetch counts corresponding to given bins.""" result = [] # With the current StatsHistogram implementation the last bin simply # takes all the values that are g...
Read/calculate hunt client resources stats. def ReadHuntClientResourcesStats(self, hunt_id, cursor=None): """Read/calculate hunt client resources stats.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = """ SELECT COUNT(*), SUM(user_cpu_time_used_micros), SUM((user_cpu_t...
Reads hunt flows states and timestamps. def ReadHuntFlowsStatesAndTimestamps(self, hunt_id, cursor=None): """Reads hunt flows states and timestamps.""" query = """ SELECT flow_state, UNIX_TIMESTAMP(timestamp), UNIX_TIMESTAMP(last_update) FROM flows FORCE INDEX(flows_by_hunt) WH...
Reads hunt output plugin log entries. def ReadHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, offset, count, with_type=Non...
Counts hunt output plugin log entries. def CountHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, with_type=None, cursor=None): """Counts hunt output plu...
Will return True if hunt's task was assigned to this client before. def _CheckIfHuntTaskWasAssigned(self, client_id, hunt_id): """Will return True if hunt's task was assigned to this client before.""" if data_store.RelationalDBEnabled(): flow_id = hunt_id if hunt.IsLegacyHunt(hunt_id): # St...
Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started. def _RunAction(self, rule, client_id): """Run all the actions specified in the rule. ...
Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks. def AssignTasksToClient(self, client_id): """Examines our rules and starts up flows based on the client. Args: client_id...
Fetches metadata for the given binary from the datastore. Args: binary_type: ApiGrrBinary.Type of the binary. relative_path: Relative path of the binary, relative to the canonical URN roots for signed binaries (see _GetSignedBlobsRoots()). Returns: An ApiGrrBinary RDFProtoStruct containing metad...
Build the data structure representing the config. def Handle(self, unused_args, token=None): """Build the data structure representing the config.""" sections = {} for descriptor in config.CONFIG.type_infos: if descriptor.section in sections: continue section_data = {} for parame...
Renders specified config option. def Handle(self, args, token=None): """Renders specified config option.""" if not args.name: raise ValueError("Name not specified.") return ApiConfigOption().InitFromConfigOption(args.name)
A helper to create a proxy method in a class. def Proxy(f): """A helper to create a proxy method in a class.""" def Wrapped(self, *args): return getattr(self, f)(*args) return Wrapped
Synchronization decorator. def Synchronized(f): """Synchronization decorator.""" @functools.wraps(f) def NewFunction(self, *args, **kw): with self.lock: return f(self, *args, **kw) return NewFunction
Returns a unicode object. This function will always return a unicode object. It should be used to guarantee that something is always a unicode object. Args: string: The string to convert. Returns: a unicode object. def SmartUnicode(string): """Returns a unicode object. This function will always...
Returns a `bytes` object where each byte has been xored with key. def Xor(bytestr, key): """Returns a `bytes` object where each byte has been xored with key.""" # TODO(hanuszczak): Remove this import when string migration is done. # pytype: disable=import-error from builtins import bytes # pylint: disable=red...
Takes an int and returns the number formatted as a hex string. def FormatAsHexString(num, width=None, prefix="0x"): """Takes an int and returns the number formatted as a hex string.""" # Strip "0x". hex_str = hex(num)[2:] # Strip "L" for long values. hex_str = hex_str.replace("L", "") if width: hex_str...
A sane implementation of os.path.normpath. The standard implementation treats leading / and // as different leading to incorrect normal forms. NOTE: Its ok to use a relative path here (without leading /) but any /../ will still be removed anchoring the path at the top level (e.g. foo/../../../../bar => bar)...
A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and directory traversal is not allowed. ...
Create a 20 char passphrase with easily typeable chars. def GeneratePassphrase(length=20): """Create a 20 char passphrase with easily typeable chars.""" valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" valid_chars += "0123456789 ,-_&$#" return "".join(random.choice(valid_chars) for i in ran...
A utility function to read a passphrase from stdin. def PassphraseCallback(verify=False, prompt1="Enter passphrase:", prompt2="Verify passphrase:"): """A utility function to read a passphrase from stdin.""" while 1: try: p1 = getpass.getpass(prompt1) if...
Resolves a hostname to an IP address. def ResolveHostnameToIP(host, port): """Resolves a hostname to an IP address.""" ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0, socket.IPPROTO_TCP) # getaddrinfo returns tuples (family, socktype, proto, canonname, sockaddr). ...
Expires old cache entries. def Expire(self): """Expires old cache entries.""" while len(self._age) > self._limit: node = self._age.PopLeft() self._hash.pop(node.key, None) self.KillObject(node.data)
Add the object to the cache. def Put(self, key, obj): """Add the object to the cache.""" # Remove the old entry if it is there. node = self._hash.pop(key, None) if node: self._age.Unlink(node) # Make a new node and insert it. node = Node(key=key, data=obj) self._hash[key] = node ...
Expire a specific object from cache. def ExpireObject(self, key): """Expire a specific object from cache.""" node = self._hash.pop(key, None) if node: self._age.Unlink(node) self.KillObject(node.data) return node.data
Expire all the objects with the key matching the regex. def ExpireRegEx(self, regex): """Expire all the objects with the key matching the regex.""" reg = re.compile(regex) for key in list(self._hash): if reg.match(key): self.ExpireObject(key)
Expire all the objects with the key having a given prefix. def ExpirePrefix(self, prefix): """Expire all the objects with the key having a given prefix.""" for key in list(self._hash): if key.startswith(prefix): self.ExpireObject(key)
Remove the object from the cache completely. def Pop(self, key): """Remove the object from the cache completely.""" node = self._hash.get(key) if node: del self._hash[key] self._age.Unlink(node) return node.data
Fetch the object from cache. Objects may be flushed from cache at any time. Callers must always handle the possibility of KeyError raised here. Args: key: The key used to access the object. Returns: Cached object. Raises: KeyError: If the object is not present in the cache. de...