forked from aluckhur/xcption
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxcption.py
More file actions
executable file
·6420 lines (5337 loc) · 252 KB
/
xcption.py
File metadata and controls
executable file
·6420 lines (5337 loc) · 252 KB
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
#!/usr/bin/python3
# XCPtion - NetApp XCP,robocopy,cloudsync, rclone and ndmpcopy wrapper
# Written by Haim Marko
# Enjoy
#version
version = '3.3.4.5'
import configparser
import csv
import argparse
import re
import logging
import logging.handlers
import sys
import os
import json
import pprint
import nomad
import requests
import subprocess
import shutil
import croniter
import datetime
import time
import copy
import fnmatch
import socket
import string
import base64
import random
from hurry.filesize import size
from prettytable import PrettyTable
from jinja2 import Environment, FileSystemLoader
from treelib import Node, Tree
pp = pprint.PrettyPrinter(indent=1)
#general settings DO NOT CHANGE
dcname = 'DC1'
#default windows tool
defaultwintool = 'xcp'
#xcp windows location
winpath = 'C:\\NetApp\\XCP'
xcpwinpath = 'C:\\NetApp\\XCP\\xcp.exe'
xcpwincopyparam = "-preserve-atime -acl -root"
xcpwinsyncparam = "-preserve-atime -acl -root"
xcpwinverifyparam = "-v -l -nodata -preserve-atime"
#robocopy windows location
robocopywinpath = 'C:\\NetApp\\XCP\\robocopy_wrapper.ps1'
robocopywinpathassess = 'C:\\NetApp\\XCP\\robocopy_wrapper.ps1'
robocopyargs = '/COPY:DATSO /MIR /NP /DCOPY:DAT /MT:32 /R:0 /W:0 /TEE /BYTES /NDL'
#location of the script
root = os.path.dirname(os.path.abspath(__file__))
#path to file containing the location of robocopy unicode log file (usefull for hebrew)
robocopylogpath = os.path.join(root,'windows','robocopy_log_file_dir')
#xcp repo and cache dir location
xcprepopath = os.path.join(root,'system','xcp_repo')
#xcplinux path - need wrapper to support xcp 1.6
xcppath = os.path.join(root,'system','xcp_wrapper.sh')
xcplocation = '/usr/local/bin/xcp'
#xcp indexes path
xcpindexespath = os.path.join(xcprepopath,'catalog','indexes')
#cache dir for current state
cachedir = os.path.join(xcprepopath,'nomadcache')
#smartassess dir for current state
smartassessdir = os.path.join(xcprepopath,'smartassess')
#path to nomad bin
nomadpath = '/usr/local/bin/nomad'
#location for the jobs dir
jobsdir = os.path.join(xcprepopath,'jobs')
#exclude dirictory files location
excludedir = os.path.join(xcprepopath,'excludedir')
#file containing loaded jobs
jobdictjson = os.path.join(jobsdir,'jobs.json')
#smartassess json jobs file
smartassessjobdictjson = os.path.join(smartassessdir,'smartassessjobs.json')
#job template dirs
ginga2templatedir = os.path.join(root,'template')
#webtemplates
webtemplatedir = os.path.join(root,'webtemplates')
#file upload location within the webtempate dir
uploaddir = os.path.join(webtemplatedir,'upload')
#cloudsync integration script
cloudsyncscript = os.path.join(root,'cloudsync','cloudsync.py')
#rclone bin
rclonebin = os.path.join(root,'system','rclone_wrapper.sh')
#rclone conf dir
rcloneconffile = os.path.join(xcprepopath,'rclone','rclone.conf')
rcloneglobalflags = '--no-check-certificate --log-level debug --stats 1m --retries 1 --auto-confirm --multi-thread-streams 32 --checkers 32 --progress --metadata --transfers 16'
#ndmpcopy bin
ndmpcopybin = os.path.join(root,'system','ndmpcopy_wrapper.sh')
#log file location
logdirpath = os.path.join(root,'log')
logfilepath = os.path.join(logdirpath,'xcption.log')
#creating the logs directory
if not os.path.isdir(logdirpath):
try:
os.mkdir(logdirpath)
except Exception as e:
logging.error("could not create log directoy:" + logdirpath)
exit (1)
#default nomad job properties
defaultjobcron = "0 0 * * * *" #nightly @ midnight
defaultcpu = 3000
defaultmemory = 800
#max logs for status -l
maxloglinestodisplay = 50
#max syncs to keep per job (when sync count is bigger than this number older syncs will be deleted)
maxsyncsperjob = 10
#smartassess globals
minsizekfortask_minborder = 0.5*1024*1024*1024 #512GB
mininodespertask_minborder = 100000
maxjobs = 100
totaljobssizek = 0
totaljobsinode = 0
totaljobscreated = 0
#default http port for flask
defaulthttpport = 1234
parent_parser = argparse.ArgumentParser(add_help=False)
parser = argparse.ArgumentParser()
parser.add_argument('-v','--version', help="print version information", action='store_true')
parser.add_argument('-d','--debug', help="log debug messages to console", action='store_true')
subparser = parser.add_subparsers(dest='subparser_name', help='sub commands that can be used')
# create the sub commands
parser_nodestatus = subparser.add_parser('nodestatus', help='display cluster nodes status',parents=[parent_parser])
parser_status = subparser.add_parser('status', help='display status',parents=[parent_parser])
parser_assess = subparser.add_parser('assess', help='assess filesystem and create csv file',parents=[parent_parser])
parser_map = subparser.add_parser('map', help='map shares/exports',parents=[parent_parser])
parser_load = subparser.add_parser('load', help='load/update configuration from csv file',parents=[parent_parser])
parser_create = subparser.add_parser('create', help='create ad-hoc task',parents=[parent_parser])
parser_baseline = subparser.add_parser('baseline', help='start initial baseline',parents=[parent_parser])
parser_sync = subparser.add_parser('sync', help='activate scheduled sync',parents=[parent_parser])
parser_syncnow = subparser.add_parser('syncnow', help='initiate sync now',parents=[parent_parser])
parser_pause = subparser.add_parser('pause', help='disable sync schedule',parents=[parent_parser])
parser_resume = subparser.add_parser('resume', help='resume sync schedule',parents=[parent_parser])
parser_abort = subparser.add_parser('abort', help='abort running task')
parser_verify = subparser.add_parser('verify', help='start verify to validate consistency between source and destination')
parser_delete = subparser.add_parser('delete', help='delete existing tasks',parents=[parent_parser])
parser_modify = subparser.add_parser('modify', help='modify task job',parents=[parent_parser])
parser_copydata = subparser.add_parser('copy-data', help='monitored copy of source to destination (nfs only)',parents=[parent_parser])
parser_deletedata = subparser.add_parser('delete-data',help='monitored delete of data using xcp (nfs only)',parents=[parent_parser])
parser_nomad = subparser.add_parser('nomad', description='hidden command, usded to update xcption nomad cache',parents=[parent_parser])
parser_export = subparser.add_parser('export', help='export tasks to csv',parents=[parent_parser])
parser_web = subparser.add_parser('web', help='start web interface to display status',parents=[parent_parser])
parser_fileupload = subparser.add_parser('fileupload', help='transfer files to all nodes, usefull for xcp license update on all nodes',parents=[parent_parser])
parser_status.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_status.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_status.add_argument('-t','--jobstatus',help="change the scope of the command to specific job status ex:complete,running,failed,pending,aborted", required=False,type=str,metavar='jobstatus')
parser_status.add_argument('-v','--verbose',help="provide verbose per phase info", required=False,action='store_true')
parser_status.add_argument('-p','--phase',help="change the scope of the command to specific phase ex:baseline,sync#,verify#,lastsync", required=False,type=str,metavar='phase')
parser_status.add_argument('-n','--node',help="change the scope of the command to specific node", required=False,type=str,metavar='node')
parser_status.add_argument('-e','--error',help="change the scope of the command to jobs with errors", required=False,action='store_true')
parser_status.add_argument('-o','--output',help="output type: [csv|json]",choices=['csv','json'],required=False,type=str,metavar='output')
parser_status.add_argument('-l','--logs',help="display job logs", required=False,action='store_true')
parser_assess.add_argument('-s','--source',help="source path",required=True,type=str)
parser_assess.add_argument('-d','--destination',help="destination path",required=True,type=str)
parser_assess.add_argument('-l','--depth',help="filesystem depth to create jobs, range of 1-12",required=True,type=int)
parser_assess.add_argument('-b','--basedepth',help="lower filesystem depth to create jobs, when not provided it will default to depth, range of 1-12 lower/equal to depth",required=False,type=int, default=-1)
parser_assess.add_argument('-c','--csvfile',help="output CSV file",required=True,type=str)
parser_assess.add_argument('-p','--cpu',help="CPU allocation in MHz for each job",required=False,type=int)
parser_assess.add_argument('-m','--ram',help="RAM allocation in MB for each job",required=False,type=int)
parser_assess.add_argument('-r','--robocopy',help="use robocopy instead of xcp for windows jobs", required=False,action='store_true')
parser_assess.add_argument('-u','--failbackuser',help="failback user required for xcp for windows jobs, see xcp.exe copy -h", required=False,type=str)
parser_assess.add_argument('-g','--failbackgroup',help="failback group required for xcp for windows jobs, see xcp.exe copy -h", required=False,type=str)
parser_assess.add_argument('-j','--job',help="xcption job name", required=False,type=str,metavar='jobname')
parser_assess.add_argument('-n','--cron',help="create all task with schedule ", required=False,type=str,metavar='cron')
parser_assess.add_argument('-a','--acl',help="use no-win-acl to prevent acl copy for cifs jobs or nfs4-acl to enable nfs4-acl copy", choices=['no-win-acl','nfs4-acl'], required=False,type=str,metavar='aclcopy')
parser_map.add_argument('-s','--hosts',help="comma seperated servers to map shares or exportrts",required=True,type=str)
parser_map.add_argument('-p','--protocol',help="server protocol: [cifs|nfs]",choices=['cifs','nfs'],required=True,type=str,metavar='type')
parser_map.add_argument('-o','--output',help="output type: [csv|json]",choices=['table','csv','json'],required=False,default='table',type=str,metavar='output')
parser_create.add_argument('-j','--job',help="xcption job name", required=True, type=str,metavar='jobname')
parser_create.add_argument('-s','--source',help="source path",required=True,type=str)
parser_create.add_argument('-d','--destination',help="destination path",required=True,type=str)
parser_create.add_argument('-p','--cpu',help="CPU allocation in MHz for each job",required=False,type=int)
parser_create.add_argument('-m','--ram',help="RAM allocation in MB for each job",required=False,type=int)
parser_create.add_argument('-t','--tool',help="tool to use, can be [xcp|robocopy|rclone|ndmpcopy|cloudsync]", choices=['xcp','robocopy','rclone','ndmpcopy','cloudsync'],required=False,default='xcp',type=str,metavar='tool')
parser_create.add_argument('-n','--cron',help="create all task with schedule ", required=False,type=str,metavar='cron')
parser_create.add_argument('-e','--exclude',help="comma separated exclude paths",required=False,type=str)
parser_create.add_argument('-v','--novalidation',help="create can be faster for windows paths since validation is prevented", required=False,action='store_true')
#parser_create.add_argument('-a','--acl',help="use no-win-acl to prevent acl copy for cifs jobs or nfs4-acl to enable nfs4-acl copy", choices=['no-win-acl','nfs4-acl'], required=False,type=str,metavar='aclcopy')
parser_copydata.add_argument('-s','--source',help="source nfs path (nfssrv:/mount)",required=True,type=str)
parser_copydata.add_argument('-d','--destination',help="destination nfs path (nfssrv:/mount)",required=True,type=str)
parser_copydata.add_argument('-f','--force',help="force copy event if destination contains files", required=False,action='store_true')
parser_copydata.add_argument('-a','--nfs4acl',help="use to include nfs4-acl", required=False,action='store_true')
parser_deletedata.add_argument('-s','--source',help="source nfs path (nfssrv:/mount)",required=True,type=str)
parser_deletedata.add_argument('-t','--tool',help="tool to use (default is xcp)",choices=['xcp','rclone'],required=False,default='xcp',type=str,metavar='tool')
parser_deletedata.add_argument('-f','--force',help="force delete data without confirmation", required=False,action='store_true')
parser_load.add_argument('-c','--csvfile',help="input CSV file with the following columns: JOB NAME,SOURCE PATH,DEST PATH,SYNC SCHED,CPU MHz,RAM MB,TOOL,FAILBACKUSER,FAILBACKGROUP,EXCLUDE DIR FILE",required=True,type=str)
parser_load.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_load.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_load.add_argument('-v','--novalidation',help="load can be faster for windows paths since validation is prevented", required=False,action='store_true')
parser_baseline.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_baseline.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_baseline.add_argument('-f','--force',help="force re-baseline", required=False,action='store_true')
parser_sync.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_sync.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_syncnow.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_syncnow.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_pause.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_pause.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_resume.add_argument('-j','--job', help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_resume.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_abort.add_argument('-j','--job', help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_abort.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_abort.add_argument('-t','--type',help="specify the type of job to abort, can be baseline,sync or verify", choices=['baseline','sync','verify'],required=True,type=str,metavar='type')
parser_abort.add_argument('-f','--force',help="force abort", required=False,action='store_true')
parser_verify.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_verify.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_verify.add_argument('-q','--quick',help="perform quicker verify by using xcp random file verify (1 out of 1000)", required=False,action='store_true')
parser_verify.add_argument('-w','--withdata',help="perform deep data verification (full content verification)", required=False,action='store_true')
parser_verify.add_argument('-r','--reverse',help="perform reverse verify (dst will be compared to the src)", required=False,action='store_true')
parser_verify.add_argument('-n','--nometadata',help="dont verify file ownerhip, acl and attr", required=False,action='store_true', default=False)
parser_delete.add_argument('-j','--job', help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_delete.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_delete.add_argument('-f','--force',help="force delete", required=False,action='store_true')
parser_modify.add_argument('-j','--job', help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_modify.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_modify.add_argument('-t','--tojob',help="move selected tasks to this job", required=False,type=str,metavar='tojob')
parser_modify.add_argument('-c','--cron',help="modify the sync schedule for this job", required=False,type=str,metavar='cron')
parser_modify.add_argument('-p','--cpu',help="modify CPU allocation in MHz for each job",required=False,type=int)
parser_modify.add_argument('-m','--ram',help="modify RAM allocation in MB for each job",required=False,type=int)
parser_modify.add_argument('-f','--force',help="force modify", required=False,action='store_true')
parser_export.add_argument('-c','--csvfile',help="input CSV file with the following columns: Job Name,SRC Path,DST Path,Schedule,CPU,Memory",required=True,type=str)
parser_export.add_argument('-j','--job',help="change the scope of the command to specific job", required=False,type=str,metavar='jobname')
parser_export.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_web.add_argument('-p','--port',help="tcp port to start the web server on (default:"+str(defaulthttpport)+')', required=False,default=defaulthttpport,type=int,metavar='port')
parser_fileupload.add_argument('-f','--file',help="path to upload", required=True,type=str,metavar='file')
parser_fileupload.add_argument('-l','--linuxpath',help="destination path for linux hosts. license file default: /opt/NetApp/xFiles/xcp/license", required=False,type=str,metavar='linuxpath')
parser_fileupload.add_argument('-w','--windowspath',help="destination path for linux hosts. license file default: C:\\NetApp\\XCP\\license", required=False,type=str,metavar='windowspath')
parser_fileupload.add_argument('-p','--port',help="tcp port to start the web server on (default:"+str(defaulthttpport)+')', required=False,default=defaulthttpport,type=int,metavar='port')
parser_smartassess = subparser.add_parser('smartassess',help='create tasks based on capacity and file count (nfs only)',parents=[parent_parser])
action_subparser = parser_smartassess.add_subparsers(title="action",dest="smartassess_command")
parser_smartassess_start = action_subparser.add_parser('start',help='scan src to create tasks based on capacity and inode count (nfs only)',parents=[parent_parser])
parser_smartassess_status = action_subparser.add_parser('status',help='display scan status and filesystem info',parents=[parent_parser])
parser_smartassess_createcsv = action_subparser.add_parser('createcsv',help='create csv job file based on the scan results',parents=[parent_parser])
parser_smartassess_delete = action_subparser.add_parser('delete',help='delete existing scan information',parents=[parent_parser])
parser_smartassess_start.add_argument('-s','--source',help="source nfs path (nfssrv:/mount)",required=True,type=str)
parser_smartassess_start.add_argument('-l','--depth',help="filesystem depth to create jobs, range of 1-12",required=True,type=int)
parser_smartassess_start.add_argument('-k','--locate-cross-task-hardlink',help="located hardlinks that will be converted to regular files when splited to diffrent jobs",required=False,action='store_true')
#check capacity parameter
def checkcapacity (capacity):
matchObj = re.match(r"^(\d+)(\s+)?(K|B|M|G|T)(i)?B$",capacity)
if not matchObj:
raise argparse.ArgumentTypeError("invalid capacity")
return capacity
#convert K to human readable
def k_to_hr (k):
hr = format(k,',')+'KiB'
if 1024 <= k <= 1024*1024:
hr = format(int(k/1024),',')+'MiB'
elif 1024*1024 <= k <= 1024*1024*1024:
hr = format(int(k/1024/1024),',')+'GiB'
elif 1024*1024*1024*1024 <= k:
hr = format(int(k/1024/1024/1024),',')+'TiB'
return hr
parser_smartassess_status.add_argument('-s','--source',help="change the scope of the command to specific source path", required=False,type=str,metavar='srcpath')
parser_smartassess_status.add_argument('-i','--min-inodes',help="minimum required inodes per task default is:"+format(mininodespertask_minborder,','), required=False,type=int,metavar='mininodes')
parser_smartassess_status.add_argument('-a','--min-capacity',help="minimum required capacity per task default is:"+k_to_hr(minsizekfortask_minborder), required=False,type=checkcapacity,metavar='mincapacity')
parser_smartassess_status.add_argument('-t','--tasks',help="provide verbose task information per suggested path", required=False,action='store_true')
parser_smartassess_status.add_argument('-l','--hardlinks',help="provide cross task hardlink information per suggested path", required=False,action='store_true')
parser_smartassess_createcsv.add_argument('-s','--source',help="create CSV for the following src", required=True,type=str,metavar='srcpath')
parser_smartassess_createcsv.add_argument('-d','--destination',help="set destination path", required=True,type=str,metavar='dstpath')
parser_smartassess_createcsv.add_argument('-c','--csvfile',help="output CSV file",required=True,type=str)
parser_smartassess_createcsv.add_argument('-i','--min-inodes',help="minimum required inodes per task default is:"+format(mininodespertask_minborder,','), required=False,type=int,metavar='maxinodes')
parser_smartassess_createcsv.add_argument('-a','--min-capacity',help="minimum required capacity per task default is:"+k_to_hr(minsizekfortask_minborder), required=False,type=checkcapacity,metavar='mincapacity')
parser_smartassess_createcsv.add_argument('-p','--cpu',help="CPU allocation in MHz for each job",required=False,type=int)
parser_smartassess_createcsv.add_argument('-m','--ram',help="RAM allocation in MB for each job",required=False,type=int)
parser_smartassess_createcsv.add_argument('-j','--job',help="xcption job name", required=False,type=str,metavar='jobname')
parser_smartassess_delete.add_argument('-s','--source',help="change the scope of the command to specific path", required=False,type=str,metavar='srcpath')
parser_smartassess_delete.add_argument('-f','--force',help="force delete", required=False,action='store_true')
#parser_smartassess.print_help()
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
#initialize logging
log = logging.getLogger()
log.setLevel(logging.DEBUG)
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.WARNING)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
formatterdebug = logging.Formatter('%(asctime)s - %(levelname)s - %(funcName)s - %(message)s')
# create file handler which logs even debug messages
#fh = logging.FileHandler(logfilepath)
fh = logging.handlers.RotatingFileHandler(logfilepath, maxBytes=1048576, backupCount=5)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatterdebug)
log.addHandler(fh)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
if args.debug: ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
log.addHandler(ch)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logging.debug("starting " + os.path.basename(sys.argv[0]))
#initialize dict objects
jobsdict = {}
smartassessdict = {}
dstdict = {}
nomadout = {}
#creation of the nomad instance
n = nomad.Nomad(host="localhost", timeout=5)
#baseutl for nomad rest api requests
nomadapiurl = 'http://localhost:4646/v1/'
#return nomad job details has dict, assert if not exists
def getnomadjobdetails (nomadjobname):
job = {}
try:
job = n.job.get_job(nomadjobname)
except Exception as e:
assert not job
return job
#load smartassess from json
def load_smartassess_jobs_from_json (jobdictjson):
global smartassessdict
if os.path.exists(jobdictjson):
try:
logging.debug("loading existing json file:"+jobdictjson)
with open(jobdictjson) as f:
smartassessdict = json.load(f)
except Exception as e:
logging.debug("could not load existing json file:"+jobdictjson)
#load jobsdict from json
def load_jobs_from_json (jobdictjson):
global jobsdict
if os.path.exists(jobdictjson):
try:
logging.debug("loading existing json file:"+jobdictjson)
with open(jobdictjson) as f:
jobsdict = json.load(f)
except Exception as e:
logging.debug("could not load existing json file:"+jobdictjson)
#run ssh to remote host
def ssh (hostname:str, cmd: list = []):
cmdarr = ['ssh','-oStrictHostKeyChecking=no','-oBatchMode=yes',hostname] + cmd
logging.debug ("ssh command: ssh "+hostname+" "+" ".join(cmd))
result = subprocess.run(cmdarr, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = {'returncode': result.returncode,
'stdout': result.stdout.decode('utf-8'),
'stderr': result.stderr.decode('utf-8'),
'stdoutlines': result.stdout.decode('utf-8').splitlines()
}
matchObj = re.search(r" jobId \'(\d+)\'",output['stdout'])
if matchObj:
output['jobid'] = matchObj.group(1)
for line in output['stdoutlines']:
if line.startswith("ERROR:"):
output['error'] = line
return(output)
#validate ontap ndmp
def validate_ontap_ndmp(ontappath):
matchObj = re.match(r"^([a-zA-Z0-9\._%+-_]+)@([a-zA-Z0-9-_]+):\/([a-zA-Z0-9-_]+)\/([a-zA-Z0-9_]+)(.*)$",ontappath)
if matchObj:
ontapuser = matchObj.group(1)
ontaphost = matchObj.group(2)
svm = matchObj.group(3)
vol = matchObj.group(4)
dir = matchObj.group(5)
if not matchObj or (dir and not dir.startswith('/')):
logging.error("invalid ontap ndmp path:"+ontappath+" should be in the following format: user@cluster:/svm/vol[/dir]")
exit(1)
out = ssh(ontapuser+'@'+ontaphost,['node','run','-node','*','-command','version'])
if out['returncode']:
if 'is not a recognized command' in out['stdout']:
# could not run node run command - will not work if using vserver level login
logging.error("could not validtae:" + ontapuser+'@'+ontaphost+" is ontap cluster level login")
else:
logging.error("could not connect to:" + ontapuser+'@'+ontaphost+ " using SSH: "+out['stderr']+' '+out['stdout'])
exit(1)
out = ssh(ontapuser+'@'+ontaphost,"network interface show -role cluster-mgmt -instance".split(" "))
if out['returncode']:
logging.error("could not identify ontap cluste-mgmt lif")
exit(1)
matchObj = re.search(r"Vserver Name:\s([a-zA-Z0-9_-]+)",out['stdout'])
if matchObj:
clustername = matchObj.group(1)
else:
logging.error("could not identify ontap cluster name")
exit(1)
out = ssh(ontapuser+'@'+ontaphost,['vserver','services','ndmp','show','-vserver',clustername])
if out['returncode']:
logging.error("could not connect to:" + ontapuser+'@'+ontaphost+ " using SSH: "+out['stderr']+' '+out['stdout'])
exit(1)
if 'Enable NDMP on Vserver: false' in out['stdout']:
logging.warning("NDMP is not active on OnTap SVM: "+svm+" please start it using: vserver services ndmp on -vserver "+clustername)
# elif 'Enable NDMP on Vserver: true' in out['stdout']:
# logging.info("SSH connectivity and NDMP readiness validated to ontap cluster: "+clustername)
ndmpinfo = {}
ndmpinfo['host'] = ontaphost
ndmpinfo['user'] = ontapuser
ndmpinfo['path'] = '/'+svm+'/'+vol+dir
# get ndmp password
cmd = 'vserver services ndmp generate-password -vserver '+clustername+' -user '+ontapuser
out = ssh(ontapuser+'@'+ontaphost,cmd.split(' '))
matchObj = re.search(r"Password:\s(\w+)",out['stdout'])
if matchObj:
ndmpinfo['ndmppass'] = matchObj.group(1)
# get volume details
cmd = 'volume show -vserver '+svm+' -volume '+vol+' -fields state,junction-path,type,node'
out = ssh(ontapuser+'@'+ontaphost,cmd.split(' '))
matchObj = re.search(fr"\s{vol}\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*",out['stdout'])
if matchObj:
ndmpinfo['atate'] = matchObj.group(1)
ndmpinfo['junction'] = matchObj.group(2)
ndmpinfo['type'] = matchObj.group(3)
ndmpinfo['node'] = matchObj.group(4)
else:
logging.error(f"could not find ontap volume: {svm}:{vol}")
exit(1)
if ndmpinfo['atate'] != 'online':
logging.error(f"ontap volume: {svm}:{vol} is not online")
exit(1)
#when volume is mounted validate path exists
if ndmpinfo['junction'].startswith('/'):
cmd = 'vserver security file-directory show -vserver '+svm+' -path'
out = ssh(ontapuser+'@'+ontaphost,cmd.split(' ')+['"'+ndmpinfo['junction']+dir+'/.'+'"'])
matchObj = re.search(fr"File Path:\s+{ndmpinfo['junction']}",out['stdout'])
if not matchObj:
logging.error(f"ontap path: {svm}:{vol}{dir} does not exists")
exit(1)
else:
logging.warning(f"could not validate path because ontap volume: {svm}:{vol} is not mounted on the svm")
#look for intercluster IP address we will use for NDMP on the owning node
cmd = 'network interface show -vserver '+clustername+' -role intercluster -curr-node '+ndmpinfo['node']+' -status-admin up -status-oper up -fields curr-node,address'
out = ssh(ontapuser+'@'+ontaphost,cmd.split(' '))
matchObj = re.search(fr"\s+([0-9.]+)\s+{ndmpinfo['node']}\s*",out['stdout'])
if matchObj:
ndmpinfo['ndmpip'] = matchObj.group(1)
else:
logging.error(f"could not find ip address to use for ontap NDMP for: {svm}:{vol}, make sure intercluster lif is avaialble on node:{ndmpinfo['node']}")
exit(1)
ndmpinfo['ndmppath'] = ndmpinfo['ndmpip']+':'+ndmpinfo['path']
return(ndmpinfo)
#create ad-hock task
def create_job(job,source,destination,tool,cron,cpu,ram,exclude):
# set default args
if not cpu:
cpu = defaultcpu
if not ram:
ram = defaultmemory
if not cron:
cron = defaultjobcron
#build exlude file dir
excludefile = ''
if exclude:
excludearr = exclude.split(',')
excludearr = ["{}\n".format(i) for i in excludearr]
excludefile = os.path.join(excludedir,job+'.exclude')
logging.debug(f"creating exludefile:{excludefile} for src:{source}")
with open(excludefile, 'w') as fp:
fp.writelines(excludearr)
# create task structure
taskinfo = (job,source,destination,cron,cpu,ram,tool,'','',excludefile)
csvlines = "#JOB NAME,SOURCE PATH,DEST PATH,SYNC SCHED,CPU MHz,RAM MB,TOOL,FAILBACKUSER,FAILBACKGROUP,EXCLUDE DIRS,ACL COPY\n"
csvlines += ",".join(str(x) for x in taskinfo)+"\n"
csvfile = '/tmp/xcptionjob.'+str(os.getpid())
try:
with open(csvfile, 'w') as f:
f.write(csvlines)
except:
logging.error("ERROR: could not create file:"+csvfile)
exit(1)
parse_csv(csvfile)
os.remove(csvfile)
#parse input csv file
def parse_csv(csv_path):
global jobsdict
global dstdict
if not os.path.exists(csv_path):
logging.error("cannot find csv file:"+csv_path)
exit(1)
#checking existing job json file and try to load it
load_jobs_from_json(jobdictjson)
with open(csv_path) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
line = ' '.join(row)
if line_count == 0 or re.search(r"^\s*\#",line) or re.search(r"^\s*$",line):
line_count += 1
else:
logging.debug("parsing csv line:"+line)
jobname = row[0]
src = row[1]
dst = row[2]
if (jobfilter == '' or jobfilter == jobname) and (srcfilter == '' or fnmatch.fnmatch(src, srcfilter)):
cron = ''
if 3 < len(row): cron = row[3]
if cron == '': cron = defaultjobcron
try:
now = datetime.datetime.now()
cront = croniter.croniter(cron, now)
except Exception as e:
logging.error("cron format: "+cron+ " for src: "+ src + " is incorrect")
exit(1)
cpu = ''
if 4 < len(row): cpu = row[4]
if cpu == '': cpu = defaultcpu
memory = ''
if 5 < len(row): memory = row[5]
if memory == '': memory = defaultmemory
ostype = 'linux'
if src.__contains__('\\'):
ostype = 'windows'
tool = defaultwintool
if 6 < len(row): tool = row[6]
if tool == '': tool = defaultwintool
failbackuser =''
if 7 < len(row): failbackuser = row[7]
failbackgroup =''
if 8 < len(row): failbackgroup = row[8]
excludedirfile = ''
if 9 < len(row) and row[9] != '' : excludedirfile = os.path.join(excludedir,row[9])
#check if exclude file exists
if excludedirfile != '' and not os.path.isfile(excludedirfile):
logging.error("exclude dir file:"+excludedirfile+" for src:"+src+" could not be found")
exit(1)
aclcopy = ''
if 10 < len(row) and row[10] != '': aclcopy = row[10]
if aclcopy != '':
if not aclcopy in ['nfs4-acl','no-win-acl']:
logging.error("provided acl copy method:"+aclcopy+" for src:"+src+" is not supported. can be one of the following: nfs4-acl,no-win-acl")
exit(1)
if aclcopy == 'nfs4-acl' and ostype == 'windows':
logging.error("acl type: nfs4-acl is not supported for windows task")
exit(1)
if aclcopy == 'no-win-acl' and ostype == 'linux':
logging.error("acl type: nfs4-acl is not supported for windows task")
exit(1)
#logging.debug("parsing entry for job:"+jobname+" src:" + src + " dst:" + dst + " ostype:" + ostype + " tool:"+tool+" failbackuser:"+failbackuser+" failback group:"+failbackgroup+" exclude dir file:"+excludedirfile)
logging.debug(f"parsing entry for task:{jobname} src:{src} dst:{dst} ostype:{ostype} tool:{tool} failbackuser:{failbackuser} failbackgroup{failbackgroup} exclude dir file:{excludedirfile} aclcopy:{aclcopy}")
srcbase = src.replace(':/','-_')
srcbase = srcbase.replace('/','_')
srcbase = srcbase.replace(' ','-')
srcbase = srcbase.replace('\\','_')
srcbase = srcbase.replace('$','_dollar')
srcbase = srcbase.replace('@','_at_')
srcbase = srcbase.replace(':','_')
srcbase = srcbase.replace('(','_')
srcbase = srcbase.replace(')','_')
dstbase = dst.replace(':/','-_')
dstbase = dstbase.replace('/','_')
dstbase = dstbase.replace(' ','-')
dstbase = dstbase.replace('\\','_')
dstbase = dstbase.replace('$','_dollar')
dstbase = dstbase.replace('@','_at_')
dstbase = dstbase.replace(':','_')
dstbase = srcbase.replace('(','_')
dstbase = srcbase.replace(')','_')
#validate no duplicate src and destination
for j in jobsdict:
for s in jobsdict[j]:
if j == jobname and s==src and jobsdict[j][s]["dst"] == dst:
continue
if s == src and jobsdict[j][s]["dst"] != dst:
logging.warning("duplicate source found:" + src+"->"+dst)
#exit(1)
if dst == jobsdict[j][s]["dst"]:
logging.error("duplicate dst path: " + dst)
exit(1)
if not jobname in jobsdict:
jobsdict[jobname]={}
createcloudsync = False
if tool == 'cloudsync':
cloudsync_cmd = [cloudsyncscript,'validate','-s',escapestr(src),'-d',escapestr(dst)]
cloudsyncrel = {}
try:
logging.debug("running command: "+' '.join(cloudsync_cmd))
validatejson = subprocess.check_output(cloudsync_cmd,stderr=subprocess.STDOUT)
cloudsyncrel = json.loads(validatejson.decode('utf-8'))
except Exception as e:
logging.error("cannot validate source/destination paths for cloudsync src:"+src+" dst:"+dst)
os.system(' '.join(cloudsync_cmd))
exit(1)
if cloudsyncrel:
log.info("cloudsync relationship for src:"+src+" dst:"+dst+" already exists. status:"+cloudsyncrel['activity']['status']+' type:"'+cloudsyncrel['activity']['type']+'"')
else:
log.info("cloudsync relationship for src:"+src+" dst:"+dst+" does not exists")
createcloudsync = True
#set required params
srchost=''; srcpath=''; dsthost=''; dstpath='';
elif tool == 'rclone':
rclone_cmd = [rclonebin,'--config', rcloneconffile] + rcloneglobalflags.split(' ') + ['lsd',src+'/xcption_check_connectivity_to_bucket']
logging.debug("running command: "+' '.join(rclone_cmd))
if subprocess.call(rclone_cmd,stderr=subprocess.STDOUT,stdout=subprocess.DEVNULL):
logging.error("cannot validate src using rclone: " + src+ " ,check config file: "+rcloneconffile)
exit(1)
rclone_cmd = [rclonebin,'--config', rcloneconffile] + rcloneglobalflags.split(' ') + ['lsd',dst+'/xcption_check_connectivity_to_bucket']
logging.debug("running command: "+' '.join(rclone_cmd))
if subprocess.call(rclone_cmd,stderr=subprocess.STDOUT,stdout=subprocess.DEVNULL):
logging.error("cannot alidate dst using rclone: " + dst+ " ,check config file: "+rcloneconffile)
exit(1)
#set required params
srchost=''; srcpath=''; dsthost=''; dstpath='';
elif tool == 'ndmpcopy':
validate_ontap_ndmp(src)
validate_ontap_ndmp(dst)
#set required params
srchost=''; srcpath=''; dsthost=''; dstpath='';
else:
if ostype == 'linux':
if not re.search(r"\S+\:\/\S+", src):
logging.error("src path format is incorrect: " + src)
exit(1)
if not re.search(r"\S+\:\/\S+", dst):
logging.error("dst path format is incorrect: " + dst)
exit(1)
if args.subparser_name in ['load','create']:
#check if src/dst can be mounted
subprocess.call( [ 'mkdir', '-p','/tmp/temp_mount' ] )
logging.info("validating src:" + src + " and dst:" + dst+ " are mountable")
if subprocess.call( [ 'mount', '-t', 'nfs', '-o','vers=3', src, '/tmp/temp_mount' ],stderr=subprocess.STDOUT):
logging.error("cannot mount src using nfs: " + src)
exit(1)
subprocess.call( [ 'umount', '/tmp/temp_mount' ],stderr=subprocess.STDOUT)
if subprocess.call( [ 'mount', '-t', 'nfs', '-o','vers=3', dst, '/tmp/temp_mount' ],stderr=subprocess.STDOUT):
logging.error("cannot mount dst using nfs: " + dst)
exit(1)
subprocess.call( [ 'umount', '/tmp/temp_mount' ],stderr=subprocess.STDOUT)
if aclcopy == 'nfs4-acl':
if subprocess.call( [ 'mount', '-t', 'nfs4', src, '/tmp/temp_mount' ],stderr=subprocess.STDOUT):
logging.error("cannot mount src:"+src+" using nfs version 4 which is required for nfs4 acl processing")
exit(1)
subprocess.call( [ 'umount', '/tmp/temp_mount' ],stderr=subprocess.STDOUT)
if subprocess.call( [ 'mount', '-t', 'nfs4', dst, '/tmp/temp_mount' ],stderr=subprocess.STDOUT):
logging.error("cannot mount dst:"+dst+"using nfs version 4 which is required for nfs4 acl processing")
exit(1)
subprocess.call( [ 'umount', '/tmp/temp_mount' ],stderr=subprocess.STDOUT)
srchost,srcpath = src.split(":")
dsthost,dstpath = dst.split(":")
if ostype == 'windows':
if not re.search('^(\\\\?([^\\/]*[\\/])*)([^\\/]+)$', src):
logging.error("src path format is incorrect: " + src)
exit(1)
if not re.search('^(\\\\?([^\\/]*[\\/])*)([^\\/]+)$', dst):
logging.error("dst path format is incorrect: " + dst)
exit(1)
if not args.novalidation:
logging.info("validating src:" + src + " and dst:" + dst+ " cifs paths are available from one of the windows servers")
pscmd = 'if (test-path "'+src+'") {exit 0} else {exit 1}'
psstatus = run_powershell_cmd_on_windows_agent(pscmd)['status']
if psstatus != 'complete':
logging.error("cannot validate src:"+src+" using cifs, validation is:"+psstatus)
exit(1)
pscmd = 'if (test-path "'+dst+'") {exit 0} else {exit 1}'
psstatus = run_powershell_cmd_on_windows_agent(pscmd)['status']
if psstatus != 'complete':
logging.error("cannot validate dst:"+dst+" using cifs, validation status is:"+psstatus)
exit(1)
else:
logging.debug("skipping path validation src:"+src+" dst:"+dst)
srchost = src.split('\\')[2]
srcpath = src.replace('\\\\'+srchost,'')
dsthost = dst.split('\\')[2]
dstpath = dst.replace('\\\\'+dsthost,'')
baseline_job_name = 'baseline_'+'_'+srcbase
sync_job_name = 'sync_'+'_'+srcbase
verify_job_name = 'verify_'+'_'+srcbase
#address situations where file name exceed 250 bytes
randnum = str(random.randint(1000000,9000000))
if len(baseline_job_name) > 150:
baseline_job_name = 'baseline_'+'_'+srcbase[:100]+randnum
if len(sync_job_name) > 150:
sync_job_name = 'sync_'+'_'+srcbase[:100]+randnum
if len(verify_job_name) > 150:
verify_job_name = 'verify_'+'_'+srcbase[:100]+randnum
xcpindexname = srcbase +'-'+dstbase
if len(xcpindexname) > 180: xcpindexname = xcpindexname[:180]
#fill dict with info
jobsdict[jobname][src] = {}
jobsdict[jobname][src]["dst"] = dst
jobsdict[jobname][src]["srchost"] = srchost
jobsdict[jobname][src]["srcpath"] = srcpath
jobsdict[jobname][src]["dsthost"] = dsthost
jobsdict[jobname][src]["dstpath"] = dstpath
jobsdict[jobname][src]["srcbase"] = srcbase
jobsdict[jobname][src]["dstbase"] = dstbase
jobsdict[jobname][src]["baseline_job_name"] = baseline_job_name
jobsdict[jobname][src]["sync_job_name"] = sync_job_name
jobsdict[jobname][src]["verify_job_name"] = verify_job_name
jobsdict[jobname][src]["xcpindexname"] = xcpindexname
jobsdict[jobname][src]["cron"] = cron
jobsdict[jobname][src]["cpu"] = cpu
jobsdict[jobname][src]["memory"] = memory
jobsdict[jobname][src]["ostype"] = ostype
jobsdict[jobname][src]["tool"] = tool
jobsdict[jobname][src]["failbackuser"] = failbackuser
jobsdict[jobname][src]["failbackgroup"] = failbackgroup
jobsdict[jobname][src]["dcname"] = dcname
jobsdict[jobname][src]["excludedirfile"] = excludedirfile
jobsdict[jobname][src]["aclcopy"] = aclcopy
jobsdict[jobname][src]["createcloudsync"] = createcloudsync
logging.debug("parsed the following relationship:"+src+" -> "+dst)
dstdict[dst] = 1
line_count += 1
#dumping jobsdict to json file
try:
with open(jobdictjson, 'w') as fp:
json.dump(jobsdict, fp)
fp.close()
except Exception as e:
logging.error("cannot write job json file:"+jobdictjson)
exit(1)
# start nomad job from hcl file
def start_nomad_job_from_hcl(hclpath, nomadjobname):
if not os.path.exists(hclpath):
logging.error("cannot find hcl file:"+hclpath)
exit(1)
logging.debug("reading hcl file:"+hclpath)
with open(hclpath) as f:
hclcontent = f.read()
#hclcontent = hclcontent.replace('\n', '').replace('\r', '').replace('\t','')
hcljson = {}
hcljson['JobHCL'] = hclcontent
hcljson['Canonicalize'] = True
response = requests.post(nomadapiurl+'jobs/parse',json=hcljson)
if response.ok:
nomadjobdict={}
nomadjobdict['Job'] = json.loads(response.content)
try:
nomadout = n.job.plan_job(nomadjobname, nomadjobdict)
except Exception as e:
logging.error("job planning failed for job:"+nomadjobname+" please run: nomad job plan "+hclpath+ " for more details")
exit(1)
logging.debug("starting job:"+nomadjobname)
try:
nomadout = n.job.register_job(nomadjobname, nomadjobdict)
except Exception as e:
logging.error("job:"+nomadjobname+" creation failed")
exit(1)
else:
logging.error("could not start "+nomadjobname)
return False
return True
def check_job_status (jobname,log=False):
jobdetails = {}
try:
jobdetails = n.job.get_job(jobname)
except Exception as e:
jobdetails = None
if not jobdetails:
logging.debug("job:"+jobname+" does not exist")
return False,'',''
#if job exists retrun the allocation status
results ={}
results['stdout'] = ''
results['stderr'] = ''
results['status'] = 'unknown'
#will be used for fileupload
results['allocations'] = {}
allocid = ''
if jobdetails:
response = requests.get(nomadapiurl+'job/'+jobname+'/allocations')
if not response.ok:
results['status'] = 'failure'
else:
jobdetails = json.loads(response.content)
try:
results['status'] = jobdetails[0]['ClientStatus']
allocid = jobdetails[0]['ID']
results['allocations'] = jobdetails
except Exception as e:
results['status'] = 'unknown'
if log == True and (results['status'] == 'complete' or results['status'] == 'failed') and allocid != '':
response = requests.get(nomadapiurl+'client/fs/logs/'+allocid+'?task='+jobname+'&type=stdout&plain=true')
if response.ok:
logging.debug("stdout log for job:"+jobname+" is available using api")
lines = response.content.splitlines()
if lines:
results['stdout'] = response.content.decode('utf-8')
response = requests.get(nomadapiurl+'client/fs/logs/'+allocid+'?task='+jobname+'&type=stderr&plain=true')
if response.ok:
logging.debug("stderr log for job:"+jobname+" is available using api")
lines = response.content.splitlines()
if lines:
results['stderr'] = response.content.decode('utf-8')
return results
#run powershell commnad on windows agent
def run_powershell_cmd_on_windows_agent (pscmd,log=False):
results = {}
psjobname = pscmd[:15]+str(os.getpid())
psjobname = psjobname.replace(' ','_')
psjobname = 'win_'+psjobname
psjobname = psjobname.replace('}','-')
psjobname = psjobname.replace('{','-')
psjobname = psjobname.replace(')','-')
psjobname = psjobname.replace('(','-')
psjobname = psjobname.replace(':/','-_')
psjobname = psjobname.replace('/','_')
psjobname = psjobname.replace(' ','-')
psjobname = psjobname.replace('\\','_')
psjobname = psjobname.replace('$','_dollar')
psjobname = psjobname.replace(';','=')
psjobname = psjobname.replace('\"','_')
psjobname = psjobname.replace('\'','_')
psjobname = psjobname.replace(':','-')
psjobname = psjobname.replace('*','x')
#loading job ginga2 templates
templates_dir = ginga2templatedir
env = Environment(loader=FileSystemLoader(templates_dir) )
try:
ps_template = env.get_template('nomad_windows_powershell.txt')
except Exception as e:
logging.error("could not find template file: " + os.path.join(templates_dir,'nomad_windows_powershell.txt'))
exit(1)
psjobname = psjobname + os.getpid().__str__()
pscmd = pscmd.replace('\\','\\\\')
pscmd = pscmd.replace('\"','\\\"')
pscmd = pscmd.replace("\'","\\\'")
#creating create job to validate
powershell_job_file = os.path.join('/tmp',psjobname+'.hcl')
logging.debug("creating job file: " + powershell_job_file)
with open(powershell_job_file, 'w') as fh:
fh.write(ps_template.render(
dcname=dcname,
powershelljob=psjobname,
cmd=pscmd
))
#start job and monitor status'
psjobstatus = 'not started'
if start_nomad_job_from_hcl(powershell_job_file, psjobname):
retrycount = 100