def disconnectAgent(self, name): """ Disconnect agent """ self.info("Disconnect agent Name=%s" % name) if name not in ASI.instance().agentsRegistered: self.trace("disconnect agent, agent %s not found" % name) return self.context.CODE_NOT_FOUND agentProfile = ASI.instance().agentsRegistered[name] ASI.instance().stopClient(client=agentProfile['address']) return self.context.CODE_OK
def getRunning(self, b64=False): """ Returns all registered agent """ self.trace("get running agents") ret = ASI.instance().getAgents() return ret
def resetRunningAgent(self, client): """Reset all running agents used by the client passed as argument""" self.trace('Trying to cleanup active agents') for p in client['agents']: # we can reset only agent in ready state (ready message received) if 'agent-name' in p: agent = ASI.instance().getAgent(aname=p['agent-name']) if agent is not None: self.trace( 'Reset Agent=%s for Script=%s and Adapter=%s' % (p['agent-name'], p['script-id'], p['source-adapter'])) data = { 'event': 'agent-reset', 'script_id': p['script-id'], 'source-adapter': p['source-adapter'], 'uuid': p['uuid'] } ASI.instance().notify(client=agent['address'], data=data)
def onRequest(self, client, tid, request): """Reimplemented from ServerAgent""" self.__mutex__.acquire() try: _body_ = request['body'] if client not in self.testsConnected: self.__mutex__.release() return self.testsConnected[client]['task-id'] = _body_['task-id'] # handle notify and save some statistics on the database if request['cmd'] == Messages.RSQ_NOTIFY: try: if _body_['event'] in [ 'agent-data', 'agent-notify', 'agent-init', 'agent-reset', 'agent-alive', 'agent-ready' ]: if _body_['event'] == 'agent-ready': self.testsConnected[client]['agents'].append({ 'agent-name': _body_['destination-agent'], 'script-id': _body_['script_id'], 'uuid': _body_['uuid'], 'source-adapter': _body_['source-adapter'] }) ASI.instance().notifyAgent(client, tid, data=_body_) except Exception as e: self.error('unable to handle notify for agent: %s' % e) if _body_['event'] == 'testcase-stopped': # reset agents self.resetRunningAgent(client=self.testsConnected[client]) if _body_['task-id'] in self.tests: if not self.tests[_body_['task-id']]: # check connected time of the associated user and test # if connected-at of the user > connected-at of the test # then not necessary to send events userFounded = self.context.getUser( login=_body_['from']) if userFounded is not None: if client not in self.testsConnected: self.error('unknown test from %s' % str(client)) else: if userFounded[ 'connected-at'] < self.testsConnected[ client]['connected-at']: if _body_['channel-id']: ESI.instance().notify( body=('event', _body_), toAddress=_body_['channel-id']) else: ESI.instance().notify(body=('event', _body_)) else: self.error('test unknown: %s' % _body_['task-id']) if _body_['event'] == 'script-stopped': # reset agents self.resetRunningAgent(client=self.testsConnected[client]) if _body_['task-id'] in self.tests: self.tests.pop(_body_['task-id']) else: self.error('task-id unknown: %s' % _body_['task-id']) if client in self.testsConnected: self.testsConnected.pop(client) else: self.error('test unknown: %s' % str(client)) # handle requests elif request['cmd'] == Messages.RSQ_CMD: self.trace("cmd received: %s" % _body_['cmd']) if 'cmd' in _body_: # handle interact command if _body_['cmd'] == Messages.CMD_INTERACT: self.trace('interact called') if _body_['task-id'] in self.tests: if not self.tests[_body_['task-id']]: # check connected time of the associated user and test # if connected-at of the user > connected-at of # the test then not necessary to send events userFounded = self.context.getUser( login=_body_['from']) if userFounded is not None: if client not in self.testsConnected: self.error('unknown test from %s' % str(client)) else: if userFounded[ 'connected-at'] < self.testsConnected[ client]['connected-at']: self.__fifoThread.putItem( lambda: self.onInteract( client, tid, bodyReq=_body_, timeout=_body_['timeout'])) else: self.error('test unknown: %s' % _body_['task-id']) else: self.error('cmd unknown %s' % _body_['cmd']) rsp = {'cmd': _body_['cmd'], 'res': Messages.CMD_ERROR} NetLayerLib.ServerAgent.failed(self, client, tid, body=rsp) else: self.error('cmd is missing') # handle other request else: self.trace('%s received ' % request['cmd']) except Exception as e: self.error("unable to handle incoming request: %s" % e) self.__mutex__.release()
def cleanup(self): """ Cleanup the server """ self.info('Cleanup...') self.trace("Cleanup agent manager") try: AgentsManager.finalize() except Exception: pass self.trace("Cleanup context") try: Context.finalize() except Exception: pass self.trace("Cleanup projects manager") try: ProjectsManager.finalize() except Exception: pass self.trace("Cleanup users manager") try: UsersManager.finalize() except Exception: pass self.trace("Cleanup task manager") try: TaskManager.finalize() except Exception: pass self.trace("Cleanup test public manager") try: RepoPublic.finalize() except Exception: pass self.trace("Cleanup test repo manager") try: RepoTests.finalize() except Exception: pass self.trace("Cleanup test archives manager") try: RepoArchives.finalize() except Exception: pass self.trace("Cleanup helper manager") try: HelperManager.finalize() except Exception: pass self.trace("Cleanup adapters manager") try: RepoAdapters.finalize() except Exception: pass self.trace("Cleanup adapters data storage") try: StorageDataAdapters.finalize() except Exception: pass self.trace("Cleanup WSU") try: RestServerInterface.instance().stop() RestServerInterface.finalize() except Exception: pass self.trace("Cleanup ESI") try: EventServerInterface.instance().stopSA() EventServerInterface.finalize() except Exception: pass self.trace("Cleanup TSI") try: TestServerInterface.instance().stopSA() TestServerInterface.finalize() except Exception: pass self.trace("Cleanup ASI") try: AgentServerInterface.instance().stopSA() AgentServerInterface.finalize() except Exception: pass self.trace("Cleanup db manager") try: DbManager.finalize() except Exception: pass self.trace("Cleanup settings") try: Settings.finalize() except Exception: pass self.trace("Cleanup logger, cli") try: CliFunctions.finalize() Logger.finalize() except Exception: pass
def initialize(self): """ Starts all modules Exit if the service is alreayd running or if the config file is missing """ starttime = time.time() if self.isrunning(): sys.stdout.write(" (server is already running)") sys.exit(1) # run the server as daemon only for linux if platform.system() == "Linux": self.daemonize() try: # Initialize self.info("Starting up server...") self.trace("** System encoding (in): %s" % sys.stdin.encoding) self.trace("** System encoding (out): %s" % sys.stdout.encoding) self.info("Settings, Logger and CLI ready") DbManager.initialize() DbManager.instance().isUp() self.info("Database manager ready") # Initialize the core Context.initialize() self.info("Context ready") ProjectsManager.initialize(context=Context.instance()) self.info("Projects Manager ready") UsersManager.initialize(context=Context.instance()) self.info("Users Manager ready") TaskManager.initialize(context=Context) self.info("Task Manager ready") # Initialize all repositories RepoTests.initialize(context=Context.instance()) self.info("Repo manager for tests ready") RepoArchives.initialize(context=Context.instance()) self.info("Repo manager for archives ready") RepoAdapters.initialize(context=Context.instance()) StorageDataAdapters.initialize(context=Context.instance()) self.info("Adapters Manager and Storage Data ready") RepoPublic.initialize() self.info("Repo manager for public area is ready") HelperManager.initialize() self.info("Helper manager ready") AgentsManager.initialize(context=Context.instance()) self.info("Agents Manager ready") # Initialize all interfaces self.info("Starting ESI on %s:%s" % (Settings.get('Bind', 'ip-esi'), Settings.getInt('Bind', 'port-esi'))) EventServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-esi'), Settings.getInt( 'Bind', 'port-esi') ), sslSupport=Settings.getInt( 'Client_Channel', 'channel-ssl'), wsSupport=Settings.getInt( 'Client_Channel', 'channel-websocket-support'), context=Context.instance() ) self.info("Starting TSI on %s:%s" % (Settings.get('Bind', 'ip-tsi'), Settings.getInt('Bind', 'port-tsi'))) TestServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-tsi'), Settings.getInt( 'Bind', 'port-tsi') ), context=Context.instance() ) self.info("Starting RSU on %s:%s" % (Settings.get('Bind', 'ip-rsi'), Settings.getInt('Bind', 'port-rsi'))) RestServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-rsi'), Settings.getInt( 'Bind', 'port-rsi') ) ) self.info("Starting ASI on %s:%s" % (Settings.get('Bind', 'ip-asi'), Settings.getInt('Bind', 'port-asi'))) AgentServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-asi'), Settings.getInt( 'Bind', 'port-asi') ), sslSupport=Settings.getInt( 'Agent_Channel', 'channel-ssl'), wsSupport=Settings.getInt( 'Agent_Channel', 'channel-websocket-support'), tsi=TestServerInterface.instance(), context=Context.instance() ) # Start on modules RestServerInterface.instance().start() self.info("RSI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-rsi'), Settings.get('Bind', 'port-rsi'))) EventServerInterface.instance().startSA() self.info("ESI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-esi'), Settings.get('Bind', 'port-esi'))) TestServerInterface.instance().startSA() self.info("TSI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-tsi'), Settings.get('Bind', 'port-tsi'))) AgentServerInterface.instance().startSA() self.info("ASI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-asi'), Settings.get('Bind', 'port-asi'))) # Now start the scheduler and reload tasks taskReloaded = TaskManager.instance().loadBackups() if taskReloaded is None: self.info("Reload tasks disabled") elif taskReloaded: self.info("Tasks reloaded") else: self.error("Failed to reload tasks") except Exception as e: self.error("Unable to start server: %s" % str(e)) self.cleanup() sys.exit(3) stoptime = time.time() self.info("%s successfully started (in %s sec.)" % (Settings.get('Server', 'name'), int(stoptime - starttime))) # only for windows platform if platform.system() == "Windows": print("Server successfully started...") self.setrunning() self.run()