#Orchestrator_Logging #Orchestrator_Weekday_Support #Orchestrator_Fix_ProcessStop #Orchestrator_flag_processClose_optional

dev-linux
Ivan Maslov 5 years ago
parent 97434690c1
commit cd5a4684bc

@ -104,6 +104,34 @@
dataType: "text" dataType: "text"
}); });
} }
mGlobal.Controller.CMDRunGUILogout=function() {
///Обнулить таблицу
lCMDCode="for /f \"skip=1 tokens=2\" %s in ('query user %USERNAME%') do (tscon \\dest:console)"
lCMDCode = lCMDCode.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f")
.replace('"', "\\\"");
$.ajax({
type: "POST",
url: 'ProcessingRun',
data: '{"actionList":[{"type":"ActivityCMDRun", "code":"'+lCMDCode+'"}]}',
success:
function(lData,l2,l3)
{
var lResponseJSON=JSON.parse(lData)
///Отправить запрос на формирование таблицы
lHTMLCode=console.log("CMDRun result: "+lResponseJSON[0].result)
},
dataType: "text"
});
}
///Перезагрузить Orchestrator ///Перезагрузить Orchestrator
mGlobal.Controller.OrchestratorRestart=function() { mGlobal.Controller.OrchestratorRestart=function() {
$.ajax({ $.ajax({
@ -391,6 +419,7 @@
<div class="ui fluid action input"> <div class="ui fluid action input">
<input class="openrpa-controller-cmd-run-input" type="text" placeholder="CMD Code..."> <input class="openrpa-controller-cmd-run-input" type="text" placeholder="CMD Code...">
<div class="ui button" onclick="mGlobal.Controller.CMDRun();">Run!</div> <div class="ui button" onclick="mGlobal.Controller.CMDRun();">Run!</div>
<div class="ui button" onclick="mGlobal.Controller.CMDRunGUILogout();">GUI Logout</div>
</div> </div>
</div> </div>
<div class="actions"> <div class="actions">
@ -398,6 +427,7 @@
<i class="checkmark icon"></i> <i class="checkmark icon"></i>
Close Close
</div> </div>
</div> </div>
</div> </div>

@ -27,14 +27,16 @@
"____processPath":"C:\\Abs\\Archive\\scopeSrcUL\\OpenRPA\\OpenRPA_32.cmd", "____processPath":"C:\\Abs\\Archive\\scopeSrcUL\\OpenRPA\\OpenRPA_32.cmd",
"processPath":"C:\\Abs\\Archive\\scopeSrcUL\\OpenRPA\\Orchestrator\\RobotDaemon\\runProcessOpenRPARobotDaemon_x32.cmd", "processPath":"C:\\Abs\\Archive\\scopeSrcUL\\OpenRPA\\Orchestrator\\RobotDaemon\\runProcessOpenRPARobotDaemon_x32.cmd",
"__processArgs":"Аргументы, передаваемые при запуске процесса", "__processArgs":"Аргументы, передаваемые при запуске процесса",
"processArgs":"" "processArgs":"",
"__weekdayNumList":"Список номеров дней недели, по которым выполнять инициализаци активности. Отсчет ведется от 0 до 6",
"weekdayNumList":[1,2,3]
}, },
{ {
"description":"Запуск Python консоли", "description":"Запуск Python консоли",
"__activityType":"processStart/processStop", "__activityType":"processStart/processStop",
"activityType":"processStart", "activityType":"processStart",
"__time":"__Время запуска активности", "__time":"__Время запуска активности",
"time":"09:19", "time":"23:24",
"__timeZone":"Часовой пояс, в рамках которого указано время. По-умолчанию часовой пояс МСК (GMT+4). Формат UTC offset in the form ±HHMM[SS[.ffffff]] ", "__timeZone":"Часовой пояс, в рамках которого указано время. По-умолчанию часовой пояс МСК (GMT+4). Формат UTC offset in the form ±HHMM[SS[.ffffff]] ",
"timeZone":"+0400", "timeZone":"+0400",
"__processPath":"Полный путь/наименование процесса. Запуск производится через subprocess. Идентификатор процесса в дальнейшем сохраняется и его можно будет закрыть с помощью параметра processCode", "__processPath":"Полный путь/наименование процесса. Запуск производится через subprocess. Идентификатор процесса в дальнейшем сохраняется и его можно будет закрыть с помощью параметра processCode",
@ -55,8 +57,8 @@
{ {
"activityType":"loopActivity", "activityType":"loopActivity",
"loopSeconds":6, "loopSeconds":6,
"loopTimeStart":"01:45", "loopTimeStart":"10:45",
"loopTimeEnd":"01:46", "loopTimeEnd":"21:46",
"pythonPackageName":"CheckActivity", "pythonPackageName":"CheckActivity",
"pythonFunctionName":"test_activity", "pythonFunctionName":"test_activity",
"pythonFunctionArgList":["TestArg1","TestArg2"], "pythonFunctionArgList":["TestArg1","TestArg2"],

@ -8,6 +8,13 @@ import signal
import pdb import pdb
import orchestratorServer import orchestratorServer
import orchestratorTimer import orchestratorTimer
import logging
#Создать файл логирования
# add filemode="w" to overwrite
if not os.path.exists("Reports"):
os.makedirs("Reports")
logging.basicConfig(filename="Reports\ReportRun_"+datetime.datetime.now().strftime("%Y_%m_%d__%H_%M_%S")+".log", level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
lGlobalDict={} lGlobalDict={}
#"JSONConfigurationDict":<JSON> #"JSONConfigurationDict":<JSON>
@ -44,75 +51,81 @@ while True:
#Циклический обход правил #Циклический обход правил
lFlagSearchActivityType=True lFlagSearchActivityType=True
for lItem in lDaemonConfigurationObject["activityList"]: for lItem in lDaemonConfigurationObject["activityList"]:
if lFlagSearchActivityType: #Проверка дней недели, в рамках которых можно запускать активность
#Определить вид активности lItemWeekdayList=lItem.get("weekdayNumList",[0,1,2,3,4,5,6])
if lItem["activityType"]=="processStart": if lCurrentDateTime.weekday() in lItemWeekdayList:
#Вид активности - запуск процесса if lFlagSearchActivityType:
#Сформировать временной штамп, относительно которого надо будет проверять время #Определить вид активности
#часовой пояс пока не учитываем if lItem["activityType"]=="processStart":
lActivityDateTime=datetime.datetime.strptime(lItem["time"],"%H:%M") #Вид активности - запуск процесса
lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day) #Сформировать временной штамп, относительно которого надо будет проверять время
#Убедиться в том, что время наступило #часовой пояс пока не учитываем
if ( lActivityDateTime=datetime.datetime.strptime(lItem["time"],"%H:%M")
lActivityDateTime>=lDaemonStartDateTime and lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
lCurrentDateTime>=lActivityDateTime and #Убедиться в том, что время наступило
(lItem["activityType"],lActivityDateTime,lItem["processPath"]) not in lDaemonActivityLogDict): if (
#Выполнить операцию lActivityDateTime>=lDaemonStartDateTime and
print(datetime.datetime.now().isoformat()+":: ProcessStart:"+lItem["processPath"]) lCurrentDateTime>=lActivityDateTime and
#Запись в массив отработанных активностей (lItem["activityType"],lActivityDateTime,lItem["processPath"]) not in lDaemonActivityLogDict):
lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processPath"])]={"ActivityStartDateTime":lCurrentDateTime} #Выполнить операцию
#Лог print(datetime.datetime.now().isoformat()+":: ProcessStart:"+lItem["processPath"])
lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)}) logging.info("ProcessStart:"+lItem["processPath"])
#Запустить процесс #Запись в массив отработанных активностей
lItemArgs=[lItem["processPath"]] lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processPath"])]={"ActivityStartDateTime":lCurrentDateTime}
lItemArgs.extend(lItem["processArgs"]) #Лог
subprocess.Popen(lItemArgs,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)})
#Определить вид активности #Запустить процесс
if lItem["activityType"]=="processStop": lItemArgs=[lItem["processPath"]]
#Вид активности - остановка процесса lItemArgs.extend(lItem["processArgs"])
#Сформировать временной штамп, относительно которого надо будет проверять время subprocess.Popen(lItemArgs,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#часовой пояс пока не учитываем #Определить вид активности
lActivityDateTime=datetime.datetime.strptime(lItem["time"],"%H:%M") if lItem["activityType"]=="processStop":
lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day) #Вид активности - остановка процесса
#Убедиться в том, что время наступило #Сформировать временной штамп, относительно которого надо будет проверять время
if ( #часовой пояс пока не учитываем
lActivityDateTime>=lDaemonStartDateTime and lActivityDateTime=datetime.datetime.strptime(lItem["time"],"%H:%M")
lCurrentDateTime>=lActivityDateTime and lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
(lItem["activityType"],lActivityDateTime,lItem["processName"]) not in lDaemonActivityLogDict): #Убедиться в том, что время наступило
#Запись в массив отработанных активностей if (
lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processName"])]={"ActivityStartDateTime":lCurrentDateTime} lActivityDateTime>=lDaemonStartDateTime and
#Сформировать команду на завершение lCurrentDateTime>=lActivityDateTime and
lActivityCloseCommand='taskkill /im '+lItem["processName"] (lItem["activityType"],lActivityDateTime,lItem["processName"]) not in lDaemonActivityLogDict):
#TODO Сделать безопасную обработку,если параметра нет в конфигурации #Запись в массив отработанных активностей
if lItem['flagCloseForce']: lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processName"])]={"ActivityStartDateTime":lCurrentDateTime}
lActivityCloseCommand+=" /F" #Сформировать команду на завершение
#Завершить процессы только текущего пользоваиеля lActivityCloseCommand='taskkill /im '+lItem["processName"]
if lItem['flagCloseOnlyCurrentUser']: #TODO Сделать безопасную обработку,если параметра нет в конфигурации
lActivityCloseCommand+=' /fi "username eq %username%"' if lItem.get('flagCloseForce',False):
#Лог lActivityCloseCommand+=" /F"
lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)}) #Завершить процессы только текущего пользоваиеля
#Завершить процесс if lItem.get('flagCloseOnlyCurrentUser',False):
os.system(lActivityCloseCommand) lActivityCloseCommand+=' /fi "username eq %username%"'
print(datetime.datetime.now().isoformat()+":: ProcessStop "+lItem["processName"]) #Лог
#Вид активности - запуск отдельного потока с циклическим вызовом lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processName"], "activityStartDateTime":str(lCurrentDateTime)})
if lItem["activityType"]=="loopActivity": #Завершить процесс
#Сформировать временной штамп, относительно которого надо будет проверять время os.system(lActivityCloseCommand)
#часовой пояс пока не учитываем print(datetime.datetime.now().isoformat()+":: ProcessStop "+lItem["processName"])
lActivityDateTime=datetime.datetime.strptime(lItem["loopTimeStart"],"%H:%M") logging.info("ProcessStop "+lItem["processName"])
lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day) #Вид активности - запуск отдельного потока с циклическим вызовом
#Убедиться в том, что время наступило if lItem["activityType"]=="loopActivity":
if ( #Сформировать временной штамп, относительно которого надо будет проверять время
lActivityDateTime>=lDaemonStartDateTime and #часовой пояс пока не учитываем
lCurrentDateTime>=lActivityDateTime and lActivityDateTime=datetime.datetime.strptime(lItem["loopTimeStart"],"%H:%M")
(lItem["activityType"],lActivityDateTime,lItem["processPath"]) not in lDaemonActivityLogDict): lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
#Запись в массив отработанных активностей
lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processPath"])]={"ActivityStartDateTime":lCurrentDateTime}
lActivityTimeEndDateTime=datetime.datetime.strptime(lItem["loopTimeEnd"],"%H:%M") lActivityTimeEndDateTime=datetime.datetime.strptime(lItem["loopTimeEnd"],"%H:%M")
lActivityTimeEndDateTime=lActivityTimeEndDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day) lActivityTimeEndDateTime=lActivityTimeEndDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
#Лог #Убедиться в том, что время наступило
lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)}) if (
#Запуск циклической процедуры lCurrentDateTime<lActivityTimeEndDateTime and
orchestratorTimer.activityLoopStart(lItem["loopSeconds"],lItem["processPath"],lItem["processArgs"],lActivityTimeEndDateTime,lItem["pythonPackageName"],lItem["pythonFunctionName"],lItem["pythonFunctionArgList"]) lCurrentDateTime>=lActivityDateTime and
(lItem["activityType"],lActivityDateTime,lItem["processPath"]) not in lDaemonActivityLogDict):
logging.info("ActivityLoop Start ")
#Запись в массив отработанных активностей
lDaemonActivityLogDict[(lItem["activityType"],lActivityDateTime,lItem["processPath"])]={"ActivityStartDateTime":lCurrentDateTime}
#Лог
lGlobalDict["ActivityLogScheduleList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)})
#Запуск циклической процедуры
orchestratorTimer.activityLoopStart(lItem["loopSeconds"],lItem["processPath"],lItem["processArgs"],lActivityTimeEndDateTime,lItem["pythonPackageName"],lItem["pythonFunctionName"],lItem["pythonFunctionArgList"])
#Уснуть до следующего прогона #Уснуть до следующего прогона
time.sleep(lDaemonLoopSeconds) time.sleep(lDaemonLoopSeconds)

@ -2,6 +2,7 @@ from threading import Timer
import datetime import datetime
import subprocess import subprocess
import importlib import importlib
import logging
class RepeatedTimer(object): class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs): def __init__(self, interval, function, *args, **kwargs):
self._timer = None self._timer = None
@ -34,6 +35,7 @@ def activityLoopExecution(inProcessPath,inProcessArgList,inLoopTimeEndDateTime,i
lResultGoLoop=True lResultGoLoop=True
lCurrentDateTime=datetime.datetime.now() lCurrentDateTime=datetime.datetime.now()
print (datetime.datetime.now().isoformat()+":: Loop activity check") print (datetime.datetime.now().isoformat()+":: Loop activity check")
logging.info("Loop activity check")
#Запустить процесс, если установлен inProcessPath #Запустить процесс, если установлен inProcessPath
if inProcessPath is not None: if inProcessPath is not None:
if inProcessPath != "": if inProcessPath != "":
@ -52,6 +54,7 @@ def activityLoopExecution(inProcessPath,inProcessArgList,inLoopTimeEndDateTime,i
lFunction(*inPythonFunctionArgList) lFunction(*inPythonFunctionArgList)
except Exception as e: except Exception as e:
print (datetime.datetime.now().isoformat()+":: Loop activity error: module/function not founded") print (datetime.datetime.now().isoformat()+":: Loop activity error: module/function not founded")
logging.info("Loop activity error: module/function not founded")
#Выключить таймер, если время наступило #Выключить таймер, если время наступило
if lCurrentDateTime>=inLoopTimeEndDateTime: if lCurrentDateTime>=inLoopTimeEndDateTime:

Loading…
Cancel
Save