# -*- coding: utf-8 -*- """ @file sequential.py @brief Example script to schedule a sequential job @par History - Arthur Russakoff, Jul 26 2019, initial version - Brian Helgans, Dec 02 2019, updated to add log name as input - Brian Helgans, Dec 17 2019, rewritten as a class """ import os import datetime import json from pathlib import Path import subprocess from . import log as Log from .timer import timethis from .exceptions import AlgorithmExecutionError class Sequential: ''' The algorithm will run once initialized and scheduled. NOTE: operational users should feel free to replace this module in it's entirety. ''' def __init__(self, executable, config, log_path=None, testname=None): """ All process run parameters must be set. :param executable: executable name (e.g. algorithms.exe) :param config: main configuration file (e.g. Config.xml) :param log_path: a directory that will contain the log """ self.exe = executable self.cfg = config if log_path is None: self.log_path = Path("./") if testname is None: self.testname = self._generate_job_id() else: self.log_path = Path(log_path) if testname is None: self.testname = self.log_path self.log_path = self.log_path @timethis def schedule(self): """ calls the execution routine NOTE: operational users should feel free to replace this module in it's entirety. """ __func = "Sequential.schedule" #the setup Log.info(__func, "Creating Log in: "+ str(self.log_path)) self.log_path.mkdir(parents=True, exist_ok=True) # backing up the environment in a log with open(self.log_path / "environment.txt", "w") as outfile: line = "{:{fill}^120}".format("", fill="-") title = "{:{fill}^120}".format("environment:", fill="-") print(line, file=outfile) print(title , file=outfile) print(line, file=outfile) print("environment=" + str(json.dumps(dict(os.environ))), file=outfile) print(line, file=outfile) print("configuration: ", self.cfg, file=outfile) print(line, file=outfile) self._execute() def _execute(self): ''' executes a sequential process. ''' try: logfile = self.log_path / "log.txt" with logfile.open("w") as openfile: subprocess.run([self.exe, self.cfg], stdin=None, check=True, stdout=openfile, stderr=openfile, shell=False) except Exception as e: raise AlgorithmExecutionError(e, "Processing failed") def _generate_job_id(self): """ generate a unique job ID for this test """ now = datetime.datetime.now() pid = str(os.getpid()) JOB_ID = "framework_job_%d%d%d%d%d%d_%d_%s" % (now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pid) return JOB_ID