text
stringlengths
18
773k
def process_raw(self, raw: str) -> None: """Pre-process raw string. Prepare users to work with APIItems. Create booleans with user levels. """ raw_dict = dict(group.split('=') for group in raw.splitlines()) raw_users = { user: { group: user i...
def start(self): """Start session.""" conn = self.loop.create_connection( lambda: self, self.session.host, self.session.port) task = self.loop.create_task(conn) task.add_done_callback(self.init_done)
def init_done(self, fut): """Server ready. If we get OSError during init the device is not available. """ try: if fut.exception(): fut.result() except OSError as err: _LOGGER.debug('RTSP got exception %s', err) self.stop() ...
def stop(self): """Stop session.""" if self.transport: self.transport.write(self.method.TEARDOWN().encode()) self.transport.close() self.rtp.stop()
def connection_made(self, transport): """Connect to device is successful. Start configuring RTSP session. Schedule time out handle in case device doesn't respond. """ self.transport = transport self.transport.write(self.method.message.encode()) self.time_out_hand...
def data_received(self, data): """Got response on RTSP session. Manage time out handle since response came in a reasonable time. Update session parameters with latest response. If state is playing schedule keep-alive. """ self.time_out_handle.cancel() self.sessio...
def time_out(self): """If we don't get a response within time the RTSP request time out. This usually happens if device isn't available on specified IP. """ _LOGGER.warning('Response timed out %s', self.session.host) self.stop() self.callback(SIGNAL_FAILED)
def message(self): """Return RTSP method based on sequence number from session.""" message = self.message_methods[self.session.method]() _LOGGER.debug(message) return message
def OPTIONS(self, authenticate=True): """Request options device supports.""" message = "OPTIONS " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication if authenticate else '' message += self.user_agent message += self.session_id ...
def DESCRIBE(self): """Request description of what services RTSP server make available.""" message = "DESCRIBE " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += "Accept: application/sdp\r\n...
def SETUP(self): """Set up stream transport.""" message = "SETUP " + self.session.control_url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += self.transport message += '\r\n' return message
def PLAY(self): """RTSP session is ready to send data.""" message = "PLAY " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += self.session_id message += '\r\n' return message
def authentication(self): """Generate authentication string.""" if self.session.digest: authentication = self.session.generate_digest() elif self.session.basic: authentication = self.session.generate_basic() else: return '' return "Authorizatio...
def transport(self): """Generate transport string.""" transport = "Transport: RTP/AVP;unicast;client_port={}-{}\r\n" return transport.format( str(self.session.rtp_port), str(self.session.rtcp_port))
def state(self): """Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages every self.session_timeout. """ if self.method in ['OPTIONS', 'DESCRIBE', 'SETUP', 'PLAY']: state = STATE_STARTING elif self...
def update(self, response): """Update session information from device response. Increment sequence number when starting stream, not when playing. If device requires authentication resend previous message with auth. """ data = response.splitlines() _LOGGER.debug('Received...
def generate_digest(self): """RFC 2617.""" from hashlib import md5 ha1 = self.username + ':' + self.realm + ':' + self.password HA1 = md5(ha1.encode('UTF-8')).hexdigest() ha2 = self.method + ':' + self.url HA2 = md5(ha2.encode('UTF-8')).hexdigest() encrypt_respons...
def generate_basic(self): """RFC 2617.""" from base64 import b64encode if not self.basic_auth: creds = self.username + ':' + self.password self.basic_auth = 'Basic ' self.basic_auth += b64encode(creds.encode('UTF-8')).decode('UTF-8') return self.basic_...
def retry(ExceptionToCheck, tries=10, timeout_secs=1.0, logger=None, callback_by_exception=None): """ Retry calling the decorated function using an exponential backoff. :param callback_by_exception: callback/method invocation on certain exceptions :type callback_by_exception: None or dict """ de...
def stream_url(self): """Build url for stream.""" rtsp_url = RTSP_URL.format( host=self.config.host, video=self.video_query, audio=self.audio_query, event=self.event_query) _LOGGER.debug(rtsp_url) return rtsp_url
def session_callback(self, signal): """Signalling from stream session. Data - new data available for processing. Playing - Connection is healthy. Retry - if there is no connection to device. """ if signal == SIGNAL_DATA: self.event.new_event(self.data) ...
def start(self): """Start stream.""" if not self.stream or self.stream.session.state == STATE_STOPPED: self.stream = RTSPClient( self.config.loop, self.stream_url, self.config.host, self.config.username, self.config.password, self.session_callb...
def stop(self): """Stop stream.""" if self.stream and self.stream.session.state != STATE_STOPPED: self.stream.stop()
def retry(self): """No connection to device, retry connection after 15 seconds.""" self.stream = None self.config.loop.call_later(RETRY_TIMER, self.start) _LOGGER.debug('Reconnecting to %s', self.config.host)
def connect_mysql(): """ return an inspector object """ MySQLConnection.get_characterset_info = MySQLConnection.get_charset db = create_engine(engine_name) db.echo = True db.connect() return db
def check_perm(user_id, permission_code): """ Checks whether a user has permission to perform an action. The permission_code parameter should be a permission contained in tPerm. If the user does not have permission to perfom an action, a permission error is thrown. """ try: ...
def required_perms(*req_perms): """ Decorator applied to functions requiring caller to possess permission Takes args tuple of required perms and raises PermissionsError via check_perm if these are not a subset of user perms """ def dec_wrapper(wfunc): @wraps(wfunc) def w...
def required_role(req_role): """ Decorator applied to functions requiring caller to possess the specified role """ def dec_wrapper(wfunc): @wraps(wfunc) def wrapped(*args, **kwargs): user_id = kwargs.get("user_id") try: res = db.DBSession.query...
def get_time_period(period_name): """ Given a time period name, fetch the hydra-compatible time abbreviation. """ time_abbreviation = time_map.get(period_name.lower()) if time_abbreviation is None: raise Exception("Symbol %s not recognised as a time period"%period_name) ret...
def get_datetime(timestamp): """ Turn a string timestamp into a date time. First tries to use dateutil. Failing that it tries to guess the time format and converts it manually using stfptime. @returns: A timezone unaware timestamp. """ timestamp_is_float = False try: ...
def timestamp_to_ordinal(timestamp): """Convert a timestamp as defined in the soap interface to the time format stored in the database. """ if timestamp is None: return None ts_time = get_datetime(timestamp) # Convert time to Gregorian ordinal (1 = January 1st, year 1) ordinal_ts_t...
def date_to_string(date, seasonal=False): """Convert a date to a standard string used by Hydra. The resulting string looks like this:: '2013-10-03 00:49:17.568-0400' Hydra also accepts seasonal time series (yearly recurring). If the flag ``seasonal`` is set to ``True``, this function will gene...
def guess_timefmt(datestr): """ Try to guess the format a date is written in. The following formats are supported: ================= ============== =============== Format Example Python format ----------------- -------------- --------------- ``YYYY-MM-DD`` 2002-04-21 ...
def reindex_timeseries(ts_string, new_timestamps): """ get data for timesamp :param a JSON string, in pandas-friendly format :param a timestamp or list of timestamps (datetimes) :returns a pandas data frame, reindexed with the supplied timestamos or None if no data is found """ ...
def parse_time_step(time_step, target='s', units_ref=None): """ Read in the time step and convert it to seconds. """ log.info("Parsing time step %s", time_step) # export numerical value from string using regex value = re.findall(r'\d+', time_step)[0] valuelen = len(value) try: ...
def get_time_axis(start_time, end_time, time_step, time_axis=None): """ Create a list of datetimes based on an start time, end time and time step. If such a list is already passed in, then this is not necessary. Often either the start_time, end_time, time_step is passed into an ...
def _get_all_attributes(network): """ Get all the complex mode attributes in the network so that they can be used for mapping to resource scenarios later. """ attrs = network.attributes for n in network.nodes: attrs.extend(n.attributes) for l in network.links: attrs.e...
def add_network(network,**kwargs): """ Takes an entire network complex model and saves it to the DB. This complex model includes links & scenarios (with resource data). Returns the network's complex model. As links connect two nodes using the node_ids, if the nodes are new they will not yet h...
def _get_all_resource_attributes(network_id, template_id=None): """ Get all the attributes for the nodes, links and groups of a network. Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. """ base_qry = db.DBSession.query( ...
def _get_all_templates(network_id, template_id): """ Get all the templates for the nodes, links and groups of a network. Return these templates as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. """ base_qry = db.DBSession.query( ...
def _get_all_group_items(network_id): """ Get all the resource group items in the network, across all scenarios returns a dictionary of dict objects, keyed on scenario_id """ base_qry = db.DBSession.query(ResourceGroupItem) item_qry = base_qry.join(Scenario).filter(Scenario.network_id==...
def _get_all_resourcescenarios(network_id, user_id): """ Get all the resource scenarios in a network, across all scenarios returns a dictionary of dict objects, keyed on scenario_id """ rs_qry = db.DBSession.query( Dataset.type, Dataset.unit_id, ...
def _get_metadata(network_id, user_id): """ Get all the metadata in a network, across all scenarios returns a dictionary of dict objects, keyed on dataset ID """ log.info("Getting Metadata") dataset_qry = db.DBSession.query( Dataset ).outerjoin(DatasetOwner, and_(Data...
def _get_network_owners(network_id): """ Get all the nodes in a network """ owners_i = db.DBSession.query(NetworkOwner).filter( NetworkOwner.network_id==network_id).options(noload('network')).options(joinedload_all('user')).all() owners = [JSONObject(owner_i) for owner_i...
def _get_nodes(network_id, template_id=None): """ Get all the nodes in a network """ extras = {'types':[], 'attributes':[]} node_qry = db.DBSession.query(Node).filter( Node.network_id==network_id, Node.status=='A').options( ...
def _get_links(network_id, template_id=None): """ Get all the links in a network """ extras = {'types':[], 'attributes':[]} link_qry = db.DBSession.query(Link).filter( Link.network_id==network_id, Link.status=='A').o...
def _get_groups(network_id, template_id=None): """ Get all the resource groups in a network """ extras = {'types':[], 'attributes':[]} group_qry = db.DBSession.query(ResourceGroup).filter( ResourceGroup.network_id==network_id, ...
def _get_scenarios(network_id, include_data, user_id, scenario_ids=None): """ Get all the scenarios in a network """ scen_qry = db.DBSession.query(Scenario).filter( Scenario.network_id == network_id).options( noload('network')).filter( ...
def get_network(network_id, summary=False, include_data='N', scenario_ids=None, template_id=None, **kwargs): """ Return a whole network as a dictionary. network_id: ID of the network to retrieve include_data: 'Y' or 'N'. Indicate whether scenario data is to be returned. ...
def get_nodes(network_id, template_id=None, **kwargs): """ Get all the nodes in a network. args: network_id (int): The network in which to search template_id (int): Only return nodes whose type is in this template. """ user_id = kwargs.get('user_id') try: ...
def get_links(network_id, template_id=None, **kwargs): """ Get all the links in a network. args: network_id (int): The network in which to search template_id (int): Only return links whose type is in this template. """ user_id = kwargs.get('user_id') try: ...
def get_groups(network_id, template_id=None, **kwargs): """ Get all the resource groups in a network. args: network_id (int): The network in which to search template_id (int): Only return resource groups whose type is in this template. """ user_id = kwargs.get('user_i...
def get_network_by_name(project_id, network_name,**kwargs): """ Return a whole network as a complex model. """ try: res = db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one() net = get_network(res.id, 'Y', Non...
def network_exists(project_id, network_name,**kwargs): """ Return a whole network as a complex model. """ try: db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one() return 'Y' except NoResultFound: r...
def update_network(network, update_nodes = True, update_links = True, update_groups = True, update_scenarios = True, **kwargs): """ Update an entire network """ log.info("Updating Network %s", network.name) user_id = kwargs.get('user_id') #check_perm('update_network') ...
def set_network_status(network_id,status,**kwargs): """ Activates a network by setting its status attribute to 'A'. """ user_id = kwargs.get('user_id') #check_perm(user_id, 'delete_network') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.che...
def get_network_extents(network_id,**kwargs): """ Given a network, return its maximum extents. This would be the minimum x value of all nodes, the minimum y value of all nodes, the maximum x value of all nodes and maximum y value of all nodes. @returns NetworkExtents object """ rs =...
def add_nodes(network_id, nodes,**kwargs): """ Add nodes to network """ start_time = datetime.datetime.now() names=[] # used to check uniqueness of node name for n_i in nodes: if n_i.name in names: raise HydraError("Duplicate Node Name: %s"%(n_i.name)) nam...
def add_links(network_id, links,**kwargs): ''' add links to network ''' start_time = datetime.datetime.now() user_id = kwargs.get('user_id') names=[] # used to check uniqueness of link name before saving links to database for l_i in links: if l_i.name in names: rai...
def update_node(node, flush=True, **kwargs): """ Update a node. If new attributes are present, they will be added to the node. The non-presence of attributes does not remove them. The flush argument indicates whether dbsession.flush should be called. THis is set to False when update_node is cal...
def update_nodes(nodes,**kwargs): """ Update multiple nodes. If new attributes are present, they will be added to the node. The non-presence of attributes does not remove them. %TODO:merge this with the 'update_nodes' functionality in the 'update_netework' function, so we're not duplicating fun...
def set_node_status(node_id, status, **kwargs): """ Set the status of a node to 'X' """ user_id = kwargs.get('user_id') try: node_i = db.DBSession.query(Node).filter(Node.id == node_id).one() except NoResultFound: raise ResourceNotFoundError("Node %s not found"%(node_id)) ...
def purge_network(network_id, purge_data,**kwargs): """ Remove a network from DB completely Use purge_data to try to delete the data associated with only this network. If no other resources link to this data, it will be deleted. """ user_id = kwargs.get('user_id') try: n...
def _purge_datasets_unique_to_resource(ref_key, ref_id): """ Find the number of times a a resource and dataset combination occurs. If this equals the number of times the dataset appears, then we can say this dataset is unique to this resource, therefore it can be deleted """ count_qr...
def delete_node(node_id, purge_data,**kwargs): """ Remove node from DB completely If there are attributes on the node, use purge_data to try to delete the data. If no other resources link to this data, it will be deleted. """ user_id = kwargs.get('user_id') try: ...
def add_link(network_id, link,**kwargs): """ Add a link to a network """ user_id = kwargs.get('user_id') #check_perm(user_id, 'edit_topology') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.check_write_permission(user_id) except NoR...
def update_link(link,**kwargs): """ Update a link. """ user_id = kwargs.get('user_id') #check_perm(user_id, 'edit_topology') try: link_i = db.DBSession.query(Link).filter(Link.id == link.id).one() link_i.network.check_write_permission(user_id) except NoResultFound: ...
def set_link_status(link_id, status, **kwargs): """ Set the status of a link """ user_id = kwargs.get('user_id') #check_perm(user_id, 'edit_topology') try: link_i = db.DBSession.query(Link).filter(Link.id == link_id).one() except NoResultFound: raise ResourceNotFoundError...
def delete_link(link_id, purge_data,**kwargs): """ Remove link from DB completely If there are attributes on the link, use purge_data to try to delete the data. If no other resources link to this data, it will be deleted. """ user_id = kwargs.get('user_id') try: l...
def add_group(network_id, group,**kwargs): """ Add a resourcegroup to a network """ user_id = kwargs.get('user_id') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.check_write_permission(user_id=user_id) except NoResultFound: rai...
def update_group(group,**kwargs): """ Update a group. If new attributes are present, they will be added to the group. The non-presence of attributes does not remove them. """ user_id = kwargs.get('user_id') try: group_i = db.DBSession.query(ResourceGroup).filter(ResourceG...
def set_group_status(group_id, status, **kwargs): """ Set the status of a group to 'X' """ user_id = kwargs.get('user_id') try: group_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id == group_id).one() except NoResultFound: raise ResourceNotFoundError("ResourceGr...
def delete_group(group_id, purge_data,**kwargs): """ Remove group from DB completely If there are attributes on the group, use purge_data to try to delete the data. If no other resources group to this data, it will be deleted. """ user_id = kwargs.get('user_id') try: ...
def get_scenarios(network_id,**kwargs): """ Get all the scenarios in a given network. """ user_id = kwargs.get('user_id') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.check_read_permission(user_id=user_id) except NoResultFound: ...
def validate_network_topology(network_id,**kwargs): """ Check for the presence of orphan nodes in a network. """ user_id = kwargs.get('user_id') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.check_write_permission(user_id=user_id) exce...
def get_resources_of_type(network_id, type_id, **kwargs): """ Return the Nodes, Links and ResourceGroups which have the type specified. """ nodes_with_type = db.DBSession.query(Node).join(ResourceType).filter(Node.network_id==network_id, ResourceType.type_id==type_id).all() links_with_t...
def clean_up_network(network_id, **kwargs): """ Purge any deleted nodes, links, resourcegroups and scenarios in a given network """ user_id = kwargs.get('user_id') #check_perm(user_id, 'delete_network') try: log.debug("Querying Network %s", network_id) net_i = db.DBSession.qu...
def get_all_resource_attributes_in_network(attr_id, network_id, **kwargs): """ Find every resource attribute in the network matching the supplied attr_id """ user_id = kwargs.get('user_id') try: a = db.DBSession.query(Attr).filter(Attr.id == attr_id).one() except NoResultFound: ...
def get_all_resource_data(scenario_id, include_metadata='N', page_start=None, page_end=None, **kwargs): """ A function which returns the data for all resources in a network. - """ rs_qry = db.DBSession.query( ResourceAttr.attr_id, Attr.name.label('attr_name'), ...
def clone_network(network_id, recipient_user_id=None, new_network_name=None, project_id=None, project_name=None, new_project=True, **kwargs): """ Create an exact clone of the specified network for the specified user. If project_id is specified, put the new network in there. Otherwise create a new ...
def copy_data_from_scenario(resource_attrs, source_scenario_id, target_scenario_id, **kwargs): """ For a given list of resource attribute IDS copy the dataset_ids from the resource scenarios in the source scenario to those in the 'target' scenario. """ #Get all the resource scenarios we wis...
def get_scenario(scenario_id,**kwargs): """ Get the specified scenario """ user_id = kwargs.get('user_id') scen_i = _get_scenario(scenario_id, user_id) scen_j = JSONObject(scen_i) rscen_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.scenario_id==scenario_id).options...
def add_scenario(network_id, scenario,**kwargs): """ Add a scenario to a specified network. """ user_id = int(kwargs.get('user_id')) log.info("Adding scenarios to network") _check_network_ownership(network_id, user_id) existing_scen = db.DBSession.query(Scenario).filter(Scenario.name==...
def update_scenario(scenario,update_data=True,update_groups=True,flush=True,**kwargs): """ Update a single scenario as all resources already exist, there is no need to worry about negative IDS flush = True flushes to the DB at the end of the function. flush = False does not ...
def set_scenario_status(scenario_id, status, **kwargs): """ Set the status of a scenario. """ user_id = kwargs.get('user_id') _check_can_edit_scenario(scenario_id, kwargs['user_id']) scenario_i = _get_scenario(scenario_id, user_id) scenario_i.status = status db.DBSession.flush() ...
def purge_scenario(scenario_id, **kwargs): """ Set the status of a scenario. """ _check_can_edit_scenario(scenario_id, kwargs['user_id']) user_id = kwargs.get('user_id') scenario_i = _get_scenario(scenario_id, user_id) db.DBSession.delete(scenario_i) db.DBSession.flush() retu...
def _get_as_obj(obj_dict, name): """ Turn a dictionary into a named tuple so it can be passed into the constructor of a complex model generator. """ if obj_dict.get('_sa_instance_state'): del obj_dict['_sa_instance_state'] obj = namedtuple(name, tuple(obj_dict.keys())) for k,...
def get_resource_scenario(resource_attr_id, scenario_id, **kwargs): """ Get the resource scenario object for a given resource atttribute and scenario. This is done when you know the attribute, resource and scenario and want to get the value associated with it. """ user_id = kwargs.ge...
def bulk_update_resourcedata(scenario_ids, resource_scenarios,**kwargs): """ Update the data associated with a list of scenarios. """ user_id = kwargs.get('user_id') res = None res = {} net_ids = db.DBSession.query(Scenario.network_id).filter(Scenario.id.in_(scenario_ids)).all() i...
def update_resourcedata(scenario_id, resource_scenarios,**kwargs): """ Update the data associated with a scenario. Data missing from the resource scenario will not be removed from the scenario. Use the remove_resourcedata for this task. If the resource scenario does not exist, it wi...
def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs): """ Remove the data associated with a resource in a scenario. """ _check_can_edit_scenario(scenario_id, kwargs['user_id']) _delete_resourcescenario(scenario_id, resource_attr_id, suppress_error=quiet)
def delete_resourcedata(scenario_id, resource_scenario, quiet = False, **kwargs): """ Remove the data associated with a resource in a scenario. The 'quiet' parameter indicates whether an non-existent RS should throw an error. """ _check_can_edit_scenario(scenario_id, kwargs['user_id...
def _update_resourcescenario(scenario, resource_scenario, dataset=None, new=False, user_id=None, source=None): """ Insert or Update the value of a resource's attribute by first getting the resource, then parsing the input data, then assigning the value. returns a ResourceScenario object. ...
def assign_value(rs, data_type, val, unit_id, name, metadata={}, data_hash=None, user_id=None, source=None): """ Insert or update a piece of data in a scenario. If the dataset is being shared by other resource scenarios, a new dataset is inserted. If the dataset is ONLY bein...
def add_data_to_attribute(scenario_id, resource_attr_id, dataset,**kwargs): """ Add data to a resource scenario outside of a network update """ user_id = kwargs.get('user_id') _check_can_edit_scenario(scenario_id, user_id) scenario_i = _get_scenario(scenario_id, user_id) try: ...
def get_scenario_data(scenario_id,**kwargs): """ Get all the datasets from the group with the specified name @returns a list of dictionaries """ user_id = kwargs.get('user_id') scenario_data = db.DBSession.query(Dataset).filter(Dataset.id==ResourceScenario.dataset_id, ResourceScenario.s...
def get_attribute_data(attr_ids, node_ids, **kwargs): """ For a given attribute or set of attributes, return all the resources and resource scenarios in the network """ node_attrs = db.DBSession.query(ResourceAttr).\ options(joinedload_all('attr')...
def get_resource_data(ref_key, ref_id, scenario_id, type_id=None, expunge_session=True, **kwargs): """ Get all the resource scenarios for a given resource in a given scenario. If type_id is specified, only return the resource scenarios for the attributes within the type. """ ...
def get_attribute_datasets(attr_id, scenario_id, **kwargs): """ Retrieve all the datasets in a scenario for a given attribute. Also return the resource attributes so there is a reference to the node/link """ user_id = kwargs.get('user_id') scenario_i = _get_scenario(scenario_id, user_i...
def get_resourcegroupitems(group_id, scenario_id, **kwargs): """ Get all the items in a group, in a scenario. If group_id is None, return all items across all groups in the scenario. """ rgi_qry = db.DBSession.query(ResourceGroupItem).\ filter(ResourceGroupItem.scenario_id=...