INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Determine whether or not we need to redistribute the ready state
def needs_distribute_ready(self): '''Determine whether or not we need to redistribute the ready state''' # Try to pre-empty starvation by comparing current RDY against # the last value sent. alive = [c for c in self.connections() if c.alive()] if any(c.ready <= (c.last_ready_sent...
Read some number of messages
def read(self): '''Read some number of messages''' found = Client.read(self) # Redistribute our ready state if necessary if self.needs_distribute_ready(): self.distribute_ready() # Finally, return all the results we've read return found
Profile the block
def profiler(): '''Profile the block''' import cProfile import pstats pr = cProfile.Profile() pr.enable() yield pr.disable() ps = pstats.Stats(pr).sort_stats('tottime') ps.print_stats()
Generator for count messages of the provided size
def messages(count, size): '''Generator for count messages of the provided size''' import string # Make sure we have at least 'size' letters letters = islice(cycle(chain(string.lowercase, string.uppercase)), size) return islice(cycle(''.join(l) for l in permutations(letters, size)), count)
Collect data into fixed - length chunks or blocks
def grouper(iterable, n): '''Collect data into fixed-length chunks or blocks''' args = [iter(iterable)] * n for group in izip_longest(fillvalue=None, *args): group = [g for g in group if g != None] yield group
Basic benchmark
def basic(topic='topic', channel='channel', count=1e6, size=10, gevent=False, max_in_flight=2500, profile=False): '''Basic benchmark''' if gevent: from gevent import monkey monkey.patch_all() # Check the types of the arguments count = int(count) size = int(size) max_in_fligh...
Read a stream of floats and give summary statistics
def stats(): '''Read a stream of floats and give summary statistics''' import re import sys import math values = [] for line in sys.stdin: values.extend(map(float, re.findall(r'\d+\.?\d+', line))) mean = sum(values) / len(values) variance = sum((val - mean) ** 2 for val in value...
Whether or not enough time has passed since the last failure
def ready(self): '''Whether or not enough time has passed since the last failure''' if self._last_failed: delta = time.time() - self._last_failed return delta >= self.backoff() return True
Print the status of the daemon.
def execute_status(args, root_dir=None): """Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorc...
Print the current log file.
def execute_log(args, root_dir): """Print the current log file. Args: args['keys'] (int): If given, we only look at the specified processes. root_dir (string): The path to the root directory the daemon is running in. """ # Print the logs of all specified processes if args.get('keys...
Print stderr and stdout of the current running process.
def execute_show(args, root_dir): """Print stderr and stdout of the current running process. Args: args['watch'] (bool): If True, we open a curses session and tail the output live in the console. root_dir (string): The path to the root directory the daemon is runni...
Fetches a song track by given ID.
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a song track by given ID. :param track_id: the track ID. :type track_id: str :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`. ''...
Show a specific indicator by id
def show(self, user, feed, id): """ Show a specific indicator by id :param user: feed username :param feed: feed name :param id: indicator endpoint id [INT] :return: dict Example: ret = Indicator.show('csirtgadgets','port-scanners', '1234') "...
Submit action on the Indicator object
def create(self): """ Submit action on the Indicator object :return: Indicator Object """ uri = '/users/{0}/feeds/{1}/indicators'\ .format(self.user, self.feed) data = { "indicator": json.loads(str(self.indicator)), "comment": self.co...
Submit action against the IndicatorBulk endpoint
def create_bulk(self, indicators, user, feed): from .constants import API_VERSION if API_VERSION == '1': print("create_bulk currently un-avail with APIv1") raise SystemExit """ Submit action against the IndicatorBulk endpoint :param indicators: list of I...
An alias for bind_key ( event_type ROOT_WINDOW key_string cb ).: param event_type: Either KeyPress or KeyRelease.: type event_type: str: param key_string: A string of the form Mod1 - Control - a. Namely a list of zero or more modifiers separated by - followed by a single non - modifier key.: type key_string: str: param...
def bind_global_key(conn, event_type, key_string, cb): """ An alias for ``bind_key(event_type, ROOT_WINDOW, key_string, cb)``. :param event_type: Either 'KeyPress' or 'KeyRelease'. :type event_type: str :param key_string: A string of the form 'Mod1-Control-a'. Namely, a list o...
Binds a function cb to a particular key press key_string on a window wid. Whether it s a key release or key press binding is determined by event_type. bind_key will automatically hook into the event module s dispatcher so that if you re using event. main () for your main loop everything will be taken care of for you.: ...
def bind_key(conn, event_type, wid, key_string, cb): """ Binds a function ``cb`` to a particular key press ``key_string`` on a window ``wid``. Whether it's a key release or key press binding is determined by ``event_type``. ``bind_key`` will automatically hook into the ``event`` module's dispatcher,...
A utility function to turn strings like Mod1 + Mod4 + a into a pair corresponding to its modifiers and keycode.
def parse_keystring(conn, key_string): """ A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param key_string: String starting with zero or more modifiers followed by exactly one key press. Avail...
Finds the keycode associated with a string representation of a keysym.
def lookup_string(conn, kstr): """ Finds the keycode associated with a string representation of a keysym. :param kstr: English representation of a keysym. :return: Keycode, if one exists. :rtype: int """ if kstr in keysyms: return get_keycode(conn, keysyms[kstr]) elif len(kstr) ...
Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment.
def get_keyboard_mapping(conn): """ Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode(conn) return conn.core.GetKeyboardMapping(mn, mx - mn + 1)
Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment.
def get_keyboard_mapping_unchecked(conn): """ Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode() return conn.core.GetKeyboardMappingUnchecked...
Get the keysym associated with a particular keycode in the current X environment. Although we get a list of keysyms from X in get_keyboard_mapping this list is really a table with keysys_per_keycode columns and mx - mn rows ( where mx is the maximum keycode and mn is the minimum keycode ).
def get_keysym(conn, keycode, col=0, kbmap=None): """ Get the keysym associated with a particular keycode in the current X environment. Although we get a list of keysyms from X in 'get_keyboard_mapping', this list is really a table with 'keysys_per_keycode' columns and ``mx - mn`` rows (where ``mx``...
Given a keysym find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this including all columns.
def get_keycode(conn, keysym): """ Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int...
Fetches and creates the keycode - > modifier mask mapping. Typically you shouldn t have to use this --- xpybutil will keep this up to date if it changes.
def get_keys_to_mods(conn): """ Fetches and creates the keycode -> modifier mask mapping. Typically, you shouldn't have to use this---xpybutil will keep this up to date if it changes. This function may be useful in that it should closely replicate the output of the ``xmodmap`` command. For exam...
Takes a state ( typically found in key press or button press events ) and returns a string list representation of the modifiers that were pressed when generating the event.
def get_modifiers(state): """ Takes a ``state`` (typically found in key press or button press events) and returns a string list representation of the modifiers that were pressed when generating the event. :param state: Typically from ``some_event.state``. :return: List of modifier string repres...
Grabs a key for a particular window and a modifiers/ key value. If the grab was successful return True. Otherwise return False. If your client is grabbing keys it is useful to notify the user if a key wasn t grabbed. Keyboard shortcuts not responding is disorienting!
def grab_key(conn, wid, modifiers, key): """ Grabs a key for a particular window and a modifiers/key value. If the grab was successful, return True. Otherwise, return False. If your client is grabbing keys, it is useful to notify the user if a key wasn't grabbed. Keyboard shortcuts not responding is...
Ungrabs a key that was grabbed by grab_key. Similarly it will return True on success and False on failure.
def ungrab_key(conn, wid, modifiers, key): """ Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return True on success and False on failure. When ungrabbing a key, the parameters to this function should be *precisely* the same as the parameters to ``grab_key``. :param wid: A ...
Whenever the keyboard mapping is changed this function needs to be called to update xpybutil s internal representing of the current keysym table. Indeed xpybutil will do this for you automatically.
def update_keyboard_mapping(conn, e): """ Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the curren...
A function that intercepts all key press/ release events and runs their corresponding callback functions. Nothing much to see here except that we must mask out the trivial modifiers from the state in order to find the right callback. Callbacks are called in the order that they have been added. ( FIFO. ): param e: A Key...
def run_keybind_callbacks(e): """ A function that intercepts all key press/release events, and runs their corresponding callback functions. Nothing much to see here, except that we must mask out the trivial modifiers from the state in order to find the right callback. Callbacks are called in the...
Takes a dictionary of changes ( mapping old keycode to new keycode ) and regrabs any keys that have been changed with the updated keycode.
def __regrab(changes): """ Takes a dictionary of changes (mapping old keycode to new keycode) and regrabs any keys that have been changed with the updated keycode. :param changes: Mapping of changes from old keycode to new keycode. :type changes: dict :rtype: void """ for wid, mods, kc ...
Return a list of Storage objects from the API.
def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite """ res = self.get_request('/storage/' + storage_type) return Storage._create_storage_objs(res['sto...
Return a Storage object from the API.
def get_storage(self, storage): """ Return a Storage object from the API. """ res = self.get_request('/storage/' + str(storage)) return Storage(cloud_manager=self, **res['storage'])
Create a Storage object. Returns an object based on the API s response.
def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, ...
Modify a Storage object. Returns an object based on the API s response.
def modify_storage(self, storage, size, title, backup_rule={}): """ Modify a Storage object. Returns an object based on the API's response. """ res = self._modify_storage(str(storage), size, title, backup_rule) return Storage(cloud_manager=self, **res['storage'])
Attach a Storage object to a Server. Return a list of the server s storages.
def attach_storage(self, server, storage, storage_type, address): """ Attach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {}} if storage: body['storage_device']['storage'] = str(storage) if storage_type: ...
Detach a Storage object to a Server. Return a list of the server s storages.
def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) ret...
Reset after repopulating from API.
def _reset(self, **kwargs): """ Reset after repopulating from API. """ # there are some inconsistenciens in the API regarding these # note: this could be written in fancier ways, but this way is simpler if 'uuid' in kwargs: self.uuid = kwargs['uuid'] ...
Save ( modify ) the storage to the API. Note: only size and title are updateable fields.
def save(self): """ Save (modify) the storage to the API. Note: only size and title are updateable fields. """ res = self.cloud_manager._modify_storage(self, self.size, self.title) self._reset(**res['storage'])
Return a dict that can be serialised to JSON and sent to UpCloud s API.
def to_dict(self): """ Return a dict that can be serialised to JSON and sent to UpCloud's API. Uses the convenience attribute `os` for determining `action` and `storage` fields. """ body = { 'tier': self.tier, 'title': self.title, 'siz...
Fetches an album by given ID.
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches an album by given ID. :param album_id: the album ID. :type album_id: str :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1....
Prints name author size and age
def lookup(self): """ Prints name, author, size and age """ print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author, self.size, self.age)
Open url and return amount of pages
def _get_max_page(self, url): """ Open url and return amount of pages """ html = requests.get(url).text pq = PyQuery(html) try: tds = int(pq("h2").text().split()[-1]) if tds % 25: return tds / 25 + 1 return tds / 25 ...
Build and return url. Also update max_page.
def build(self, update=True): """ Build and return url. Also update max_page. """ ret = self.base + self.query page = "".join(("/", str(self.page), "/")) if self.category: category = " category:" + self.category else: category = "" ...
Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path
def build(self, update=True): """ Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path """ query_str = "?page={}".format(self.page) if s...
Parse url and yield namedtuple Torrent for every torrent on page
def _items(self): """ Parse url and yield namedtuple Torrent for every torrent on page """ torrents = map(self._get_torrent, self._get_rows()) for t in torrents: yield t
Parse row into namedtuple
def _get_torrent(self, row): """ Parse row into namedtuple """ td = row("td") name = td("a.cellMainLink").text() name = name.replace(" . ", ".").replace(" .", ".") author = td("a.plain").text() verified_author = True if td(".lightgrey>.ka-verify") else Fal...
Return all rows on page
def _get_rows(self): """ Return all rows on page """ html = requests.get(self.url.build()).text if re.search('did not match any documents', html): return [] pq = PyQuery(html) rows = pq("table.data").find("tr") return map(rows.eq, range(rows.si...
Yield torrents in range from page_from to page_to
def pages(self, page_from, page_to): """ Yield torrents in range from page_from to page_to """ if not all([page_from < self.url.max_page, page_from > 0, page_to <= self.url.max_page, page_to > page_from]): raise IndexError("Invalid page numbers") ...
Yield torrents in range from current page to last page
def all(self): """ Yield torrents in range from current page to last page """ return self.pages(self.url.page, self.url.max_page)
Set field and order set by arguments
def order(self, field, order=None): """ Set field and order set by arguments """ if not order: order = ORDER.DESC self.url.order = (field, order) self.url.set_page(1) return self
Change category of current search and return self
def category(self, category): """ Change category of current search and return self """ self.url.category = category self.url.set_page(1) return self
Remove this FirewallRule from the API.
def destroy(self): """ Remove this FirewallRule from the API. This instance must be associated with a server for this method to work, which is done by instantiating via server.get_firewall_rules(). """ if not hasattr(self, 'server') or not self.server: raise ...
Fetches new release categories by given ID.
def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches new release categories by given ID. :param category_id: the station ID. :type category_id: str :param terr: the current territory. :return: API response. :rtype: list ...
Fetcher top tracks belong to an artist by given ID.
def fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN): ''' Fetcher top tracks belong to an artist by given ID. :param artist_id: the artist ID. :type artist_id: str :param terr: the current territory. :return: API response. :rtype: dict ...
List all tags as Tag objects.
def get_tags(self): """List all tags as Tag objects.""" res = self.get_request('/tag') return [Tag(cloud_manager=self, **tag) for tag in res['tags']['tag']]
Return the tag as Tag object.
def get_tag(self, name): """Return the tag as Tag object.""" res = self.get_request('/tag/' + name) return Tag(cloud_manager=self, **res['tag'])
Create a new Tag. Only name is mandatory.
def create_tag(self, name, description=None, servers=[]): """ Create a new Tag. Only name is mandatory. Returns the created Tag object. """ servers = [str(server) for server in servers] body = {'tag': Tag(name, description, servers).to_dict()} res = self.request(...
PUT/ tag/ name. Returns a dict that can be used to create a Tag object.
def _modify_tag(self, name, description, servers, new_name): """ PUT /tag/name. Returns a dict that can be used to create a Tag object. Private method used by the Tag class and TagManager.modify_tag. """ body = {'tag': Tag(new_name, description, servers).to_dict()} res =...
PUT/ tag/ name. Returns a new Tag object based on the API response.
def modify_tag(self, name, description=None, servers=None, new_name=None): """ PUT /tag/name. Returns a new Tag object based on the API response. """ res = self._modify_tag(name, description, servers, new_name) return Tag(cloud_manager=self, **res['tag'])
Remove tags from a server.
def remove_tags(self, server, tags): """ Remove tags from a server. - server: Server object or UUID string - tags: list of Tag objects or strings """ uuid = str(server) tags = [str(tag) for tag in tags] url = '/server/{0}/untag/{1}'.format(uuid, ','.join...
Helper for assigning object attributes from API responses.
def assignIfExists(opts, default=None, **kwargs): """ Helper for assigning object attributes from API responses. """ for opt in opts: if(opt in kwargs): return kwargs[opt] return default
Try a given operation ( API call ) n times.
def try_it_n_times(operation, expected_error_codes, custom_error='operation failed', n=10): """ Try a given operation (API call) n times. Raises if the API call fails with an error_code that is not expected. Raises if the API call has not succeeded within n attempts. Waits 3 seconds betwee each att...
Extract a pseudorandom key suitable for use with hkdf_expand from the input_key_material and a salt using HMAC with the provided hash ( default SHA - 512 ).
def hkdf_extract(salt, input_key_material, hash=hashlib.sha512): ''' Extract a pseudorandom key suitable for use with hkdf_expand from the input_key_material and a salt using HMAC with the provided hash (default SHA-512). salt should be a random, application-specific byte string. If salt is None or the empty str...
Expand pseudo_random_key and info into a key of length bytes using HKDF s expand function based on HMAC with the provided hash ( default SHA - 512 ). See the HKDF draft RFC and paper for usage notes.
def hkdf_expand(pseudo_random_key, info=b"", length=32, hash=hashlib.sha512): ''' Expand `pseudo_random_key` and `info` into a key of length `bytes` using HKDF's expand function based on HMAC with the provided hash (default SHA-512). See the HKDF draft RFC and paper for usage notes. ''' hash_len = hash().digest_s...
Generate output key material based on an info value
def expand(self, info=b"", length=32): ''' Generate output key material based on an `info` value Arguments: - info - context to generate the OKM - length - length in bytes of the key to generate See the HKDF draft RFC for guidance. ''' return hkdf_expand(self._prk, info, length, self._hash)
Helper function for creating Server. login_user blocks.
def login_user_block(username, ssh_keys, create_password=True): """ Helper function for creating Server.login_user blocks. (see: https://www.upcloud.com/api/8-servers/#create-server) """ block = { 'create_password': 'yes' if create_password is True else 'no', 'ssh_keys': { ...
Reset the server object with new values given as params.
def _reset(self, server, **kwargs): """ Reset the server object with new values given as params. - server: a dict representing the server. e.g the API response. - kwargs: any meta fields such as cloud_manager and populated. Note: storage_devices and ip_addresses may be given in...
Sync changes from the API to the local object.
def populate(self): """ Sync changes from the API to the local object. Note: syncs ip_addresses and storage_devices too (/server/uuid endpoint) """ server, IPAddresses, storages = self.cloud_manager.get_server_data(self.uuid) self._reset( server, ...
Sync local changes in server s attributes to the API.
def save(self): """ Sync local changes in server's attributes to the API. Note: DOES NOT sync IPAddresses and storage_devices, use add_ip, add_storage, remove_ip, remove_storage instead. """ # dict comprehension that also works with 2.6 # http://stackoverflow.com...
Shutdown/ stop the server. By default issue a soft shutdown with a timeout of 30s.
def shutdown(self, hard=False, timeout=30): """ Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s. After the a timeout a hard shutdown is performed if the server has not stopped. Note: API responds immediately (unlike in start), with state: started. ...
Start the server. Note: slow and blocking request.
def start(self, timeout=120): """ Start the server. Note: slow and blocking request. The API waits for confirmation from UpCloud's IaaS backend before responding. """ path = '/server/{0}/start'.format(self.uuid) self.cloud_manager.post_request(path, timeout=timeout) ...
Restart the server. By default issue a soft restart with a timeout of 30s and a hard restart after the timeout.
def restart(self, hard=False, timeout=30, force=True): """ Restart the server. By default, issue a soft restart with a timeout of 30s and a hard restart after the timeout. After the a timeout a hard restart is performed if the server has not stopped. Note: API responds immediat...
Allocate a new ( random ) IP - address to the Server.
def add_ip(self, family='IPv4'): """ Allocate a new (random) IP-address to the Server. """ IP = self.cloud_manager.attach_ip(self.uuid, family) self.ip_addresses.append(IP) return IP
Release the specified IP - address from the server.
def remove_ip(self, IPAddress): """ Release the specified IP-address from the server. """ self.cloud_manager.release_ip(IPAddress.address) self.ip_addresses.remove(IPAddress)
Attach the given storage to the Server.
def add_storage(self, storage=None, type='disk', address=None): """ Attach the given storage to the Server. Default address is next available. """ self.cloud_manager.attach_storage(server=self.uuid, storage=storage.uuid, ...
Remove Storage from a Server.
def remove_storage(self, storage): """ Remove Storage from a Server. The Storage must be a reference to an object in Server.storage_devices or the method will throw and Exception. A Storage from get_storage(uuid) will not work as it is missing the 'address' property. ""...
Add tags to a server. Accepts tags as strings or Tag objects.
def add_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.assign_tags(self.uuid, tags): tags = self.tags + [str(tag) for tag in tags] object.__setattr__(self, 'tags', tags)
Add tags to a server. Accepts tags as strings or Tag objects.
def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tags): new_tags = [tag for tag in self.tags if tag not in tags] object.__setattr__(self, 'tags', new_tags)
Helper function for automatically adding several FirewallRules in series.
def configure_firewall(self, FirewallRules): """ Helper function for automatically adding several FirewallRules in series. """ firewall_rule_bodies = [ FirewallRule.to_dict() for FirewallRule in FirewallRules ] return self.cloud_manager.configure_f...
Prepare a JSON serializable dict from a Server instance with nested.
def prepare_post_body(self): """ Prepare a JSON serializable dict from a Server instance with nested. Storage instances. """ body = dict() # mandatory body['server'] = { 'hostname': self.hostname, 'zone': self.zone, 'title': se...
Prepare a JSON serializable dict for read - only purposes.
def to_dict(self): """ Prepare a JSON serializable dict for read-only purposes. Includes storages and IP-addresses. Use prepare_post_body for POST and .save() for PUT. """ fields = dict(vars(self).items()) if self.populated: fields['ip_addresses'] = ...
Return the server s IP address.
def get_ip(self, access='public', addr_family=None, strict=None): """ Return the server's IP address. Params: - addr_family: IPv4, IPv6 or None. None prefers IPv4 but will return IPv6 if IPv4 addr was not available. - access: 'public' or 'private' ...
Alias for get_ip ( public )
def get_public_ip(self, addr_family=None, *args, **kwargs): """Alias for get_ip('public')""" return self.get_ip('public', addr_family, *args, **kwargs)
Alias for get_ip ( private )
def get_private_ip(self, addr_family=None, *args, **kwargs): """Alias for get_ip('private')""" return self.get_ip('private', addr_family, *args, **kwargs)
Blocking wait until target_state reached. update_interval is in seconds.
def _wait_for_state_change(self, target_states, update_interval=10): """ Blocking wait until target_state reached. update_interval is in seconds. Warning: state change must begin before calling this method. """ while self.state not in target_states: if self.state == ...
Start a server and waits ( blocking wait ) until it is fully started.
def ensure_started(self): """ Start a server and waits (blocking wait) until it is fully started. """ # server is either starting or stopping (or error) if self.state in ['maintenance', 'error']: self._wait_for_state_change(['stopped', 'started']) if self.sta...
Destroy a server and its storages. Stops the server before destroying.
def stop_and_destroy(self, sync=True): """ Destroy a server and its storages. Stops the server before destroying. Syncs the server state from the API, use sync=False to disable. """ def _self_destruct(): """destroy the server and all storages attached to it.""" ...
Revert the state to the version stored on disc.
def revert(self): """Revert the state to the version stored on disc.""" if self.filepath: if path.isfile(self.filepath): serialised_file = open(self.filepath, "r") try: self.state = json.load(serialised_file) except ValueErr...
Synchronise and update the stored state to the in - memory state.
def sync(self): """Synchronise and update the stored state to the in-memory state.""" if self.filepath: serialised_file = open(self.filepath, "w") json.dump(self.state, serialised_file) serialised_file.close() else: print("Filepath to the persisten...
Reset after repopulating from API ( or when initializing ).
def _reset(self, **kwargs): """ Reset after repopulating from API (or when initializing). """ # set object attributes from params for key in kwargs: setattr(self, key, kwargs[key]) # set defaults (if need be) where the default is not None for attr in ...
Return a dict that can be serialised to JSON and sent to UpCloud s API.
def to_dict(self): """ Return a dict that can be serialised to JSON and sent to UpCloud's API. """ return dict( (attr, getattr(self, attr)) for attr in self.ATTRIBUTES if hasattr(self, attr) )
Also try to create the bucket.
def _require_bucket(self, bucket_name): """ Also try to create the bucket. """ if not self.exists(bucket_name) and not self.claim_bucket(bucket_name): raise OFSException("Invalid bucket: %s" % bucket_name) return self._get_bucket(bucket_name)
Will fail if the bucket or label don t exist
def del_stream(self, bucket, label): """ Will fail if the bucket or label don't exist """ bucket = self._require_bucket(bucket) key = self._require_key(bucket, label) key.delete()
Authenticate a HTTP request by filling in Authorization field header.
def authenticate_request(self, method, bucket='', key='', headers=None): '''Authenticate a HTTP request by filling in Authorization field header. :param method: HTTP method (e.g. GET, PUT, POST) :param bucket: name of the bucket. :param key: name of key within bucket. :param hea...
Return a list of resource IDs to check for broken links.
def get_resources_to_check(client_site_url, apikey): """Return a list of resource IDs to check for broken links. Calls the client site's API to get a list of resource IDs. :raises CouldNotGetResourceIDsError: if getting the resource IDs fails for any reason """ url = client_site_url + u"d...
Return the URL for the given resource ID.
def get_url_for_id(client_site_url, apikey, resource_id): """Return the URL for the given resource ID. Contacts the client site's API to get the URL for the ID and returns it. :raises CouldNotGetURLError: if getting the URL fails for any reason """ # TODO: Handle invalid responses from the client...
Check whether the given URL is dead or alive.
def check_url(url): """Check whether the given URL is dead or alive. Returns a dict with four keys: "url": The URL that was checked (string) "alive": Whether the URL was working, True or False "status": The HTTP status code of the response from the URL, e.g. 200, 401, 500 (...
Post the given link check result to the client site.
def upsert_result(client_site_url, apikey, resource_id, result): """Post the given link check result to the client site.""" # TODO: Handle exceptions and unexpected results. url = client_site_url + u"deadoralive/upsert" params = result.copy() params["resource_id"] = resource_id requests.post(ur...
Get links from the client site check them and post the results back.
def get_check_and_report(client_site_url, apikey, get_resource_ids_to_check, get_url_for_id, check_url, upsert_result): """Get links from the client site, check them, and post the results back. Get resource IDs from the client site, get the URL for each resource ID from the client ...
Returns buffered bytes without advancing the position.
def peek(self, n=1): """Returns buffered bytes without advancing the position.""" if n > len(self._readbuffer) - self._offset: chunk = self.read(n) self._offset -= len(chunk) # Return up to 512 bytes to reduce allocation overhead for tight loops. return self._rea...