def __init__(self, server_key, enable_thermal=False): self._server_key = server_key self._graph_ref = GraphReference() self._sensor_file_locks = SensorFileLocks() self._sensor_dir = os.path.join(get_temp_workplace_dir(), str(server_key), "sensor_dir") self._sensors = {} with self._graph_ref.get_session() as session: sensors = GraphReference.get_asset_sensors(session, server_key) for sensor_info in sensors: sensor = Sensor( self._sensor_dir, server_key, sensor_info, self._sensor_file_locks, graph_ref=self._graph_ref, ) self._sensors[sensor.name] = sensor if enable_thermal: self._load_thermal = True if not os.path.isdir(self._sensor_dir): os.mkdir(self._sensor_dir) for s_name in self._sensors: self._sensors[s_name].set_to_defaults()
def plays(cls): """Get plays (user-defined scripts) available for execution Returns: tuple: list of bash files as well as python scripts """ graph_ref = GraphReference() with graph_ref.get_session() as session: play_path = GraphReference.get_play_path(session) if not play_path: return ([], []) play_files = [ f for f in os.listdir(play_path) if os.path.isfile(os.path.join(play_path, f)) ] is_py_file = lambda f: os.path.splitext(f)[1] == ".py" return ( [os.path.splitext(f)[0] for f in play_files if not is_py_file(f)], [os.path.splitext(f)[0] for f in play_files if is_py_file(f)], )
def asset_exists(cls, key): """Check if asset with the key exists""" graph_ref = GraphReference() with graph_ref.get_session() as session: asset_info = GraphReference.get_asset_and_components(session, key) return asset_info is not None
def execute_play(cls, play_name): """Execute a specific play Args: play_name(str): playbook name """ graph_ref = GraphReference() with graph_ref.get_session() as session: play_path = GraphReference.get_play_path(session) if not play_path: return file_filter = ( lambda f: os.path.isfile(os.path.join(play_path, f)) and os.path.splitext(f)[0] == play_name ) play_file = [f for f in os.listdir(play_path) if file_filter(f)][0] subprocess.Popen( os.path.join(play_path, play_file), stderr=subprocess.DEVNULL, close_fds=True, )
def _handle_status_request(self, details): """Get overall system status/details including hardware assets; environment state & play details """ assets = IStateManager.get_system_status(flatten=False) graph_ref = GraphReference() with graph_ref.get_session() as session: stage_layout = GraphReference.get_stage_layout(session) # send system topology and assets' power-interconnections self._write_data( details["client"], ServerToClientRequests.sys_layout, {"assets": assets, "stageLayout": stage_layout}, ) self._write_data( details["client"], ServerToClientRequests.ambient_upd, {"ambient": ISystemEnvironment.get_ambient(), "rising": False}, ) self._write_data( details["client"], ServerToClientRequests.play_list, {"plays": list(itertools.chain(*IStateManager.plays()))}, ) self._write_data( details["client"], ServerToClientRequests.mains_upd, {"mains": ISystemEnvironment.mains_status()}, )
def _handle_layout_request(self, details): """Save assets' positions/coordinates""" graph_ref = GraphReference() with graph_ref.get_session() as session: GraphReference.save_layout(session, details["payload"]["assets"], stage=details["payload"]["stage"])
def initialize(force_snmp_init=False): """ Initialize redis state using topology defined in the graph db """ graph_ref = GraphReference() redis_store = redis.StrictRedis(host="localhost", port=6379) with graph_ref.get_session() as session: results = session.run( """ MATCH (asset:Asset) OPTIONAL MATCH (asset:Asset)-[:HAS_OID]->(oid) return asset, collect(oid) as oids """ ) for record in results: asset_type = record["asset"].get("type") asset_key = str(record["asset"].get("key")) init_from_snmprec = ( not redis_store.exists("{}-{}:state".format(asset_key, asset_type)) ) or force_snmp_init redis_store.set("{}-{}:state".format(asset_key, asset_type), 1) formatted_key = asset_key.zfill(10) temp_ordering_key = formatted_key + "-temp_oids_ordering" graph_oids = {} for oid in record["oids"]: # loop over oids that are defined in the graph db graph_oids[oid.get("OID")] = { "dtype": oid.get("dataType"), "value": oid.get("defaultValue"), } # Set-up in the SNMPSim format if "SNMPSim" in record["asset"].labels and record["oids"] and init_from_snmprec: # Read a file containing static .snmprec data static_oid_file = record["asset"].get("staticOidFile") static_oid_path = os.path.join( os.environ.get("SIMENGINE_STATIC_DATA"), static_oid_file ) with open(static_oid_path, "r") as sfile_handler: for line in sfile_handler: oid, dtype, value = line.replace("\n", "").split("|") if oid in graph_oids: dtype = graph_oids[oid]["dtype"] value = graph_oids[oid]["value"] key_and_oid = format_as_redis_key(formatted_key, oid) redis_store.lpush(temp_ordering_key, key_and_oid) redis_store.set(key_and_oid, "{}|{}".format(dtype, value)) redis_store.sort( temp_ordering_key, store=formatted_key + "-oids_ordering", alpha=True ) redis_store.delete(temp_ordering_key) redis_store.rpush(asset_key, formatted_key)
def get_ambient_props(cls) -> tuple: """Get runtime ambient properties (ambient behaviour description) Returns: thermal parameters for up/down events, randomizer ambient properties returns None if System Environment hasn't been initialized yet """ graph_ref = GraphReference() with graph_ref.get_session() as session: return GraphReference.get_ambient_props(session)
def get_voltage_props(cls) -> dict: """Get runtime voltage properties (ambient behaviour description) Returns: voltage fluctuation properties such as method being used (normal/gauss) & properties associated with the random method """ graph_ref = GraphReference() with graph_ref.get_session() as session: return GraphReference.get_voltage_props(session)
def set_ambient_props(cls, props): """Update runtime thermal properties of the room temperature Args: props: ambient behaviour specs such as "event" (upon what event: up/down), "degrees" (how much rises/dropw), "rate" (seconds), "pause_at" (should stop at this temperature) """ graph_ref = GraphReference() with graph_ref.get_session() as session: GraphReference.set_ambient_props(session, props)
class HardwareDataSource: graph_ref = GraphReference() @classmethod def get_all_assets(cls): return NotImplementedError() @classmethod def get_affected_assets(cls, asset_key): return NotImplementedError() @classmethod def get_mains_powered_assets(cls): return NotImplementedError()
def get_system_status(cls, flatten=True): """Get states of all system components Args: flatten(bool): If false, the returned assets in the dict will have their child-components nested Returns: dict: Current information on assets including their states, load etc. """ graph_ref = GraphReference() with graph_ref.get_session() as session: # cache assets assets = GraphReference.get_assets_and_connections(session, flatten) return cls._get_assets_states(assets, flatten)
def get_state_manager_by_key(cls, key, supported_assets=None): """Infer asset manager from key""" from enginecore.state.hardware.room import Asset if not supported_assets: supported_assets = Asset.get_supported_assets() graph_ref = GraphReference() with graph_ref.get_session() as session: asset_info = GraphReference.get_asset_and_components(session, key) sm_mro = supported_assets[asset_info["type"]].StateManagerCls.mro() module = ".".join(__name__.split(".")[:-1]) # api module return next(filter(lambda x: x.__module__.startswith(module), sm_mro))(asset_info)
def __init__(self, asset_key, server_dir, socket_port): self._graph_ref = GraphReference() self._server_key = asset_key self._serversocket = None with self._graph_ref.get_session() as session: self._storcli_details = GraphReference.get_storcli_details( session, asset_key) self._storcli_dir = os.path.join(server_dir, "storcli") os.makedirs(self._storcli_dir) dir_util.copy_tree(os.environ.get("SIMENGINE_STORCLI_TEMPL"), self._storcli_dir) self.start_server(asset_key, socket_port)
def set_play_path(cls, path): """Update play folder containing scripts""" graph_ref = GraphReference() with graph_ref.get_session() as session: GraphReference.set_play_path(session, path)
"""Add asset to a system model or update/create connection(s). This module provides high-level control over system model. """ import json import os from enum import Enum import time import sys import libvirt from enginecore.model.graph_reference import GraphReference from enginecore.model.supported_sensors import SUPPORTED_SENSORS import enginecore.tools.query_helpers as qh GRAPH_REF = GraphReference() # attributes shared by all the assets CREATE_SHARED_ATTR = [ "x", "y", "name", "type", "key", "off_delay", "on_delay", "min_voltage", "power_on_ac", ] # Labels used by the app SIMENGINE_NODE_LABELS = []
def init_connection(cls): cls.graph_ref = GraphReference()
def set_voltage_props(cls, props): """Update runtime voltage properties of the mains power voltage""" graph_ref = GraphReference() with graph_ref.get_session() as session: GraphReference.set_voltage_props(session, props)
def get_sensor_definitions(cls, asset_key): """Get sensor definitions """ graph_ref = GraphReference() with graph_ref.get_session() as session: return GraphReference.get_asset_sensors(session, asset_key)
def get_thermal_cpu_details(cls, asset_key): """Query existing cpu->sensor relationship""" graph_ref = GraphReference() with graph_ref.get_session() as session: return GraphReference.get_thermal_cpu_details(session, asset_key)
def __init__(self, key=None): self.count = 0 self._graph_ref = GraphReference() RecordedEntity.num_entities = RecordedEntity.num_entities + 1 self.key = RecordedEntity.num_entities if not key else key
def __init__(self, asset_info): self._graph_ref = GraphReference() self._asset_key = asset_info["key"] self._asset_info = asset_info