text
stringlengths
81
112k
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....
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] ...
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 FirewallRu...
Prepare a JSON serializable dict from a Server instance with nested. Storage instances. def prepare_post_body(self): """ Prepare a JSON serializable dict from a Server instance with nested. Storage instances. """ body = dict() # mandatory body['server']...
Prepare a JSON serializable dict for read-only purposes. Includes storages and IP-addresses. Use prepare_post_body for POST and .save() for PUT. def to_dict(self): """ Prepare a JSON serializable dict for read-only purposes. Includes storages and IP-addresses. Use prep...
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' def get_ip(self, access='public', addr_family=None, strict=None): """ Return ...
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. Warning: state change must begin before calling this method. def _wait_for_state_change(self, target_states, update_interval=10): """ Blocking wait until target_state reached. update_interval is in seconds. Warni...
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']: sel...
Destroy a server and its storages. Stops the server before destroying. Syncs the server state from the API, use sync=False to disable. 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,...
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...
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.c...
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 ...
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(...
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. :param method: HTTP method (e.g. GET, PUT, POST) :param bucket: name of the bucket. :param key: name of key within bucket. :param headers: dictionary of additional HTTP headers. :return: boto.connection.HTTPR...
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 def get_resources_to_check(client_site_url, apikey): """Return a list of resource IDs to check ...
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 def get_url_for_id(client_site_url, apikey, resource_id): """Return the URL for the given resource ID. Contacts the ...
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 (int) "reason": The ...
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() pa...
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 site, check each URL, and post the results back to the client site. This function can be called repeatedly to keep on getting more links from ...
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 alloc...
Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached.. def read(self, n=-1): """Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached.. """ ...
Read in the table of contents for the ZIP file. def _RealGetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp endrec = _EndRecData(fp) if not endrec: raise BadZipfile("File is not a zip file") if self.debug > 1: print(endr...
Return file-like object for 'name'. def open(self, name, mode="r", pwd=None): """Return file-like object for 'name'.""" if mode not in ("r", "U", "rU"): raise RuntimeError('open() requires mode "r", "U", or "rU"') if not self.fp: raise RuntimeError( "Atte...
Remove a member from the archive. def remove(self, member): """Remove a member from the archive.""" # Make sure we have an info object if isinstance(member, ZipInfo): # 'member' is already an info object zinfo = member else: # Get info object for name...
Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). def _get_codename(self, pathname, basename): """Return (filenam...
Imports the class for the given class name. def import_class(class_path): ''' Imports the class for the given class name. ''' module_name, class_name = class_path.rsplit(".", 1) module = import_module(module_name) claz = getattr(module, class_name) return claz
Creating an ExecutorPool is a costly operation. Executor needs to be instantiated only once. def _executor(self): ''' Creating an ExecutorPool is a costly operation. Executor needs to be instantiated only once. ''' if self.EXECUTE_PARALLEL is False: executor_path = "batc...
this borrows too much from the internals of ofs maybe expose different parts of the api? def make_label(self, path): """ this borrows too much from the internals of ofs maybe expose different parts of the api? """ from datetime import datetime from StringIO impor...
stub. this really needs to be a call to the remote restful interface to get the appropriate host and headers to use for this upload def get_proxy_config(self, headers, path): """ stub. this really needs to be a call to the remote restful interface to get the appropriate host and...
This is the main function that uploads. We assume the bucket and key (== path) exists. What we do here is simple. Calculate the headers we will need, (e.g. md5, content-type, etc). Then we ask the self.get_proxy_config method to fill in the authentication information and tell us which re...
Fetches all mood stations. :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`. def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN): ''' Fetches all mood stations. :par...
Fetches a mood station by given ID. :param station_id: the station ID :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id`. def fetch_mood_station(self, station_id, terr=KKBOXTerritory....
Fetches next page based on previously fetched data. Will get the next page url from data['paging']['next']. :param data: previously fetched API response. :type data: dict :return: API response. :rtype: dict def fetch_next_page(self, data): ''' Fetches ne...
Fetches data from specific url. :return: The response. :rtype: dict def fetch_data(self, url): ''' Fetches data from specific url. :return: The response. :rtype: dict ''' return self.http._post_data(url, None, self.http._headers_with_access_token())
Fetches a shared playlist by given ID. :param playlist_id: the playlist ID. :type playlist_id: str :param terr: the current territory. :return: API response. :rtype: dictcd See `https://docs-en.kkbox.codes/v1.1/reference#sharedplaylists-playlist_id`. def fetch_shared_p...
Return a FirewallRule object based on server uuid and rule position. def get_firewall_rule(self, server_uuid, firewall_rule_position, server_instance=None): """ Return a FirewallRule object based on server uuid and rule position. """ url = '/server/{0}/firewall_rule/{1}'.format(server_u...
Return all FirewallRule objects based on a server instance or uuid. def get_firewall_rules(self, server): """ Return all FirewallRule objects based on a server instance or uuid. """ server_uuid, server_instance = uuid_and_instance(server) url = '/server/{0}/firewall_rule'.forma...
Create a new firewall rule for a given server uuid. The rule can begiven as a dict or with FirewallRule.prepare_post_body(). Returns a FirewallRule object. def create_firewall_rule(self, server, firewall_rule_body): """ Create a new firewall rule for a given server uuid. The r...
Delete a firewall rule based on a server uuid and rule position. def delete_firewall_rule(self, server_uuid, firewall_rule_position): """ Delete a firewall rule based on a server uuid and rule position. """ url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position...
Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies. def configure_firewall(self, server, firewall_rule_bodies): """ Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies. """ server_uuid, server_instance = uuid_and_instanc...
POSTs a raw SMTP message to the Sinkhole API :param data: raw content to be submitted [STRING] :return: { list of predictions } def post(self, data): """ POSTs a raw SMTP message to the Sinkhole API :param data: raw content to be submitted [STRING] :return: { list of p...
Returns the lowered method. Capitalize headers, prepend HTTP_ and change - to _. def pre_process_method_headers(method, headers): ''' Returns the lowered method. Capitalize headers, prepend HTTP_ and change - to _. ''' method = method.lower() # Standard WSGI supported headers ...
Define headers that needs to be included from the current request. def headers_to_include_from_request(curr_request): ''' Define headers that needs to be included from the current request. ''' return { h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE}
Based on the given request parameters, constructs and returns the WSGI request object. def get_wsgi_request_object(curr_request, method, url, headers, body): ''' Based on the given request parameters, constructs and returns the WSGI request object. ''' x_headers = headers_to_include_from_request(cu...
Override the default values for the wsgi environment variables. def _base_environ(self, **request): ''' Override the default values for the wsgi environment variables. ''' # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, #...
Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __error_middleware. def request(self, method, endpoint, body=None, timeout=-1): """ Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __error_middl...
Perform a POST request to a given endpoint in UpCloud's API. def post_request(self, endpoint, body=None, timeout=-1): """ Perform a POST request to a given endpoint in UpCloud's API. """ return self.request('POST', endpoint, body, timeout)
Middleware that raises an exception when HTTP statuscode is an error code. def __error_middleware(self, res, res_json): """ Middleware that raises an exception when HTTP statuscode is an error code. """ if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]): err_dic...
Create a new file to swift object storage. def put_stream(self, bucket, label, stream_object, params={}): ''' Create a new file to swift object storage. ''' self.claim_bucket(bucket) self.connection.put_object(bucket, label, stream_object, headers=self._conve...
PURPOSE Compute Friedman and Popescu's H statistic, in order to look for an interaction in the passed gradient-boosting model among the variables represented by the elements of the passed array or frame and specified by the passed indices or columns. See Jerome H. Friedman and Bogdan E. Popescu, 2008,...
PURPOSE Compute Friedman and Popescu's two-variable H statistic, in order to look for an interaction in the passed gradient- boosting model between each pair of variables represented by the elements of the passed array or frame and specified by the passed indices or columns. See Jerome H. Friedman and...
Performs a search against the predict endpoint :param q: query to be searched for [STRING] :return: { score: [0|1] } def get(self, q, limit=None): """ Performs a search against the predict endpoint :param q: query to be searched for [STRING] :return: { score: [0|1] } ...
Whether a given bucket:label object already exists. def exists(self, bucket, label): '''Whether a given bucket:label object already exists.''' fn = self._zf(bucket, label) try: self.z.getinfo(fn) return True except KeyError: return False
List labels for the given bucket. Due to zipfiles inherent arbitrary ordering, this is an expensive operation, as it walks the entire archive searching for individual 'buckets' :param bucket: bucket to list labels for. :return: iterator for the labels in the specified bucket. def list_...
List all buckets managed by this OFS instance. Like list_labels, this also walks the entire archive, yielding the bucketnames. A local set is retained so that duplicates aren't returned so this will temporarily pull the entire list into memory even though this is a generator and will slow as mor...
Get a bitstream for the given bucket:label combination. :param bucket: the bucket to use. :return: bitstream as a file-like object def get_stream(self, bucket, label, as_stream=True): '''Get a bitstream for the given bucket:label combination. :param bucket: the bucket to use. ...
Get a URL that should point at the bucket:labelled resource. Aimed to aid web apps by allowing them to redirect to an open resource, rather than proxy the bitstream. :param bucket: the bucket to use. :param label: the label of the resource to get :return: a string URI - eg 'zip:file:///home/......
Put a bitstream (stream_object) for the specified bucket:label identifier. :param bucket: as standard :param label: as standard :param stream_object: file-like object to read from or bytestring. :param params: update metadata with these params (see `update_metadata`) def put_stream(sel...
Delete a bitstream. This needs more testing - file deletion in a zipfile is problematic. Alternate method is to create second zipfile without the files in question, which is not a nice method for large zip archives. def del_stream(self, bucket, label): '''Delete a bitstream. This needs more tes...
Get the metadata for this bucket:label identifier. def get_metadata(self, bucket, label): '''Get the metadata for this bucket:label identifier. ''' if self.mode !="w": try: jsn = self._get_bucket_md(bucket) except OFSFileNotFound: # No MD ...
Update the metadata with the provided dictionary of params. :param parmams: dictionary of key values (json serializable). def update_metadata(self, bucket, label, params): '''Update the metadata with the provided dictionary of params. :param parmams: dictionary of key values (json serializabl...
Delete the metadata corresponding to the specified keys. def del_metadata_keys(self, bucket, label, keys): '''Delete the metadata corresponding to the specified keys. ''' if self.mode !="r": try: payload = self._get_bucket_md(bucket) except OFSFileNotFoun...
Given a WSGI request, makes a call to a corresponding view function and returns the response. def get_response(wsgi_request): ''' Given a WSGI request, makes a call to a corresponding view function and returns the response. ''' service_start_time = datetime.now() # Get the view ...
For the given batch request, extract the individual requests and create WSGIRequest object for each. def get_wsgi_requests(request): ''' For the given batch request, extract the individual requests and create WSGIRequest object for each. ''' valid_http_methods = ["get", "post", "put...
A view function to handle the overall processing of batch requests. def handle_batch_requests(request, *args, **kwargs): ''' A view function to handle the overall processing of batch requests. ''' batch_start_time = datetime.now() try: # Get the Individual WSGI requests. wsgi_re...
Searches within KKBOX's database. :param keyword: the keyword. :type keyword: str :param types: the search types. :return: list :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#search...
IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. def save(self): """ IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. """ body = {'ip_address': {'ptr_record': self.ptr_record}} data = self.cloud_mana...
Create IPAddress objects from API response data. Also associates CloudManager with the objects. def _create_ip_address_objs(ip_addresses, cloud_manager): """ Create IPAddress objects from API response data. Also associates CloudManager with the objects. """ # ip-addresse...
Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects. def _reset(self, **kwargs): """ Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects. """ super(T...
HTTP GET function :param uri: REST endpoint :param params: optional HTTP params to pass to the endpoint :return: list of results (usually a list of dicts) Example: ret = cli.get('/search', params={ 'q': 'example.org' }) def _get(self, uri, params={}): """ H...
HTTP POST function :param uri: REST endpoint to POST to :param data: list of dicts to be passed to the endpoint :return: list of dicts, usually will be a list of objects or id's Example: ret = cli.post('/indicators', { 'indicator': 'example.com' }) def _post(self, uri, dat...
Return a list of (populated or unpopulated) Server instances. - populate = False (default) => 1 API request, returns unpopulated Server instances. - populate = True => Does 1 + n API requests (n = # of servers), returns populated Server instances. New in 0.3.0: the...
Return a (populated) Server instance. def get_server(self, UUID): """ Return a (populated) Server instance. """ server, IPAddresses, storages = self.get_server_data(UUID) return Server( server, ip_addresses=IPAddresses, storage_devices=storag...
Return a (populated) Server instance by its IP. Uses GET '/ip_address/x.x.x.x' to retrieve machine UUID using IP-address. def get_server_by_ip(self, ip_address): """ Return a (populated) Server instance by its IP. Uses GET '/ip_address/x.x.x.x' to retrieve machine UUID using IP-addres...
Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer to the REST API documentation for correct format. ...
modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods. def modify_server(self, UUID, **kwargs): """ modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses an...
Return '/server/uuid' data in Python dict. Creates object representations of any IP-address and Storage. def get_server_data(self, UUID): """ Return '/server/uuid' data in Python dict. Creates object representations of any IP-address and Storage. """ data = self.get_re...
Pull a feed :param f: feed name (eg: csirtgadgetes/correlated) :param limit: return value limit (default 25) :return: Feed dict def feed(f, limit=25): """ Pull a feed :param f: feed name (eg: csirtgadgetes/correlated) :param limit: return value limit (default 25) :return: Feed dict ...
Create an indicator in a feed :param f: feed name (eg: wes/test) :param i: indicator dict (eg: {'indicator': 'example.com', 'tags': ['ssh'], 'description': 'this is a test'}) :return: dict of indicator def indicator_create(f, i): """ Create an indicator in a feed :param f: feed name (eg: we...
Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name. def convert_from_file(file): """ Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like ob...
Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. def _internal_convert(inp): """ Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. """ ''' Converts file in IDX format provided by file-like input into numpy.nd...
Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name. def convert_to_file(file, ndarr): """ Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file n...
Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. def convert_to_string(ndarr): """ Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. """ with contextlib.closing(BytesIO()) as bytesio: _internal_write(bytesio, ndarr...
Writes numpy.ndarray arr to a file-like object (with write() method) in IDX format. def _internal_write(out_stream, arr): """ Writes numpy.ndarray arr to a file-like object (with write() method) in IDX format. """ if arr.size == 0: raise FormatError('Cannot encode empty array.') t...
There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums, playlists and so on. Howeve...
Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates. def get_OS_UUID(cls, os): """ Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates. """ if os in cls.templates: r...
Calls the resp_generator for all the requests in parallel in an asynchronous way. def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in parallel in an asynchronous way. ''' result_futures = [self.executor_pool.submit(resp_...
Calls the resp_generator for all the requests in sequential order. def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in sequential order. ''' return [resp_generator(request) for request in requests]
Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally def setup_logging(args): """ Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally """ loglevel = logging.WARNING if args.verbose: logl...
Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') def get_ip(self, address): """ Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') """ res = self.get_request('/ip_...
Get all IPAddress objects from the API. def get_ips(self): """ Get all IPAddress objects from the API. """ res = self.get_request('/ip_address') IPs = IPAddress._create_ip_address_objs(res['ip_addresses'], cloud_manager=self) return IPs
Attach a new (random) IPAddress to the given server (object or UUID). def attach_ip(self, server, family='IPv4'): """ Attach a new (random) IPAddress to the given server (object or UUID). """ body = { 'ip_address': { 'server': str(server), 'fa...
Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). def modify_ip(self, ip_addr, ptr_record): """ Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). """ ...
Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description :return: dict def new(self, user, name, description=None): """ Creates a new Feed object :param user: feed username :param name: feed name ...
Removes a feed :param user: feed username :param name: feed name :return: true/false def delete(self, user, name): """ Removes a feed :param user: feed username :param name: feed name :return: true/false """ uri = self.client.remote + '...
Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets') def index(self, user): """ Returns a list of Feeds from the API :param user: feed username :return: list Example: ...