forked from AnykeyNL/OCI-AutoScale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoScaleALL.py
1695 lines (1524 loc) · 113 KB
/
AutoScaleALL.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
#!/home/opc/py36env/bin/python
#################################################################################################################
# OCI - Scheduled Auto Scaling Script
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl
#
# Created by: Richard Garsthagen
# Contributors: Joel Nation, Adi Zohar, Dan Iverson, T-Srikanth, Christopher Johnson, Kyle Benson, Richard Benwell
#################################################################################################################
# Application Command line parameters
#
# -t config - Config file section to use (tenancy profile)
# -ip - Use Instance Principals for Authentication
# -dt - Use Instance Principals with delegation token for cloud shell
# -a - Action - All,Up,Down
# -tag - Tag - Default Schedule
# -rg - Filter on Region
# -ic - include compartment ocid
# -ec - exclude compartment ocid
# -ignrtime - ignore region time zone
# -ignormysql- ignore mysql execution
# -printocid - print ocid of object
# -topic - topic to sent summary
# -log - send log output to OCI Logging service. Specify the Log OCID
# -h - help
#
#################################################################################################################
import oci
import datetime
import calendar
import threading
import time
import sys
import argparse
import os
import Regions
import OCIFunctions
logdetails = oci.loggingingestion.models.LogEntryBatch()
logdetails.entries = []
# You can modify / translate the tag names used by this script - case sensitive!!!
AnyDay = "AnyDay"
Weekend = "Weekend"
WeekDay = "WeekDay"
DayOfMonth = "DayOfMonth"
Version = "2022.11.05"
# ============== CONFIGURE THIS SECTION ======================
# OCI Configuration
# ============================================================
ComputeShutdownMethod = "SOFTSTOP"
LogLevel = "ALL" # Use ALL or ERRORS. When set to ERRORS only a notification will be published if error occurs
AlternativeWeekend = False # Set to True is your weekend is Friday/Saturday
RateLimitDelay = 2 # Time in seconds to wait before retry of operation
##########################################################################
# Get current host time and utc on execution
##########################################################################
current_host_time = datetime.datetime.today()
current_utc_time = datetime.datetime.utcnow()
##########################################################################
# Print header centered
##########################################################################
def print_header(name):
chars = int(90)
MakeLog("")
MakeLog('#' * chars)
MakeLog("#" + name.center(chars - 2, " ") + "#")
MakeLog('#' * chars)
##########################################################################
# Get Current Hour per the region
##########################################################################
def get_current_hour(region, ignore_region_time=False):
timezdiff = 0 # Default value if no region match is found
# Find matching time zone for region
for r in Regions.RegionTime:
if r[0] == region:
timezdiff = r[1]
# Get current host time
current_time = current_host_time
# if need to use region time
if not ignore_region_time:
current_time = current_utc_time + datetime.timedelta(hours=timezdiff)
print ("Debug: {}".format(current_time))
# get the variables to return
iDayOfWeek = current_time.weekday() # Day of week as a number
iDay = calendar.day_name[iDayOfWeek] # Day of week as string
iCurrentHour = current_time.hour
iDayOfMonth = current_time.date().day # Day of the month as a number
# Get what N-th day of the monday it is. Like 1st, 2nd, 3rd Saturday
cal = calendar.monthcalendar(current_time.year, current_time.month)
iDayNr = 0
daynrcounter = 0
for week in cal:
if cal[daynrcounter][iDayOfWeek] == current_time.day:
if cal[0][iDayOfWeek]:
iDayNr = daynrcounter + 1
else:
iDayNr = daynrcounter
daynrcounter = daynrcounter + 1
return iDayOfWeek, iDay, iCurrentHour, iDayOfMonth, iDayNr
##########################################################################
# Configure logging output
##########################################################################
def MakeLog(msg, no_end=False):
global logdetails
if no_end:
print(msg, end="")
else:
print(msg)
logdetail = oci.loggingingestion.models.LogEntry()
logdetail.id = datetime.datetime.now(datetime.timezone.utc).isoformat()
logdetail.data = msg
logdetail.time = datetime.datetime.now(datetime.timezone.utc).isoformat()
logdetails.entries.append(logdetail)
##########################################################################
# isWeekDay
##########################################################################
def isWeekDay(day):
weekday = True
if AlternativeWeekend:
if day == 4 or day == 5:
weekday = False
else:
if day == 5 or day == 6:
weekday = False
return weekday
###############################################
# isDeleted
###############################################
def isDeleted(state):
deleted = False
try:
if state == "TERMINATED" or state == "TERMINATING":
deleted = True
if state == "DELETED" or state == "DELETING":
deleted = True
except Exception:
deleted = True
MakeLog("No lifecyclestate found, ignoring resource")
MakeLog(state)
return deleted
###############################################
# AutonomousThread
###############################################
class AutonomousThread(threading.Thread):
def __init__(self, threadID, ID, NAME, CPU):
threading.Thread.__init__(self)
self.threadID = threadID
self.ID = ID
self.NAME = NAME
self.CPU = CPU
def run(self):
global total_resources
global ErrorsFound
global errors
global success
MakeLog(" - Starting Autonomous DB {} and after that scaling to {} cpus".format(self.NAME, self.CPU))
Retry = True
while Retry:
try:
response = database.start_autonomous_database(autonomous_database_id=self.ID)
Retry = False
success.append("Started Autonomous DB {}".format(self.NAME))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Starting Autonomous DB {}".format(response.status, self.NAME))
Retry = False
response = database.get_autonomous_database(autonomous_database_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
while response.data.lifecycle_state != "AVAILABLE":
response = database.get_autonomous_database(autonomous_database_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
MakeLog("Autonomous DB {} started, re-scaling to {} cpus".format(self.NAME, self.CPU))
dbupdate = oci.database.models.UpdateAutonomousDatabaseDetails()
dbupdate.cpu_core_count = self.CPU
Retry = True
while Retry:
try:
response = database.update_autonomous_database(autonomous_database_id=self.ID, update_autonomous_database_details=dbupdate)
Retry = False
success.append("Autonomous DB {} started, re-scaling to {} cpus".format(self.NAME, self.CPU))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
errors.append(" - Error ({}) re-scaling to {} cpus for {}".format(response.status, self.CPU, self.NAME))
Retry = False
###############################################
# PoolThread
###############################################
class PoolThread(threading.Thread):
def __init__(self, threadID, ID, NAME, INSTANCES):
threading.Thread.__init__(self)
self.threadID = threadID
self.ID = ID
self.NAME = NAME
self.INSTANCES = INSTANCES
def run(self):
global total_resources
global ErrorsFound
global errors
global success
MakeLog(" - Starting Instance Pool {} and after that scaling to {} instances".format(self.NAME, self.INSTANCES))
Retry = True
while Retry:
try:
response = pool.start_instance_pool(instance_pool_id=self.ID)
Retry = False
success.append(" - Starting Instance Pool {}".format(self.NAME))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
errors.append(" - Error ({}) starting instance pool {}".format(response.status, self.NAME))
Retry = False
response = pool.get_instance_pool(instance_pool_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
while response.data.lifecycle_state != "RUNNING":
response = pool.get_instance_pool(instance_pool_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
MakeLog("Instance pool {} started, re-scaling to {} instances".format(self.NAME, self.INSTANCES))
pooldetails = oci.core.models.UpdateInstancePoolDetails()
pooldetails.size = self.INSTANCES
Retry = True
while Retry:
try:
response = pool.update_instance_pool(instance_pool_id=self.ID, update_instance_pool_details=pooldetails)
Retry = False
success.append("Rescaling Instance Pool {} to {} instances".format(self.NAME, self.INSTANCES))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) rescaling instance pool {}".format(response.status, self.NAME))
Retry = False
###############################################
# AnalyticsThread
###############################################
class AnalyticsThread(threading.Thread):
def __init__(self, threadID, ID, NAME, CPU):
threading.Thread.__init__(self)
self.threadID = threadID
self.ID = ID
self.NAME = NAME
self.CPU = CPU
def run(self):
global total_resources
global ErrorsFound
global errors
global success
MakeLog(" - Starting Analytics Service {} and after that scaling to {} cpus".format(self.NAME, self.CPU))
Retry = True
while Retry:
try:
response = analytics.start_analytics_instance(analytics_instance_id=self.ID)
Retry = False
success.append("Started Analytics Service {}".format(self.NAME))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Starting Analytics Service {}".format(response.status, self.NAME))
Retry = False
response = analytics.get_analytics_instance(analytics_instance_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
while response.data.lifecycle_state != "ACTIVE":
response = analytics.get_analytics_instance(analytics_instance_id=self.ID, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
time.sleep(10)
MakeLog("Analytics Service {} started, re-scaling to {} cpus".format(self.NAME, self.CPU))
capacity = oci.analytics.models.capacity.Capacity()
capacity.capacity_value = self.CPU
capacity.capacity_type = capacity.CAPACITY_TYPE_OLPU_COUNT
details = oci.analytics.models.ScaleAnalyticsInstanceDetails()
details.capacity = capacity
Retry = True
while Retry:
try:
response = analytics.scale_analytics_instance(analytics_instance_id=self.ID, scale_analytics_instance_details=details)
Retry = False
success.append("Analytics Service {} started, re-scaling to {} cpus".format(self.NAME, self.CPU))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
errors.append("Error ({}) re-scaling Analytics to {} cpus for {}".format(response.status, self.CPU, self.NAME))
Retry = False
##########################################################################
# Load compartments
##########################################################################
def identity_read_compartments(identity, tenancy):
MakeLog("Loading Compartments...")
try:
cs = oci.pagination.list_call_get_all_results(
identity.list_compartments,
tenancy.id,
compartment_id_in_subtree=True,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
).data
# Add root compartment which is not part of the list_compartments
tenant_compartment = oci.identity.models.Compartment()
tenant_compartment.id = tenancy.id
tenant_compartment.name = tenancy.name
tenant_compartment.lifecycle_state = oci.identity.models.Compartment.LIFECYCLE_STATE_ACTIVE
cs.append(tenant_compartment)
MakeLog(" Total " + str(len(cs)) + " compartments loaded.")
return cs
except Exception as e:
raise RuntimeError("Error in identity_read_compartments: " + str(e.args))
##########################################################################
# Handle Region
##########################################################################
def autoscale_region(region):
# Global Paramters for update
global total_resources
global ErrorsFound
global errors
global success
MakeLog("Starting Auto Scaling script on region {}, executing {} actions".format(region, Action))
threads = [] # Thread array for async AutonomousDB start and rescale
tcount = 0
###############################################
# Get Current Day, time
###############################################
DayOfWeek, Day, CurrentHour, CurrentDayOfMonth, DayNr = get_current_hour(region, cmd.ignore_region_time)
if AlternativeWeekend:
MakeLog("Using Alternative weekend (Friday and Saturday as weekend")
if cmd.ignore_region_time:
MakeLog("Ignoring Region Datetime, Using local time")
MakeLog("Day of week: {}, Nth day in Month: {}, IsWeekday: {}, Current hour: {}, Current DayOfMonth: {}".format(Day, DayNr, isWeekDay(DayOfWeek), CurrentHour, CurrentDayOfMonth))
# Investigatin BUG: temporary disabling below logic
# Array start with 0 so decrease CurrentHour with 1, if hour = 0 then 23
#CurrentHour = 23 if CurrentHour == 0 else CurrentHour - 1
###############################################
# Find all resources with a Schedule Tag
###############################################
MakeLog("Getting all resources supported by the search function...")
query = "query all resources where (definedTags.namespace = '{}')".format(PredefinedTag)
query += " && compartmentId = '" + compartment_include + "'" if compartment_include else ""
query += " && compartmentId != '" + compartment_exclude + "'" if compartment_exclude else ""
sdetails = oci.resource_search.models.StructuredSearchDetails()
sdetails.query = query
NoError = True
try:
result = oci.pagination.list_call_get_all_results(search.search_resources,
sdetails,
**{
"limit": 1000
}).data
except oci.exceptions.ServiceError as response:
print ("Error: {} - {}".format(response.code, response.message))
result = oci.resource_search.models.ResourceSummaryCollection()
result.items = []
#################################################################
# Find additional resources not found by search (MySQL Service)
#################################################################
if not cmd.ignoremysql:
MakeLog("Finding MySQL instances in {} Compartments...".format(len(compartments)))
for c in compartments:
# check compartment include and exclude
if c.lifecycle_state != oci.identity.models.Compartment.LIFECYCLE_STATE_ACTIVE:
continue
if compartment_include:
if c.id != compartment_include:
continue
if compartment_exclude:
if c.id == compartment_exclude:
continue
mysql_instances = []
try:
mysql_instances = oci.pagination.list_call_get_all_results(
mysql.list_db_systems,
compartment_id=c.id,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
).data
except Exception:
MakeLog("e", True)
mysql_instances = []
continue
MakeLog(".", True)
for mysql_instance in mysql_instances:
if PredefinedTag not in mysql_instance.defined_tags or mysql_instance.lifecycle_state != "ACTIVE":
continue
summary = oci.resource_search.models.ResourceSummary()
summary.availability_domain = mysql_instance.availability_domain
summary.compartment_id = mysql_instance.compartment_id
summary.defined_tags = mysql_instance.defined_tags
summary.freeform_tags = mysql_instance.freeform_tags
summary.identifier = mysql_instance.id
summary.lifecycle_state = mysql_instance.lifecycle_state
summary.display_name = mysql_instance.display_name
summary.resource_type = "MysqlDBInstance"
try:
result.items.append(summary)
except AttributeError:
result.append(summary)
MakeLog("")
#################################################################
# All the items with a schedule are now collected.
# Let's go thru them and find / validate the correct schedule
#################################################################
total_resources += len(result)
MakeLog("")
MakeLog("Checking {} Resources for Auto Scale...".format(total_resources))
for resource in result:
# The search data is not always updated. Get the tags from the actual resource itself, not using the search data.
resourceOk = False
if cmd.print_ocid:
MakeLog("Checking {} ({}) - {}...".format(resource.display_name, resource.resource_type, resource.identifier))
else:
MakeLog("Checking {} ({})...".format(resource.display_name, resource.resource_type))
try:
if resource.resource_type == "Instance":
resourceDetails = compute.get_instance(instance_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "DbSystem":
resourceDetails = database.get_db_system(db_system_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "VmCluster":
resourceDetails = database.get_vm_cluster(vm_cluster_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "AutonomousDatabase":
resourceDetails = database.get_autonomous_database(autonomous_database_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "InstancePool":
resourceDetails = pool.get_instance_pool(instance_pool_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "OdaInstance":
resourceDetails = oda.get_oda_instance(oda_instance_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "AnalyticsInstance":
resourceDetails = analytics.get_analytics_instance(analytics_instance_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "IntegrationInstance":
resourceDetails = integration.get_integration_instance(integration_instance_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "LoadBalancer":
resourceDetails = loadbalancer.get_load_balancer(load_balancer_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "MysqlDBInstance":
resourceDetails = mysql.get_db_system(db_system_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "GoldenGateDeployment":
resourceDetails = goldengate.get_deployment(deployment_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "DISWorkspace":
resourceDetails = dataintegration.get_workspace(workspace_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
if resource.resource_type == "VisualBuilderInstance":
resourceDetails = visualbuilder.get_vb_instance(vb_instance_id=resource.identifier, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data
resourceOk = True
except:
MakeLog("Skipping resource, information can not be found")
resourceOk = False
if not isDeleted(resource.lifecycle_state) and resourceOk:
schedule = resourceDetails.defined_tags[PredefinedTag]
ActiveSchedule = ""
# Checking the right schedule based on priority
# from low to high:
#
# - Anyday
# - WeekDay or Weekend
# - Name of Day (Monday, Tuesday....)
# - Name of Day, ending with a number to indicate Nth of the month (Saturday1, Saturday2)
# - Day of month
if AnyDay in schedule:
ActiveSchedule = schedule[AnyDay]
if isWeekDay(DayOfWeek): # check for weekday / weekend
if WeekDay in schedule:
ActiveSchedule = schedule[WeekDay]
else:
if Weekend in schedule:
ActiveSchedule = schedule[Weekend]
if Day in schedule: # Check for day specific tag (today)
ActiveSchedule = schedule[Day]
if "{}{}".format(Day, DayNr) in schedule: # Check for Nth day of the Month
ActiveSchedule = schedule["{}{}".format(Day, DayNr)]
if DayOfMonth in schedule:
specificDays = schedule[DayOfMonth].split(",")
for specificDay in specificDays:
day, schedulesize = specificDay.split(":")
if int(day) == CurrentDayOfMonth:
ActiveSchedule = ("{},".format(schedulesize)*24)[:-1]
#################################################################
# Check if the active schedule contains exactly 24 numbers for each hour of the day
#################################################################
if ActiveSchedule != "":
try:
schedulehours = ActiveSchedule.split("#")[0].split(",")
if len(schedulehours) != 24:
ErrorsFound = True
errors.append(" - Error with schedule of {} - {}, not correct amount of hours, I count {}".format(resource.display_name, ActiveSchedule, len(schedulehours)))
MakeLog(" - Error with schedule of {} - {}, not correct amount of hours, i count {}".format(resource.display_name, ActiveSchedule, len(schedulehours)))
ActiveSchedule = ""
except Exception:
ErrorsFound = True
ActiveSchedule = ""
errors.append(" - Error with schedule for {}".format(resource.display_name))
MakeLog(" - Error with schedule of {}".format(resource.display_name))
MakeLog(sys.exc_info()[0])
else:
MakeLog(" - Ignoring instance, as no active schedule for today found")
###################################################################################
# if schedule validated, let see if we can apply the new schedule to the resource
###################################################################################
if ActiveSchedule != "":
DisplaySchedule = ""
c = 0
for h in schedulehours:
if c == CurrentHour:
DisplaySchedule = DisplaySchedule + "[" + h + "],"
else:
DisplaySchedule = DisplaySchedule + h + ","
c = c + 1
MakeLog(" - Active schedule for {}: {}".format(resource.display_name, DisplaySchedule))
if "*" in schedulehours[CurrentHour]:
MakeLog(" - Ignoring this service for this hour")
else:
###################################################################################
# Instance
###################################################################################
if resource.resource_type == "Instance":
# Check if value is (CPU:Memory) value for flex shapes
if schedulehours[CurrentHour][0] == "(" and schedulehours[CurrentHour][-1:] == ")":
if "flex" in resourceDetails.shape.lower():
cpu, memory = schedulehours[CurrentHour][1:-1].split(":")
if float(cpu) != resourceDetails.shape_config.ocpus or float(memory) != resourceDetails.shape_config.memory_in_gbs:
MakeLog("Changing VM size")
changedetails = oci.core.models.UpdateInstanceDetails()
configdetails = oci.core.models.UpdateInstanceShapeConfigDetails()
configdetails.ocpus = float(cpu)
configdetails.memory_in_gbs = float(memory)
changedetails.shape_config = configdetails
try:
response = compute.update_instance(instance_id=resource.identifier, update_instance_details=changedetails)
MakeLog("Modifying flex shape. CPU count: {} - Memory {}".format(cpu, memory))
except oci.exceptions.ServiceError as response:
MakeLog("Can not modify shape: {}".format(response.message))
else:
MakeLog("Ignoring schedule as VM is already in the desired state")
# except:
# MakeLog("Incorrect schedule: {}".format(schedulehours[CurrentHour]))
else:
MakeLog("Can not apply this modification {}, as shape is not a flex shape".format(schedulehours[CurrentHour]))
else:
if int(schedulehours[CurrentHour]) == 0 or int(schedulehours[CurrentHour]) == 1:
# Only perform action if VM Instance, ignoring any BM instances.
if resourceDetails.shape[:2] == "VM":
if resourceDetails.lifecycle_state == "RUNNING" and int(schedulehours[CurrentHour]) == 0:
if Action == "All" or Action == "Down":
MakeLog(" - Initiate Compute VM shutdown for {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = compute.instance_action(instance_id=resource.identifier, action=ComputeShutdownMethod)
Retry = False
success.append(" - Initiate Compute VM shutdown for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Compute VM Shutdown for {} - {}".format(response.status, resource.display_name, response.message))
MakeLog(" - Error ({}) Compute VM Shutdown for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
if resourceDetails.lifecycle_state == "STOPPED" and int(schedulehours[CurrentHour]) == 1:
if Action == "All" or Action == "Up":
MakeLog(" - Initiate Compute VM startup for {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = compute.instance_action(instance_id=resource.identifier, action="START")
Retry = False
success.append(" - Initiate Compute VM startup for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Compute VM startup for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
###################################################################################
# DBSystem
###################################################################################
if resource.resource_type == "DbSystem":
# Execute On/Off operations for Database VMs
if resourceDetails.shape[:2] == "VM":
dbnodes = database.list_db_nodes(compartment_id=resource.compartment_id, db_system_id=resource.identifier).data
for dbnodedetails in dbnodes:
if int(schedulehours[CurrentHour]) == 0 or int(schedulehours[CurrentHour]) == 1:
if dbnodedetails.lifecycle_state == "AVAILABLE" and int(schedulehours[CurrentHour]) == 0:
if Action == "All" or Action == "Down":
MakeLog(" - Initiate DB VM shutdown for {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = database.db_node_action(db_node_id=dbnodedetails.id, action="STOP")
Retry = False
success.append(" - Initiate DB VM shutdown for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) DB VM shutdown for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
if dbnodedetails.lifecycle_state == "STOPPED" and int(schedulehours[CurrentHour]) == 1:
if Action == "All" or Action == "Up":
MakeLog(" - Initiate DB VM startup for {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = database.db_node_action(db_node_id=dbnodedetails.id, action="START")
Retry = False
success.append(" - Initiate DB VM startup for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) DB VM startup for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
###################################################################################
# BM
###################################################################################
if resourceDetails.shape[:2] == "BM":
if int(schedulehours[CurrentHour]) > 1 and int(schedulehours[CurrentHour]) < 53:
if resourceDetails.cpu_core_count > int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Down":
MakeLog(" - Initiate DB BM Scale Down to {} for {}".format(int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateDbSystemDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_db_system(db_system_id=resource.identifier, update_db_system_details=dbupdate)
Retry = False
success.append(
" - Initiate DB BM Scale Down from {}to {} for {}".format(resourceDetails.cpu_core_count, (schedulehours[CurrentHour]),
resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) DB BM Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count,
int(schedulehours[CurrentHour]),
resource.display_name, response.message))
MakeLog(" - Error ({}) DB BM Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count,
int(schedulehours[CurrentHour]),
resource.display_name, response.message))
Retry = False
if resourceDetails.cpu_core_count < int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Up":
MakeLog(" - Initiate DB BM Scale UP to {} for {}".format(int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateDbSystemDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_db_system(db_system_id=resource.identifier, update_db_system_details=dbupdate)
Retry = False
success.append(
" - Initiate DB BM Scale UP from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]),
resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) DB BM Scale UP from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) DB BM Scale UP from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
###################################################################################
# Exadata
###################################################################################
if resourceDetails.shape[:7] == "Exadata":
if resourceDetails.cpu_core_count > int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Down":
MakeLog(" - Initiate Exadata CS Scale Down from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]),
resource.display_name))
dbupdate = oci.database.models.UpdateDbSystemDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_db_system(db_system_id=resource.identifier, update_db_system_details=dbupdate)
Retry = False
success.append(" - Initiate Exadata DB Scale Down to {} at {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Exadata DB Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) Exadata DB Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
if resourceDetails.cpu_core_count < int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Up":
MakeLog(" - Initiate Exadata CS Scale UP from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateDbSystemDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_db_system(db_system_id=resource.identifier, update_db_system_details=dbupdate)
Retry = False
success.append(" - Initiate Exadata DB BM Scale UP from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Exadata DB Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) Exadata DB Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
###################################################################################
# VmCluster
###################################################################################
if resource.resource_type == "VmCluster":
if int(schedulehours[CurrentHour]) >= 0 and int(schedulehours[CurrentHour]) < 401:
# Cluster VM is running, request is amount of CPU core change is needed
if resourceDetails.lifecycle_state == "AVAILABLE" and int(schedulehours[CurrentHour]) > 0:
if resourceDetails.cpus_enabled > int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Down":
MakeLog(" - Initiate ExadataC@C VM Cluster Scale Down to {} for {}".format(int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateVmClusterDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_vm_cluster(vm_cluster_id=resource.identifier, update_vm_cluster_details=dbupdate)
Retry = False
success.append(" - Initiate ExadataC&C Cluster VM Scale Down from {} to {} for {}".format(resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) ExadataC&C Cluster VM Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) ExadataC&C Cluster VM Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
if resourceDetails.cpus_enabled < int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Up":
MakeLog(
" - Initiate ExadataC@C VM Cluster Scale Up from {} to {} for {}".format(resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateVmClusterDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_vm_cluster(vm_cluster_id=resource.identifier, update_vm_cluster_details=dbupdate)
Retry = False
success.append(" - Initiate ExadataC&C Cluster VM Scale Up to {} for {}".format(int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) ExadataC&C Cluster VM Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) ExadataC&C Cluster VM Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpus_enabled, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
###################################################################################
# AutonomousDatabase
###################################################################################
# Execute CPU Scale Up/Down operations for Database BMs
if resource.resource_type == "AutonomousDatabase":
if int(schedulehours[CurrentHour]) >= 0 and int(schedulehours[CurrentHour]) < 129:
# Autonomous DB is running request is amount of CPU core change is needed
if resourceDetails.lifecycle_state == "AVAILABLE" and int(schedulehours[CurrentHour]) > 0:
if resourceDetails.cpu_core_count > int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Down":
MakeLog(" - Initiate Autonomous DB Scale Down to {} for {}".format(int(schedulehours[CurrentHour]),
resource.display_name))
dbupdate = oci.database.models.UpdateAutonomousDatabaseDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_autonomous_database(autonomous_database_id=resource.identifier, update_autonomous_database_details=dbupdate)
Retry = False
success.append(" - Initiate Autonomous DB Scale Down from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Autonomous DB Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) Autonomous DB Scale Down from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
if resourceDetails.cpu_core_count < int(schedulehours[CurrentHour]):
if Action == "All" or Action == "Up":
MakeLog(" - Initiate Autonomous DB Scale Up from {} to {} for {}".format(resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name))
dbupdate = oci.database.models.UpdateAutonomousDatabaseDetails()
dbupdate.cpu_core_count = int(schedulehours[CurrentHour])
Retry = True
while Retry:
try:
response = database.update_autonomous_database(autonomous_database_id=resource.identifier, update_autonomous_database_details=dbupdate)
Retry = False
success.append(" - Initiate Autonomous DB Scale Up to {} for {}".format(int(schedulehours[CurrentHour]), resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Autonomous DB Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
MakeLog(" - Error ({}) Autonomous DB Scale Up from {} to {} for {} - {}".format(response.status, resourceDetails.cpu_core_count, int(schedulehours[CurrentHour]), resource.display_name, response.message))
Retry = False
# Autonomous DB is running request is to stop the database
if resourceDetails.lifecycle_state == "AVAILABLE" and int(schedulehours[CurrentHour]) == 0:
if Action == "All" or Action == "Down":
MakeLog(" - Stoping Autonomous DB {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = database.stop_autonomous_database(autonomous_database_id=resource.identifier)
Retry = False
success.append(" - Initiate Autonomous DB Shutdown for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Autonomous DB Shutdown for {} - {}".format(response.status, resource.display_name, response.message))
MakeLog(" - Error ({}) Autonomous DB Shutdown for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
if resourceDetails.lifecycle_state == "STOPPED" and int(schedulehours[CurrentHour]) > 0:
if Action == "All" or Action == "Up":
# Autonomous DB is stopped and needs to be started with same amount of CPUs configured
if resourceDetails.cpu_core_count == int(schedulehours[CurrentHour]):
MakeLog(" - Starting Autonomous DB {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = database.start_autonomous_database(autonomous_database_id=resource.identifier)
Retry = False
success.append(" - Initiate Autonomous DB Startup for {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))
time.sleep(RateLimitDelay)
else:
ErrorsFound = True
errors.append(" - Error ({}) Autonomous DB Startup for {} - {}".format(response.status, resource.display_name, response.message))
MakeLog(" - Error ({}) Autonomous DB Startup for {} - {}".format(response.status, resource.display_name, response.message))
Retry = False
# Autonomous DB is stopped and needs to be started, after that it requires CPU change
if resourceDetails.cpu_core_count != int(schedulehours[CurrentHour]):
tcount = tcount + 1
thread = AutonomousThread(tcount, resource.identifier, resource.display_name, int(schedulehours[CurrentHour]))
thread.start()
threads.append(thread)
###################################################################################
# InstancePool
###################################################################################
if resource.resource_type == "InstancePool":
# Stop Resource pool action
if resourceDetails.lifecycle_state == "RUNNING" and int(schedulehours[CurrentHour]) == 0:
if Action == "All" or Action == "Down":
success.append(" - Stopping instance pool {}".format(resource.display_name))
MakeLog(" - Stopping instance pool {}".format(resource.display_name))
Retry = True
while Retry:
try:
response = pool.stop_instance_pool(instance_pool_id=resource.identifier)
Retry = False
success.append(" - Stopping instance pool {}".format(resource.display_name))
except oci.exceptions.ServiceError as response:
if response.status == 429:
MakeLog("Rate limit kicking in.. waiting {} seconds...".format(RateLimitDelay))