-
Notifications
You must be signed in to change notification settings - Fork 5
/
zettaknight_zfs.py
1253 lines (892 loc) · 46.9 KB
/
zettaknight_zfs.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015-2016 Matthew Carter, Ralph M Goodberlet.
#
# This file is part of Zettaknight.
#
# Zettaknight is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Zettaknight is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zettaknight. If not, see <http://www.gnu.org/licenses/>.
#
# Import python libs
import inspect
import re
import sys
import fileinput
import os
import json
#from zettaknight import *
import zettaknight_utils
import zettaknight_globs
import zettaknight_zpool
def nuke(pool, force=True):
'''
'''
ret = {}
if zettaknight_globs.help_flag:
ret = """Nuke:
Destroys a zpool and cleans up files associated with the zpool being destroyed.
Usage:
zettaknight nuke <pool_name>
Required Arguments:
pool_name
Specifies the zpool to destroy."""
return ret
ret[pool] = {}
ret[pool]['Nuke Zpool'] = {}
nuke_cmd = "bash {0} -p '{1}'".format(zettaknight_globs.zfs_nuke_script, pool)
if force:
nuke_cmd = "{0} -f".format(nuke_cmd)
ret[pool]['Nuke Zpool'] = zettaknight_utils.spawn_job(nuke_cmd)
#zettaknight_utils.parse_output(ret)
return ret
def zfs_maintain(dset=False):
zettaknight_utils.zlog("{0} object passed to [zfs_maintain]:\n\t{1}".format(type(dset), dset),"DEBUG")
'''
The zfs_maintain function reads in dataset and maintenance requirements from /opt/clemson/zfs_scripts/maintain.conf
Accepted configuration keys are:
- remote_server
- retention
- reservation
- quota
- user
- contact
'''
ret = {}
if zettaknight_globs.help_flag:
ret = """ZFS Maintain:
The zfs_maintain function reads in dataset and maintenance requirements from configuration files and enforces defined configurations.
Usage:
zettaknight zfs_maintain (<dataset>)
Optional Arguments:
dataset
Specifies the dataset to run maintenance functions on. If not provided, all defined datasets will have maintenance performed."""
return ret
protocol = "ssh"
if dset and str(dset) not in zettaknight_globs.zfs_conf.iterkeys():
ret[dset] = {}
ret[dset]['zfs maintain'] = {1: "{0} is not a Zettaknight controlled dataset.".format(dset)}
#zettaknight_utils.parse_output(ret)
return ret
for dataset in zettaknight_globs.zfs_conf.iterkeys():
if dset:
if str(dset) != str(dataset):
continue
ret[dataset] = {}
#return config file
ret[dataset]['Config'] = {0: str(zettaknight_globs.zfs_conf[dataset])}
ret[dataset]['Cleanup'] = cleanup_snaps(dataset, zettaknight_globs.zfs_conf[dataset]['retention'])
if 'snap' in zettaknight_globs.zfs_conf[dataset].iterkeys():
if 'translate' in zettaknight_globs.zfs_conf[dataset]['snap']:
if zettaknight_globs.zfs_conf[dataset]['snap']['translate']:
if 'remote_server' in zettaknight_globs.zfs_conf[dataset]['snap'].iterkeys():
for remote_server in zettaknight_globs.zfs_conf[dataset]['snap']['remote_server']:
remote_ssh = "{0}@{1}".format(zettaknight_globs.zfs_conf[dataset]['user'], remote_server)
ret[dataset][remote_server] = cleanup_remote_snaps(zettaknight_globs.zfs_conf[dataset]['snap']['translate'], zettaknight_globs.zfs_conf[dataset]['retention'], remote_ssh, zettaknight_globs.identity_file)
ret[dataset]['snapshot'] = create_snap(dataset, "quiet")
#ret[zettaknight_globs.fqdn] = {}
conf_out = enforce_config()
#ret[zettaknight_globs.fqdn]['enforce_config'] = conf_out[zettaknight_globs.fqdn]['enforce_config']
#ret[zettaknight_globs.fqdn]['enforce_config'] = enforce_config()
#print(ret)
#parse_output(ret)
return ret
def _touch(file_path):
'''
function to replicate touch
'''
try:
with open(file_path, 'a'):
zettaknight_utils.zlog("touching file {0}".format(file_path), "DEBUG")
os.utime(file_path, None)
return True
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
return False
def enforce_config(**kwargs):
force = False #by default, enforce config will respect mtime
if 'force' in kwargs.iterkeys() or zettaknight_utils._str_to_bool(zettaknight_globs.zettaknight_conf['config_enforcement']) is True:
force = True
ret = {}
ret[zettaknight_globs.fqdn] = {}
#check if file has been modified, if not, do nothing.
mtime = os.path.getmtime(zettaknight_globs.config_file_new)
mtime_file = zettaknight_globs.mtime_file
try:
if not os.path.isfile(mtime_file):
zettaknight_utils.zlog("creating {0}".format(mtime_file), "DEBUG")
_touch(mtime_file)
except Exception as e:
zettaknight_utils.zlog("cannot create file {0}, setting FORCE attribute".format(mtime_file), "WARNING")
force = True
try:
if mtime >= os.path.getmtime(mtime_file) or force is True:
#builds out defined datasets if they don't already exist
zettaknight_utils.zlog("[enforce_config] starting build_out_config", "DEBUG")
out0 = build_out_config()
ret[zettaknight_globs.fqdn] = out0[zettaknight_globs.fqdn]
for dataset in zettaknight_globs.zfs_conf.iterkeys():
ret[dataset] = {}
if zettaknight_globs.zfs_conf[dataset]['quota']:
ret[dataset]['Quota'] = set_quota(dataset, zettaknight_globs.zfs_conf[dataset]['quota'])
if zettaknight_globs.zfs_conf[dataset]['refquota']:
ret[dataset]['Refquota'] = set_refquota(dataset, zettaknight_globs.zfs_conf[dataset]['refquota'])
if zettaknight_globs.zfs_conf[dataset]['reservation']:
ret[dataset]['Reservation'] = set_reservation(dataset, zettaknight_globs.zfs_conf[dataset]['reservation'])
if zettaknight_globs.zfs_conf[dataset]['refreservation']:
ret[dataset]['Refreservation'] = set_refreservation(dataset, zettaknight_globs.zfs_conf[dataset]['refreservation'])
zettaknight_utils.zlog("updating {0}".format(mtime_file), "INFO")
_touch(mtime_file)
else:
ret[zettaknight_globs.fqdn]['enforce_config'] = {0: "no changes have been made to {0}".format(zettaknight_globs.config_file_new)}
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
ret[zettaknight_globs.fqdn]['enforce_config'] = {1: e}
return ret
def enforce_zpool_config(**kwargs):
force = False #by default, enforce config will respect mtime
if 'force' in kwargs.iterkeys() or zettaknight_utils._str_to_bool(zettaknight_globs.zettaknight_conf['zpool_config_enforcement']) is True:
force = True
ret = {}
#check if file has been modified, if not, do nothing.
mtime = os.path.getmtime(zettaknight_globs.pool_config_file)
zpool_mtime_file = zettaknight_globs.zpool_mtime_file
try:
if not os.path.isfile(zpool_mtime_file):
zettaknight_utils.zlog("creating {0}".format(zpool_mtime_file), "DEBUG")
_touch(zpool_mtime_file)
except Exception as e:
zettaknight_utils.zlog("cannot create file {0}, setting FORCE attribute".format(zpool_mtime_file), "WARNING")
force = True
try:
if mtime >= os.path.getmtime(zpool_mtime_file) or force is True:
for zpool in zettaknight_globs.zpool_conf.iterkeys():
print "zpool is {0}".format(zpool)
if zpool:
ret[zpool] = {}
if 'quota' in zettaknight_globs.zpool_conf[zpool].iterkeys():
quota = zettaknight_globs.zpool_conf[zpool]['quota']
zettaknight_utils.zlog("setting quota of {0} for {1}".format(quota, zpool), "INFO")
ret[zpool]['quota'] = set_quota(zpool, quota)
zettaknight_utils.zlog("updating {0}".format(zpool_mtime_file), "INFO")
_touch(zpool_mtime_file)
else:
ret[zettaknight_globs.fqdn] = {}
ret[zettaknight_globs.fqdn]['enforce_zpool_config'] = {0: "no changes have been made to {0}".format(zettaknight_globs.pool_config_file)}
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
ret[zettaknight_globs.fqdn] = {}
ret[zettaknight_globs.fqdn]['enforce_zpool_config'] = {1: e}
return ret
def failover(dataset, remote_server=False):
'''
'''
ret = {}
if zettaknight_globs.help_flag:
ret = """Failover:
Attempts a controlled failover for provided dataset to remote host defined in configuration files.
Usage:
zettaknight failover <dataset>
Required Arguments:
dataset
Specifies the dataset to fail over.
Optional Arguments:
remote_server
Specifies a remote server to attempt a failover to. By default, this information is pulled from
dataset configuration files."""
return ret
ret[dataset] = {}
ret[dataset]['Failover'] = {}
try:
user = zettaknight_globs.zfs_conf[dataset]['user']
secure = zettaknight_globs.zfs_conf[dataset]['secure']
except Exception as e:
ret[dataset]['Failover']['1'] = "Dataset: {0} not configured in configuration file.".format(dataset)
zettaknight_utils.parse_output(ret)
sys.exit(0)
try:
if not remote_server:
remote_server = zettaknight_globs.zfs_conf[dataset]['snap']['remote_server']
if isinstance(remote_server, list):
if len(remote_server) > 1:
raise Exception("Multiple remote servers defined in configuration.")
except Exception as e:
ret[dataset]['Failover']['1'] = "{0}\nRemote servers defined:\n - {1}\nRe-run with explicit remote server to failover to.".format(e, list(zettaknight_globs.zfs_conf[dataset]['snap']['remote_server']))
zettaknight_utils.parse_output(ret)
sys.exit(0)
snap_cmd = "bash {0} -d {1} -s {2}@{3} -i {4} -f".format(zettaknight_globs.snap_script, dataset, user, remote_server[0], zettaknight_globs.identity_file)
if secure:
snap_cmd = "{0} -e".format(snap_cmd)
ret[dataset]['Failover'] = zettaknight_utils.spawn_job(snap_cmd)
zettaknight_utils.parse_output(ret)
return ret
def scrub(pool):
'''
initiates a scrub of the pool
'''
ret = {}
if zettaknight_globs.help_flag:
ret = """Scrub:
Initiates a scrub of provided pool.
Usage:
zettaknight scrub <pool>
Required Arguments:
pool
Specifies the pool to scrub."""
return ret
ret[pool] = {}
ret[pool]['Scrub'] = {}
scrub_cmd = "/sbin/zpool scrub {0}".format(pool)
scrub_run = zettaknight_utils.spawn_job(scrub_cmd)
for k,v in scrub_run.iteritems():
if str(k) is "0":
ret[pool]['Scrub']['0'] = "Scrub initiated."
else:
ret[pool]['Scrub']['1'] = v
zettaknight_utils.parse_output(ret)
return ret
def take_snap(dataset, user, remote_server, secure, nosnap=False, pull_snap=False):
'''
'''
snap_cmd = "bash {0} -d {1} -i {2} -s {3}@{4}".format(zettaknight_globs.snap_script, dataset, zettaknight_globs.identity_file, user, remote_server)
if secure:
snap_cmd = "{0} -e".format(snap_cmd)
if nosnap:
snap_cmd = "{0} -r".format(snap_cmd)
if pull_snap:
snap_cmd = "{0} -p".format(snap_cmd)
print("SNAP_COMMAND: {0}".format(snap_cmd))
ret = zettaknight_utils.spawn_job(snap_cmd)
return ret
def create_snap(dataset, quiet=False):
'''
'''
zettaknight_utils.zlog("create_snap started", "DEBUG")
zettaknight_utils.check_quiet(quiet)
snap = "{0}@{1}".format(dataset, zettaknight_globs.today_date)
snap_list = zettaknight_utils.spawn_job("/sbin/zfs list -r -t snapshot -o name -H {0}".format(snap))
if int(0) not in snap_list.iterkeys():
ret = zettaknight_utils.spawn_job("/sbin/zfs snapshot -r {0}".format(snap))
else:
ret = {0: "Snapshot {0} already exists.".format(snap)}
zettaknight_utils.zlog("snapshot {0} already exists".format(snap), "INFO")
for exit_status, output in ret.iteritems():
if str(exit_status) == "0" and str(output) == "Job succeeded":
ret[exit_status] = "Snapshot created: {0}".format(snap)
zettaknight_utils.zlog("snapshot created: {0}".format(snap), "SUCCESS")
if not quiet:
snap_out = {}
snap_out[dataset] = {}
snap_out[dataset][inspect.stack()[0][3]] = ret
zettaknight_utils.parse_output(snap_out)
zettaknight_utils.zlog("create_snap exiting", "DEBUG")
return ret
def set_quota(dataset, quota):
'''
'''
#quota_cmd = "bash {0} -d {1} -q {2}".format(zettaknight_globs.quota_script,dataset,quota)
quota_cmd = "/sbin/zfs set quota={0} {1}".format(quota, dataset)
ret = {}
if zettaknight_globs.help_flag:
ret = """Set Quota:
Sets a ZFS quota on provided dataset.
Usage:
zettaknight set_quota <dataset> <quota>
Required Arguments:
dataset
Specifies the dataset to set a quota for.
quota
Specifies the quota to set. ie. 1T, 100G, etc."""
return ret
ret[dataset] = {}
ret[dataset]['Quota'] = zettaknight_utils.spawn_job(quota_cmd)
for exit_status, output in ret[dataset]['Quota'].iteritems():
if "Job succeeded" in output:
ret[dataset]['Quota'][exit_status] = "quota set to {0}".format(quota)
return ret
def set_refquota(dataset, refquota):
'''
'''
refquota_cmd = "/sbin/zfs set refquota={0} {1}".format(refquota, dataset)
ret = {}
if zettaknight_globs.help_flag:
ret = """Set RefQuota:
Sets a ZFS refquota on provided dataset.
Usage:
zettaknight set_refquota <dataset> <refquota>
Required Arguments:
dataset
Specifies the dataset to set a quota for.
refquota
Specifies the quota to set. ie. 1T, 100G, etc."""
return ret
ret[dataset] = {}
ret[dataset]['refquota'] = zettaknight_utils.spawn_job(refquota_cmd)
for exit_status, output in ret[dataset]['refquota'].iteritems():
if "Job succeeded" in output:
ret[dataset]['refquota'][exit_status] = "refquota set to {0}".format(refquota)
return ret
def set_reservation(dataset, reservation, quiet=False):
'''
'''
zettaknight_utils.check_quiet(quiet)
#reservation_cmd = "bash {0} -d {1} -r {2}".format(zettaknight_globs.quota_script,dataset,reservation)
reservation_cmd = "/sbin/zfs set reservation={0} {1}".format(reservation, dataset)
ret = {}
if zettaknight_globs.help_flag:
ret = """Set Reservation:
Sets a ZFS reservation on provided dataset.
Usage:
zettaknight set_reservation <dataset> <reservation>
Required Arguments:
dataset
Specifies the dataset to set a reservation for.
reservation
Specifies the reservation to set. ie. 1T, 100G, etc."""
return ret
ret[dataset] = {}
ret[dataset]['Reservation'] = zettaknight_utils.spawn_job(reservation_cmd)
for exit_status, output in ret[dataset]['Reservation'].iteritems():
if "Job succeeded" in output:
ret[dataset]['Reservation'][exit_status] = "reservation set to {0}".format(reservation)
return ret
def set_refreservation(dataset, refreservation):
'''
'''
refreservation_cmd = "/sbin/zfs set refreservation={0} {1}".format(refreservation, dataset)
ret = {}
if zettaknight_globs.help_flag:
ret = """Set Refreservation:
Sets a ZFS Refreservation on provided dataset.
Usage:
zettaknight set_refreservation <dataset> <refreservation>
Required Arguments:
dataset
Specifies the dataset to set a refreservation for.
refreservation
Specifies the refreservation to set. ie. 1T, 100G, etc."""
return ret
ret[dataset] = {}
ret[dataset]['refreservation'] = zettaknight_utils.spawn_job(refreservation_cmd)
for exit_status, output in ret[dataset]['refreservation'].iteritems():
if "Job succeeded" in output:
ret[dataset]['refreservation'][exit_status] = "refreservation set to {0}".format(refreservation)
return ret
def cleanup_snaps(dataset, retention):
'''
'''
cleanup_cmd = "bash {0} -d {1} -k {2}".format(zettaknight_globs.cleanup_script, dataset, retention)
ret = zettaknight_utils.spawn_job(cleanup_cmd)
return ret
def cleanup_remote_snaps(dataset, retention, remote_ssh, identity_file):
'''
'''
if not identity_file:
identity_file = zettaknight_globs.identity_file
cleanup_remote_cmd = "bash {0} -d {1} -k {2} -s {3} -i {4}".format(zettaknight_globs.cleanup_remote_script, dataset, retention, remote_ssh, identity_file)
ret = zettaknight_utils.spawn_job(cleanup_remote_cmd)
return ret
def sync(*args, **kwargs):
'''
'''
zettaknight_utils.zlog("kwargs recieved by sync\n\t{0}".format(kwargs), "DEBUG")
if zettaknight_globs.help_flag:
ret = """Sync:
Syncs snapshots to a remote server.
Usage:
zettaknight sync <dataset> <remote_ssh>
Required Arguments:
dataset
Specifies the dataset to sync.
remote_ssh
Specifies remote server to sync snapshots to."""
return ret
#if 'priority' in zettaknight_globs.zfs_conf[dataset]:
# priority = zettaknight_globs.zfs_conf[dataset]['priority']
# print(priority)
# if isinstance(priority, int):
# print("priority is an integer")
# os.nice(int(priority))
try:
if 'dataset' and 'remote_ssh' in kwargs.iterkeys():
sync_cmd = "bash {0} -d {1} -s {2}".format(zettaknight_globs.sync_script, kwargs['dataset'], kwargs['remote_ssh'])
else:
raise Exception("dataset and remote_ssh is are required kwargs for sync")
if 'identity_file' in kwargs.iterkeys():
sync_cmd = "{0} -i {1}".format(sync_cmd, kwargs['identity_file'])
if 'pull_snap' in kwargs.iterkeys():
if kwargs['pull_snap']:
sync_cmd = "{0} -p".format(sync_cmd)
if 'priority' in kwargs.iterkeys():
sync_cmd = "{0} -n {1}".format(sync_cmd, kwargs['priority'])
if 'translate' in kwargs.iterkeys():
if kwargs['translate']:
sync_cmd = "{0} -r {1}".format(sync_cmd, kwargs['translate'])
if 'timeout' in kwargs.iterkeys():
if kwargs['timeout']:
sync_cmd = "{0} -t {1}".format(sync_cmd, kwargs['timeout'])
if str(inspect.stack()[1][3]) is 'sync_all':
zettaknight_utils.zlog("starting sync job:\n\t{0}".format(sync_cmd),"INFO")
ret = zettaknight_utils.spawn_job(sync_cmd)
else:
ret = {}
ret[dataset] = {}
ret[dataset]['Snapshot sync'] = zettaknight_utils.spawn_job(sync_cmd)
except Exception as e:
zettaknight_utils.zlog("{0}".format(e),"CRITICAL")
sys.exit(1)
return ret
def sync_all(**kwargs):
'''
'''
zettaknight_utils.zlog("kwargs passed to sync_all:\n\t{0}".format(kwargs), "DEBUG")
ret = {}
if 'parallel' in zettaknight_globs.zettaknight_conf.iterkeys():
if zettaknight_globs.zettaknight_conf['parallel']:
parallel = zettaknight_utils._str_to_bool(zettaknight_globs.zettaknight_conf['parallel'])
else:
parallel = False
zettaknight_utils.zlog("[sync_all] started, parallel is {0}".format(parallel), "INFO")
if zettaknight_globs.help_flag:
ret = """Sync All:
Syncs snapshots for all defined datasets.
Datasets to sync and remote targets are pulled from the Zettaknight configuration files.
Usage:
zettaknight sync_all """
return ret
protocol = "ssh"
sync_list = []
index = 1
list_pos = 0
for dataset in zettaknight_globs.zfs_conf.iterkeys():
#kwargs to be passed to sync
my_kwargs = {}
my_kwargs['dataset'] = dataset
my_kwargs['identity_file'] = zettaknight_globs.identity_file
if 'timeout' in zettaknight_globs.zfs_conf[dataset]['snap'].iterkeys():
if zettaknight_globs.zfs_conf[dataset]['snap']['timeout']:
my_kwargs['timeout'] = zettaknight_globs.zfs_conf[dataset]['snap']['timeout']
if not parallel:
ret[dataset] = {}
if 'snap' in zettaknight_globs.zfs_conf[dataset].iterkeys():
if zettaknight_globs.zfs_conf[dataset]['snap']:
if 'backup_server' in zettaknight_globs.zfs_conf[dataset]['snap'].iterkeys():
for backup_server in zettaknight_globs.zfs_conf[dataset]['snap']['backup_server']:
try:
backup_host, backup_loc = backup_server.split(":", 1)
if backup_host is None or backup_loc is None:
raise Exception("backup_server formatted incorrectly, should be in <host>@</remote_dir>:\n\t{1}".format(backup_server))
backup_ssh = "{0}@{1}".format(zettaknight_globs.zfs_conf[dataset]['user'], backup_host)
backup_cmd = "bash {0} -d {1} -s {2} -r {3}".format(zettaknight_globs.backup_snap_script, my_kwargs['dataset'], backup_ssh, backup_loc)
if zettaknight_globs.identity_file:
backup_cmd = "{0} -i {1}".format(backup_cmd, zettaknight_globs.identity_file)
ret[dataset]["Backup Dump to {0}".format(backup_host)] = zettaknight_utils.spawn_job(backup_cmd)
except Exception as e:
zettaknight_utils.zlog("backup_server: {0}".format(e), "ERROR")
pass
if 'remote_server' in zettaknight_globs.zfs_conf[dataset]['snap'].iterkeys():
for remote_server in zettaknight_globs.zfs_conf[dataset]['snap']['remote_server']:
try:
if str(zettaknight_globs.zfs_conf[dataset]['primary']) != str(zettaknight_globs.fqdn):
if str(zettaknight_globs.zfs_conf[dataset]['primary']) == str(remote_server):
pull_snap = True
else:
pull_snap = False
else:
pull_snap = False
except KeyError:
pull_snap = False
pass
remote_ssh = "{0}@{1}".format(zettaknight_globs.zfs_conf[dataset]['user'], remote_server)
my_kwargs['remote_ssh'] = remote_ssh
if 'translate' in zettaknight_globs.zfs_conf[dataset]['snap'].iterkeys():
my_kwargs['translate'] = zettaknight_globs.zfs_conf[dataset]['snap']['translate']
sync_cmd = "bash {0} -d {1} -s {2}".format(zettaknight_globs.sync_script, my_kwargs['dataset'], my_kwargs['remote_ssh'])
if parallel:
if 'identity_file' in my_kwargs.iterkeys():
sync_cmd = "{0} -i {1}".format(sync_cmd, my_kwargs['identity_file'])
if 'pull_snap' in my_kwargs.iterkeys():
if my_kwargs['pull_snap']:
sync_cmd = "{0} -p".format(sync_cmd)
if 'priority' in my_kwargs.iterkeys():
sync_cmd = "{0} -n {1}".format(sync_cmd, my_kwargs['priority'])
if 'translate' in my_kwargs.iterkeys():
if my_kwargs['translate']:
sync_cmd = "{0} -r {1}".format(sync_cmd, my_kwargs['translate'])
if 'timeout' in my_kwargs.iterkeys():
sync_cmd = "{0} -t {1}".format(sync_cmd, my_kwargs['timeout'])
if sync_cmd:
sync_list.append(sync_cmd)
else:
ret[dataset]['Snapshot sync with {0}'.format(remote_server)] = sync(**my_kwargs)
if parallel:
job_list = zettaknight_utils.spawn_jobs(sync_list)
ret[zettaknight_globs.fqdn] = {}
for job in job_list:
ret[zettaknight_globs.fqdn]['Snapshot sync job {0}'.format(index)] = job_list[list_pos]
index += 1
list_pos += 1
zettaknight_utils.zlog("[sync_all] return:\n\t{0}".format(ret), "DEBUG")
return ret
def rename_dataset(**kwargs):
'''
'''
import paramiko
try:
conf_file = zettaknight_globs.config_file_new
if not 'keyfile' in kwargs.iterkeys():
keyfile = zettaknight_globs.identity_file
if not 'dataset' in kwargs.iterkeys():
raise ValueError('A very specific bad thing happened')
#required argument, show_help
else:
dataset = kwargs['dataset']
if not 'new_dataset' in kwargs.iterkeys():
#required argument, show_help
raise ValueError('A very specific bad thing happened')
else:
new_dataset = kwargs['new_dataset']
if not 'user' in kwargs.iterkeys():
user = zettaknight_globs.zfs_conf[dataset]['user']
print("user is {0}".format(user))
remote_server = []
for r_server in zettaknight_globs.zfs_conf[dataset]['snap']['remote_server']:
remote_server.append(r_server)
print(remote_server)
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
sys.exit(1)
ret = {}
ret[zettaknight_globs.fqdn] = {}
ret[zettaknight_globs.fqdn]['rename {0}'.format(dataset)] = {}
try:
for r in remote_server:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(r, username=user, key_filename=keyfile)
remote_sudo_cmd = "zfs rename {0} {1}".format(dataset, new_dataset)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(remote_sudo_cmd)
print ssh_stdout.read()
#call function replace_string
replace_string(dataset, new_dataset, conf_file)
cmd = "zfs rename {0} {1}".format(dataset, new_dataset)
zettaknight_utils.spawn_job(cmd)
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
sys.exit(1)
ret[zettaknight_globs.fqdn]['rename {0}'.format(dataset)] = {0 : "successfully renamed {0} to {1}, all records have been updated".format(dataset, new_dataset)}
return ret
def replace_string(string, new_string, file):
'''
function is take a given string, replace with another string in a specified file
'''
ret = {}
ret[zettaknight_globs.fqdn] = {}
try:
string = str(string)
new_string = str(new_string)
for line in fileinput.input(file, inplace=1):
if string in line:
line = line.replace(string,new_string)
ret = "replaced {0} with {1}".format(string, line)
#ret[zettaknight_globs.fqdn]['replace_string'] = {0 : "replaced {0} with {1}".format(string, line)}
sys.stdout.write(line)
except Exception as e:
zettaknight_utils.zlog("{0}".format(e), "ERROR")
sys.exit(1)
return ret
#rename secondary target
def check_usage(dset=False, quiet=False):
'''
'''
ret = {}
zettaknight_utils.check_quiet(quiet)
if dset and str(dset) not in zettaknight_globs.zfs_conf.iterkeys():
ret[dset] = {}
ret[dset]['Check Usage'] = {1: "{0} is not a Zettaknight controlled dataset.".format(dset)}
zettaknight_utils.parse_output(ret)
return ret
for dataset in zettaknight_globs.zfs_conf.iterkeys():
if dset:
if str(dset) != str(dataset):
continue
ret[dataset] = {}
ret[dataset]['Check Usage'] = {}
quota = zettaknight_globs.zfs_conf[dataset]['quota']
reservation = zettaknight_globs.zfs_conf[dataset]['reservation']
#find conversion multiplier to convert reservation to bytes
if 'G' in reservation:
res_x = float(1073741824)
res_unit = "G"
if 'T' in reservation:
res_x = float(1099511627776)
res_unit = "T"
if 'M' in reservation:
res_x = float(1048576)
res_unit = "M"
if str(reservation) == 'none':
res_x = float(1073741824)
res_unit = "G"
contact = zettaknight_globs.zfs_conf[dataset]['contact']
check_usage_cmd = "/sbin/zfs list -ro space {0} -H -p".format(dataset)
check_usage_run = zettaknight_utils.spawn_job(check_usage_cmd)
chk_code, chk_msg = check_usage_run.popitem()
chk_msg = re.sub("\n", "", chk_msg)
chk_msg_split = chk_msg.split("\t")
if not str(chk_code) == "0":
ret[dataset]['Check Usage']['1'] = "{0}Verify correct datasets are defined in configuration file\n".format(re.sub("[\[\"\]]", "", str(chk_msg_split)))
continue
if str(chk_msg_split[0]) == str(dataset):
avail = float(re.sub("[A-Za-z]", "", chk_msg_split[1])) #space available for dataset
used = float(re.sub("[A-Za-z]", "", chk_msg_split[2])) #how much space is used by the dataset
usnap = float(re.sub("[A-Za-z]", "", chk_msg_split[3])) #how much of the used space is consumed by snapshots
uds = float(re.sub("[A-Za-z]", "", chk_msg_split[4])) #how much of the space is consumed by the dataset itself
if str(reservation) != 'none':
res = (float(re.sub("[A-Za-z]", "", reservation)) * res_x)
avail_friendly = "{0:.2f}{1}".format((avail / res_x), res_unit)
used_friendly = "{0:.2f}{1}".format((used / res_x), res_unit)
usnap_friendly = "{0:.2f}{1}".format((usnap / res_x), res_unit)
uds_friendly = "{0:.2f}{1}".format((uds / res_x), res_unit)
if "e-" in str(used_friendly):
used_friendly = "{0}{1}".format(int(0), res_unit)
if "e-" in str(usnap_friendly):
usnap_friendly = "{0}{1}".format(int(0), res_unit)
if "e-" in str(uds_friendly):
uds_friendly = "{0}{1}".format(int(0), res_unit)
if str(reservation) != 'none' and used > res:
a = "{0}: {1}\n\t\t".format(zettaknight_utils.printcolors("Dataset", "OKBLUE"),zettaknight_utils.printcolors(dataset, "FAIL"))
b = "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format(zettaknight_utils.printcolors("Reservation", "OKBLUE"),zettaknight_utils.printcolors(reservation, "OKGREEN"),zettaknight_utils.printcolors("Total Used", "OKBLUE"),zettaknight_utils.printcolors(used_friendly, "WARNING"),zettaknight_utils.printcolors("Used by Snapshots", "OKBLUE"),zettaknight_utils.printcolors(usnap_friendly, "WARNING"),zettaknight_utils.printcolors("Active Dataset size", "OKBLUE"),zettaknight_utils.printcolors(uds_friendly, "WARNING"))
c = zettaknight_utils.printcolors("\nDataset exceeds space reservation", "WARNING")
msg = "{0}{1}{2}".format(a, b, c)
ret[dataset]['Check Usage']['1'] = "{0}{1}".format(b, c)
else:
a = "{0}: {1}\n\t\t".format(zettaknight_utils.printcolors("Dataset", "OKBLUE"),zettaknight_utils.printcolors(dataset, "OKGREEN"))
b = "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format(zettaknight_utils.printcolors("Reservation", "OKBLUE"),zettaknight_utils.printcolors(reservation, "OKGREEN"),zettaknight_utils.printcolors("Total Used", "OKBLUE"),zettaknight_utils.printcolors(used_friendly, "OKGREEN"),zettaknight_utils.printcolors("Used by Snapshots", "OKBLUE"),zettaknight_utils.printcolors(usnap_friendly, "OKGREEN"),zettaknight_utils.printcolors("Active Dataset size", "OKBLUE"),zettaknight_utils.printcolors(uds_friendly, "OKGREEN"))
msg = "{0}{1}".format(a, b)
ret[dataset]['Check Usage']['0'] = b
return ret
def build_out_config(force=False):
'''
This function reads in the pool config file and creates the zfs data structures defined in it
'''
ret = {}
ret[zettaknight_globs.fqdn] = {}
ret[zettaknight_globs.fqdn]['Build Config'] = {}
create_config = {}
create_config['create_config'] = False
create_config['nfs'] = False
try:
#create pools defined in zpool conf
if zettaknight_globs.zpool_conf: