-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathSUBMIT.py
404 lines (305 loc) · 12.1 KB
/
SUBMIT.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/local/bin/python3
# Copyright © 2018 by John Murray
# No rights reserved.
from ftplib import FTP
import argparse
import multiprocessing
import os
import re
import subprocess
import sys
import time
envEditor = ''
def opts():
parser = argparse.ArgumentParser(description='Submit a job to Z/OS, wait for it to end and get the output back.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='Notes.\nUserid and password will be obtained from environment variables ZOSUSER and ZOSPSWD if defined.\n'
'Hostname will be obtained from environment variables ZOSHOST if defined.\n'
'A directory called "listing" will be created if one does not exist. The script uses this directory for temporary files and listings.\n'
'If the user decides to edit the listing, the name of the editor will be obtained from environment variable ZOSEDITOR. If the variable is not defined, the editor will default to "x"')
parser.add_argument('-d',
action='store_true',
dest='debug',
default=False,
help='Run the command in debug mode')
parser.add_argument('-e',
action='store_true',
dest='edit',
default=False,
help='Edit the listing file')
parser.add_argument('-w',
default=5,
action='store',
dest='wait',
metavar='seconds',
help='Seconds to sleep before checking for job completion',
type=int)
parser.add_argument('-u',
action='store',
dest='user',
metavar='userid',
help='Userid to sign-in to zOS with')
parser.add_argument('-p',
action='store',
dest='pswd',
metavar='password',
help='Password')
parser.add_argument('-s',
action='store',
dest='host',
metavar='hostname',
help='Hostname of host to submit job to')
parser.add_argument('JCLFile',
action='store',
help='JCL file to submit')
args = parser.parse_args()
return args
def settleEnvs(args):
global envEditor
rc = True
if args.user == None:
user = os.getenv('ZOSUSER')
if user != None and len(user) != 0:
args.user = user
else:
print('User not sepcified and ZOSUSER not defined')
rc = False
if args.pswd == None:
pswd = os.getenv('ZOSPSWD')
if pswd != None and len(pswd) != 0:
args.pswd = pswd
else:
print('Password not sepcified and ZOSPSWD not defined')
rc = False
if args.host == None:
host = os.getenv('ZOSHOST')
if host != None and len(host) != 0:
args.host = host
else:
print('Host not sepcified and ZOSHOST not defined')
rc = False
if args.edit:
envEditor = os.getenv('ZOSEDITOR')
if envEditor == None or len(envEditor) == 0:
envEditor = 'x'
return rc
def debugOpts(args):
if args.debug:
print('Options:')
print('\tedit ' + str(args.edit))
print('\twait ' + str(args.wait))
print('\tuser ' + str(args.user))
print('\tpswd ' + str(args.pswd))
print('\thost ' + str(args.host))
print('\tJCLFile ' + args.JCLFile)
print()
class Error(Exception):
pass
class SubmitError(Error):
def __init__(self,
expression,
message):
self.expression = expression
self.message = message
class Submit:
def __init__(self,
debug=False,
edit=False,
wait=5,
user=None,
pswd=None,
host=None,
editor=None,
JCLFile=None):
self.debug = debug
self.edit = edit
self.wait = wait
self.user = user
self.pswd = pswd
self.host = host
self.editor = editor
self.JCLFile = JCLFile
self.jesLevelRe = re.compile(r'JESINTERFACELEVEL is ([0-9])')
self.jobNameRe = re.compile(r'\/\/([a-zA-Z0-9$#@]+)\s+JOB')
self.jobIDRe = re.compile(r'It is known to JES as ([a-zA-Z0-9$#@]+)')
self.userRe = re.compile(r'\?user\?')
self.pswdRe = re.compile(r'\?pswd\?')
self.includeRe = re.compile(r'\?([^\?]+)\?')
self.endRe = re.compile(r'^\/\/ *$')
self.jesStatus1Re = re.compile(r'^\s*(\S+)\s+(\S+)\s+(\S+)\s*')
self.jesStatus2Re = re.compile(r'^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+')
def processJob(self):
if not os.path.exists('listings'):
os.mkdir('listings')
self.openFTP()
self.jesLevel()
tmpFileName = self.buildJob()
jobID = self.sendFTP(tmpFileName)
listing = self.getJobListing(jobID)
listingFileName = self.saveListing(jobID,
listing)
if self.edit:
self.editListing(listingFileName)
self.closeFTP(jobID)
self.cleanup(tmpFileName)
def openFTP(self):
self.ftp = FTP(host=self.host,
user=self.user,
passwd=self.pswd)
self.ftp.sendcmd('site filetype=jes')
def jesLevel(self):
stat = self.ftp.sendcmd('stat')
jesLevelMatch = self.jesLevelRe.search(stat)
if jesLevelMatch == None:
raise SubmitError('jesLevelInterface',
'JESINTERFACELEVEL not found via stat command')
self.jesLevelInterface = jesLevelMatch.group(1)
if self.debug:
print('jesLevel: ' + self.jesLevelInterface)
def buildJob(self):
try:
jobNameFound = False
jclCards = self.getFile(self.JCLFile)
jclCards = self.fixJobName(jclCards)
jclCards = self.repUserPswd(jclCards)
jclCards = self.includes(jclCards)
tmpFileName = self.createJCLFile(jclCards)
if self.debug:
print('buildJob: ' + tmpFileName)
except OSError as osError:
raise SubmitError('buildJob',
'Problem opening JCLFile ' + self.JCLFile + '(' + str(osError) + ')')
return tmpFileName
def getFile(self,
fileName):
file = open(fileName, 'r')
lines = file.readlines()
file.close()
lines = ''.join(lines)
return lines
def fixJobName(self,
jclCards):
jobNameMatch = self.jobNameRe.search(jclCards)
if jobNameMatch != None:
if self.jesLevelInterface == '1':
self.jobName = self.user + '0'
else:
self.jobName = jobNameMatch.group(1)
jclCards = jclCards.replace(jobNameMatch.group(1),
self.jobName,
1)
if self.debug:
print('fixJobName:' + self.jobName)
else:
raise SubmitError('buildJob',
'Job card not found in ' + self.JCLFile)
return jclCards
def repUserPswd(self,
jclCards):
jclCards = jclCards.replace('?user?',
self.user,
1)
jclCards = jclCards.replace('?pswd?',
self.pswd,
1)
return jclCards
def includes(self,
jclCards):
while True:
includeMatch = self.includeRe.search(jclCards)
if includeMatch != None:
includeCards = self.getFile(includeMatch.group(1))
jclCards = jclCards.replace(includeMatch.group(0) + "\n",
includeCards,
1)
else:
break
return jclCards
def createJCLFile(self,
jclCards):
tmpFileName = 'listings/' + os.path.basename(self.JCLFile) + '.' + str(multiprocessing.current_process().pid)
tmpFile = open(tmpFileName, 'w')
for jclCard in jclCards.split(sep='\n'):
tmpFile.write(jclCard + '\n')
if re.search(r'^\/\/ *$', jclCard) != None:
break
tmpFile.close()
return tmpFileName
def sendFTP(self,
tmpFileName):
zosMessage = self.ftp.storlines('stor ' + os.path.basename(tmpFileName), open(tmpFileName, 'rb'))
return self.getJobID(zosMessage)
def getJobID(self,
zosMessage):
jobIDMatch = self.jobIDRe.search(zosMessage)
if jobIDMatch == None:
raise SubmitError('getJobID',
'Job ID not found in: ' + zosMessage)
jobID = jobIDMatch.group(1)
print('Job ' + self.JCLFile + ' submitted for execution on ' + self.host + ' as ' + jobID)
return jobID
def getJobListing(self,
jobID):
notFound = True
heldOutList = []
listingList = []
while notFound:
time.sleep(int(self.wait))
# These are closures: it has access to heldOutList which is in the current scope
#
def ftpDir(line):
heldOutList.append(line)
def ftpRetr(line):
listingList.append(line)
self.ftp.dir(ftpDir)
for heldOut in heldOutList:
if self.jesLevelInterface == '1':
jesStatus1Match = self.jesStatus1Re.match(heldOut)
job, jobid, state = jesStatus1Match.group(1, 2, 3)
else:
jesStatus2Match = self.jesStatus2Re.match(heldOut)
job, jobid, owner, state = jesStatus2Match.group(1, 2, 3, 4)
if jobid == jobID:
if state == 'OUTPUT':
self.ftp.retrlines('RETR ' + jobid, ftpRetr)
listing = '\n'.join(listingList)
notFound = False
break
return listing
def saveListing(self,
jobID,
listing):
listingFileName = 'listings/' + os.path.basename(self.JCLFile) + '.' + jobID
listingFile = open(listingFileName, 'w')
listingFile.write(listing.encode(encoding="ascii", errors="replace").decode())
listingFile.close()
print('Job output for ' + self.JCLFile + ' is in ' + listingFileName)
return listingFileName
def editListing(self,
listingFileName):
completed = subprocess.run([self.editor, listingFileName])
def closeFTP(self,
jobID):
self.ftp.delete(jobID)
self.ftp.close()
def cleanup(self,
tmpFileName):
completed = subprocess.run(['rm', tmpFileName])
def main():
try:
args = opts()
if settleEnvs(args):
debugOpts(args)
submit = Submit(debug=args.debug,
edit=args.edit,
wait=args.wait,
user=args.user,
pswd=args.pswd,
host=args.host,
editor=envEditor,
JCLFile=args.JCLFile)
submit.processJob()
except SubmitError as submitError:
print('SubmitError: ' + submitError.expression + ' - ' + submitError.message)
if __name__ == '__main__':
main()