def stopTimer(): global timer global leftTime global time LogManager.log("Old Login Daemon Cancelled") timer.cancel() leftTime = time
def PrintFieldStatus(fieldDictionaryData): fieldStatusPlayer1 = ["", "", "", "", "", "", "", ""] fieldStatusPlayer2 = ["", "", "", "", "", "", "", ""] fieldPrintFormat = "{0:>10} |{1:>10} |{2:>10} |{3:>10} |{4:>10} |{5:>10} |{6:>10} |{7:>10} |" for indexOfFieldNumber, indexOfCard in fieldDictionaryData.iteritems(): if indexOfCard[0][3] != 0: playerNumber = int( indexOfCard[0][DefineManager.PLAYER_NUMBER_SAVED_POINT]) zonePosition = int(indexOfCard[0][3]) if playerNumber == 1: fieldStatusPlayer1[zonePosition] = indexOfCard[0][0] elif playerNumber == 2: fieldStatusPlayer2[zonePosition] = indexOfCard[0][0] else: LogManager.PrintLog("AdvancedPrintManager", "PrintFieldStatus", "unknown player", DefineManager.LOG_LEVEL_INFO) fieldOfPlayer1 = fieldPrintFormat.format(*fieldStatusPlayer1) fieldOfPlayer2 = fieldPrintFormat.format(*fieldStatusPlayer2) LogManager.PrintLog("AdvancedPrintManager", "PrintFieldStatus", "player1: " + fieldOfPlayer1, DefineManager.LOG_LEVEL_INFO) LogManager.PrintLog("AdvancedPrintManager", "PrintFieldStatus", "player2: " + fieldOfPlayer2, DefineManager.LOG_LEVEL_INFO)
def find_ip(): LogManager.log("Searching IP Address...") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) ip = s.getsockname()[0] s.close() LogManager.log("IP Address found: (" + ip + ")") return ip
def startTimer(): global timer global leftTime actualTime = leftTime if leftTime <= 30 else 30 leftTime = leftTime - actualTime timer = threading.Timer(actualTime * 60.0, timerFunc) timer.daemon = True timer.start() LogManager.log("Login Daemon Started")
def exchangeCapabilities(self, clientsock): """ Exchange the capabilities with the manager. First sends the agent capabilities. Then waits for the remote manager capabilities. Creates a Netconf session and returns it. @type clientsock: socket @param clientsock: The socket for the current client @rtype: session @return: The session created by the SessionManager. """ # Loading hello element along with static capabilities from hello.xml file helloRoot = NonvalidatingReader.parseUri(C.HELLO_URI) helloNode = helloRoot.documentElement # Finding a unique session-id for that session self.session = sessionManager.getInstance().createSession( clientsock, self.username) sessionId = self.session.getSessionId() LogManager.getInstance().logInfo( "opening Netconf session: (sessionId=%s)" % (self.session.getSessionId())) # Setup the session-id value within session-id node sessionIdNode = helloRoot.createElementNS(C.NETCONF_XMLNS, C.SESSION_ID) helloNode.appendChild(sessionIdNode) sessionIdNode.appendChild(helloRoot.createTextNode(str(sessionId))) # Get the unique instance of the singleton ModuleManager: moduleManager = ModuleManager.getInstance() # Add the capabilities related to the modules to the hello message: for node in helloNode.childNodes: if (node.nodeType == Node.ELEMENT_NODE and node.tagName == C.CAPABILITIES): for module in moduleManager.getModules(): capabNode = helloRoot.createElementNS( C.NETCONF_XMLNS, C.CAPABILITY) capabText = helloRoot.createTextNode(module.namespace) capabNode.appendChild(capabText) node.appendChild(capabNode) # Convert the hello element to String before sending hellostr = util.convertNodeToString(helloNode) # Sending capabilities along with a new session-id self.send(hellostr) # Receiving capabilities of the manager data = self.receive() # Printing Manager capabilities LogManager.getInstance().logInfo( "Manager capabilities received: (sessionId=%s)" % (self.session.getSessionId()))
def start_web(): LogManager.getLogger(True) app = Bottle() routeDict = { '/hello': { 'f': helloworld }, '/': { 'f': webSetup }, '/device': { 'f': deviceSetting }, '/__exit': { 'f': exit }, '/web/images/<filename:re:.*\.(jpg|png)>': { 'f': jpgs }, '/web/<filename:re:.*\.html>': { 'f': htmls }, '/web/<filename:re:.*\.js>': { 'f': javascripts }, '/web/css/<filename:re:.*\.css>': { 'f': stylesheets }, '/web/css/images/<filename:re:.*\.(jpg|png)>': { 'f': cssImages }, '/web/<filename:re:.*\.swf>': { 'f': adobeflash }, '/web/<filename:re:.*\.xap>': { 'f': silvelight }, '/web/fonts/<filename:re:.*\.(otf|eot|svg|ttf|woff|woff2)>': { 'f': fonts }, '/web/plugins/<filename:re:.*\.(css|png)>': { 'f': webPlugins }, } for url in routeDict: fun = routeDict[url] if 'm' in fun: app.route(url, method=fun['m'])(fun['f']) else: app.route(url)(fun['f']) try: global server server = MyWSGIRefServer(host="0.0.0.0", port="8080") app.run(server=server, reloader=False) except: LogManager.getLogger().error(traceback.format_exc())
def getOperation(self, name): if self.operations.has_key(name): mainFileName = self.operations[name]["mainFileName"] className = self.operations[name]["className"] operation = OperationFactory.getInstance().createOperation(name, mainFileName, className) else: LogManager.getInstance().logError("Operation %s is not known." % (name)) operation = None return operation
def MakeNewDirectory(targetDirectoryPath, newDirectoryName): if not os.path.exists(targetDirectoryPath + newDirectoryName): os.makedirs(targetDirectoryPath + newDirectoryName + "/") LogManager.PrintLog("DirectoryManager", "MakeNewDirectory", "create dir: " + newDirectoryName, DefineManager.LOG_LEVEL_INFO) return True LogManager.PrintLog("DirectoryManager", "MakeNewDirectory", "the dir already exist", DefineManager.LOG_LEVEL_WARN) return False
def loadFile(self, filename): if (self.activationFlag): output = self.xem.ConfigureFPGA(filename) if (self.xem.NoError == output): LogManager.Instance().write( "class OpalKelly: Bit file loaded successfully") elif (self.xem.FileError == output): LogManager.Instance().write( "class OpalKelly: Invalid file name") else: LogManager.Instance().write( "class OpalKelly: No device found, loading bit file aborted")
def getOperation(self, name): if self.operations.has_key(name): mainFileName = self.operations[name]["mainFileName"] className = self.operations[name]["className"] operation = OperationFactory.getInstance().createOperation( name, mainFileName, className) else: LogManager.getInstance().logError("Operation %s is not known." % (name)) operation = None return operation
def parseConfigurationFile(self): try: # Parse configuration file self.doc = amara.parse("file:" + C.YENCAP_CONF_HOME + "/netconfd.xml") # Read IP version (4 or 6) ipVersion = int(str(self.doc.yencap.ipversion)) if ipVersion not in [4, 6]: raise Exception( "Ip version must be 4 or 6 in %s/netconfd.xml file." % (C.YENCAP_CONF_HOME)) # Read application protocol (only ssh is implemented.) appProtocol = str(self.doc.yencap.protocol.active) if appProtocol == "ssh": sshData = {} sshData["hostKeyType"] = str( self.doc.yencap.protocol.ssh.privatekeyfile.keytype) sshData["hostKeyFile"] = str( self.doc.yencap.protocol.ssh.privatekeyfile) self.monserver = ServerSSH(ipVersion, sshData) LogManager.getInstance().logInfo("Netconf over SSH started.") else: raise Exception( "Only ssh is supported as a transport protocol.") # Read options for elem in self.doc.yencap.options.option: name = str(elem.name) value = str(elem.value) if (name == "accesscontrol"): if (value == "active"): rbacManager.getInstance().setActive(True) elif (value == "unactive"): rbacManager.getInstance().setActive(False) else: raise Exception( "accesscontrol option value must be one of active or unactive." ) else: raise Exception("Unknown option in %s/netconfd.xml." % (C.YENCAP_CONF_HOME)) except Exception, exp: LogManager.getInstance().logError( 'Error while reading %s/netconfd.xml: %s' % (C.YENCAP_CONF_HOME, str(exp)))
def sshAuthentication(self, clientsock): # setup logging paramiko.util.log_to_file(C.SYSLOG_FILE) # Check that SSH server parameters have been set: if (self.sshData == None): return clientsock, False, None else: # Load private key of the server filekey = self.sshData["hostKeyFile"] if (not filekey.startswith("/")): filekey = C.YENCAP_CONF_HOME + "/" + filekey # Build a key object from the file path: if (self.sshData["hostKeyType"] == "dss"): priv_host_key = paramiko.DSSKey(filename=filekey) elif (self.sshData["hostKeyType"] == "rsa"): priv_host_key = paramiko.RSAKey(filename=filekey) try: event = threading.Event() # Create a new SSH session over an existing socket, or socket-like object. t = Transport(clientsock) # Add a host key to the list of keys used for server mode. t.add_server_key(priv_host_key) # paramiko.ServerInterface defines an interface for controlling the behavior of paramiko in server mode. server = SSHServerModule() # Negotiate a new SSH2 session as a server. t.start_server(event, server) while 1: event.wait(0.1) if not t.is_active(): return clientsock, False, None if event.isSet(): break # Return the next channel opened by the client over this transport, in server mode. channel = t.accept(20) if channel is None: return clientsock, False, None except Exception, e: LogManager.getInstance().logError("Caught exception: %s: %s" % (str(e.__class__), str(e))) traceback.print_exc() try: t.close() except: pass return clientsock, False, None
def sshAuthentication(self, clientsock): # setup logging paramiko.util.log_to_file(C.SYSLOG_FILE) # Check that SSH server parameters have been set: if (self.sshData == None): return clientsock, False, None else: # Load private key of the server filekey = self.sshData["hostKeyFile"] if (not filekey.startswith("/")): filekey = C.YENCAP_CONF_KEYS + "/" + filekey # Build a key object from the file path: if (self.sshData["hostKeyType"] == "dss"): priv_host_key = paramiko.DSSKey(filename=filekey) elif (self.sshData["hostKeyType"] == "rsa"): priv_host_key = paramiko.RSAKey(filename=filekey) try: event = threading.Event() # Create a new SSH session over an existing socket, or socket-like object. t = Transport(clientsock) # Add a host key to the list of keys used for server mode. t.add_server_key(priv_host_key) # paramiko.ServerInterface defines an interface for controlling the behavior of paramiko in server mode. server = SSHServerModule() # Negotiate a new SSH2 session as a server. t.start_server(event, server) while 1: event.wait(0.1) if not t.is_active(): return clientsock, False, None if event.isSet(): break # Return the next channel opened by the client over this transport, in server mode. channel = t.accept(20) if channel is None: return clientsock, False, None except Exception, e: LogManager.getInstance().logError("Caught exception: %s: %s" % (str(e.__class__), str(e))) traceback.print_exc() try: t.close() except: pass return clientsock, False, None
def updateConfig(self, configName, configType): """ Replace the module root nodes when it is unfresh in self.runningConfig. @type configName : string @param configName : the name of the configuration datastore ('running', 'candidate' or 'startup') @type configType : string @param configType : the type of the configuration datastore ('state' or 'config') """ configuration = self.configurations[configName][configType] self.prefixes = self.moduleManager.getPrefixes() for module in self.moduleManager.getModules(): if (not module.isConfigFresh(configName, configType)): try: if configType == "config": moduleReply = module.getConfig(configName) elif configType == "state": moduleReply = module.get(configName) if moduleReply.isError(): msg = "Error: DatastoreManager:updateConfig(): Module %s: %s" % ( module.name, moduleReply.error_message) LogManager.getInstance().logError(msg) else: module.updateConfigTime(configName, configType) newNode = moduleReply.getXMLNodeReply() ctx = Context(configuration, processorNss=self.prefixes) nodes = Evaluate(module.path, ctx) if len(nodes) == 1: parentNode = nodes[0] if parentNode.hasChildNodes(): find = False for oldNode in parentNode.childNodes: if oldNode.tagName == newNode.tagName: parentNode.replaceChild( newNode, oldNode) find = True if not find: parentNode.appendChild(newNode) #oldNode.appendChild(newNode) else: parentNode.appendChild(newNode) except Exception, exp: LogManager.getInstance().logError("Module %s: %s" % (module.name, str(exp)))
def exchangeCapabilities(self, clientsock): """ Exchange the capabilities with the manager. First sends the agent capabilities. Then waits for the remote manager capabilities. Creates a Netconf session and returns it. @type clientsock: socket @param clientsock: The socket for the current client @rtype: session @return: The session created by the SessionManager. """ # Loading hello element along with static capabilities from hello.xml file helloRoot = NonvalidatingReader.parseUri(C.HELLO_URI) helloNode = helloRoot.documentElement # Finding a unique session-id for that session self.session = sessionManager.getInstance().createSession(clientsock, self.username) sessionId = self.session.getSessionId() LogManager.getInstance().logInfo("opening Netconf session: (sessionId=%s)" % (self.session.getSessionId())) # Setup the session-id value within session-id node sessionIdNode = helloRoot.createElementNS(C.NETCONF_XMLNS, C.SESSION_ID) helloNode.appendChild(sessionIdNode) sessionIdNode.appendChild(helloRoot.createTextNode(str(sessionId))) # Get the unique instance of the singleton ModuleManager: moduleManager = ModuleManager.getInstance() # Add the capabilities related to the modules to the hello message: for node in helloNode.childNodes: if (node.nodeType== Node.ELEMENT_NODE and node.tagName == C.CAPABILITIES): for module in moduleManager.getModules(): capabNode = helloRoot.createElementNS(C.NETCONF_XMLNS, C.CAPABILITY) capabText = helloRoot.createTextNode(module.namespace) capabNode.appendChild(capabText) node.appendChild(capabNode) # Convert the hello element to String before sending hellostr = util.convertNodeToString(helloNode) # Sending capabilities along with a new session-id self.send(hellostr) # Receiving capabilities of the manager data = self.receive() # Printing Manager capabilities LogManager.getInstance().logInfo("Manager capabilities received: (sessionId=%s)" % (self.session.getSessionId()))
def MoveFileToDirectory(targetDirectoryPath, targetFileName, targetFolderPath): MakeNewDirectory(targetDirectoryPath, targetFolderPath) try: shutil.move( targetDirectoryPath + targetFileName, targetDirectoryPath + targetFolderPath + "/" + targetFileName) LogManager.PrintLog("DirectoryManager", "MoveFileToDirectory", "file moved successfully", DefineManager.LOG_LEVEL_INFO) except: LogManager.PrintLog("DirectoryManager", "MoveFileToDirectory", "file move process has problem", DefineManager.LOG_LEVEL_ERROR)
def start_test_uff(self, table, seq): uff_name = table.iloc[seq].tasks batch = table.iloc[seq].batch_size precision = table.iloc[seq].precision input_nodes_str = table.iloc[seq].input_nodes output_nodes_name = table.iloc[seq].output_node input_nodes_list = eval(input_nodes_str) # str=>list input_params = "" # concat uffInput params for node in input_nodes_list: input_params += " --uffInput=" + node[0] + "," node_size = node[1] node_size = node_size[1:] for size in node_size: input_params += size + "," input_params = input_params[:-1] # remove redundent comma command = self.exec_root + 'trtexec --uff={} --output={}{} --batch={} --{} --uffNHWC'.format( uff_name, output_nodes_name, input_params, batch, precision) print('*' * 30) print(command) print('*' * 30) log = subprocess.run(command, shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8') # write log log_writer = LogManager.LogManager('./logs/') log_writer.WriteText(log, uff_name[:-4] + ".txt") result = self.get_means(log) return result
def createOperation(self, name, mainFileName, className): newOperation = None # Load operation name #name = name + "_Operation" try: mod = self.importName("Operations." + mainFileName, className) newOperation = mod() except Exception,exp: import traceback traceback.print_exc() LogManager.getInstance().logError("operation %s couldn't be loaded. Error:%s" % (className, str(exp)))
def start_test_onnx(self, table, seq): onnx_name = table.iloc[seq].tasks batch_size = table.iloc[seq].batch_size precision = table.iloc[seq].precision input_nodes_str = table.iloc[seq].input_nodes input_nodes_names = eval(input_nodes_str) def multi_batch(strings, batch_size): strings[0] = str(int(strings[0]) * batch_size) return strings shapes = "--shapes=" + ','.join([ n[0] + ":0:" + 'x'.join(multi_batch(n[1], batch_size)) for n in input_nodes_names ]).replace("-", "") # onnx_name = os.path.basename(onnx_name).split('.')[0] + ".onnx" command = '/usr/src/tensorrt/bin/trtexec --onnx={} {} --{}'.format( onnx_name, shapes, precision) # command = self.exec_root + 'trtexec --onnx={} {} --{}'.format(onnx_name, shapes, precision) print('*' * 30) print(command) print('*' * 30) log_onnxtest = subprocess.run( command, shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8') # save means result = self.get_means(log_onnxtest) # write log log_writer = LogManager.LogManager('./logs/') log_writer.WriteText(log_onnxtest, onnx_name[:-5] + '.txt') return result
def createModule(self, moduleDescr): logm = LogManager.getInstance() newModule = None # Load module name name = moduleDescr["name"] + "_Module" try: logm.logInfo("Now trying to load module %s..." % (name)) mod = self.importName("Modules." + name + "." + name, name) newModule = mod(moduleDescr["name"], moduleDescr["xpath"], moduleDescr["namespace"], moduleDescr["cachelifetime"], moduleDescr["parameters"]) if moduleDescr["yanguri"] != None: newModule.yanguri = moduleDescr["yanguri"] # Pretty print module loading...OK logm.logInfo("module %s has been loaded successfully." % (name)) except Exception, exp: import traceback traceback.print_exc() logm.logError("module %s couldn't be loaded: %s" % (name, str(exp)))
def showLog(): #textEdit = QTextEdit(str(LogManager.readLog())) #textEdit.show() msgBox = QMessageBox(QMessageBox.Information, "SerraAutoLogin Log", "", QMessageBox.NoButton, wParent) msgBox.setInformativeText("SerraAutoLogin Log History") msgBox.setDetailedText(str(LogManager.readLog())) msgBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) msgBox.exec()
def createOperation(self, name, mainFileName, className): newOperation = None # Load operation name #name = name + "_Operation" try: mod = self.importName("Operations." + mainFileName, className) newOperation = mod() except Exception, exp: import traceback traceback.print_exc() LogManager.getInstance().logError( "operation %s couldn't be loaded. Error:%s" % (className, str(exp)))
def main(): try: LogManager.getInstance().logInfo("YencaP is starting...") if len(sys.argv) != 1: usage = "Usage: netconfd" print usage sys.exit(1) else: # Parse the configuration file the get the active application protocol and the options. cp = ConfigParser() monserver = cp.parseConfigurationFile() # Start the Netconf server, listening on port specified. monserver.listener() except Exception, exp: print exp sys.exit(1)
def StaticCradDataLoader(): global cardData cardData = None with open('Data/CardData.json') as dataFile: cardData = json.load(dataFile) LogManager.PrintLog("CardDatabaseManager", "StaticCardDataLoader", "card data loaded keys: " + ', '.join(cardData.keys()), DefineManager.LOG_LEVEL_INFO)
def main(): try: LogManager.getInstance().logInfo("YencaP is starting...") if len(sys.argv)!=1: usage = "Usage: netconfd" print usage sys.exit(1) else: # Parse the configuration file the get the active application protocol and the options. cp = ConfigParser() monserver = cp.parseConfigurationFile() # Start the Netconf server, listening on port specified. monserver.listener() except Exception,exp: print exp sys.exit(1)
def __init__(self): self.logger = LogManager.create_logger('MASTER') self.closing = False self.logger.info('Initialising AutoHome server...') self.mr = ModuleRunner(self) self.stats = StatsController(self) self.server = TelnetServer(self) self.mainloop()
def loop(self): # Loop until ending connection while 1: # Receving a new Netconf request data = self.receive() processeddata = "" if (data == -1): msg = "Problem while receiving message. Please check application protocol and options (sessionId=%s)" % ( self.session.getSessionId()) LogManager.getInstance().logError(msg) sessionManager.getInstance().closeSession(self.session) break elif (data == -2): # Remote socket was badly closed. Closing session. msg = "Remote socket seems closed: (sessionId=%s). Closing Netconf session..." % ( self.session.getSessionId()) LogManager.getInstance().logError(msg) sessionManager.getInstance().closeSession(self.session) break else: # Processing the Netconf request try: processeddata = self.processrequest(data) except Exception, exp: LogManager.getInstance().logError( "remote socket seems closed: (sessionId=%s,error=%s)" % (self.session.getSessionId(), str(exp))) if (processeddata == ''): moduleReply = ModuleReply( error_type=ModuleReply.PROTOCOL, error_tag=ModuleReply.UNKNOWN_ELEMENT, error_severity=ModuleReply.ERROR, error_message="The response is unexpectedly empty.") nodeReply = moduleReply.getXMLNodeReply() processeddata = util.convertNodeToString(nodeReply) # Sending the response self.send(processeddata) if self.session.mustBeClosed == 1: LogManager.getInstance().logInfo( "closing Netconf session: (sessionId=%s)" % (self.session.getSessionId())) sessionManager.getInstance().closeSession(self.session) break
def parseConfigurationFile(self): try: # Parse configuration file self.doc = amara.parse("file:" + C.YENCAP_CONF_HOME + "/netconfd.xml") # Read IP version (4 or 6) ipVersion = int(str(self.doc.yencap.ipversion)) if ipVersion not in [4, 6]: raise Exception("Ip version must be 4 or 6 in %s/netconfd.xml file." % (C.YENCAP_CONF_HOME)) # Read application protocol (only ssh is implemented.) appProtocol = str(self.doc.yencap.protocol.active) if appProtocol == "ssh": sshData = {} sshData["hostKeyType"] = str(self.doc.yencap.protocol.ssh.privatekeyfile.keytype) sshData["hostKeyFile"] = str(self.doc.yencap.protocol.ssh.privatekeyfile) self.monserver = ServerSSH(ipVersion, sshData) LogManager.getInstance().logInfo("Netconf over SSH started.") else: raise Exception("Only ssh is supported as a transport protocol.") # Read options for elem in self.doc.yencap.options.option: name = str(elem.name) value = str(elem.value) if (name == "accesscontrol"): if (value == "active"): rbacManager.getInstance().setActive(True) elif (value == "unactive"): rbacManager.getInstance().setActive(False) else: raise Exception("accesscontrol option value must be one of active or unactive.") else: raise Exception("Unknown option in %s/netconfd.xml." % (C.YENCAP_CONF_HOME)) except Exception, exp: LogManager.getInstance().logError('Error while reading %s/netconfd.xml: %s' % (C.YENCAP_CONF_HOME, str(exp)))
def __init__(self, parent): self.parent = parent self.logger = LogManager.create_logger('MODULES') self.closing = False self.thread_handler = ModuleThreadHandler(self.logger) self.logger.info('Initialising modules...') self.get_modules() self.logger.info(f"Currently running {len(self.modules)} module{'s' if len(self.modules) != 1 else ''}...")
def DetectOutOfLog(logMessage): outOfLogMessage = re.search( "Truncating log, which has reached the size limit of (.+?)\n", logMessage) if outOfLogMessage != None: LogManager.PrintLog( "ExceptionManager", "DetectOutOfLog", "log message will discontinue, size: " + outOfLogMessage.group(1), DefineManager.LOG_LEVEL_WARN) return True return False
def updateConfig(self, configName, configType): """ Replace the module root nodes when it is unfresh in self.runningConfig. @type configName : string @param configName : the name of the configuration datastore ('running', 'candidate' or 'startup') @type configType : string @param configType : the type of the configuration datastore ('state' or 'config') """ configuration = self.configurations[configName][configType] self.prefixes = self.moduleManager.getPrefixes() for module in self.moduleManager.getModules(): if (not module.isConfigFresh(configName, configType)): try: ctx = Context(configuration, processorNss = self.prefixes) nodes = Evaluate(module.path, ctx) if len(nodes) == 1: oldNode = nodes[0] parentNode = oldNode.parentNode if configType == "config": moduleReply = module.getConfig(configName) elif configType == "state": moduleReply = module.get(configName) if moduleReply.isError(): msg = "Error: DatastoreManager:updateConfig(): Module %s: %s" % (module.name, moduleReply.error_message) LogManager.getInstance().logError(msg) else: module.updateConfigTime(configName, configType) newNode = moduleReply.getXMLNodeReply() parentNode.replaceChild(newNode, oldNode) except Exception,exp: LogManager.getInstance().logError("Module %s: %s" % (module.name, str(exp)))
def __init__(self, cntrlr): """Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note: Do not include the `self` parameter in the ``Args`` section. Args: param1 (str): Description of `param1`. param2 (:obj:`int`, optional): Description of `param2`. Multiple lines are supported. param3 (:obj:`list` of :obj:`str`): Description of `param3`. """ self.controller = cntrlr self.helper_class = HelperClassPy.HelperClassPy() self.configuration_manager = ConfigurationManager.ConfigurationManager( ) self.script_manager = ScriptManager.ScriptManager( self.configuration_manager) self.logging_manager = LogManager.LogManager() self.communications_manager = CommunicationsManager.CommunicationsManager( ) # pass pointers to helper class self.helper_class.model = self self.helper_class.communications = self.communications_manager self.helper_class.configuration = self.configuration_manager self.helper_class.controller = self.controller self.helper_class.logging = self.logging_manager #self.setup_last_known_project_configuration() self.revision_major = 0 self.revision_minor = 0 self.revision_build = 0 self.project_directory = None self.project_configuration = None self.bbt_configuration_content = {} self.bbt_configuration_content[ 'current project'] = None # project path self.bbt_configuration_content[ 'current project config'] = None # config file name self.bbt_configuration_content['configurations history'] = [ ] # list of dictionaries self.history_size = 10 self.bbt_configuration_content['history size'] = self.history_size
def getModuleInstance(self, name, httpSession): # Now trying to load the module: newModule = None try: # Build an instance of the module (like BGP module for instance) # with a dictionnary containing the parameters defined in modules.xml (__init__) mod = self.modules[name] modz = self.importName("Components.Modules." + name + "." + name, name) newModule = modz(name, mod["xpath"], mod["namespace"], httpSession.session_id) LogManager.getInstance().logInfo( "module %s has been loaded successfully." % (name)) except Exception, exp: traceback.print_exc() LogManager.getInstance().logInfo( "module %s couldn't be loaded. Error:%s" % (name, str(exp))) return None
def updateConfig(): global username global password global time global url global loginAtStartup LogManager.log("Updating config file...") file = open('config.ini', 'w') config = configparser.ConfigParser() config.add_section('SerraAutoLogin') config.set('SerraAutoLogin', 'Username', username) config.set('SerraAutoLogin', 'cryptedpassword', Vigenere.encryptMessage("NoobTest", password)) config.set('SerraAutoLogin', 'Url', url) config.set('SerraAutoLogin', 'loginAtStartup', loginAtStartup) config.set('SerraAutoLogin', 'Time', str(time)) config.set('SerraAutoLogin', 'FirstRun', '0') config.write(file) file.close() LogManager.log("Config file updated") stopTimer() startTimer()
def configurePLL(self): if (self.activationFlag): self.xem.GetPLL22393Configuration(self.pll) self.pll.SetReference(48.0) self.pll.SetPLLParameters(0, 400, 48, True) self.pll.SetOutputSource(0, ok.PLL22393.ClkSrc_PLL0_0) self.pll.SetOutputDivider(0, 4) self.pll.SetOutputEnable(0, True) self.xem.SetPLL22393Configuration(self.pll) return self.pll.GetPLLFrequency(0) else: LogManager.Instance().write( "class OpalKelly: PLL configuration failed")
def SearchCardById(cardId): global cardData if cardId != "" and cardId != None: LogManager.PrintLog("CardDatabaseManager", "SearchCardById", "search card id: " + cardId, DefineManager.LOG_LEVEL_DEBUG) for indexOfCardType in cardData.keys(): for indexOfCardInfo in cardData[indexOfCardType]: if indexOfCardInfo["cardId"] == cardId: LogManager.PrintLog("CardDatabaseManager", "SearchCardById", "find card id: " + cardId, DefineManager.LOG_LEVEL_DEBUG) return indexOfCardInfo LogManager.PrintLog("CardDatabaseManager", "SearchCardById", "cannot find card id: " + cardId, DefineManager.LOG_LEVEL_WARN) else: return None return None
def FindLatestLogFile(hearthStoneLogFilesPath=DefineManager. DEFAULT_HEARTH_STONE_LOG_FILES_PATH): listOfFiles = SearchDirectoryFiles(hearthStoneLogFilesPath) listOfFiles.sort() latestSavedFile = listOfFiles[-1] LogManager.PrintLog("DirectoryManager", "FindLatestLogFile", "last file: " + latestSavedFile, DefineManager.LOG_LEVEL_INFO) return latestSavedFile
def loop(self): # Loop until ending connection while 1 : # Receving a new Netconf request data = self.receive() processeddata = "" if (data == -1): msg = "Problem while receiving message. Please check application protocol and options (sessionId=%s)" % (self.session.getSessionId()) LogManager.getInstance().logError(msg) sessionManager.getInstance().closeSession(self.session) break elif (data == -2): # Remote socket was badly closed. Closing session. msg = "Remote socket seems closed: (sessionId=%s). Closing Netconf session..." % (self.session.getSessionId()) LogManager.getInstance().logError(msg) sessionManager.getInstance().closeSession(self.session) break else: # Processing the Netconf request try: processeddata = self.processrequest(data) except Exception,exp: LogManager.getInstance().logError("remote socket seems closed: (sessionId=%s,error=%s)" % (self.session.getSessionId() , str(exp))) if (processeddata == ''): moduleReply = ModuleReply( error_type=ModuleReply.PROTOCOL, error_tag=ModuleReply.UNKNOWN_ELEMENT, error_severity=ModuleReply.ERROR, error_message="The response is unexpectedly empty.") nodeReply = moduleReply.getXMLNodeReply() processeddata = util.convertNodeToString(nodeReply) # Sending the response self.send(processeddata) if self.session.mustBeClosed == 1: LogManager.getInstance().logInfo("closing Netconf session: (sessionId=%s)" % (self.session.getSessionId())) sessionManager.getInstance().closeSession(self.session) break
def createModule(self, moduleDescr): logm = LogManager.getInstance() newModule = None # Load module name name = moduleDescr["name"] + "_Module" try: logm.logInfo("Now trying to load module %s..." % (name)) mod = self.importName("Modules." + name +"."+name, name) newModule = mod(moduleDescr["name"], moduleDescr["xpath"], moduleDescr["namespace"], moduleDescr["cachelifetime"], moduleDescr["dictionnary"]) # Pretty print module loading...OK logm.logInfo("module %s has been loaded successfully." % (name)) except Exception,exp: import traceback traceback.print_exc() logm.logError("module %s couldn't be loaded: %s" % (name, str(exp)))
def handleconnection(self, clientsock): """ Handles incoming connection. @type clientsock: socket @param clientsock: The client socket """ #clientsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if self.ipVersion == 4: host, port = clientsock.getpeername() elif self.ipVersion == 6: host, port, flowinfo, scopeid = clientsock.getpeername() # Acquire a lock for accessing the pool of sockets: self.lockpool.acquire() LogManager.getInstance().logInfo("received new connection from (%s, %i)" % (host,port)) try: if len(self.waitinglist)==0 and (activeCount()-1)>=self.MAXTHREADS: #Too many connections clientsock.close() return if len(self.waitinglist)==0: self.startthread() # Authenticates the new client. clientsock,authenticated,self.username = self.sshAuthentication(clientsock) if (authenticated): self.queue.append(clientsock) LogManager.getInstance().logInfo("SSH Connection established. Authentication succeeded: (%s, %i)." % (host,port)) else: # Authentication failed LogManager.getInstance().logError("SSH Connection not established. Authentication failed: (%s, %i). Closing socket." % (host,port)) clientsock.close() return self.sem.release() finally: self.lockpool.release()
print("\n\n") exit(0) jsonLog = None try: logData = EncryptedLogManager.loadFromDisk(args.log, args.token, compress=True) jsonLog = json.loads(logData) except InvalidLogFileException: print('invalid') exit(255) try: log = LogManager() log.loadFromJSON(jsonLog) except invalidEventException: print('invalid') exit(255) if args.action == 'state': state = log.getActualLogState() print(','.join(sorted(state[0]))) print(','.join(sorted(state[1]))) rooms = state[2] keys = sorted(rooms.keys()) for key in keys: print(str(key) + ":" + ','.join(rooms[key])) exit(0) if args.action == 'rooms':