Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Imports
- from __future__ import print_function
- import argparse
- import platform
- import shutil
- import socket
- import subprocess
- import time
- import zipfile
- import os.path
- import mysql.connector
- import psutil
- import atexit
- import os
- import functools
- import signal
- import sys
- from uptime import uptime
- import datetime
- import inspect
- import pdb
- db = None
- cursor = None
- cmonrevbaseline = 1
- nmrcalcrevbaseline = 1
- nmrcalirevbaseline = 1
- nmrmeasurerevbaseline = 1
- class DbSetup:
- def __init__(self, defaultrev):
- self.dbstart = 'CREATE DATABASE IF NOT EXISTS `apphandler`'
- self.sqlprocctr = ("CREATE TABLE IF NOT EXISTS `procctr` (\n"
- " `id` INT(11) NOT NULL AUTO_INCREMENT,\n"
- " `appname` VARCHAR(20) DEFAULT '',\n"
- "`cmd` ENUM(\"\", \"start\", \"stop\", \"update\", \"ready\") DEFAULT 'start',\n "
- " `status` VARCHAR(100) DEFAULT 'none',\n"
- " `revision` VARCHAR(100) DEFAULT '{}',\n"
- " PRIMARY KEY (`id`)\n"
- ") DEFAULT CHARSET=utf8 COMMENT='Table that controls the processes' AUTO_INCREMENT=1 ;").format(
- defaultrev)
- self.sqlprocapps = ('CREATE TABLE IF NOT EXISTS `procapps` (\n'
- ' `id` INT(11) NOT NULL AUTO_INCREMENT,\n'
- ' `name` VARCHAR(255) DEFAULT \'\',\n'
- ' `revcode` VARCHAR(255) DEFAULT \'\',\n'
- ' `appblobs` LONGBLOB,\n'
- ' PRIMARY KEY (`id`)\n'
- ') DEFAULT CHARSET=utf8 COMMENT=\'Table with information about apps\' AUTO_INCREMENT=1 ;')
- self.procappschecker = 'SELECT COUNT(*) AS antal FROM `procapps`'
- self.proctrchecker = 'SELECT COUNT(*) AS antal FROM `procctr`'
- self.procctrsetup = ('INSERT INTO procctr (appname)\n'
- 'VALUES\n'
- '("cmonapp"),\n'
- '("nmrcalculator"),\n'
- '("nmrcalibrate"),\n'
- '("nmrmeasure")')
- self.procctrcheck = "SHOW TABLES LIKE 'procctr'"
- self.changedefault = "UPDATE procctr SET cmd='ready' WHERE appname='nmrcalibrate';"
- self.bufferextender = 'SET GLOBAL net_buffer_length=1000000;'
- self.packetextender = 'SET GLOBAL max_allowed_packet=1000000000'
- self.dropprocctr = 'DROP TABLE IF EXISTS procctr;'
- def dropctr(self):
- try:
- wlog("M", "Attempting to drop procctr table")
- dbcursor = db.cursor(buffered=True)
- dbcursor.execute(self.dropprocctr)
- db.commit()
- dbcursor.close()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def dbinitializer(self):
- try:
- wlog("M", "Attempting to initialize database")
- cursor.execute(self.dbstart)
- db.commit()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def restrictionremover(self):
- try:
- wlog("M", "Attempting to remove database restrictions")
- cursor.execute(self.bufferextender)
- db.commit()
- cursor.execute(self.packetextender)
- db.commit()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def changedefaults(self):
- try:
- wlog("M", "Attempting to change defaults")
- dbcursor = db.cursor(buffered=True)
- dbcursor.execute(self.changedefault)
- db.commit()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def dbtablesetup(self):
- try:
- wlog("M", "Attempting to setup tables")
- global cursor
- cursor.close()
- cursor = db.cursor(buffered=True)
- cursor.execute(self.proctrchecker)
- db.commit()
- procctr = cursor.fetchone()[0]
- if procctr is 0:
- wlog("M", "Setting up procctr table with default values")
- cursor.execute(self.procctrsetup)
- db.commit()
- elif procctr is not 0:
- wlog("M", "Procctr table defaults already in place")
- cursor.close()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def crtproccontroller(self):
- try:
- wlog("M", "Attempting to create procctr table")
- # create proc controller if it doesn't exist
- global cursor
- cursor.close()
- cursor = db.cursor(buffered=True)
- cursor.execute(self.sqlprocctr)
- db.commit()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def crtprocapps(self):
- try:
- wlog("M", "Attempting to create procctr table")
- global cursor
- cursor = db.cursor(buffered=True)
- cursor.execute(self.procctrcheck)
- db.commit()
- if cursor.fetchone()[0] is None:
- wlog("D", "Couldn't fetch procctr because it doesn't exist, creating it")
- cursor.execute(self.sqlprocapps)
- db.commit()
- cursor.close()
- wlog("M", "Success")
- elif cursor.fetchone()[0] > 0:
- wlog("M", "Procctr table already exists, no reason to create it")
- else:
- cursor.execute(self.sqlprocapps)
- db.commit()
- cursor.close()
- wlog("M", "Success")
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- except Exception as err:
- wlog("D", "Caught exception: {}".format(err.message))
- class InitialReader:
- def __init__(self, host, database):
- self.host = host
- self.database = database
- self.connectsucces = False
- @staticmethod
- def connect(self):
- attempts = 0
- while True:
- try:
- dbconfig = {
- 'user': "catmin",
- 'password': "nano4a",
- 'host': self.host,
- 'database': self.database,
- 'raise_on_warnings': True,
- 'use_pure': False,
- }
- wlog("M", "Attempting to connect to {}, currently at attempt: {}".format(self.host, attempts))
- global db
- global cursor
- db = mysql.connector.connect(**dbconfig)
- cursor = db.cursor(buffered=True)
- db.database = self.database
- self.connectsucces = True
- wlog("M", "Succesfully connected to {} on attempt #{}".format(self.host, attempts))
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- wlog("D", "Try number: {} | Retrying on ip: {}".format(attempts, self.host))
- time.sleep(7)
- self.connectsucces = False
- attempts += 1
- if attempts == 20:
- wlog("D", "Rebooting because max attempts reached")
- os.system("shutdown -t 0 -r -f")
- continue
- wlog("M", "Done with attempt")
- break
- def rdefrev(self):
- if self.connectsucces:
- try:
- result = self.defrevfetch(self.getprocappids())
- wlog("M", "Selected revision from procctr table: {}".format(result))
- return result
- except Exception as err:
- wlog("D", "Caught an exception: ".format(err.message))
- def defrevfetch(self, procappsids):
- result = None
- try:
- wlog("M", "Attempting to get revision from procctr table")
- statement = 'SELECT revision FROM procctr WHERE appname = "cmonapp"'
- cursor.execute(statement)
- db.commit()
- result = cursor.fetchone()[0]
- wlog("M", "Succesfully retrieved cmonrev value from procctr table")
- wlog("M", "Result revision: {}".format(result))
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- global cmonrevbaseline
- global nmrcalcrevbaseline
- global nmrmeasurerevbaseline
- global nmrcalirevbaseline
- try:
- if result in procappsids:
- wlog("M", "Attempting to assign result to global baseline")
- cmonrevbaseline = result
- nmrcalcrevbaseline = result
- nmrmeasurerevbaseline = result
- nmrcalirevbaseline = result
- wlog("M", "Succesfully assigned result to global baseline")
- return result
- else:
- wlog("M", "Attempting to assign max id from procapps to global baseline")
- statement = 'SELECT MAX(id) FROM procapps;'
- cursor.execute(statement)
- result = cursor.fetchone()[0]
- cmonrevbaseline = result
- nmrcalcrevbaseline = result
- nmrmeasurerevbaseline = result
- nmrcalirevbaseline = result
- wlog("M", "Succesfully assigned max id from procapps to global baseline")
- return result
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- def getprocappids(self):
- try:
- wlog("M", "Attempting to fetch all ids from procapps")
- statement = 'SELECT id FROM procapps'
- cursor.execute(statement)
- db.commit()
- return [str(item[0]) for item in cursor.fetchall()]
- except Exception as err:
- wlog("D", err.message)
- class DbInteractor:
- def __init__(self):
- self.cnx = None
- self.dbcursor = None
- self.sqlprocapps = ('CREATE TABLE IF NOT EXISTS `procapps` (\n'
- ' `id` INT(11) NOT NULL AUTO_INCREMENT,\n'
- ' `name` VARCHAR(20) DEFAULT \'\',\n'
- ' `revcode` VARCHAR(255) DEFAULT \'\',\n'
- ' `appblobs` LONGBLOB,\n'
- ' PRIMARY KEY (`id`)\n'
- ') DEFAULT CHARSET=utf8 COMMENT=\'Table with information about apps\' AUTO_INCREMENT=1 ;')
- self.dbstart = 'CREATE DATABASE IF NOT EXISTS `apphandler`'
- self.dbcheck = 'SHOW DATABASES LIKE "apphandler";'
- self.tablecheck = 'SHOW TABLES LIKE "procapps";'
- def iblob(self, filepath, ip, username, password, appname, revcode, autoupdateall):
- confignodb = {
- 'user': username,
- 'password': password,
- 'host': ip,
- 'raise_on_warnings': True,
- 'use_pure': False,
- }
- connectsucces = None
- insertsuccess = False
- last_id = 0
- try:
- wlog("M", "Attempting to connect on {}".format(ip))
- self.cnx = mysql.connector.connect(**confignodb)
- self.dbcursor = self.cnx.cursor(buffered=True)
- connectsucces = True
- wlog("M", "Connected succesfully")
- except mysql.connector.Error as err:
- if err.errno == 2003:
- connectsucces = False
- if connectsucces:
- self.dbcursor.execute(self.dbcheck)
- self.cnx.commit()
- if not self.dbcursor.rowcount:
- wlog("M", "No database")
- self.dbcursor.execute(self.dbstart)
- self.cnx.commit()
- else:
- wlog("M", "Database already exists")
- packetextender = 'SET GLOBAL max_allowed_packet=1073741824;'
- self.dbcursor.execute(packetextender)
- self.cnx.commit()
- self.cnx.database = "apphandler"
- self.dbcursor = self.cnx.cursor(buffered=True)
- self.dbcursor.execute(self.tablecheck)
- self.cnx.commit()
- if not self.dbcursor.rowcount:
- try:
- # Create procapps table if it doesn't exist
- wlog("M", "Attempting to create procapps table")
- self.dbcursor.execute(self.sqlprocapps)
- self.cnx.commit()
- wlog("M", "Succesfully created procapps table")
- except mysql.connector.Error as err:
- wlog("D", "Something went wrong with creating the procapps table")
- wlog("D", "Error number: {} | Error Message {}".format(err.errno, err.msg))
- else:
- wlog("M", "Procapps table already exist already exists")
- if self.cnx and self.dbcursor is not None:
- wlog("M", "Deploying {} onto {}".format(filepath, ip))
- try:
- fileread = open(filepath, 'rb').read()
- sql = 'INSERT INTO procapps (appblobs, name, revcode) VALUES (_binary %s,_binary %s,_binary %s)'
- self.dbcursor.execute(sql, (fileread, appname, revcode))
- self.cnx.commit()
- last_id = self.dbcursor.getlastrowid()
- insertsuccess = True
- self.dbcursor.close()
- except mysql.connector.Error as err:
- wlog("M", "Error number: {} | Error Message {}".format(err.errno, err.msg))
- if insertsuccess and autoupdateall:
- update_success = self.autoupdater(self.cnx, 'all', last_id)
- if not update_success:
- wlog("M", "failed to autostart")
- else:
- wlog("M", "successfully managed to autostart")
- else:
- wlog("M", "Could not connect to chosen host, please attempt a different ip")
- def autoupdater(self, cnx, apptype, revid):
- CTRL_TABLE_EXIST = 'SHOW TABLES LIKE "procctr"'
- CTRL_TABLE_UPDATE_ALL = 'UPDATE procctr set revision = {revcode}, cmd="update"'
- update_success = False
- poll_cnt = 60
- cursor = cnx.cursor()
- cursor.execute(CTRL_TABLE_EXIST)
- cursor.fetchall()
- if cursor.rowcount > 0:
- q = CTRL_TABLE_UPDATE_ALL.format(revcode=revid)
- cursor.execute(q)
- cnx.commit()
- while True:
- q = 'SELECT COUNT(id) from procctr WHERE cmd = "ready" AND status = "running" AND revision = {}'
- cursor.execute(q.format(revid))
- res = cursor.fetchall()
- cnx.commit()
- if res[0][0] >= 4:
- update_success = True
- break
- if poll_cnt < 0:
- break
- poll_cnt = poll_cnt - 1
- time.sleep(5)
- wlog("M", "waiting for update (and autostart all) to complete of revision =" + str(revid))
- return update_success
- def readblob(self, outputpath, idtag, outputname):
- wlog("M", "Reading blob with id: {}".format(idtag))
- ospath = os.path.join(outputpath, str(idtag)).replace('\\', '/')
- ospathwithname = os.path.join(outputpath, str(idtag), outputname).replace('\\', '/')
- while True:
- try:
- if not os.path.exists(ospath):
- wlog("M", "Creating directory: {}".format(ospath))
- try:
- os.makedirs(ospath)
- wlog("M", "Succesfully created path to place blob into")
- except Exception as err:
- wlog("D",
- "Exception caught while creating: {} | Error Message {}".format(ospath, err.message))
- with open(ospathwithname, "wb+") as output_file:
- try:
- global cursor
- cursor = db.cursor(buffered=True)
- sql = 'SELECT appblobs FROM procapps WHERE id = %s'
- cursor.execute(sql, (idtag,))
- db.commit()
- ablob = cursor.fetchone()
- output_file.write(ablob[0])
- except Exception as err:
- print(type(err).__name__)
- wlog("D", "Exception caught while unzipping: {} | Error Message {}".format(ospathwithname,
- err.message))
- except Exception as err:
- wlog("D", "Could not find a blob with id: {}".format(idtag))
- wlog("D", "Error: {}".format(err.message))
- time.sleep(10)
- continue
- break
- class ZipHandler:
- def __init__(self):
- pass
- def unzip(self, outpath, outname, revision, archivename):
- try:
- zippath = os.path.join(outpath, str(revision), outname)
- archivepath = os.path.join(outpath, str(revision), archivename)
- wlog("M", "Zip path: {}".format(zippath))
- wlog("M", "Zip unzip path: {}".format(archivepath))
- with zipfile.ZipFile(zippath, "r") as zip_ref:
- if os.path.exists(archivepath) is False:
- zip_ref.extractall(archivepath)
- elif os.path.exists(archivepath):
- shutil.rmtree(archivepath, ignore_errors=True)
- zip_ref.extractall(archivepath)
- except Exception as err:
- wlog("D", "Caught exception, message: {}".format(err.message))
- class ProcHandler:
- def __init__(self):
- pass
- def running(self, appname):
- name = None
- if appname == "cmonapp.exe":
- name = appname.replace(".exe", "")
- elif appname == "nmrcalibrate.exe":
- name = appname.replace(".exe", "")
- elif appname == "nmrcalculatorapp.exe":
- name = appname.replace("app.exe", "")
- elif appname == "nmrmeasureapp.exe":
- name = appname.replace("app.exe", "")
- dbcursor = db.cursor()
- wlog("M", "Process not running: {}".format(name))
- statussql = 'UPDATE apphandler.procctr SET status = "running" WHERE appname = %s'
- dbcursor.execute(statussql, (name,))
- db.commit()
- def startproc(self, revision, firstpath, secondpath, ip, exename):
- si = subprocess.STARTUPINFO()
- # si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
- si.wShowWindow = subprocess.SW_HIDE
- if exename == 'cmonapp.exe':
- start = True
- procs = list(psutil.process_iter())
- for proc in procs:
- if exename == proc.name():
- start = False
- break
- if start:
- wlog("M", "Starting {}".format(exename))
- path = os.path.join(firstpath, str(revision), secondpath).replace("/", "\\")
- result = subprocess.Popen([path, "ip", ip],
- creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=si)
- wlog("M", result)
- if result is not None:
- wlog("M", "{} succesfully started".format(exename))
- self.running(exename.replace(".exe", ""))
- return result
- elif exename == 'nmrcalculatorapp.exe':
- start = True
- procs = list(psutil.process_iter())
- for proc in procs:
- if exename == proc.name():
- start = False
- break
- if start:
- wlog("M", "Starting {}".format(exename))
- path = os.path.join(firstpath, str(revision), secondpath).replace("/", "\\")
- result = subprocess.Popen(
- [path, "ip", ip, "treatAsLocal", "True"],
- creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=si)
- wlog("M", result)
- if result is not None:
- wlog("M", "{} succesfully started".format(exename))
- self.running(exename.replace(".exe", ""))
- return result
- elif exename == 'nmrcalibrate.exe':
- start = True
- procs = list(psutil.process_iter())
- for proc in procs:
- if exename == proc.name():
- start = False
- break
- if start:
- wlog("M", "Starting {}".format(exename))
- path = os.path.join(firstpath, str(revision), secondpath).replace("/", "\\")
- result = subprocess.Popen([path, "ip", ip],
- creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=si)
- wlog("M", result)
- if result is not None:
- wlog("M", "{} succesfully started".format(exename))
- self.running(exename.replace(".exe", ""))
- return result
- elif exename == 'nmrmeasureapp.exe':
- start = True
- procs = list(psutil.process_iter())
- for proc in procs:
- if exename == proc.name():
- start = False
- break
- if start:
- wlog("M", "Starting {}".format(exename))
- path = os.path.join(firstpath, str(revision), secondpath).replace("/", "\\")
- result = subprocess.Popen(
- [path, "ip", ip, "treatAsLocal", "True"],
- creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=si)
- wlog("M", result)
- if result is not None:
- wlog("M", "{} succesfully started".format(exename))
- self.running(exename.replace(".exe", ""))
- return result
- else:
- wlog("M", "No recognizeable executeable name")
- def stpprocwname(self, exename):
- printvar = False
- for proc in psutil.process_iter():
- if proc.name() == exename:
- try:
- proc.kill()
- printvar = True
- except Exception as err:
- print("D", "Caught exception: {}".format(err))
- if printvar is True:
- wlog("M", "Killing {}".format(exename))
- elif printvar is False:
- wlog("M", "No {} to kill".format(exename))
- def stpprocwproc(self, proc, appname):
- try:
- global cursor
- cursor = db.cursor(buffered=True)
- db.database = "apphandler"
- if proc is not None:
- proc.kill()
- time.sleep(1)
- wlog("M", "Process not running: {}".format(appname))
- statussql = 'UPDATE procctr SET status = "stopped" WHERE appname = %s'
- cursor.execute(statussql, (appname,))
- db.commit()
- cursor.close()
- else:
- wlog("M", "Did not find any process to kill: {}".format(appname))
- except Exception as err:
- print("D", "Caught exception: {}".format(err))
- def stpappswproc(self, cmonproc, calcproc, calibrateproc, measureproc):
- if cmonproc is not None:
- self.stpprocwproc(cmonproc, "cmonapp")
- else:
- wlog("M", "Can't stop because process doesn't exist")
- if calcproc is not None:
- self.stpprocwproc(calcproc, "nmrcalculator")
- else:
- wlog("M", "Can't stop because process doesn't exist")
- if calibrateproc is not None:
- self.stpprocwproc(calibrateproc, "nmrcalibrate")
- else:
- wlog("M", "Can't stop because process doesn't exist")
- if measureproc is not None:
- self.stpprocwproc(measureproc, "nmrmeasure")
- else:
- wlog("M", "Can't stop because process doesn't exist")
- def stopallapps(self):
- self.stpprocwname("cmonapp.exe")
- self.stpprocwname("nmrcalculatorapp.exe")
- self.stpprocwname("nmrcalibrate.exe")
- self.stpprocwname("nmrmeasureapp.exe")
- time.sleep(3)
- class DbCmdChecker:
- def __init__(self, connectionobject):
- self.statuschecker = True
- self.setallcmdstostart = False
- self.cmonproc = None
- self.nmrmeasureproc = None
- self.nmrcalculatorproc = None
- self.nmrcalibrateproc = None
- self.cmoncmd = None
- self.nmrcalccmd = None
- self.nmrcalicmd = None
- self.nmrmeasurecmd = None
- self.cmonrev = None
- self.nmrcalcrev = None
- self.nmrcalirev = None
- self.nmrmeasurerev = None
- self.connectionobject = connectionobject
- self.attempts = 0
- def checkdb(self, interval, firstpathtocmon, secondpathtocmon, cmonexename, firstpathtocalibrate,
- secondpathtocalibrate, calibrateexename, firstpathtocalc, secondpathtocalc,
- calcexename, firstpathtomeasure, secondpathtomeasure, measureexename, ip):
- while True:
- wlog("M", "--------------------------------------------")
- programstabilizer()
- self.fetchcmds()
- self.ftchrevs()
- self.gbcollector()
- self.insertip()
- if self.setallcmdstostart:
- self.updatecmds()
- self.setallcmdstostart = False
- # Cmon handling
- if firstpathtocmon is None:
- wlog("M", "No executable path to cmon")
- elif firstpathtocmon is not None:
- self.dchndlrcmon(self.cmonrev, firstpathtocmon, secondpathtocmon, ip, cmonexename)
- # calibrate handling
- if firstpathtocalibrate is None:
- wlog("M", "No executable path to nmrcalibrate")
- elif firstpathtocalibrate is not None:
- self.dchandlrcali(self.nmrcalirev, firstpathtocalibrate, secondpathtocalibrate, ip,
- calibrateexename)
- # calchandling
- if firstpathtocalc is None:
- wlog("M", "No executable path to nmrcalculator")
- elif firstpathtocalc is not None:
- self.dchandlrcalc(self.nmrcalcrev, firstpathtocalc, secondpathtocalc, ip, calcexename)
- # measurehandling
- if firstpathtomeasure is None:
- wlog("M", "No executable path to nmrmeasure")
- elif firstpathtomeasure is not None:
- self.dchandlrmeasure(self.nmrmeasurerev, firstpathtomeasure, secondpathtomeasure, ip,
- measureexename)
- time.sleep(interval)
- cursor.close()
- def fetchcmds(self):
- while True:
- try:
- wlog("M", "Fetching commands")
- global cursor
- cursor = db.cursor(buffered=True)
- cmonsql = "SELECT cmd FROM procctr WHERE appname = 'cmonapp'"
- nmrcalcsql = "SELECT cmd FROM procctr WHERE appname = 'nmrcalculator'"
- nmrcalibratesql = "SELECT cmd FROM procctr WHERE appname = 'nmrcalibrate'"
- nmrmeasureappsql = "SELECT cmd FROM procctr WHERE appname = 'nmrmeasure'"
- cursor.execute(cmonsql)
- db.commit()
- self.cmoncmd = cursor.fetchone()[0]
- cursor.execute(nmrcalcsql)
- db.commit()
- self.nmrcalccmd = cursor.fetchone()[0]
- cursor.execute(nmrcalibratesql)
- db.commit()
- self.nmrcalicmd = cursor.fetchone()[0]
- cursor.execute(nmrmeasureappsql)
- db.commit()
- self.nmrmeasurecmd = cursor.fetchone()[0]
- wlog("M", "Got cmds: Cmon {} | Nmrcalc {} | Nmrcalicmd {} | Nmrmeasure {}".format(self.cmoncmd,
- self.nmrcalccmd,
- self.nmrcalicmd,
- self.nmrmeasurecmd))
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- InitialReader.connect(self.connectionobject)
- continue
- break
- def ftchrevs(self):
- while True:
- try:
- wlog("M", "Fetching revisions")
- global cursor
- cursor = db.cursor(buffered=True)
- cmonrevsql = "SELECT revision FROM procctr WHERE appname = 'cmonapp'"
- nmrcalcrevsql = "SELECT revision FROM procctr WHERE appname = 'nmrcalculator'"
- nmrcalirevsql = "SELECT revision FROM procctr WHERE appname = 'nmrcalibrate'"
- nmrmeasurerevsql = "SELECT revision FROM procctr WHERE appname = 'nmrmeasure'"
- cursor.execute(cmonrevsql)
- db.commit()
- self.cmonrev = cursor.fetchone()[0]
- cursor.execute(nmrcalcrevsql)
- db.commit()
- self.nmrcalcrev = cursor.fetchone()[0]
- cursor.execute(nmrcalirevsql)
- db.commit()
- self.nmrcalirev = cursor.fetchone()[0]
- cursor.execute(nmrmeasurerevsql)
- db.commit()
- self.nmrmeasurerev = cursor.fetchone()[0]
- wlog("M", "Got revisions: Cmon {} | Nmrcalc {} | Nmrcalicmd {} | Nmrmeasure {}".format(self.cmonrev,
- self.nmrcalcrev,
- self.nmrcalirev,
- self.nmrmeasurerev))
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- InitialReader.connect(self.connectionobject)
- continue
- break
- def insertip(self):
- ip = socket.gethostbyname(socket.gethostname())
- try:
- global db
- global cursor
- db.database = "tsl"
- checktable = "SHOW TABLES like 'ipinfo'"
- createtable = ('CREATE TABLE IF NOT EXISTS `ipinfo` (\n'
- ' `id` INT(11) NOT NULL AUTO_INCREMENT,\n'
- ' `ip` VARCHAR(255) DEFAULT \'\',\n'
- ' `platform` VARCHAR(255) DEFAULT \'\',\n'
- ' `uptime` LONGBLOB,\n'
- ' PRIMARY KEY (`id`)\n'
- ') DEFAULT CHARSET=utf8 COMMENT=\'Table with information about apps\' AUTO_INCREMENT=1 ;')
- # updateip = "UPDATE {} SET {}=\"{}\" WHERE id={}".format("ipinfo", "ip", ip, 1)
- update = "REPLACE INTO {} ({}, {}, {}, {}) VALUES ({}, '{}', '{}', '{}');".format("ipinfo", "id", "ip",
- "platform", "uptime", 1,
- ip, platform.platform(),
- uptime())
- cursor.execute(checktable)
- if cursor.fetchone()[0] > 0:
- wlog("M", "Ipinfo table already exists, no reason to create it")
- else:
- wlog("M", "Creating Ipinfo table and replacing ip")
- cursor.execute(createtable)
- db.commit()
- cursor.execute(update)
- db.commit()
- db.database = "apphandler"
- except mysql.connector.Error as err:
- db.rollback()
- wlog("D", "Caught a mysql exception | number: {} | message: {}".format(err.errno, err.msg))
- def updatebundler(self, revision):
- global cmonrevbaseline
- global nmrcalcrevbaseline
- global nmrmeasurerevbaseline
- global nmrcalirevbaseline
- wlog("M",
- "BU| Base / Cmonrev {} / {} | Base / Measurerev {} / {} | Base / Calcrev {} / {} | Base / Calirev {} / {}".format(
- cmonrevbaseline, self.cmonrev, nmrmeasurerevbaseline, self.nmrmeasurerev, nmrcalcrevbaseline,
- self.nmrcalcrev, nmrcalirevbaseline, self.nmrcalirev))
- if self.cmonrev != cmonrevbaseline:
- self.updateaction(revision, self.cmonrev)
- elif self.nmrcalcrev != nmrcalcrevbaseline:
- self.updateaction(revision, self.nmrcalcrev)
- elif self.nmrmeasurerev != nmrmeasurerevbaseline:
- self.updateaction(revision, self.nmrmeasurerev)
- elif self.nmrcalirev != nmrcalirevbaseline:
- self.updateaction(revision, self.nmrcalirev)
- wlog("M",
- "AU| Base / Cmonrev {} / {} | Base / Measurerev {} / {} | Base / Calcrev {} / {} | Base / Calirev {} / {}".format(
- cmonrevbaseline, self.cmonrev, nmrmeasurerevbaseline, self.nmrmeasurerev, nmrcalcrevbaseline,
- self.nmrcalcrev, nmrcalirevbaseline, self.nmrcalirev))
- def settoupdateall(self):
- names = ["cmonapp", "nmrcalculator", "nmrmeasure", "nmrcalibrate"]
- for element in names:
- try:
- wlog("M", "Attempting to set status to update")
- db.database = "apphandler"
- name = element
- wlog("M", "Appname: {}".format(name))
- cmdupdate = 'UPDATE procctr SET status = "updating" WHERE appname = "{}"'.format(name)
- cur = db.cursor(buffered=True)
- cur.execute(cmdupdate)
- db.commit()
- wlog("M", "Succesfully set status for {} to update".format(name))
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- def settoupdate(self, appname):
- try:
- wlog("M", "Attempting to set status to update")
- db.database = "apphandler"
- name = appname.split('.')[0]
- wlog("M", "Appname: {}".format(name))
- cmdupdate = 'UPDATE procctr SET status = "updating" WHERE appname = "{}"'.format(name)
- cur = db.cursor(buffered=True)
- cur.execute(cmdupdate)
- db.commit()
- wlog("M", "Succesfully set status for {} to update".format(name))
- except mysql.connector.Error as err:
- wlog("D", "Mysql Connection Error: {} | Message: {}".format(err.msg, err.errno))
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- def updateaction(self, revision, procrevision):
- # Reset process state
- prochandler = ProcHandler()
- prochandler.stpappswproc(self.cmonproc, self.nmrcalculatorproc, self.nmrcalibrateproc,
- self.nmrmeasureproc)
- wlog("M", "Attempting to update procrev: {}".format(procrevision))
- self.settoupdateall()
- # Read specified blob from database
- dbint = DbInteractor()
- dbint.readblob(os.path.expanduser("~/artifacts/"), revision, "output.zip")
- # Unzip the zip file
- zipper = ZipHandler()
- zipper.unzip(os.path.expanduser("~/artifacts/"), "output.zip", revision, "")
- self.updateglobalrevs(procrevision)
- self.updateobjectrevs(procrevision)
- self.updaterevisions(revision)
- self.setallcmdstostart = True
- wlog("M", "Succesfully updated to procrev: {}".format(procrevision))
- wlog("M", "procrev: {}".format(procrevision))
- def updateglobalrevs(self, procrevision):
- global cmonrevbaseline
- global nmrmeasurerevbaseline
- global nmrcalirevbaseline
- global nmrcalcrevbaseline
- cmonrevbaseline = procrevision
- nmrmeasurerevbaseline = procrevision
- nmrcalirevbaseline = procrevision
- nmrcalcrevbaseline = procrevision
- def updateobjectrevs(self, procrevision):
- self.cmonrev = procrevision
- self.nmrcalirev = procrevision
- self.nmrcalcrev = procrevision
- self.nmrmeasurerev = procrevision
- def ready(self, appname):
- if appname == "cmonapp.exe":
- name = appname.replace(".exe", "")
- if appname == "nmrcalibrate.exe":
- name = appname.replace(".exe", "")
- if appname == "nmrcalculatorapp.exe":
- name = appname.replace("app.exe", "")
- if appname == "nmrmeasureapp.exe":
- name = appname.replace("app.exe", "")
- dbcursor = db.cursor()
- cmdreset = 'UPDATE apphandler.procctr SET cmd = "ready" WHERE appname = %s'
- dbcursor.execute(cmdreset, (name,))
- db.commit()
- def updatecmds(self):
- try:
- wlog("M", "Updating commands")
- self.cmoncmd = "start"
- self.nmrcalccmd = "start"
- self.nmrmeasurecmd = "start"
- self.nmrcalicmd = "start"
- wlog("M", "Succesfully updated commands")
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- def updaterevisions(self, revision):
- try:
- wlog("M", "Attempting to update revisions")
- revcodesql = 'UPDATE procctr SET revision = %s WHERE appname = %s'
- cur = db.cursor(buffered=True)
- cur.execute(revcodesql, (revision, "cmonapp"))
- db.commit()
- cur.execute(revcodesql, (revision, "nmrcalculator"))
- db.commit()
- cur.execute(revcodesql, (revision, "nmrcalibrate"))
- db.commit()
- cur.execute(revcodesql, (revision, "nmrmeasure"))
- db.commit()
- wlog("M", "Fetched revisions successfully")
- except Exception as err:
- wlog("D", "Caught an exception: {}".format(err.message))
- def dchndlrcmon(self, revision, firstpath, secondpath, ip, exename):
- if self.cmoncmd == 'start':
- wlog("M", "Attempting to launch cmon")
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.cmonproc = localproc
- self.ready(exename)
- elif self.cmoncmd == 'stop':
- prochandler = ProcHandler()
- prochandler.stpprocwproc(self.cmonproc, "cmonapp")
- self.ready(exename)
- elif self.cmoncmd == 'update':
- self.statuschecker = None
- self.updatebundler(revision)
- self.ready(exename)
- self.statusupdater(self.cmonproc, "cmonapp", firstpath, secondpath, ip, exename, revision)
- def dchandlrcalc(self, revision, firstpath, secondpath, ip, exename):
- if self.nmrcalccmd == 'start':
- wlog("M", "Attempting to launch nmrcalculator")
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrcalculatorproc = localproc
- self.ready(exename)
- elif self.nmrcalccmd == 'stop':
- prochandler = ProcHandler()
- prochandler.stpprocwproc(self.nmrcalculatorproc, "nmrcalculator")
- self.ready(exename)
- elif self.nmrcalccmd == 'update':
- self.updatebundler(revision)
- self.ready(exename)
- self.statusupdater(self.nmrcalculatorproc, "nmrcalculator", firstpath, secondpath, ip, exename, revision)
- def dchandlrcali(self, revision, firstpath, secondpath, ip, exename):
- if self.nmrcalicmd == 'start':
- wlog("M", "Attempting to launch nmrcalibrate")
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrcalibrateproc = localproc
- self.ready(exename)
- elif self.nmrcalicmd == 'stop':
- prochandler = ProcHandler()
- prochandler.stpprocwproc(self.nmrcalibrateproc, "nmrcalibrate")
- self.ready(exename)
- elif self.nmrcalicmd == 'update':
- self.updatebundler(revision)
- self.ready(exename)
- self.statusupdater(self.nmrcalibrateproc, "nmrcalibrate", firstpath, secondpath, ip, exename, revision)
- def dchandlrmeasure(self, revision, firstpath, secondpath, ip, exename):
- if self.nmrmeasurecmd == 'start':
- wlog("M", "Attempting to launch nmrmeasure")
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrmeasureproc = localproc
- self.ready(exename)
- elif self.nmrmeasurecmd == 'stop':
- prochandler = ProcHandler()
- prochandler.stpprocwproc(self.nmrmeasureproc, "nmrmeasure")
- self.ready(exename)
- elif self.nmrmeasurecmd == 'update':
- self.updatebundler(revision)
- self.ready(exename)
- self.statusupdater(self.nmrmeasureproc, "nmrmeasure", firstpath, secondpath, ip, exename, revision)
- def statusupdater(self, proc, appname, firstpath, secondpath, ip, exename, revision):
- global cursor
- cursor = db.cursor(buffered=True)
- db.database = "apphandler"
- cmonsql = "SELECT status FROM procctr WHERE appname = 'cmonapp'"
- nmrcalcsql = "SELECT status FROM procctr WHERE appname = 'nmrcalculator'"
- nmrcalibratesql = "SELECT status FROM procctr WHERE appname = 'nmrcalibrate'"
- nmrmeasureappsql = "SELECT status FROM procctr WHERE appname = 'nmrmeasure'"
- if proc is not None:
- status = proc.poll()
- wlog("M", "Status for proc: {}".format(status))
- time.sleep(2)
- statussecond = proc.poll()
- wlog("M", "Status for proc: {}".format(statussecond))
- else:
- status = 1
- statussecond = 1
- self.supdatenmrcmon(appname, cmonsql, cursor, exename, firstpath, ip, revision, secondpath, status,
- statussecond)
- self.supdatenmrcalc(appname, cursor, exename, firstpath, ip, nmrcalcsql, revision, secondpath, status,
- statussecond)
- self.supdatenmrcali(appname, cursor, exename, firstpath, ip, nmrcalibratesql, revision, secondpath, status,
- statussecond)
- self.supdatenmrmeasure(appname, cursor, exename, firstpath, ip, nmrmeasureappsql, revision, secondpath, status,
- statussecond)
- if proc is not None:
- if status is None:
- try:
- cursor = db.cursor(buffered=True)
- wlog("M", "Proc running, attempting to update cmd for: {}".format(appname))
- statussql = "UPDATE procctr SET status = 'running' WHERE appname = '{}'".format(appname)
- cursor.execute(statussql)
- db.commit()
- wlog("M", "Succesfully updated cmd for {}".format(appname))
- except Exception as err:
- wlog("D", "Caught exception while updating cmd for: {}".format(appname))
- wlog("D", "Exception: {}".format(err))
- else:
- try:
- wlog("M", "Process not running attempting to update cmd for: {}".format(appname))
- cursor = db.cursor(buffered=True)
- statussql = "UPDATE procctr SET status = 'stopped' WHERE appname = '{}'".format(appname)
- cursor.execute(statussql)
- db.commit()
- wlog("M", "Succesfully updated cmd for {}".format(appname))
- except Exception as err:
- wlog("D", "Caught exception while updating cmd for: {}".format(appname))
- wlog("D", "Exception: {}".format(err))
- cursor.close()
- def supdatenmrcmon(self, appname, cmonsql, dbcursor, exename, firstpath, ip, revision, secondpath, status, statussecond):
- if appname == 'cmonapp':
- if status is not None:
- # Status for cmon
- dbcursor.execute(cmonsql)
- db.commit()
- cmonstatus = dbcursor.fetchone()[0]
- wlog("M", "Status for: {} - {}".format(appname, cmonstatus))
- if cmonstatus == 'running':
- if statussecond is None:
- wlog("M", "{} has uptime".format(appname))
- else:
- wlog("M", "{} no uptime, attempting to start".format(appname))
- self.cmoncmd = 'failed'
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.cmonproc = localproc
- time.sleep(3)
- if self.nmrcalibrateproc.poll() is not None:
- self.supdatenmrcmon(appname, dbcursor, exename, firstpath, ip, cmonsql, revision, secondpath, status, statussecond)
- def supdatenmrcalc(self, appname, dbcursor, exename, firstpath, ip, nmrcalcsql, revision, secondpath, status, statussecond):
- if appname == 'nmrcalculator':
- if status is not None:
- # Status for cmon
- dbcursor.execute(nmrcalcsql)
- db.commit()
- nmrcalcstatus = dbcursor.fetchone()[0]
- ("M", "Status for: {} - {}".format(appname, nmrcalcstatus))
- if nmrcalcstatus == 'running':
- if statussecond is None:
- wlog("M", "{} has uptime".format(appname))
- else:
- wlog("M", "{} no uptime, attempting to start".format(appname))
- self.nmrcalccmd = 'failed'
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrcalculatorproc = localproc
- time.sleep(3)
- if localproc.poll() is not None:
- self.supdatenmrcalc(appname, dbcursor, exename, firstpath, ip, nmrcalcsql, revision, secondpath, status, statussecond)
- else:
- wlog("M", "{} started correctly".format(appname))
- def supdatenmrcali(self, appname, dbcursor, exename, firstpath, ip, nmrcalibratesql, revision, secondpath, status, statussecond):
- if appname == 'nmrcalibrate':
- if status is not None:
- # Status for cmon
- dbcursor.execute(nmrcalibratesql)
- db.commit()
- nmrcalistatus = dbcursor.fetchone()[0]
- ("M", "Status for: {} - {}".format(appname, nmrcalistatus))
- if nmrcalistatus == 'running':
- if statussecond is None:
- wlog("M", "{} has uptime".format(appname))
- else:
- wlog("M", "{} no uptime, attempting to start".format(appname))
- self.nmrcalicmd = 'failed'
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrcalibrateproc = localproc
- time.sleep(3)
- if localproc.poll() is not None:
- self.supdatenmrcali(appname, dbcursor, exename, firstpath, ip, nmrcalibratesql, revision, secondpath, status, statussecond)
- else:
- wlog("M", "{} started correctly".format(appname))
- def supdatenmrmeasure(self, appname, dbcursor, exename, firstpath, ip, nmrmeasureappsql, revision, secondpath, status, statussecond):
- if appname == 'nmrmeasure':
- if status is not None:
- # Status for cmon
- dbcursor.execute(nmrmeasureappsql)
- db.commit()
- nmrmeasurestatus = dbcursor.fetchone()[0]
- ("M", "Status for: {} - {}".format(appname, nmrmeasurestatus))
- if nmrmeasurestatus == 'running':
- if statussecond is None:
- wlog("M", "{} has uptime".format(appname))
- else:
- wlog("M", "{} no uptime, attempting to start".format(appname))
- self.nmrmeasurecmd = 'failed'
- prochandler = ProcHandler()
- localproc = prochandler.startproc(revision, firstpath, secondpath, ip, exename)
- if localproc is not None:
- self.nmrmeasureproc = localproc
- time.sleep(3)
- if localproc.poll() is not None:
- self.supdatenmrmeasure(appname, dbcursor, exename, firstpath, ip, nmrmeasureappsql, revision, secondpath, status, statussecond)
- else:
- wlog("M", "{} started correctly".format(appname))
- def scanartifacts(self):
- import os
- root = os.path.expanduser("~/artifacts/")
- return [item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item))]
- def gbcollector(self):
- global cmonrevbaseline
- global nmrcalcrevbaseline
- global nmrcalirevbaseline
- global nmrmeasurerevbaseline
- revlist = [str(cmonrevbaseline), str(nmrcalcrevbaseline), str(nmrcalirevbaseline), str(nmrmeasurerevbaseline)]
- directorylist = self.scanartifacts()
- removallist = []
- for element in directorylist:
- if element not in revlist:
- wlog("M", "Directory set to be deleted: {}".format(element))
- removallist.append(element)
- if not removallist:
- wlog("M", "Nothing to remove")
- else:
- for element in removallist:
- wlog("M", "Removing directory: {}".format(element))
- shutil.rmtree(os.path.expanduser("~/artifacts/{}".format(element)))
- def connectionkiller():
- try:
- wlog("M", "Attempting to kill cursor and connection")
- global cursor
- global db
- cursor.close()
- db.close()
- except mysql.connector.Error as err:
- wlog("D", "Caught mysql error number: {} | message: {}".format(err.errno, err.msg))
- WATCHED_FILES = [__file__]
- WATCHED_FILES_MTIMES = [(f, os.path.getmtime(f)) for f in WATCHED_FILES]
- def programstabilizer():
- global WATCHED_FILES
- global WATCHED_FILES_MTIMES
- for f, mtime in WATCHED_FILES_MTIMES:
- if os.path.getmtime(f) != mtime:
- wlog("M", "script has changed restarting it")
- if platform.system() == 'Linux':
- os.system('clear')
- os.execv(__file__, sys.argv)
- elif platform.system() == 'Windows':
- os.system('cls')
- os.execv(sys.executable, ['python'] + sys.argv)
- def restartifclosed():
- wlog("M", "script has changed, restarting it")
- # When running the script via `./pywin.py` (e.g. Linux/Mac OS), use
- if platform.system() == 'Linux':
- os.execv(__file__, sys.argv)
- elif platform.system() == 'Windows':
- # When running the script via `python pywin.py` (e.g. Windows), use
- os.execv(sys.executable, ['python'] + sys.argv)
- def argumentparsing():
- """Function that handles how the script handles arugments"""
- par = argparse.ArgumentParser(
- description="Pywin script for Nanonord")
- blobgrp = par.add_argument_group()
- blobgrp.add_argument("-bd", dest='bd', help="Deploy blob to database", action="store_true")
- blobgrp.add_argument("-fp", dest='fp', help="Specify filepath for blob", type=str)
- blobgrp.add_argument("-ho", dest='ho', help="Specify host ip", type=str)
- blobgrp.add_argument("-db", dest='db', help="Specify database", type=str)
- blobgrp.add_argument("-u", dest='u', default="catmin", help="Specify username", type=str)
- blobgrp.add_argument("-pw", dest='pw', default="nano4a", help="Specify password", type=str)
- blobgrp.add_argument("-pn", dest='pn', default="package", help="Specify packagename", type=str)
- blobgrp.add_argument("-r", dest='r', default="norev", help="Specify revision", type=str)
- blobgrp.add_argument(
- "--autoupdateall",
- dest='autoupdateall',
- help="Automatically force update if deploy is sucessfull",
- action="store_true")
- agentgrp = par.add_argument_group()
- agentgrp.add_argument("-a", help="runs the script as an agent", action="store_true")
- agentgrp.add_argument("-adb", dest='agentdb', default="192.168.210.120", help="Specify database where controller is", type=str)
- agentgrp.add_argument("-apdb", dest='appsdb', default="192.168.210.120", help="Specify what database apps should point to", type=str)
- args = par.parse_args()
- return args
- def executer(args):
- if args.a is True and args.agentdb and args.appsdb is not None:
- agentflow(args.agentdb, args.appsdb)
- if args.bd and args.fp and args.ho and args.db and args.u and args.pw and args.pn and args.r is not None:
- dbint = DbInteractor()
- dbint.iblob(args.fp, args.ho, args.u, args.pw, args.pn, args.r, args.autoupdateall)
- elif args.bd and args.ho and args.db and args.u and args.pw and args.pn and args.r is not None:
- wlog("M", "You didn't specify filepath")
- elif args.bd and args.fp and args.db and args.u and args.pw and args.pn and args.r is not None:
- wlog("M", "You didn't specify the host")
- elif args.bd and args.fp and args.ho and args.u and args.pw and args.pn and args.r is not None:
- wlog("M", "You didn't specify the database")
- _registered_exit_funs = set()
- _executed_exit_funs = set()
- def register_exit_fun(fun=None, signals=[signal.SIGTERM], logfun=lambda s: print(s, file=sys.stderr)):
- def stringify_sig(signum):
- if sys.version_info < (3, 5):
- smap = dict([(getattr(signal, x), x) for x in dir(signal)
- if x.startswith('SIG')])
- return smap.get(signum, signum)
- else:
- return signum
- def fun_wrapper():
- if fun not in _executed_exit_funs:
- try:
- fun()
- finally:
- _executed_exit_funs.add(fun)
- def signal_wrapper(signum=None, frame=None):
- if signum is not None:
- if logfun is not None:
- logfun("signal {} received by process with PID {}".format(
- stringify_sig(signum), os.getpid()))
- fun_wrapper()
- # Only return the original signal this process was hit with
- # in case fun returns with no errors, otherwise process will
- # return with sig 1.
- if signum is not None:
- if signum == signal.SIGINT:
- raise KeyboardInterrupt
- # XXX - should we do the same for SIGTERM / SystemExit?
- print(signum)
- sys.exit(signum)
- def register_fun(fun, signals):
- if not callable(fun):
- raise TypeError("{!r} is not callable".format(fun))
- set([fun]) # raise exc if obj is not hash-able
- signals = set(signals)
- for sig in signals:
- # Register function for this signal and pop() the previously
- # registered one (if any). This can either be a callable,
- # SIG_IGN (ignore signal) or SIG_DFL (perform default action
- # for signal).
- old_handler = signal.signal(sig, signal_wrapper)
- if old_handler not in (signal.SIG_DFL, signal.SIG_IGN):
- # ...just for extra safety.
- if not callable(old_handler):
- continue
- # This is needed otherwise we'll get a KeyboardInterrupt
- # strace on interpreter exit, even if the process exited
- # with sig 0.
- if (sig == signal.SIGINT and
- old_handler is signal.default_int_handler):
- continue
- # There was a function which was already registered for this
- # signal. Register it again so it will get executed (after our
- # new fun).
- if old_handler not in _registered_exit_funs:
- atexit.register(old_handler)
- _registered_exit_funs.add(old_handler)
- # This further registration will be executed in case of clean
- # interpreter exit (no signals received).
- if fun not in _registered_exit_funs or not signals:
- atexit.register(fun_wrapper)
- _registered_exit_funs.add(fun)
- # This piece of machinery handles 3 usage cases. register_exit_fun()
- # used as:
- # - a function
- # - a decorator without parentheses
- # - a decorator with parentheses
- if fun is None:
- @functools.wraps
- def outer(fun):
- return register_fun(fun, signals)
- return outer
- else:
- register_fun(fun, signals)
- return fun
- def wlog(messagetype, message):
- messagecaller = inspect.stack()[1][3]
- timevar = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- if messagetype == "M":
- print("[{}][{}]{} - {}".format(timevar, messagetype, messagecaller.center(22), message))
- elif messagetype == "D":
- debugline = format(sys.exc_info()[-1].tb_lineno)
- print("[{}][{}L{}]{} - {}".format(timevar, messagetype, debugline, messagecaller.center(18), message))
- def agentflow(ctrdatabase, appsdatabase):
- # Setting up database and default table
- wlog("AFLOW", "Starting initial database connection & read")
- reader = InitialReader(ctrdatabase, "apphandler")
- InitialReader.connect(reader)
- value = reader.rdefrev()
- wlog("M", "Default startup value: {}".format(value))
- wlog("AFLOW", "Setting up DbSetup connection")
- dbsetup = DbSetup(value)
- dbsetup.dropctr()
- dbsetup.crtprocapps()
- dbsetup.crtproccontroller()
- dbsetup.dbtablesetup()
- # Set base state, that no apps are running
- prochandler = ProcHandler()
- prochandler.stopallapps()
- # Db interaction
- wlog("AFLOW", "Retrieving default blob from value: {}".format(value))
- dbinteractor = DbInteractor()
- wlog("M", "Using this value to read default blob with: {}".format(value))
- dbinteractor.readblob(os.path.expanduser("~/artifacts/"), value, "output.zip")
- # Ziphandler
- wlog("AFLOW", "Default zip section with value: {}".format(value))
- zipper = ZipHandler()
- zipper.unzip(os.path.expanduser("~/artifacts/"), "output.zip", value, "")
- # Db pinger
- wlog("AFLOW", "Starting to ping database")
- pinger = DbCmdChecker(reader)
- pinger.checkdb(2, os.path.expanduser("~/artifacts/"), "archive/build/matlab/app/cmonapp/cmonapp.exe",
- "cmonapp.exe",
- os.path.expanduser("~/artifacts/"), "archive/build/matlab/app/nmrcalibrate/nmrcalibrate.exe",
- "nmrcalibrate.exe",
- os.path.expanduser("~/artifacts/"), "archive/build/matlab/app/nmrcalculatorapp/nmrcalculatorapp.exe",
- "nmrcalculatorapp.exe",
- os.path.expanduser("~/artifacts/"), "archive/build/matlab/app/nmrmeasureapp/nmrmeasureapp.exe",
- "nmrmeasureapp.exe",
- appsdatabase)
- cursor.close()
- db.close()
- register_exit_fun(connectionkiller())
- register_exit_fun(restartifclosed())
- def main():
- args = argumentparsing()
- executer(args)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement