import json import syslog as sl from syslog import syslog, LOG_INFO import traceback import datetime import subprocess import Activity import shutil import LuaConvertToJson import os import time import MasterjobLuaTemplate import logConfig import m7z_mod import fsio import status_mod import FilePaths # Fake globals for syntax check import notify_activity if False: response = None request = None session = None db = None status_mod.sessionUserMgr.setLastVisit(session, request) if logConfig.masterSessFrgt: session.forget(response) defaultJob = [{ 'id': 1, 'Name': 'n.a.', 'Slot': 0, 'Comment': '', 'Date': 978303600, 'Version': '', 'steps': [ #Operation Mode Step {'Column': 0, 'Name': 'Operation Mode', 'Row': 0, 'Type': 7, 'id': 1, 'children': [ {'children': [{'invisible': False, 'leaf': True, 'myText': 'Select active column', 'myValue': 0, 'readonly': False, 'type': 'COMBOBOX'}], 'expanded': True, 'myText': 'Options'}], 'execPy': '', 'expanded': False, 'leaf': False}, #Start Step {'Column': 0, 'Name': 'Start', 'Row': 2, 'Type': 0, 'id': 3, "children": [ {"myText": "Options", "expanded": True, "children": [{"myText": "Job step info display time", "myValue": "1", "type": "NUMBERFIELD_U", "min": 0.1, "max": 10, "step": 0.1, "default": 1, "invisible": False, "readonly": False, "leaf": True}]}, {"myText": "ID Code Source", "expanded": True, "children": [ {"myText": "Source Selection Start", "myValue": "0", 'StepType': 0, "type": "COMBOBOX", "invisible": False, "readonly": False, "leaf": True, "choice": [[0, "no id code"], [1, "Cycle Counter"], [2, "Open Protocol"], [3, "Scanner"], [4, "Multiple ID Inputs"], [5, 'VW XML']]}, {"myText": "Delete ID code after start", "myValue": "false", "type": "CHECKBOX", "invisible": False, "readonly": False, "leaf": True}, ]}, {'children': [{'choice': [[0, 'auto'], [1, 'select'], [2, 'manual']], 'invisible': False, 'leaf': True, 'myText': 'Operation Mode', 'myValue': "0", 'readonly': True, 'StepType': 0, 'type': 'COMBOBOX'}, { 'invisible': False, 'leaf': False, 'myText': 'Trigger', 'readonly': True, 'expanded': False, 'children': [ {'invisible': False, 'leaf': True, 'myText': 'HMI', 'myValue': "true", # str(prg_sel), 'readonly': False, 'type': 'CHECKBOX'}, #{'invisible': False, # 'leaf': True, # 'myText': 'Pin for HMI (optional)', # 'myValue': "", # str(prg_sel), # 'readonly': False, # 'type': 'EDITBOX'}, {'invisible': False, 'leaf': True, 'myText': 'Open Protocol', 'myValue': "true", # str(prg_sel), 'readonly': False, 'type': 'CHECKBOX'}, {'invisible': False, 'leaf': True, 'myText': 'BMS Signal ManOp', 'myValue': "true", # str(prg_sel), 'readonly': False, 'type': 'CHECKBOX'} ] }, { 'invisible': False, 'leaf': True, 'myText': 'Allow Prg selection', 'myValue': "false", 'readonly': False, 'type': 'CHECKBOX' }, { 'invisible': False, 'leaf': True, 'myText': 'Allow Job selection', 'myValue': "false", 'readonly': False, 'type': 'CHECKBOX' }], 'expanded': True, 'myText': 'Operation Mode Settings'} ], 'execPy': "",}, #End Step {'Column': 0, 'Name': 'End', 'Row': 3, 'Type': 2, 'id': 4 , "children": [ {"myText": "Options", "expanded": True, "children": [ {"myText": "Enable tool", "myValue": "false", "type": "CHECKBOX", "invisible": True, "readonly": True, "leaf": True, "execPy": ""} ]}], "execPy": ""}] }] JOB_PATH = '/home/tool/config/jobs/' @auth.requires(request.ajax==True, requires_login=True) def fileEmpty(path): return os.stat(path).st_size == 0 @auth.requires(request.ajax==True, requires_login=True) def processJobs(): if request.env.request_method == "GET": try: job = LuaConvertToJson.getMasterJob() except Exception as e: syslog(sl.LOG_ERR, traceback.format_exc()) for l in traceback.format_stack(): syslog(sl.LOG_ERR, "---> {0}".format(l)) print("Exeception getting masterjob", e) job = defaultJob return response.json(job) if request.env.request_method == "POST": try: data = json.loads(request.body.read()) except: pass if not isinstance(data, list): data = [data] date = int(time.time()) user = session.auth.user.username data[0]['User'] = user data[0]['Date'] = date MasterjobLuaTemplate.writeIdleCw(data, JOB_PATH, session) # fsio.jsondump("mastjob.json", data) return response.json({'Date': date, 'User': user}) @auth.requires(request.ajax==True, requires_login=True) def reset(): idle_cw_default = os.path.join(FilePaths.JOB_DEFAULT_PATH, 'idle_cw.lua') idle_en_default = os.path.join(FilePaths.JOB_DEFAULT_PATH, 'idle_en.lua') init_default = os.path.join(FilePaths.JOB_DEFAULT_PATH, 'init.lua') op_modes_default = os.path.join(FilePaths.JOB_DEFAULT_PATH, 'opmodes_declare.lua') idle_cw = os.path.join(FilePaths.JOB_PATH, 'idle_cw.lua') idle_en = os.path.join(FilePaths.JOB_PATH, 'idle_en.lua') init = os.path.join(FilePaths.JOB_PATH, 'init.lua') op_modes = os.path.join(FilePaths.JOB_PATH, 'opmodes_declare.lua') manual_mode = os.path.join(FilePaths.JOB_PATH, "2") default_manual_mode = os.path.join(FilePaths.JOB_DEFAULT_PATH, "2") masterjob = os.path.join(FilePaths.JOB_PATH, 'masterjob') try: fsio.shcopyfile(idle_cw_default, idle_cw) fsio.shcopyfile(idle_en_default, idle_en) fsio.shcopyfile(init_default, init) fsio.shcopyfile(op_modes_default, op_modes) shutil.rmtree(manual_mode, ignore_errors=True) if os.path.isdir(default_manual_mode): shutil.copytree(default_manual_mode, manual_mode) notify_activity.configChanged(masterjob, Activity.MASTERJOB_CHANGED, session=session) except Exception as e: syslog(LOG_INFO, "Reset mode error: " + str(e)) return '' def __genModeFileName(number): ts = time.time() dateStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y_%m_%d') return dateStamp + '_mode.nxmod' @auth.requires(request.ajax==True, requires_login=True) def get_mode_pwd(): return response.json(FilePaths.gen_mode_rev_pwd()) @auth.requires(request.ajax==True, requires_login=True) def exportMode(): res = {'success': False, 'msg': 'Unknown error'} fsio.fsLock.acquire() try: expfname = __genModeFileName(request.vars.num) res = {'success': True, 'msg': '/tmp/' + expfname} pwd = FilePaths.gen_mode_rev_pwd() syslog(LOG_INFO, "START exportMode.subprocess to " + expfname + " at " + time.asctime()) p = subprocess.Popen(['/home/tool/bin/7za', "a", "/tmp/{0}".format(expfname), "/home/tool/config/jobs/idle_*.lua", "/home/tool/config/jobs/init.lua", "/home/tool/config/jobs/opmodes_declare.lua", "/home/tool/config/jobs/2*/*", "-mx7", "-p{0}".format(pwd)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() syslog(LOG_INFO, "DONE exportMode.subprocess to " + expfname + " at " + time.asctime()) syslog(LOG_INFO, "RESULT exportMode.subprocess to stdout: " + str(stdout)) syslog(LOG_INFO, "RESULT exportMode.subprocess to stderr: " + str(stderr)) if p.returncode != 0: # Failure res['success'] = False res['msg'] = str(stderr) except Exception, e: res['success'] = False res['msg'] = str(e) finally: fsio.fsLock.release() return response.json(res) @auth.requires_login() def importMode(): for i, k in dict(request).items(): print i, " ", k res = {'success': False, 'msg': 'Unknown error'} destRootDir = '/tmp/' # destDir = 'luamod' filename = 'luamod.zip' # destPath = destRootDir + destDir + '/' fsio.fsXngLock.acquire() try: filepath = destRootDir + filename with open(filepath, 'w') as f: f.write(request.vars.fileupload.value) pwd = FilePaths.gen_mode_rev_pwd() returncode = m7z_mod.test_pwd(filepath, pwd) if returncode != 0: return response.json(m7z_mod.get_import_impossible_msg()) shutil.rmtree("/home/tool/config/jobs/2/", ignore_errors=True) p = subprocess.Popen(['/home/tool/bin/7za', "x", filepath, "-p{0}".format(pwd), "-o{0}".format("/home/tool/config/jobs"), "-y"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode != 0: # Failure res['success'] = False res['msg'] = str(stderr) else: notify_activity.configChanged("/home/tool/config/mod_importer", Activity.MASTERJOB_CHANGED, activityArgs=[], session=session) if not os.path.isdir("/home/tool/config/jobs/2"): from MasterjobLuaTemplate import default_op_modes default_op_modes() return response.json({'success': True, 'msg': ':-)'}) except Exception, e: res['success'] = False res['msg'] = str(e) finally: fsio.fsXngLock.release() return response.json(res)