-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.py
executable file
·92 lines (79 loc) · 2.64 KB
/
job.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/python
import subprocess
import time
import os
import sys
class job:
def __init__(self, n, l, e, c, logappend=False, verbose=True, mailcmd='mailx -s'):
self.name=n
self.log=l
self.email=e
self.cmd=c
self.mailcmd=mailcmd
self.logappend=logappend
self.verbose=verbose
def run(self):
# get hostname
proc = subprocess.Popen('hostname', stdout=subprocess.PIPE)
host = proc.stdout.read().rstrip('\n')
# open log files
logfile= "%s.log" % self.log
error_logfile= "%s.err" % self.log
# if logs should not be appended to existing logfiles, remove them first
if not self.logappend:
if (os.path.exists(logfile)):
os.remove(logfile)
if (os.path.exists(error_logfile)):
os.remove(error_logfile)
status=False
# run all jobs
for runcmd in self.cmd:
# append logs to logfiles
fstdout = open(logfile, 'a')
fstdout.write("job: " + runcmd + "\n")
fstderr = open(error_logfile, 'a')
fstderr.write("job: " + runcmd + "\n")
# start time
stime=time.asctime()
start=time.time()
# run job
process=subprocess.Popen( runcmd, shell=True, stdout=fstdout, stderr=fstderr)
fstdout.close()
fstderr.close()
process.communicate()
status=process.returncode
# end time
end=time.time()
# check status and send email
if status:
f=open("message.temp", 'w')
f.write("And error has occured during the job: %s.\n" % self.name)
f.write("Run command was: %s.\n" % runcmd)
f.write("Run started at: %s.\n" % stime)
f.write("Duration: %s.\n" % time.strftime('%H:%M:%S', time.gmtime(end-start)))
f.write("Print error log file %s and break.\n" % error_logfile)
efile = open(error_logfile, 'r')
for line in efile:
f.write(line)
f.close()
cmd="cat message.temp | %s 'Job Monitor: An error has occured durring the job %s on %s.' %s" % (self.mailcmd, self.name, host, self.email)
#print cmd
subprocess.call(cmd, shell=True)
os.remove("message.temp")
elif status==False and self.verbose:
f=open("message.temp", 'w')
f.write("Successful job: %s.\n" % self.name)
f.write("Run command was: %s.\n" % runcmd)
f.write("Run started at: %s.\n" % stime)
f.write("Duration: %s.\n" % time.strftime('%H:%M:%S', time.gmtime(end-start)))
f.close()
cmd="cat message.temp | %s 'Job Monitor: Successful job %s on %s.' %s" % (self.mailcmd, self.name, host, self.email)
#print cmd
subprocess.call(cmd, shell=True)
os.remove("message.temp")
return status
def main():
j=job('myjob', 'mylog', 'stollenwerk@th.physik.uni-bonn.de', ['sleep 1', 'sleep sdfjkl', 'sleep 2'], logappend=True)
j.run()
if __name__=="__main__":
main()