/
schedules.py
2478 lines (2116 loc) · 104 KB
/
schedules.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
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#class Schedules
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# --------------------------------------------------------------------------
"""Main file for performing schedule related operations for client/agent/backupset/subclient.
SchedulePattern: Class for creating the necessary pattern for a schedule creation/modification
SchedulePattern:
__init__(class_object) -- initialise object of the SchedulePattern
class
_time_converter(_time_string, time_format) -- converts utc to epoch and vice versa
_pattern_json(pattern_option_dict) -- forms the pattern json based on the
dict provided
_one_time(pattern_dict) -- sets the one time schedule pattern
_daily(pattern_dict) -- sets the daily schedule pattern
_weekly(pattern_dict) -- sets the weekly schedule pattern
_monthly(pattern_dict) -- sets the monthly schedule pattern
_monthly_relative(pattern_dict) -- set the monthly_relative schedule pattern
_yearly(pattern_dict) -- sets the yearly schedule pattern
_yearly_relative(pattern_dict) -- sets the yearly_relative schedule pattern
_continuous(pattern_dict) -- sets the continuous schedule pattern
_automatic(pattern_dict) -- sets the automatic schedule pattern
_after_job_completes(pattern_dict) -- sets the after job completes schedule pattern
create_schedule_pattern(pattern_dict) -- creates a schedule pattern for the user
given pattern
create_schedule(task_req,pattern_dict) -- creates a scheduling request from the
pattern provided
Schedules: Initializes instance of all schedules for a commcell entity.
Schedules:
__init__(class_object) -- initialise object of the Schedules class
__str__() -- string of all schedules associated with the commcell entity
__repr__() -- returns the string for the instance of the Schedules class
_get_sch_id_from_task_id() -- gets the schedule id from the provided task id
_get_schedule_id() -- gets the schedule if with the provided inputs
_get_schedules() -- gets all the schedules associated with the commcell entity
has_schedule(schedule_name) -- checks if schedule exists for the comcell entity or not
delete(schedule_name) -- deletes the given schedule
refresh() -- refresh the schedules associated with the commcell entity
Schedule: Class for performing operations for a specific Schedule.
Schedule:
__init__(class_object) -- initialise object of the Schedule class
_get_schedule_properties -- get all schedule properties
is_disabled -- Get the schedule status whether its disabled
schedule_freq_type -- gets the schedule frequence type
name -- gets the name of the schedule
name(new_name) -- sets the name of the schedule
one_time -- gets the one time schedule pattern dict
one_time(pattern_dict) -- sets the one time schedule pattern
daily -- gets the daily schedule pattern
daily(pattern_dict) -- sets the daily schedule pattern
weekly -- gets the weekly schedule pattern
weekly(pattern_dict) -- sets the weekly schedule pattern
monthly -- gets the monthly schedule pattern
monthly(pattern_dict) -- gets the monthly schedule pattern
monthly_relative -- gets the monthly_relative schedule pattern
monthly_relative(pattern_dict) -- set the monthly_relative schedule pattern
yearly -- gets the yearly schedule pattern
yearly(pattern_dict) -- sets the yearly schedule pattern
yearly_relative -- gets the yearly_relative schedule pattern
yearly_relative(pattern_dict) -- sets the yearly_relative schedule pattern
continuous -- gets the continuous schedule pattern
continuous(pattern_dict) -- sets the continuous schedule pattern
automatic -- gets the automatic schedule pattern
automatic(pattern_dict) -- sets the automatic schedule pattern
active_start_date -- gets the start date of schedule pattern
active_start_date(active_start_date) -- sets the start date of schedule pattern
active_start_time -- gets the start time of schedule pattern
active_start_time(active_start_time) -- sets the start time of schedule pattern
enable() -- enables the schedule
disable() -- disables the schedule
run_now() -- Triggers the schedule immediately
_modify_task_properties -- modifies the schedule properties
based on the setters
_process_schedule_update_response -- processes the response and
gives the error_code and message
refresh() -- refresh the properties of the schedule
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import calendar
from .exception import SDKException
class OperationType:
""" Operation Types supported to get schedules of particular optype"""
REPORTS = 'Reports'
DATA_AGING = 'DATA_AGING'
class SchedulePattern:
"""Class for getting the schedule pattern"""
_days_to_run = {
2: 'monday',
4: 'tuesday',
8: 'wednesday',
16: 'thursday',
32: 'friday',
64: 'saturday',
1: 'sunday',
}
_relative_weekday = {
1: 'sunday',
2: 'monday',
3: 'tuesday',
4: 'wednesday',
5: 'thursday',
6: 'friday',
7: 'saturday',
8: 'days',
9: 'weekday',
10: 'weekend_day'
}
_relative_day = {
1: 'first',
2: 'second',
3: 'third',
4: 'fourth',
5: 'last'
}
def __init__(self, schedule_pattern=None):
"""initialise object of the SchedulePattern class"""
if not schedule_pattern:
self._pattern = {'freq_type': 'Init'}
else:
self._pattern = schedule_pattern
@staticmethod
def _time_converter(_time, time_format, utc_to_epoch=True):
"""
converts a time string to epoch time based on the time format provided
Args:
_time (str/int) -- UTC time or EPOCH time
time_format (str) -- format of the time you need process
Raises:
SDKException if time format is wrong
"""
try:
if utc_to_epoch:
date_time = datetime.strptime(_time, time_format)
return int(
(date_time - datetime.utcfromtimestamp(0)).total_seconds())
utc_time = datetime.utcfromtimestamp(_time)
return utc_time.strftime(time_format)
except ValueError:
raise SDKException(
'Schedules',
'102',
"Incorrect data format, should be {0}".format(time_format))
def _pattern_json(self, pattern_option_dict):
"""
forms a pattern json and set the class variable
Args:
pattern_option_dict (dict) -- dictionary with the parameters needed for
forming the corresponding pattern
{'freq_type',
'active_start_date',
'active_start_time',
'freq_recurrence_factor',
'freq_interval'}
"""
if ('freq_type' not in pattern_option_dict) or (
pattern_option_dict['freq_type'] == self._pattern['freq_type']):
for key, value in pattern_option_dict.items():
if key in ('active_start_date', 'active_end_date'):
self._pattern[key] = self._time_converter(
pattern_option_dict[key] + ' 00:00', '%m/%d/%Y %H:%M')
elif key in ('active_start_time', 'active_end_time'):
self._pattern[key] = self._time_converter(
'1/1/1970 ' + pattern_option_dict[key], '%m/%d/%Y %H:%M')
else:
self._pattern[key] = value
else:
if pattern_option_dict['freq_type'] == 'One_Time':
default_start_time = str(datetime.now().strftime('%H:%M'))
else:
default_start_time = '09:00'
_active_start_date = pattern_option_dict.get(
'active_start_date', str(datetime.now().strftime('%m/%d/%Y')))
_active_start_time = pattern_option_dict.get(
'active_start_time', default_start_time)
self._pattern = {
'freq_type': pattern_option_dict['freq_type'],
'active_start_date': self._time_converter(
_active_start_date + ' 00:00',
'%m/%d/%Y %H:%M'),
'active_start_time': self._time_converter(
'1/1/1970 ' + _active_start_time,
'%m/%d/%Y %H:%M'),
'freq_recurrence_factor': pattern_option_dict.get(
'freq_recurrence_factor',
0),
'freq_interval': pattern_option_dict.get(
'freq_interval',
0),
'freq_relative_interval': pattern_option_dict.get(
'freq_relative_interval',
0),
'timeZone': {
'TimeZoneName': pattern_option_dict.get(
'time_zone',
'')}}
if "active_end_date" in pattern_option_dict:
self._pattern["active_end_date"] = self._time_converter(
pattern_option_dict["active_end_date"] + ' 00:00', '%m/%d/%Y %H:%M')
if "exception_dates" in pattern_option_dict:
self._pattern["repeatPattern"] = [{"exception": True,
"onDayNumber": self.exception_dates(
pattern_option_dict["exception_dates"])}
]
if "end_after" in pattern_option_dict:
self._pattern["active_end_occurence"] = pattern_option_dict["end_after"]
if "repeat_every" in pattern_option_dict:
self._pattern.update(self._repeat_pattern(pattern_option_dict))
@staticmethod
def _repeat_pattern(pattern_dict):
"""
Forms repeat pattern json based on the pattern dict provided
Args:
pattern_dict (dict) -- Dictionary containing repeat_every and repeat_end parameters
{
"repeat_every": "08:00",
"repeat_end": "23:00"
}
Returns:
Dict with subdayinterval and endtime information to plug into the pattern json
"""
_repeat_time = datetime.strptime(
pattern_dict.get(
"repeat_every", "08:00"), "%H:%M")
_freq_subday = (_repeat_time.hour * 3600 + _repeat_time.minute * 60)
return {'freq_subday_interval': _freq_subday,
'active_end_time': SchedulePattern._time_converter(
'1/1/1970 ' + pattern_dict["repeat_end"], '%m/%d/%Y %H:%M')
}
def _one_time(self, pattern_dict):
"""
sets the pattern type as one time with the parameters provided,
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictonary with the schedule pattern
{
"active_start_date": date_in_%m/%d/%y (str),
"active_start_time": time_in_%h:%m (str)
}
"""
pattern_dict['freq_type'] = 1
self._pattern_json(pattern_dict)
def _daily(self, pattern_dict):
"""
sets the pattern type as daily with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"repeat_days": days_to_repeat (int)
}
"""
_repeat_days = 1
if self._pattern['freq_type'] == 4:
_repeat_days = self._pattern['freq_recurrence_factor']
_freq_recurrence_factor = pattern_dict.get('repeat_days', _repeat_days)
pattern_dict['freq_type'] = 4
pattern_dict['freq_recurrence_factor'] = 1 if not isinstance(
_freq_recurrence_factor, int) else _freq_recurrence_factor
self._pattern_json(pattern_dict)
def _weekly(self, pattern_dict):
"""
sets the pattern type as weekly with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"repeat_weeks": weeks_to_repeat (int)
"weekdays": list of weekdays ['Monday','Tuesday']
}
"""
try:
_repeat_weeks = 1
_freq_interval = 0
if self._pattern['freq_type'] == 8:
_repeat_weeks = self._pattern['freq_recurrence_factor']
_freq_interval = self._pattern['freq_interval']
pattern_dict['freq_type'] = 8
# encoding
if 'weekdays' in pattern_dict:
_freq_interval_list = pattern_dict['weekdays']
for weekday in _freq_interval_list:
_freq_interval += (
list(
self._days_to_run.keys())[
list(
self._days_to_run.values()).index(
weekday.lower())])
elif _freq_interval == 0:
o_str = 'Weekdays need to be specified'
raise SDKException('Schedules', '102', o_str)
_freq_recurrence_factor = pattern_dict.get(
'_repeat_weeks', _repeat_weeks)
pattern_dict['freq_interval'] = _freq_interval
pattern_dict['freq_recurrence_factor'] = 1 if not isinstance(
_freq_recurrence_factor, int) else _freq_recurrence_factor
self._pattern_json(pattern_dict)
except ValueError:
raise SDKException('Schedules', '102',
"Incorrect weekday specified")
def _monthly(self, pattern_dict):
"""
sets the pattern type as monthly with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"repeat_months": months_to_repeat (int)
"on_day": Day to run schedule (int)
}
"""
_repeat_months = 1
_on_day = 10
if self._pattern['freq_type'] == 16:
_repeat_months = self._pattern['freq_recurrence_factor']
_on_day = self._pattern['freq_interval']
_freq_recurrence_factor = pattern_dict.get(
'repeat_months', _repeat_months)
_freq_interval = pattern_dict.get('on_day', _on_day)
pattern_dict['freq_recurrence_factor'] = 1 if not isinstance(
_freq_recurrence_factor, int) else _freq_recurrence_factor
pattern_dict['freq_interval'] = 1 if not isinstance(
_freq_interval, int) else _freq_interval
pattern_dict['freq_type'] = 16
self._pattern_json(pattern_dict)
def _monthly_relative(self, pattern_dict):
"""
sets the pattern type as monthly_relative with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"relative_time": relative day of the schedule (str) 'first',
'second',..
"relative_weekday": Day to run schedule (str) 'sunday','monday'...
"repeat_months": months_to_repeat
}
"""
_freq_recurrence_factor = 1
_freq_interval = 1
_freq_relative_interval = 1
try:
if self._pattern['freq_type'] == 32:
_freq_recurrence_factor = self._pattern['freq_recurrence_factor']
_freq_interval = self._pattern['freq_interval']
_freq_relative_interval = self._pattern['freq_relative_interval']
if 'relative_time' in pattern_dict:
_freq_relative_interval = (
list(
self._relative_day.keys())[
list(
self._relative_day.values()).index(
pattern_dict['relative_time'].lower())])
if 'relative_weekday' in pattern_dict:
_freq_interval = (
list(
self._relative_weekday.keys())[
list(
self._relative_weekday.values()).index(
pattern_dict['relative_weekday'].lower())])
_freq_recurrence_factor = pattern_dict.get(
'repeat_months', _freq_recurrence_factor)
pattern_dict['freq_recurrence_factor'] = 1 if not isinstance(
_freq_recurrence_factor, int) else _freq_recurrence_factor
pattern_dict['freq_interval'] = _freq_interval
pattern_dict['freq_relative_interval'] = _freq_relative_interval
pattern_dict['freq_type'] = 32
self._pattern_json(pattern_dict)
except ValueError as v_error:
raise SDKException('Schedules', '102',
str(v_error))
def _yearly(self, pattern_dict):
"""
sets the pattern type as monthly with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"on_month": month to run schedule (str) January, Febuary...
"on_day": Day to run schedule (int)
}
"""
try:
_freq_recurrence_factor = 1
_freq_interval = 10
if self._pattern['freq_type'] == 64:
_freq_recurrence_factor = self._pattern['freq_recurrence_factor']
_freq_interval = self._pattern['freq_interval']
if 'on_month' in pattern_dict:
_freq_recurrence_factor = list(
calendar.month_name).index(
pattern_dict['on_month'].title())
_freq_interval = pattern_dict.get('on_day', _freq_interval)
pattern_dict['freq_recurrence_factor'] = _freq_recurrence_factor
pattern_dict['freq_interval'] = 1 if not isinstance(
_freq_interval, int) else _freq_interval
pattern_dict['freq_type'] = 64
self._pattern_json(pattern_dict)
except ValueError as ve:
raise SDKException('Schedules', '102',
str(ve))
def _yearly_relative(self, pattern_dict):
"""
sets the pattern type as monthly_relative with the parameters provided
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_time": time_in_%H/%S (str),
"relative_time": relative day of the schedule (str) 'first',
'second',..
"relative_weekday": Day to run schedule (str) 'sunday','monday'...
"on_month": month to run the schedule(str) January, February...
}
"""
_freq_recurrence_factor = 1
_freq_interval = 1
_freq_relative_interval = 1
try:
if self._pattern['freq_type'] == 128:
_freq_recurrence_factor = self._pattern['freq_recurrence_factor']
_freq_interval = self._pattern['freq_interval']
_freq_relative_interval = self._pattern['freq_relative_interval']
if 'relative_time' in pattern_dict:
_freq_relative_interval = (
list(
self._relative_day.keys())[
list(
self._relative_day.values()).index(
pattern_dict['relative_time'].lower())])
if 'relative_weekday' in pattern_dict:
_freq_interval = (
list(
self._relative_weekday.keys())[
list(
self._relative_weekday.values()).index(
pattern_dict['relative_weekday'].lower())])
if 'on_month' in pattern_dict:
_freq_recurrence_factor = list(
calendar.month_name).index(
pattern_dict['on_month'].title())
pattern_dict['freq_recurrence_factor'] = _freq_recurrence_factor
pattern_dict['freq_interval'] = _freq_interval
pattern_dict['freq_relative_interval'] = _freq_relative_interval
pattern_dict['freq_type'] = 128
self._pattern_json(pattern_dict)
except ValueError as ve:
raise SDKException('Schedules', '102',
str(ve))
def _continuous(self, pattern_dict):
"""
sets the pattern type as one time with the parameters provided,
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
job_interval: interval between jobs in mins(int)
}
"""
_freq_recurrence_factor = pattern_dict.get('job_interval', 30)
pattern_dict['freq_interval'] = 30 if not isinstance(
_freq_recurrence_factor, int) else _freq_recurrence_factor
pattern_dict['freq_type'] = 4096
self._pattern_json(pattern_dict)
def _automatic(self, pattern_dict):
"""
sets the pattern type as one time with the parameters provided,
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
min_interval_hours: minimum hours between jobs(int)
min_interval_minutes: minimum minutes between jobs(int)
max_interval_hours: maximum hours between jobs(int)
max_interval_minutes: maximum minutes between jobs(int)
min_sync_interval_hours: minimum sync hours
between jobs(int)
min_sync_interval_minutes: minimum sync minutes
between jobs(int)
ignore_opwindow_past_maxinterval: (bool)
wired_network_connection: (bool)
min_network_bandwidth: (int) kbps
specific_network: (dict){ip_address:(str),subnet:(int)}
dont_use_metered_network: (bool)
ac_power: (bool)
stop_if_on_battery: (bool)
stop_sleep_if_runningjob: (bool)
cpu_utilization_below : (int)%
cpu_utilization_above : (int)%
disk_use_threshold: (int)%
number_of_log_files: (int)
}
"""
automatic_pattern = {
"maxBackupInterval": pattern_dict.get("max_interval_hours",
self._pattern.get("maxBackupInterval", 72)),
"ignoreOpWindowPastMaxInterval": pattern_dict.get("ignore_opwindow_past_maxinterval",
self._pattern.get(
"ignoreOpWindowPastMaxInterval",
False)),
"minBackupIntervalMinutes": pattern_dict.get("min_interval_minutes",
self._pattern.get(
"minBackupIntervalMinutes", 15)),
"maxBackupIntervalMinutes": pattern_dict.get("max_interval_minutes",
self._pattern.get(
"maxBackupIntervalMinutes", 0)),
"minSyncInterval": pattern_dict.get("min_sync_interval_hours",
self._pattern.get("minSyncInterval", 0)),
"minBackupInterval": pattern_dict.get("min_interval_hours",
self._pattern.get("minBackupInterval", 0)),
"minSyncIntervalMinutes": pattern_dict.get("min_sync_interval_minutes",
self._pattern.get("minSyncIntervalMinutes",
2)),
"stopIfOnBattery": {
"enabled": pattern_dict.get("stop_if_on_battery",
self._pattern.get("stopIfOnBattery",
{'enabled': False})['enabled'])
},
"acPower": {
"enabled": pattern_dict.get("ac_power",
self._pattern.get("acPower",
{'enabled': False})['enabled'])
},
"specfificNetwork": {
"enabled": True if 'specific_network' in pattern_dict
else (self._pattern.get("specfificNetwork",
{'enabled': False})['enabled']),
"ipAddress": {
"family": 32,
"address": pattern_dict.get('specific_network',
{"ip_address": "0.0.0.0"})["ip_address"],
"subnet": pattern_dict.get('specific_network',
{"subnet": 24})["subnet"],
}
},
"stopSleepIfBackUp": {
"enabled": pattern_dict.get("stop_sleep_if_runningjob",
self._pattern.get("stopSleepIfBackUp",
{'enabled': False})['enabled'])
},
"emergencyBackup": {
"emergencyBackupCommandName": "",
"emergencyBackup": {
"enabled": False
}
},
"cpuUtilization": {
"enabled": True if 'cpu_utilization_below' in pattern_dict
else (self._pattern.get("cpuUtilization",
{'enabled': False})['enabled']),
"threshold": pattern_dict.get("cpu_utilization_below",
self._pattern.get("cpuUtilization",
{'threshold': 10})['threshold'])
},
"dontUseMeteredNetwork": {
"enabled": pattern_dict.get("dont_use_metered_network",
self._pattern.get("dontUseMeteredNetwork",
{'enabled': False})['enabled'])
},
"cpuUtilizationAbove": {
"enabled": True if 'cpu_utilization_above' in pattern_dict
else (self._pattern.get("cpuUtilizationAbove",
{'enabled': False})['enabled']),
"threshold": pattern_dict.get("cpu_utilization_above",
self._pattern.get("cpuUtilizationAbove",
{'threshold': 10})['threshold'])
},
"wiredNetworkConnection": {
"enabled": pattern_dict.get("wired_network_connection",
self._pattern.get("wiredNetworkConnection",
{'enabled': False})['enabled'])
},
"minNetworkBandwidth": {
"enabled": True if 'min_network_bandwidth' in pattern_dict
else (self._pattern.get("minNetworkBandwidth",
{'enabled': False})['enabled']),
"threshold": pattern_dict.get("min_network_bandwidth",
self._pattern.get("minNetworkBandwidth",
{'threshold': 128})['threshold'])
},
"sweepStartTime": pattern_dict.get("sweep_start_time",
self._pattern.get("sweepStartTime", 3600)
),
"useStorageSpaceFromMA": pattern_dict.get("use_storage_space_ma",
self._pattern.get("useStorageSpaceFromMA", False)
),
"diskUsedPercent": {
"enabled": True if 'disk_use_threshold' in pattern_dict
else (self._pattern.get("diskUsedPercent",
{'enabled': False})['enabled']),
"threshold": pattern_dict.get("disk_use_threshold",
self._pattern.get("diskUsedPercent",
{'threshold': 80})['threshold'])
},
"logFileNum": {
"enabled": True if 'number_of_log_files' in pattern_dict
else (self._pattern.get("logFileNum",
{'enabled': False})['enabled']),
"threshold": pattern_dict.get("number_of_log_files",
self._pattern.get("logFileNum",
{'threshold': 50})['threshold'])
}
}
self._pattern = automatic_pattern
def _after_job_completes(self, pattern_dict):
"""
sets the pattern type as after job completes with the parameters provided,
send only required keys to change only those values
Args:
pattern_dict (dict) -- Dictionary with the schedule pattern
{
"active_start_date": date_in_%m/%d/%y (str),
"active_start_time": time_in_%H/%S (str),
"repeat_days": days_to_repeat (int)
}
"""
pattern_dict['freq_type'] = 'After_Job_Completes'
pattern_dict['freq_recurrence_factor'] = pattern_dict.get('repeat_days', 4096)
self._pattern_json(pattern_dict)
@staticmethod
def exception_dates(day_list):
"""
Provided a Scheduler version of exception as an on day number
Args:
day_list (list) -- List of exception dates [1,2,3]
Returns (int) -- on_day number for the pattern json
"""
on_day = 0
for value in day_list:
on_day |= (1 << (value - 1))
return on_day
def create_schedule_pattern(self, pattern_dict):
"""
calls the required type of schedule module and forms the pattern json
Args:
pattern_dict (Dict) --
freq_type is mandatory, all other fields specified below can be skipped and system
defaults will be set
for reference on pattern_dict check create_schedule
Returns:
pattern which can be plugged into the create or modify task request to
create or modify schedules
"""
if 'freq_type' not in pattern_dict:
raise SDKException('Schedules', '102',
"Frequency type is required to create pattern")
try:
getattr(
self,
'_' +
pattern_dict['freq_type'].lower())(pattern_dict)
return self._pattern
except AttributeError:
raise SDKException('Schedules', '102',
"freq_type specified is wrong")
def create_schedule(self, task_req, pattern_dict, schedule_id=None):
"""
returns a schedule task_req after including pattern
Args:
task_req: task_req for immediate job operation to be converted to a schedule
freq_type is mandatory, all other fields specified below can be skipped and system
defaults will be set
with the same dict, pass
time_zone: Time Zone Name(default is taken as COmmServe Time Zone)
Common Time Zones examples -- 'CommServe Time Zone', 'Client Time Zone', 'UTC'
for one_time: {
"freq_type": 'one_time',
"active_start_date": date_in_%m/%d/%y (str),
"active_start_time": time_in_%h:%m (str)
}
for daily: {
"freq_type": 'daily',
"active_start_time": time_in_%H/%S (str),
"repeat_days": days_to_repeat (int)
}
for weekly: {
"freq_type": 'weekly',
"active_start_time": time_in_%H/%S (str),
"repeat_weeks": weeks_to_repeat (int)
"weekdays": list of weekdays ['Monday','Tuesday']
}
for monthly: {
"freq_type": 'monthly',
"active_start_time": time_in_%H/%S (str),
"repeat_months": weeks_to_repeat (int)
"on_day": Day to run schedule (int)
}
for monthly_relative: {
"active_start_time": time_in_%H/%S (str),
"relative_time": relative day of the schedule (str) 'first',
'second',..
"relative_weekday": Day to run schedule (str) 'sunday','monday'...
"repeat_months": months_to_repeat
}
for yearly: {
"active_start_time": time_in_%H/%S (str),
"on_month": month to run schedule (str) January, Febuary...
"on_day": Day to run schedule (int)
}
for yearly_relative: {
"active_start_time": time_in_%H/%S (str),
"relative_time": relative day of the schedule (str) 'first',
'second',..
"relative_weekday": Day to run schedule (str) 'sunday','monday'...
"on_month": month to run the schedule(str) January, Febuary...
}
for continuous: {
job_interval: interval between jobs in mins(int)
}
for automatic: {
min_interval_hours: minimum hours between jobs(int)
min_interval_minutes: minimum minutes between jobs(int)
max_interval_hours: maximum hours between jobs(int)
max_interval_minutes: maximum minutes between jobs(int)
min_sync_interval_hours: minimum sync hours
between jobs(int)
min_sync_interval_minutes: minimum sync minutes
between jobs(int)
ignore_opwindow_past_maxinterval: (bool)
wired_network_connection: (bool)
min_network_bandwidth: (int) kbps
specific_network: (dict){ip_address:(str),subnet:(int)}
dont_use_metered_network: (bool)
ac_power: (bool)
stop_if_on_battery: (bool)
stop_sleep_if_runningjob: (bool)
cpu_utilization_below : (int)%
cpu_utilization_above : (int)%
disk_use_threshold: (int)%
number_of_log_files: (int)
}
for after_job_completes : {
"freq_type": 'after_job_completes',
"active_start_date": date_in_%m/%d/%y (str),
"active_start_time": time_in_%H/%S (str),
"repeat_days": days_to_repeat (int)
}
Sample Usage inside the individual operation function:
Add a schedule_pattern parameter to the function and include the below line before making
the sdk make_request call
if schedule_pattern:
request_json = SchedulePattern().create_schedule(task_req,schedule_pattern)
pattern_dict (Dict) -- schedule pattern to be merged with the task request
Returns:
Schedule task request
"""
_automatic_pattern = {}
if pattern_dict["freq_type"] == 'automatic':
_pattern = {"freq_type": 1024}
_automatic_pattern = self.create_schedule_pattern(pattern_dict)
else:
_pattern = self.create_schedule_pattern(pattern_dict)
_task_info = task_req["taskInfo"]
if _task_info.get("task"):
_task_info["task"]["taskType"] = 2
for subtask in _task_info['subTasks']:
if schedule_id:
if subtask["subTask"]['subTaskId'] != schedule_id:
continue
else:
subtask["subTask"]['subTaskName'] = pattern_dict.get(
'schedule_name', '')
subtask["pattern"] = _pattern
if pattern_dict["freq_type"] == 'automatic':
if 'options' in subtask:
_task_options = subtask['options']
if 'commonOpts' in _task_options:
_task_options["commonOpts"]["automaticSchedulePattern"] = _automatic_pattern
else:
_task_options["commonOpts"] = \
{"automaticSchedulePattern": _automatic_pattern}
if 'run_synthetic_full' in pattern_dict:
synthetic_pattern = pattern_dict['run_synthetic_full']
if synthetic_pattern == 'every_x_days':
synthetic_interval = pattern_dict.get(
'days_between_synthetic_full', 30)
else:
synthetic_interval = 30
_data_opt = {
'autoCopy': True,
'daysBetweenSyntheticBackup': synthetic_interval,
'useAutomaticIntervalForSyntheticFull': (
synthetic_pattern == 'extended_retention'),
'enableRunFullConsolidationBackup': (
synthetic_pattern == 'space_reclaim')
}
if 'backupOpts' in _task_options:
if 'dataOpt' in _task_options["backupOpts"]:
_task_options['backupOpts']['dataOpt'].update(_data_opt)
else:
_task_options['backupOpts']['dataOpt'] = _data_opt
else:
_task_options['backupOpts'] = {
'dataOpt': _data_opt
}
else:
subtask['options'] = {
'commonOpts': {
'automaticSchedulePattern': _automatic_pattern}}
task_req["taskInfo"] = _task_info
return task_req
class Schedules:
"""Class for getting the schedules of a commcell entity."""
def __init__(self, class_object, operation_type=None):