-
Notifications
You must be signed in to change notification settings - Fork 3
/
jetlag.py
2129 lines (1930 loc) · 71.8 KB
/
jetlag.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
####
# The basic concept of universal is:
# (1) to use either Tapis or Agave
# (2) to describe a single machine that is:
# (a) a storage machine
# (b) an execution machine with FORK
# (c) an execution machine with some scheduler
# (3) Has a generic app which
# (a) takes input.tgz
# (b) unpacks and executes run_dir/runapp.sh
# from inside the run_dir/ directory
# (c) packs everything up into output.tgz
#
#####
import hashlib, base64
import os
import diagrequests as requests
import pprint
from math import log, ceil
from subprocess import Popen, PIPE
import sys
import re
import json
from time import sleep, time
from random import randint
#from tapis_config import *
from copy import copy, deepcopy
from datetime import datetime
import codecs, pickle
import importlib.machinery
from getpass import getpass
os.environ["AGAVE_JSON_PARSER"]="jq"
job_done = ["FAILED", "FINISHED", "STOPPED", "BLOCKED"]
def codeme(m):
t = type(m)
if t == str:
m = m.encode()
elif t == bytes:
pass
else:
raise Exception(str(t))
h = hashlib.md5(m)
v = base64.b64encode(h.digest())
s = re.sub(r'[\+/]','_', v.decode())
return s[:-2]
def decode_bytes(bs):
s = ''
if type(bs) == bytes:
for k in bs:
s += chr(k)
return s
has_color = False
if sys.stdout.isatty():
try:
# Attempt to import termcolor...
from termcolor import colored
has_color = True
except:
# If this fails, attempt to install it...
try:
from pip import main as pip_main
except:
try:
from pip._internal import main as pip_main
except:
pass
try:
pip_main(["install", "--user", "termcolor"])
has_color = True
except:
pass
if not has_color:
# Don't colorize anything if
# this isn't a tty
def colored(a,_):
return a
# Agave/Tapis uses all of these http status codes
# to indicate succes.
success_codes = [200, 201, 202]
pp = pprint.PrettyPrinter(indent=2)
def age(fname):
"Compute the age of a file in seconds"
t1 = os.path.getmtime(fname)
t2 = time()
return t2 - t1
last_time = time()
def old_pause():
global last_time
now = time()
sleep_time = last_time + pause_time - now
if sleep_time > 0:
sleep(sleep_time)
last_time = time()
time_array = []
pause_files = 5
pause_time = 30
poll_time = 5
def key2(a):
return int(1e6*a[1])
def pause():
global time_array
home = os.environ['HOME']
tmp_dir = home+"/tmp/times"
if len(time_array) == 0:
os.makedirs(tmp_dir, exist_ok=True)
time_array = []
for i in range(pause_files):
tmp_file = tmp_dir+"/t_"+str(i)
if not os.path.exists(tmp_file):
with open(tmp_file,"w") as fd:
pass
tmp_age = os.path.getmtime(tmp_file)
time_array += [[tmp_file,tmp_age-pause_time]]
time_array = sorted(time_array,key=key2)
stime = time_array[0][1]+pause_time
now = time()
delt = stime - now
if delt > 0:
sleep(delt)
with open(time_array[0][0],"w") as fd:
pass
time_array[0][1] = os.path.getmtime(time_array[0][0])
last_time_array = []
def pause1():
global last_time_array
now = time()
last_time_array += [now]
nback = 3
nsec = 10
nmargin = 5
if len(last_time_array) > nback:
if now - last_time_array[-nback] < nsec:
stime = nsec - now + last_time_array[-nback]
sleep(stime)
else:
old_pause()
if len(last_time_array) > nback + nmargin:
last_time_array = last_time_array[-nback:]
def check(response):
"""
Called after receiving a response from the requests library to ensure that
an error was not received.
"""
if response.status_code not in success_codes:
requests.show()
msg = str(response)
if response.content is not None:
msg += response.content.decode()
raise Exception(msg)
def idstr(val,max_val):
"""
This function is used to generate a unique
id string to append to the end of each
job name.
"""
assert val < max_val
d = int(log(max_val,10))+1
fmt = "%0" + str(d) + "d"
return fmt % val
def pcmd(cmd,input=None,cwd=None):
"""
Generalized pipe command with some convenient options
"""
#print(colored(' '.join(cmd),"magenta"))
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True, cwd=cwd)
if input is not None:
print("send input...")
out, err = p.communicate(input=input)
else:
out, err = p.communicate()
print(colored(out,"green"),end='')
if err != '':
print(colored(err,"red"),end='')
return p.returncode, out, err
# Read a file
def readf(fname):
with open(fname,"r") as fd:
return fd.read()
def check_data(a,b,prefix=[]):
"""
Used to compare data sets to see if updating
is needed. So far, only used for storage systems.
"""
keys = set()
keys.update(a.keys())
keys.update(b.keys())
err = 0
for k in keys:
if k in a and k not in b:
if len(prefix)>0 and prefix[-1] == "auth":
pass
else:
print("only in a:",prefix+[k],"=>",a[k])
err += 1
elif k in b and k not in a:
pass #print("only in b:",k,"=>",b[k])
elif type(a[k]) == dict and type(b[k]) == dict:
err += check_data(a[k],b[k],prefix + [k])
elif a[k] != b[k]:
if len(prefix)>0 and prefix[-1] == "auth":
pass
else:
print("not equal:",prefix+[k],"=>",a[k],"!=",b[k])
err += 1
return err
def mk_input(input_tgz):
"""
Generate a tarball from a hash of file names/contents.
"""
pcmd(["rm","-fr","run_dir"])
os.mkdir("run_dir")
for k in input_tgz.keys():
with open("run_dir/"+k,"w") as fd:
print(input_tgz[k].strip(),file=fd)
pcmd(["tar","czf","input.tgz","run_dir"])
def load_input(pass_var,is_password):
"""
Load a password either from an environment variable or a file.
"""
if pass_var in os.environ:
return os.environ[pass_var]
pfname = os.environ["HOME"]+"/."+pass_var
if os.path.exists(pfname):
print("reading %s from %s..." % (pass_var, pfname))
os.environ[pass_var] = readf(pfname).strip()
return os.environ[pass_var]
if is_password:
os.environ[pass_var] = getpass(pass_var+": ").strip()
else:
os.environ[pass_var] = input(pass_var+": ").strip()
if not os.path.exists(pfname):
fd = os.open(pfname, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0o0600)
os.write(fd,os.environ[pass_var].encode('ASCII'))
os.close(fd)
return os.environ[pass_var]
class RemoteJobWatcher:
def __init__(self,uv,jobid):
self.uv = uv
self.jobid = jobid
self.last_status = "EMPTY"
self.jdata = None
def wait(self):
s = None
while True:
self.uv.poll()
n = self.status()
if n != s:
print(n)
s = n
sleep(poll_time)
if n in job_done:
return
def stop(self):
self.uv.job_stop(self.jobid)
def get_result(self):
if hasattr(self,"result"):
return self.result
if self.status() == "FINISHED":
jobdir="jobdata-"+self.jobid
if not os.path.exists(jobdir):
os.makedirs(jobdir, exist_ok=True)
self.uv.get_file(self.jobid,"output.tgz",jobdir+"/output.tgz")
pcmd(["tar","xf","output.tgz"],cwd=jobdir)
if self.jdata is None:
self.status(self.jobid)
outs = self.uv.show_job(self.jobid,verbose=False,recurse=False)
for out in outs:
if re.match(r'.*(\.(out|err))$',out):
self.uv.get_file(self.jobid, out, jobdir+"/"+re.sub(r'.*\.','job.',out))
if os.path.exists(jobdir+'/run_dir/result.py'):
with open(jobdir+'/run_dir/result.py',"r") as fd:
# Mostly, PhySL data structures look like Python
# data structures. Unfortunately, PhySL will
# construct a list as list(1,2,3). This is illegal
# in Python. Convert to list((1,2,3)). A more
# general solution is probably needed.
val = fd.read().strip()
if re.match(r'^list\(', val):
val = 'list('+re.sub(r'^list','',val)+')'
try:
self.result = eval(val)
except Exception as e:
self.result = val
else:
self.result = None
return self.result
return None
def diag(self):
"""
Diagnose a job to see
whether it worked or
what might have caused
it to fail.
"""
f = self.full_status()
if "lastStatusMessage" in f:
print("Last Status:",f["lastStatusMessage"])
h = self.history()
print("History:")
if len(h) > 3:
pp.pprint(h[-3:])
else:
pp.pprint(h)
def full_status(self):
return self.uv.job_status(self.jobid)
def status(self):
if self.last_status in job_done:
return self.last_status
self.jdata = self.full_status()
self.last_status = self.jdata["status"]
return self.last_status
def history(self):
return self.uv.job_history(self.jobid)
def err_output(self):
self.get_result()
try:
with open("jobdata-"+self.jobid+"/job.err","r") as fd:
return fd.read()
except FileNotFoundError as fnf:
return ""
def std_output(self):
self.get_result()
try:
with open("jobdata-"+self.jobid+"/job.out","r") as fd:
return fd.read()
except FileNotFoundError as fnf:
return ""
class Universal:
"""
The Universal (i.e. Tapis or Agave) submitter thingy.
"""
def __init__(self):
self.auth_age = 0
self.public_key = None
self.private_key = None
# Required options with default values.
# Values of "uknown" or -666 mean the
# user must supply a value.
self.values = {
"jetlag_id" : "unknown",
"backend" : {},
"notify" : 'unknown',
"sys_user" : 'unknown',
"sys_pw" : 'unknown',
"machine_user" : '{machine_user}',
"machine" : 'unknown',
"domain" : "unknown",
"port" : 22,
"queue" : "unknown",
"max_jobs_per_user" : -666,
"max_jobs" : -666,
"max_nodes" : -666,
"scratch_dir" : "/scratch/{machine_user}",
"work_dir" : "/work/{machine_user}",
"home_dir" : "/home/{machine_user}",
"root_dir" : "/",
"max_run_time" : "unknown",
"max_procs_per_node" : -666,
"min_procs_per_node" : -666,
"allocation" : "{allocation}",
"app_name" : "{machine}-{machine_user}_queue_{other}",
"fork_app_name" : "{machine}-{machine_user}_fork_{other}",
"app_version" : "1.0.0",
"deployment_path" : "new-{utype}-deployment",
"scheduler" : "unknown",
"custom_directives" : ''
}
def loadf(self,utype,user,passw,baseurl=None,tenant=None,notify=None,jetlag_id=None):
if baseurl is None:
if utype.lower() == 'agave':
baseurl = "https://sandbox.agaveplatform.org"
else:
baseurl = "https://api.tacc.utexas.edu"
if tenant is None:
if utype.lower() == 'agave':
tenant = "sandbox"
else:
tenant = "tacc.prod"
backend = {
"baseurl" : baseurl,
"tenant" : tenant,
"user" : user,
"pass" : passw,
"utype" : utype
}
self.load(backend, notify, jetlag_id)
def load(self,backend,notify=None,jetlag_id=None):
self.values['backend']=backend
if jetlag_id is not None:
self.values['jetlag_id']=jetlag_id
self.values['notify']=notify
self.set_backend()
self.create_or_refresh_token()
if jetlag_id is None or jetlag_id.strip().lower() in ["none", "unknown", ""]:
return
# Jetlag id is: machine-login_user-creating_user
# If the creating user is missing, we search through
# the jetlag id's to see if we can find something
# that matches the machine and login_user. If that
# is missing or not unique, it cannot be used.
g = re.match(r'^(\w+)-(\w+)(?:-(\w+)|)', jetlag_id)
assert g, 'Invalid jetlag id: %s' % jetlag_id
if g.group(3) is None:
jids = self.jetlag_ids()
found = None
for jid in jids:
g2 = re.match(r'^(\w+)-(\w+)(?:-(\w+)|)', jid)
if g.group(1) == g2.group(1) and g.group(2) == g2.group(2):
assert found is None, "Invalid jetlag id: '%s'" % jetlag_id
found = g2
assert found, "Invalid jetlag id: '%s'" % jetlag_id
g = g2
self.values['other'] = g.group(3)
self.values['machine_user'] = g.group(2)
self.values['machine'] = g.group(1)
self.values['storage_id'] = "%s-%s-storage-%s" % (g.group(1), g.group(2), g.group(3))
self.values['execm_id'] = "%s-%s-exec-%s" % (g.group(1), g.group(2), g.group(3))
self.values['forkm_id'] = "%s-%s-fork-%s" % (g.group(1), g.group(2), g.group(3))
self.values['app_id'] = "%s-%s_queue_%s-1.0.0" % (g.group(1), g.group(2), g.group(3))
self.values['fork_app_id'] = "%s-%s_fork_%s-1.0.0" % (g.group(1), g.group(2), g.group(3))
ex = self.get_exec()
self.values['work_dir'] = re.sub(r'/+$','',ex['workDir'])
self.values['scratch_dir'] = re.sub(r'/+$','',ex['scratchDir'])
self.values['scheduler'] = ex['scheduler']
self.values['custom_directives'] = ex['queues'][0]['customDirectives']
self.values['max_run_time'] = ex['queues'][0]['maxRequestedTime']
self.values['max_procs_per_node'] = ex['queues'][0]['maxProcessorsPerNode']
self.values['max_jobs'] = ex['queues'][0]['maxJobs']
self.values['max_nodes'] = ex['queues'][0]['maxNodes']
self.values['max_procs_per_node'] = ex['queues'][0]['maxProcessorsPerNode']
self.values['min_procs_per_node'] = ex['queues'][0]['maxProcessorsPerNode']
self.values['queue'] = ex['queues'][0]['name']
self.values['domain'] = ex['site']
self.values['max_jobs_per_user'] = ex['maxSystemJobsPerUser']
self.values['job_dir'] = self.jobs_dir()
def check_values(self, values):
values = self.fill(values)
for k in values:
# We can't get minProcsPerNode back from Agave/Tapis
if k == "min_procs_per_node":
continue
assert k in self.values, "Missing: "+k
assert values[k] == self.values[k],'k: '+k+' = '+str(values[k]) + " != " + str(self.values[k])
def initf(self,utype,machine,machine_user,domain,port:int=22,
queue='unknown',max_jobs_per_user:int=1,max_jobs:int=1,
max_nodes:int=1,scratch_dir="/scratch/{machine_user}",
work_dir="/work/{machine_user}",home_dir="/home/{machine_user}",\
root_dir="/",max_run_time="01:00:00",max_procs_per_node=16,\
min_procs_per_node=16,allocation="N/A",\
scheduler="SLURM",custom_directives=None,\
user=None,passw=None,baseurl=None, \
tenant=None,notify=None):
self.loadf(utype,user,passw,baseurl,tenant,notify,None)
self.values["machine"] = machine
self.values["apiurl"] = baseurl
self.values["domain"] = domain
self.values["allocation"] = allocation
self.values["max_run_time"] = max_run_time
self.values["other"]= user
self.values["machine_user"] = machine_user
self.values["work_dir"] = self.fill(work_dir)
self.values["home_dir"] = self.fill(home_dir)
self.values["scratch_dir"] = self.fill(scratch_dir)
self.values["root_dir"] = self.fill(root_dir)
self.values["queue"] = queue
self.values["scheduler"] = scheduler
self.values["custom_directives"] = custom_directives
self.values["min_procs_per_node"] = min_procs_per_node
self.values["max_procs_per_node"] = max_procs_per_node
self.values["max_jobs_per_user"] = max_jobs_per_user
self.values["max_jobs"] = max_jobs
self.values["max_nodes"] = max_nodes
self.values["app_name"] = self.fill("{machine}-{machine_user}_queue_{other}")
self.values["fork_app_name"] = self.fill("{machine}-{machine_user}_fork_{other}")
self.values["storage_id"] = self.fill('{machine}-{machine_user}-storage-{other}')
self.values["execm_id"] = self.fill('{machine}-{machine_user}-exec-{other}')
self.values["forkm_id"] = self.fill('{machine}-{machine_user}-fork-{other}')
self.mk_extra()
def init(self,**kwargs):
# Required options with default values.
# Values of "uknown" or -666 mean the
# user must supply a value.
assert "backend" in kwargs.keys(), "backend is required"
self.values["backend"] = kwargs["backend"]
machine_meta = {}
for k in kwargs:
if k not in ["notify", "backend"]:
machine_meta[k] = kwargs[k]
self.set_backend()
# Check the values supplied in kwargs are
# of the expected name and type
for k in kwargs.keys():
assert k in self.values.keys(),\
"Invalid argument '%s'" % k
assert type(self.values[k]) == type(kwargs[k]),\
"The type of arg '%s' should be '%s'" % (k, str(type(self.values[k])))
self.values[k] = kwargs[k]
self.values["sys_pw"] = self.values["backend"]["pass"]
self.values["sys_user"] = self.fill(self.values["backend"]["user"])
# we are initializing with raw data here...
self.values["other"] = self.values["sys_user"]
self.create_or_refresh_token()
# Check for missing values
for k in self.values:
assert self.values[k] != "unknown", "Please supply a string value for '%s'" % k
assert self.values[k] != -666, "Please supply an integer value for '%s'" % k
self.values["storage_id"] = self.fill('{machine}-{machine_user}-storage-{other}')
self.values["execm_id"] = self.fill('{machine}-{machine_user}-exec-{other}')
self.values["forkm_id"] = self.fill('{machine}-{machine_user}-fork-{other}')
self.mk_extra()
name = "machine-config-"+self.values["other"]+"-"+self.values["jetlag_id"]
mm = {
"name" : name,
"value" : machine_meta
}
def mk_extra(self):
# Create a few extra values
self.jobs_dir()
self.values['app_id'] = self.fill("{app_name}-{app_version}")
self.values['fork_app_id'] = self.fill("{fork_app_name}-{app_version}")
# Authenticate to Agave/Tapis
# Use generic refresh if possible
self.set_auth_type('PASSWORD')
def set_backend(self):
backend = self.values["backend"]
for bk in ["user", "pass", "tenant", "utype"]:
assert bk in backend.keys(), "key '%s' is required in backend: %s" % (bk,str(backend))
self.values["sys_user"] = sys_user = backend["user"]
pass_var = backend["pass"]
self.values["sys_pw_env"] = pass_var
tenant = backend["tenant"]
self.values["tenant"] = backend["tenant"]
self.values["utype"] = backend["utype"]
self.values["apiurl"] = backend["baseurl"]
def get_auth_file(self):
user = self.fill("{sys_user}")
burl = codeme("~".join([
self.values["backend"]["tenant"],
self.values["backend"]["baseurl"],
self.values["backend"]["utype"],
self.values["backend"]["user"]
]))
if self.values['utype'] == 'tapis':
auth_file = os.environ["HOME"]+"/.tapis/"+user+"/"+burl+"/current"
else:
auth_file = os.environ["HOME"]+"/.agave/"+user+"/"+burl+"/current"
return auth_file
def getauth(self):
auth_file = self.get_auth_file()
auth_age = os.path.getmtime(auth_file)
if auth_age == self.auth_age:
return self.auth_data
self.auth_age = auth_age
with open(auth_file,"r") as fd:
auth_data = json.loads(fd.read())
self.values["apiurl"] = auth_data["baseurl"]
self.values["authtoken"] = auth_data["access_token"]
self.auth_data = auth_data
return auth_data
def getheaders(self,data=None):
"""
We need basically the same auth headers for
everything we do. Factor out their initialization
to a common place.
"""
self.getauth()
headers = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Authorization': self.fill('Bearer {authtoken}'),
'Connection': 'keep-alive',
'User-Agent': 'python-requests/2.22.0',
}
if data is not None:
assert type(data) == str
headers['Content-type'] = 'application/json'
headers['Content-Length'] = str(len(data))
return headers
def fill(self,s,cycle={}):
"""
Similar to string's format method, except that we
don't require double curly's. We simply don't replace
things we don't recognize. Also, this can apply to
a data structure, not just a string.
"""
if type(s) == dict:
ns = {}
for k in s.keys():
ns[k] = self.fill(s[k])
return ns
elif type(s) == list:
nl = []
for item in s:
nl += [self.fill(item)]
return nl
elif type(s) == tuple:
nl = []
for item in s:
nl += [self.fill(item)]
return tuple(nl)
elif type(s) == str:
while True:
done = True
ns = ''
li = 0
for g in re.finditer(r'{(\w+)}',s):
ns += s[li:g.start(0)]
li = g.end(0)
key = g.group(1)
assert key not in cycle, key+":"+s
val = None
if key in self.values.keys():
cy = copy(cycle)
cy[key]=1
val = self.fill(self.values[key],cy)
else:
if re.match(r'.*_USER$',key):
val = load_input(key,False)
elif re.match(r'.*_PASSWORD$',key):
val = load_input(key,True)
if val is not None:
ns += str(val)
done = False
else:
ns += s[g.start(0):g.end(0)]
ns += s[li:]
s = ns
if done:
break
return s
else:
return s
def configure_from_password(self):
"""
Completely configure the univeral system
starting from a password.
"""
self.set_auth_type("PASSWORD")
self.mk_storage(force=True)
self.install_key()
self.configure_from_ssh_keys()
def configure_from_ssh_keys(self, pub_key=None, priv_key=None):
"""
Completely configure the univeral system
starting from ssh keys.
"""
if pub_key is not None or priv_key is not None:
self.public_key = pub_key.strip()
self.private_key = priv_key.strip()
self.set_auth_type("SSHKEYS")
self.mk_storage(force=True)
self.mk_execution(force=True)
self.mk_app(force=True)
def set_auth_type(self, auth):
"""
Determine whether we are using passw or ssh
"""
if auth == "SSHKEYS":
if self.public_key is None:
# Create and load ssh keys
if not os.path.exists("uapp-key.pub"):
r, o, e =pcmd(["ssh-keygen","-m","PEM","-t","rsa","-f","uapp-key","-P",""])
assert r == 0
self.public_key = readf('uapp-key.pub')
self.private_key = readf('uapp-key')
# Create the ssh auth structure for
# use by storage and execution systems
self.ssh_auth = self.fill({
"username" : "{machine_user}",
"publicKey" : self.public_key,
"privateKey" : self.private_key,
"type" : "SSHKEYS"
})
self.auth = self.ssh_auth
elif auth == "PASSWORD":
# Create the password auth structure for
# use by storage and execution systems
self.pw_auth = self.fill({
"username" : "{machine_user}",
"password" : "",
"type" : "PASSWORD"
})
self.auth = self.pw_auth
else:
raise Exception("auth:"+str(auth))
print("auth is now:",self.auth['type'])
def get_storage(self):
headers = self.getheaders()
response = requests.get(
self.fill('{apiurl}/systems/v2/{storage_id}'), headers=headers)
if response.status_code == 404:
return None
check(response)
json_data = response.json()
json_data = json_data["result"]
return json_data
def get_exec(self):
headers = self.getheaders()
url = self.fill('{apiurl}/systems/v2/{execm_id}')
response = requests.get(url, headers=headers)
if response.status_code == 403:
print(url)
if response.status_code == 404:
return None
check(response)
json_data = response.json()
json_data = json_data["result"]
return json_data
def get_auth_type(self):
storage = self.get_storage()
if storage == None:
return "PASSWORD"
return storage["storage"]["auth"]["type"]
##### Storage Machine Setup
def mk_storage(self,force=False):
storage_id = self.values["storage_id"]
print("STORAGE MACHINE:",storage_id)
port = int(self.values["port"])
storage = self.fill({
"id" : storage_id,
"name" : "{machine} storage ({machine_user})",
"description" : "The {machine} computer",
"site" : "{domain}",
"type" : "STORAGE",
"storage" : {
"host" : "{machine}.{domain}",
"port" : port,
"protocol" : "SFTP",
"rootDir" : "{root_dir}",
"homeDir" : "{home_dir}",
"auth" : self.auth,
"publicAppsDir" : "{home_dir}/apps"
}
})
if not force:
headers = self.getheaders()
response = requests.get(
self.fill('{apiurl}/systems/v2/{storage_id}'), headers=headers)
print(self.fill('{apiurl}/systems/v2/{storage_id}'))
check(response)
json_data = response.json()
json_data = json_data["result"]
storage_update = (check_data(storage, json_data) > 0)
else:
storage_update = True
if storage_update or (not self.check_machine(storage_id)):
json_storage = json.dumps(storage)
headers = self.getheaders(json_storage)
response = requests.post(
self.fill('{apiurl}/systems/v2/'), headers=headers, data=json_storage)
check(response)
assert self.check_machine(storage_id)
def files_list(self, dir):
headers = self.getheaders()
params = (('limit','100'),('offset','0'),)
if self.values["utype"] == 'tapis':
dir = self.values["home_dir"]+"/"+dir
pause()
response = requests.get(
self.fill('{apiurl}/files/v2/listings/system/{storage_id}//'+dir), headers=headers, params=params)
check(response)
return response.json()["result"]
def job_by_name(self,name):
headers = self.getheaders()
params = (
('name', name),
)
response = requests.get(
self.fill('{apiurl}/jobs/v2'), headers=headers, params=params)
check(response)
return response.json()["result"]
def job_cleanup(self):
"""
Job cleanup walks through the job directory
on the remote machine and checks to see if
the input staging data is still needed. If
not, it cleans it up.
This command also displays the output of
the job if possible.
"""
if self.is_tapis():
fdata = self.files_list(self.jobs_dir())
else:
fdata = self.files_list(self.jobs_dir())
for f in fdata:
if f["format"] == "folder":
job_name = f["name"]
if not re.match(r'[\w-]{10,}',job_name):
print("Invalid job name:",job_name)
continue
headers = self.getheaders()
jdata = self.job_by_name(job_name)
if len(jdata) == 0:
print("Could not lookup job by name:",job_name)
continue
elif len(jdata) > 1:
print("Multiple jobs with name:",job_name)
continue
jentry = jdata[0]
if "status" not in jentry.keys():
continue
if jentry["status"] not in job_done:
continue
jobid = jentry["id"]
headers = self.getheaders()
pause()
pause()
print("Deleting job data for:",job_name,jobid)
response = requests.delete(
self.fill('{apiurl}/files/v2/media/system/{storage_id}/{job_dir}/'+job_name), headers=headers)
check(response)
def create_or_refresh_token(self):
auth_file = self.get_auth_file()
print("auth_file:",auth_file)
if os.path.exists(auth_file):
self.auth_mtime = os.path.getmtime(auth_file)
if not self.refresh_token():
self.create_token()
def create_token(self):
if "sys_pw" not in self.values or self.values["sys_pw"] == "unknown":
self.values["sys_pw"] = self.values["backend"]["pass"]
self.values["sys_user"] = self.fill(self.values["sys_user"])
self.values["sys_pw"] = self.fill(self.values["sys_pw"])
auth = (
self.values["sys_user"],
self.values["sys_pw"]
)
while True:
# Create a client name and search to see if it exists
client_name = "client-"+str(randint(1,int(1e10)))
data = {
'clientName': client_name,
'tier': 'Unlimited',
'description': '',
'callbackUrl': ''
}
break
url = self.fill('{apiurl}/clients/v2/')+client_name
response = requests.get(url, auth=auth)
jdata = response.json()['result']
if response.status_code in [404, 400]:
break
check(response)
assert jdata["name"] == client_name
url = self.fill('{apiurl}/clients/v2/')
response = requests.post(url, data=data, auth=auth)
check(response)
jdata = response.json()["result"]
c_key = jdata['consumerKey']
c_secret = jdata['consumerSecret']
data = {
'grant_type':'password',
'scope':'PRODUCTION',
'username':self.values['sys_user'],
'password':self.values['sys_pw']
}
response = requests.post(self.fill('{apiurl}/token'), data=data, auth=(c_key, c_secret))
jdata = response.json()
now = time()
delt = int(jdata["expires_in"])
ts = now + delt
fdata = {
"tenantid":self.values['tenant'],
"baseurl":self.values['apiurl'],
"apisecret":c_secret,
"apikey":c_key,
"username":self.values['sys_user'],
"access_token":jdata['access_token'],
"refresh_token":jdata["refresh_token"],
"expires_in":delt,
"created_at":int(now),
"expires_at":datetime.utcfromtimestamp(ts).strftime('%c')
}
auth_file = self.get_auth_file()
os.makedirs(os.path.dirname(auth_file), exist_ok=True)
with open(auth_file,"w") as fd:
fd.write(json.dumps(fdata))
return fdata
def refresh_token(self):
"""
This is under construction (i.e. it doesn't work).
In principle, it can refresh an agave/tapis token.
"""
auth_file = self.get_auth_file()
if not os.path.exists(auth_file):
return False
if age(auth_file) < 30*60:
return True
auth_data = self.getauth()
data = {
'grant_type': 'refresh_token',
'refresh_token': auth_data['refresh_token'],