def prepareDaemon(self): """ Prepare daemon """ if not Settings.cfgFileIsPresent(): sys.stdout.write(" (config file doesn't exist)") sys.exit(2) try: # Initialize Settings.initialize() Logger.initialize() CliFunctions.initialize(parent=self) except Exception as e: self.error("Unable to initialize settings: %s" % str(e)) else: # config file exist so prepare the deamon self.prepare( pidfile="%s/%s/%s.pid" % (Settings.getDirExec(), Settings.get( 'Paths', 'run'), Settings.get('Server', 'acronym')), name=Settings.get('Server', 'name'), stdout="%s/%s/output.log" % (Settings.getDirExec(), Settings.get('Paths', 'logs')), stderr="%s/%s/output.log" % (Settings.getDirExec(), Settings.get('Paths', 'logs')), stdin="/dev/null", runningfile="%s/%s/%s.running" % (Settings.getDirExec(), Settings.get( 'Paths', 'run'), Settings.get('Server', 'acronym')), )
def trace(self, txt): """ Display message in the screen @param txt: message @type txt: string """ Logger.debug("[%s] %s" % (self.__class__.__name__, unicode(txt).encode('utf-8')))
def error(self, err): """ Log error @param err: @type err: """ Logger.error("[%s] %s" % (self.__class__.__name__, unicode(err).encode('utf-8')))
def hupHandler(self, signum, frame): """ Hup handler """ self.info('Reloading configuration...') Settings.finalize() Settings.initialize() Logger.reconfigureLevel() self.info('Configuration reloaded!')
def addLog(self, txt): """ Append log to the logsEdit widget """ Logger.instance().debug(txt) self.logsEdit.insertHtml( "%s - %s<br />" % (self.formatTimestamp(time.time()), unicode(self.strip_html(txt)))) self.autoScrollOnTextEdit()
def addLogError(self, txt): """ Add log error """ Logger.instance().error(txt) self.logsEdit.insertHtml( "<span style='color:red'>%s - %s</span><br />" % (self.formatTimestamp(time.time()), self.strip_html(txt))) self.autoScrollOnTextEdit()
def addLogWarning(self, txt): """ Add log warning """ Logger.instance().info(txt) self.logsEdit.insertHtml( "<span style='color:darkorange'>%s - %s</span><br />" % (self.formatTimestamp(time.time()), self.strip_html(txt))) self.autoScrollOnTextEdit()
def trace(self, txt): """ Display message in the screen @param txt: message @type txt: string """ if sys.version_info[0] < 3: if not isinstance(txt, unicode): txt = unicode(txt, 'latin2') Logger.debug("[%s] %s" % (self.__class__.__name__, txt))
def error(self, err): """ Log error @param err: @type err: """ if sys.version_info[0] < 3: if not isinstance(err, unicode): err = unicode(err, 'latin2') Logger.error("[%s] %s" % (self.__class__.__name__, err))
def sendMessage(self, cmd, data='', more={}): """ Send a message to the client """ inData = False msg = {'cmd': cmd} # save data to temp area idFile = '' if len(data): try: idFile = "%s" % uuid.uuid4() pluginDataFile = '%s/%s' % (self.clientTmpPath, idFile) with open(pluginDataFile, mode='w') as myfile: myfile.write(json.dumps(data)) inData = True except Exception as e: print("unable to write data file from plugin: %s" % e) Logger.instance().error( "unable to write data file from plugin: %s" % e) self.debug().addLogError("internal error on send message") msg.update({'in-data': inData}) # add data parameters if inData: msg.update({'data-id': idFile}) # add more params msg.update(more) # adding reference msg.update({ 'id': self.pluginName, 'name': self.pluginName, 'type': self.pluginType }) Logger.instance().debug("%s" % msg) # encode message and send to stdout datagram = json.dumps(msg) datagramEncoded = base64.b64encode(bytes(datagram, "utf8")) print(str(datagramEncoded, "utf8")) sys.stdout.flush()
def isUp(self): """ Try to connect to the database Detect the version of the mysql server """ timeoutVal = Settings.getInt('Boot', 'timeout-sql-server') timeout = False go = False startTime = time.time() while (not go) and (not timeout): # timeout elapsed ? if (time.time() - startTime) >= timeoutVal: timeout = True else: try: self.trace("try to connect to the database") conn = MySQLdb.connect(host=Settings.get('MySql', 'ip'), user=Settings.get('MySql', 'user'), passwd=Settings.get('MySql', 'pwd'), db=Settings.get('MySql', 'db'), unix_socket=Settings.get( 'MySql', 'sock')) go = True self.trace("connection successful") except MySQLdb.Error as e: Logger.debug("connect to the database failed: %s" % str(e)) Logger.debug("retry in %s second" % Settings.get('MySql', 'retry-connect')) time.sleep(int(Settings.get('MySql', 'retry-connect'))) if timeout: raise Exception("db manager not ready: timeout") if go: self.trace("retrieve mysql version") cursor = conn.cursor() cursor.execute("SELECT VERSION()") row = cursor.fetchone() cursor.close() conn.close() self.dbVersion = row[0] self.trace(self.dbVersion)
def prepare(self): """ """ Logger.instance().debug("preparing plugin") # convert qicon to base64 pixmapIcon = self.pluginIcon.pixmap(64, 64, mode=QIcon.Normal, state=QIcon.Off) byteArray = QByteArray() buffer = QBuffer(byteArray) buffer.open(QIODevice.WriteOnly) pixmapIcon.save(buffer, "png", quality=100) iconBase64 = byteArray.toBase64().data() Logger.instance().debug("icon converted to base64") self.sendMessage(cmd='configure', data=str(iconBase64, 'utf8'), more={"description": self.pluginDescription})
def isUp(): """ Check if the web server if ready (apache) """ try: # init the http timeoutVal = Settings.getInt('Boot','timeout-http-server') http = httplib2.Http(timeout=timeoutVal, disable_ssl_certificate_validation=True, ca_certs="%s/Libs/cacerts.txt" % Settings.getDirExec() ) http.add_credentials( Settings.get('Web','login'), Settings.get('Web','password') ) http.force_exception_to_status_code = True scheme = 'http' portHttp = Settings.get('Web','http-port') if Settings.getInt('Web','https'): scheme = 'https' portHttp = Settings.get('Web','https-port') uri = '%s://%s:%s/%s/index.php' % ( scheme, Settings.get('Web','fqdn'), portHttp, Settings.get('Web', 'path') ) timeout = False go = False startTime = time.time() while (not go) and (not timeout): # timeout elapsed ? if (time.time() - startTime) >= timeoutVal: timeout = True else: # test the web server Logger.debug("Get index: %s" % uri) resp, content = http.request(uri, "GET") if resp['status'] == '200': Logger.debug( "200 OK received" ) go = True else: Logger.debug( "response incorrect (%s)" % resp['status'] ) Logger.debug( "response (%s)" % resp ) Logger.debug( "response content (%s)" % content ) Logger.debug( "retry in %s second" % Settings.get('Web','retry-connect') ) time.sleep( int(Settings.get('Web','retry-connect')) ) if timeout: raise Exception("timeout" ) except Exception as e: raise Exception("server web not ready: %s" % str(e) )
def onPluginMessage(self, msg): """ On message received from the client """ try: if not self.isRegistered and msg['cmd'] == 'registered': Logger.instance().debug("plugin registered") self.clientTmpPath = msg['tmp-path'] self.debugPage.addLogSuccess( txt="plugin registered [Type=%s]" % self.pluginType) self.isRegistered = True self.prepare() elif msg['cmd'] == 'keepalive': self.aliveClient.lastTimestamp = time.time() Logger.instance().debug("keepalive received") elif msg['cmd'] == 'run': data = None #read data if msg['in-data']: # read the file f = open("%s/%s" % (self.clientTmpPath, msg['data-id']), 'r') all = f.read() f.close() dataJson = json.loads(all) # delete them os.remove("%s/%s" % (self.clientTmpPath, msg['data-id'])) self.__onPluginRun(data=dataJson) elif msg['cmd'] == 'open-main': if self.mainPage is None: return if self.TAB_MAIN_PAGE is not None: self.mainTab.setCurrentIndex(self.TAB_MAIN_PAGE) self.__showWindows() if msg['in-data']: # read the file f = open("%s/%s" % (self.clientTmpPath, msg['data-id']), 'r') all = f.read() f.close() dataJson = json.loads(all) self.mainPage.insertData(data=dataJson) # delete them os.remove("%s/%s" % (self.clientTmpPath, msg['data-id'])) else: pass except Exception as e: self.debugPage.addLogError(txt="error: %s" % e) self.mainTab.setCurrentIndex(TAB_DEBUG_PAGE) self.__showWindows()
def cleanup(self): """ Cleanup the server """ self.info('Cleanup...') self.trace("finalize probes manager") try: ProbesManager.finalize() except Exception: pass self.trace("finalize agent manager") try: AgentsManager.finalize() except Exception: pass self.trace("finalize toolbox manager") try: ToolboxManager.finalize() except Exception: pass self.trace("finalize settings") try: Settings.finalize() except Exception: pass self.trace("finalize context") try: Context.finalize() except Exception: pass self.trace("finalize projects manager") try: ProjectsManager.finalize() except Exception: pass self.trace("finalize users manager") try: UsersManager.finalize() except Exception: pass self.trace("finalize stats manager") try: StatsManager.finalize() except Exception: pass self.trace("finalize task manager") try: TaskManager.finalize() except Exception: pass self.trace("finalize test public manager") try: RepoPublic.finalize() except Exception: pass self.trace("finalize test repo manager") try: RepoTests.finalize() except Exception: pass self.trace("finalize test archives manager") try: RepoArchives.finalize() except Exception: pass self.trace("finalize helper manager") try: HelperManager.finalize() except Exception: pass self.trace("finalize libraries manager") try: RepoLibraries.finalize() except Exception: pass self.trace("finalize adapters manager") try: RepoAdapters.finalize() except Exception: pass self.trace("finalize adapters data storage") try: StorageDataAdapters.finalize() except Exception: pass self.trace("finalize WSU") try: RestServerInterface.instance().stop() RestServerInterface.finalize() except Exception: pass self.trace("finalize ESI") try: EventServerInterface.instance().stopSA() EventServerInterface.finalize() except Exception: pass self.trace("finalize TSI") try: TestServerInterface.instance().stopSA() TestServerInterface.finalize() except Exception: pass self.trace("finalize PSI") try: ProbeServerInterface.instance().stopSA() ProbeServerInterface.finalize() except Exception: pass self.trace("finalize ASI") try: AgentServerInterface.instance().stopSA() AgentServerInterface.finalize() except Exception: pass self.trace("finalize db manager") try: DbManager.finalize() except Exception: pass self.trace("finalize logger, cli") try: CliFunctions.finalize() Logger.finalize() except Exception: pass
def initialize(self, ip, port, type, name, descr, defaultTool, supportProxy=False, proxyIp=None, proxyPort=None, sslSupport=True, isAgent=0, fromCmd=False): """ Initialize the tool @param ip: @type ip: @param type: @type type: @param name: @type name: @param descr: @type descr: """ self.running = False self.defaultTool = defaultTool self.tool = None if not Settings.cfgFileIsPresent(): sys.stdout.write(" (config file doesn't exist)") sys.exit(RETURN_CONFIG) try: Settings.initialize() Logger.initialize( logPathFile="%s/%s/%s.log" % (Settings.getDirExec(), Settings.get('Paths', 'logs'), name)) if (isAgent, str(type)) in plugins: self.info("Initialize %s tool type=%s..." % (type, isAgent)) if not len(ip): raise Exception("No controller ip specified!") if not len(name): raise Exception("No tool name specified!") self.tool = plugins[(isAgent, str(type))].initialize( controllerIp=str(ip), toolName=str(name), toolDesc=str(descr), defaultTool=defaultTool, controllerPort=int(port), supportProxy=supportProxy, proxyIp=str(proxyIp), proxyPort=proxyPort, sslSupport=sslSupport) self.tool.setFromCmd() self.tool.onRegistrationSuccessful = self.onRegistrationSuccessful self.tool.onRegistrationFailed = self.onRegistrationFailed self.tool.onRegistrationRefused = self.onRegistrationRefused self.tool.onToolWarningCalled = self.onToolLogWarningCalled self.tool.onToolLogErrorCalled = self.onToolLogErrorCalled self.tool.onToolDisconnection = self.onToolDisconnection self.tool.onConnectionRefused = self.onConnectionRefused self.tool.onConnectionTimeout = self.onConnectionTimeout self.tool.onProxyConnectionTimeout = self.onProxyConnectionTimeout self.tool.onProxyConnectionRefused = self.onProxyConnectionRefused self.tool.onProxyConnectionError = self.onProxyConnectionError self.tool.checkPrerequisites() self.tool.startCA() else: self.error('tool type unknown: %s' % type) self.finalize(RETURN_TYPE_UNKNOWN) except Exception as e: self.error("unable to start tool: " + str(e)) try: Settings.finalize() except: pass Logger.finalize() else: # run in loop self.running = True self.run()
if __name__ == '__main__': app = QApplication(sys.argv) # initiliaze settings application, read settings from the ini file Settings.initialize() # initialize logger logPathFile = "%s/%s" % (QtHelper.dirExec(), Settings.instance().readValue(key='Trace/file')) level = Settings.instance().readValue(key='Trace/level') size = Settings.instance().readValue(key='Trace/max-size-file') nbFiles = int(Settings.instance().readValue(key='Trace/nb-backup-max')) Logger.initialize(logPathFile=logPathFile, level=level, size=size, nbFiles=nbFiles, noSettings=True) # init the core plugin MyPlugin = CorePlugin.MainWindow(debugMode=DEBUGMODE) # create the main widget WidgetSettings = SettingsPage(parent=MyPlugin) MyPlugin.addSettingsPage(widget=WidgetSettings) WidgetMain = MainPage(parent=MyPlugin) MyPlugin.addMainPage(pageName=WidgetSettings.cfg()["plugin"]["name"], widget=WidgetMain) # register the main and settings page of the plugin