def __init__(self, **kwargs): super(VolttronCentralAgent, self).__init__(identity=vip_identity, **kwargs) _log.debug("Registering (vip_address, vip_identity) ({}, {})" .format(self.core.address, self.core.identity)) # a list of peers that have checked in with this agent. self.registry = PlatformRegistry() self.valid_data = False self._vip_channels = {} self.persistence_path = '' self._external_addresses = None
class VolttronCentralAgent(Agent): """Agent for querying WeatherUndergrounds API""" def __init__(self, **kwargs): super(VolttronCentralAgent, self).__init__(identity=vip_identity, **kwargs) _log.debug( "Registering (vip_address, vip_identity) ({}, {})".format( self.core.address, self.core.identity)) # a list of peers that have checked in with this agent. self.registry = PlatformRegistry() self.valid_data = False self._vip_channels = {} self.persistence_path = '' self._external_addresses = None def list_agents(self, uuid): platform = self.registry.get_platform(uuid) results = [] if platform: agent = self._get_rpc_agent(platform['vip_address']) results = agent.vip.rpc.call(platform['vip_identity'], 'list_agents').get(timeout=10) return results @RPC.export def list_platform_details(self): print('list_platform_details', self.registry._vips) return self.registry._vips.keys() @RPC.export def unregister_platform(self, platform_uuid): value = 'Failure' platform = self.registry.get_platform(platform_uuid) if platform: self.registry.unregister(platform['vip_address']) self._store_registry() value = 'Success' return value @RPC.export def register_platform(self, peer_identity, name, peer_address): '''Agents will call this to register with the platform. This method is successful unless an error is raised. ''' value = self._handle_register_platform(peer_address, peer_identity, name) if not value: return 'Platform Unavailable' return value def _store_registry(self): self._store('registry', self.registry.package()) def _handle_register_platform(self, address, identity=None, agentid='platform.agent'): _log.debug( 'Registering platform identity {} at vip address {} with name {}' .format(identity, address, agentid)) agent = self._get_rpc_agent(address) if not identity: identity = 'platform.agent' result = agent.vip.rpc.call(identity, "manage", address=self._external_addresses, identity=self.core.identity) if result.get(timeout=10): node = self.registry.register(address, identity, agentid) if node: self._store_registry() return node return False def _get_rpc_agent(self, address): if address == self.core.address: agent = self elif address not in self._vip_channels: agent = Agent(address=address) gevent.spawn(agent.core.run).join(0) self._vip_channels[address] = agent else: agent = self._vip_channels[address] return agent @Core.receiver('onsetup') def setup(self, sender, **kwargs): if not os.environ.get('VOLTTRON_HOME', None): raise ValueError('VOLTTRON_HOME environment must be set!') db_path = os.path.join(os.environ.get('VOLTTRON_HOME'), 'data/volttron.central') db_dir = os.path.dirname(db_path) try: os.makedirs(db_dir) except OSError as exc: if exc.errno != errno.EEXIST or not os.path.isdir(db_dir): raise self.persistence_path = db_path # Returns None if there has been no registration of any platforms. registered = self._load('registry') if registered: self.registry.unpackage(registered) self.async_caller = AsyncCall() @Core.receiver('onstart') def starting(self, sender, **kwargs): '''This event is triggered when the platform is ready for the agent ''' q = query.Query(self.core) result = q.query('addresses').get(timeout=10) #TODO: Use all addresses for fallback, #114 self._external_addresses = (result and result[0]) or self.core.address # Start server in own thread. th = threading.Thread(target=startWebServer, args=(self, )) th.daemon = True th.start() def __load_persist_data(self): persist_kv = None if os.path.exists(self.persistence_path): try: with open(self.persistence_path, 'rb') as file: persist_kv = jsonapi.loads(file.read()) file.close() except Exception as err: _log.error("Couldn't read persistence data {}".format( err.message)) return persist_kv def _store(self, key, data): persist = self.__load_persist_data() if not persist: persist = {} persist[key] = data with open(self.persistence_path, 'wb') as file: file.write(jsonapi.dumps(persist)) def _load(self, key): persist = self.__load_persist_data() value = None if persist: value = persist.get(key, None) return value @Core.receiver('onfinish') def finish(self, sender, **kwargs): stopWebServer() def _handle_list_platforms(self): return [{ 'uuid': x['uuid'], 'name': x['agentid'] } for x in self.registry.get_platforms()] def route_request(self, id, method, params): '''Route request to either a registered platform or handle here.''' print('inside route_request {}, {}, {}'.format(id, method, params)) if method == 'list_platforms': return self._handle_list_platforms() elif method == 'register_platform': return self._handle_register_platform(**params) elif method == 'unregister_platform': return self.unregister_platform(**params) fields = method.split('.') if len(fields) < 3: return RpcResponse(id=id, code=METHOD_NOT_FOUND) platform_uuid = fields[2] platform = self.registry.get_platform(platform_uuid) if not platform: return RpcResponse( id=id, code=METHOD_NOT_FOUND, message="Unknown platform {}".format(platform_uuid)) platform_method = '.'.join(fields[3:]) # get an agent agent = self._get_rpc_agent(platform['vip_address']) _log.debug("calling identity {} with parameters {} {} {}".format( platform['vip_identity'], id, platform_method, params)) result = agent.vip.rpc.call(platform['vip_identity'], "route_request", id, platform_method, params).get(timeout=10) return result
class VolttronCentralAgent(Agent): """Agent for querying WeatherUndergrounds API""" def __init__(self, **kwargs): super(VolttronCentralAgent, self).__init__(identity=vip_identity, **kwargs) _log.debug("Registering (vip_address, vip_identity) ({}, {})" .format(self.core.address, self.core.identity)) # a list of peers that have checked in with this agent. self.registry = PlatformRegistry() self.valid_data = False self._vip_channels = {} self.persistence_path = '' self._external_addresses = None def list_agents(self, uuid): platform = self.registry.get_platform(uuid) results = [] if platform: agent = self._get_rpc_agent(platform['vip_address']) results = agent.vip.rpc.call(platform['vip_identity'], 'list_agents').get(timeout=10) return results @RPC.export def list_platform_details(self): print('list_platform_details', self.registry._vips) return self.registry._vips.keys() @RPC.export def unregister_platform(self, platform_uuid): value = 'Failure' platform = self.registry.get_platform(platform_uuid) if platform: self.registry.unregister(platform['vip_address']) self._store_registry() value = 'Success' return value @RPC.export def register_platform(self, peer_identity, name, peer_address): '''Agents will call this to register with the platform. This method is successful unless an error is raised. ''' value = self._handle_register_platform(peer_address, peer_identity, name) if not value: return 'Platform Unavailable' return value def _store_registry(self): self._store('registry', self.registry.package()) def _handle_register_platform(self, address, identity=None, agentid='platform.agent'): _log.debug('Registering platform identity {} at vip address {} with name {}' .format(identity, address, agentid)) agent = self._get_rpc_agent(address) if not identity: identity = 'platform.agent' result = agent.vip.rpc.call(identity, "manage", address=self._external_addresses, identity=self.core.identity) if result.get(timeout=10): node = self.registry.register(address, identity, agentid) if node: self._store_registry() return node return False def _get_rpc_agent(self, address): if address == self.core.address: agent = self elif address not in self._vip_channels: agent = Agent(address=address) gevent.spawn(agent.core.run).join(0) self._vip_channels[address] = agent else: agent = self._vip_channels[address] return agent @Core.receiver('onsetup') def setup(self, sender, **kwargs): if not os.environ.get('VOLTTRON_HOME', None): raise ValueError('VOLTTRON_HOME environment must be set!') db_path = os.path.join(os.environ.get('VOLTTRON_HOME'), 'data/volttron.central') db_dir = os.path.dirname(db_path) try: os.makedirs(db_dir) except OSError as exc: if exc.errno != errno.EEXIST or not os.path.isdir(db_dir): raise self.persistence_path = db_path # Returns None if there has been no registration of any platforms. registered = self._load('registry') if registered: self.registry.unpackage(registered) self.async_caller = AsyncCall() @Core.receiver('onstart') def starting(self, sender, **kwargs): '''This event is triggered when the platform is ready for the agent ''' q = query.Query(self.core) result = q.query('addresses').get(timeout=10) #TODO: Use all addresses for fallback, #114 self._external_addresses = (result and result[0]) or self.core.address # Start server in own thread. th = threading.Thread(target=startWebServer, args=(self,)) th.daemon = True th.start() def __load_persist_data(self): persist_kv = None if os.path.exists(self.persistence_path): try: with open(self.persistence_path, 'rb') as file: persist_kv = jsonapi.loads(file.read()) file.close() except Exception as err: _log.error("Couldn't read persistence data {}" .format(err.message)) return persist_kv def _store(self, key, data): persist = self.__load_persist_data() if not persist: persist = {} persist[key] = data with open(self.persistence_path, 'wb') as file: file.write(jsonapi.dumps(persist)) def _load(self, key): persist = self.__load_persist_data() value = None if persist: value = persist.get(key, None) return value @Core.receiver('onfinish') def finish(self, sender, **kwargs): stopWebServer() def _handle_list_platforms(self): return [{'uuid': x['uuid'], 'name': x['agentid']} for x in self.registry.get_platforms()] def route_request(self, id, method, params): '''Route request to either a registered platform or handle here.''' print('inside route_request {}, {}, {}'.format(id, method, params)) if method == 'list_platforms': return self._handle_list_platforms() elif method == 'register_platform': return self._handle_register_platform(**params) elif method == 'unregister_platform': return self.unregister_platform(**params) fields = method.split('.') if len(fields) < 3: return RpcResponse(id=id, code=METHOD_NOT_FOUND) platform_uuid = fields[2] platform = self.registry.get_platform(platform_uuid) if not platform: return RpcResponse(id=id, code=METHOD_NOT_FOUND, message="Unknown platform {}".format(platform_uuid)) platform_method = '.'.join(fields[3:]) # get an agent agent = self._get_rpc_agent(platform['vip_address']) _log.debug("calling identity {} with parameters {} {} {}" .format(platform['vip_identity'], id, platform_method, params)) result = agent.vip.rpc.call(platform['vip_identity'], "route_request", id, platform_method, params).get(timeout=10) return result