-
Notifications
You must be signed in to change notification settings - Fork 2
/
monitor_ontap_services.py
executable file
·1183 lines (1128 loc) · 61.4 KB
/
monitor_ontap_services.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
#!/bin/python3.11
################################################################################
# THIS SOFTWARE IS PROVIDED BY NETAPP "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL NETAPP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR'
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################
#
################################################################################
# This program is used to monitor some of Data ONTAP services (EMS Message,
# Snapmirror relationships, quotas) running under AMS, and alert on any
# "matching conditions." It is intended to be run as a Lambda function, but
# can be run as a standalone program.
#
# Version: %%VERSION%%
# Date: %%DATE%%
################################################################################
import json
import re
import os
import datetime
import logging
from logging.handlers import SysLogHandler
import urllib3
from urllib3.util import Retry
import botocore
import boto3
eventResilience = 4 # Times an event has to be missing before it is removed
# from the alert history.
# This was added since the Ontap API that returns EMS
# events would often drop some events and then including
# them in the subsequent calls. If I don't "age" the
# alert history duplicate alerts will be sent.
initialVersion = "Initial Run" # The version to store if this is the first
# time the program has been run against a
# FSxN.
################################################################################
# This function is used to extract the one-, two-, or three-digit number from
# the string passed in, starting at the 'start' character. Then, multiple it
# by the unit after the number:
# D = Day = 60*60*24
# H = Hour = 60*60
# M = Minutes = 60
#
# It returns a tuple that has the extracted number and the end position.
################################################################################
def getNumber(string, start):
if len(string) <= start:
return (0, start)
#
# Check to see if it is a 1, 2 or 3 digit number.
startp1=start+1 # Single digit
startp2=start+2 # Double digit
startp3=start+3 # Triple digit
if re.search('[0-9]', string[startp1:startp2]) and re.search('[0-9]', string[startp2:startp3]):
end=startp3
elif re.search('[0-9]', string[startp1:startp2]):
end=startp2
else:
end=startp1
num=int(string[start:end])
endp1=end+1
if string[end:endp1] == "D":
num=num*60*60*24
elif string[end:endp1] == "H":
num=num*60*60
elif string[end:endp1] == "M":
num=num*60
elif string[end:endp1] != "S":
print(f'Unknown lag time specifier "{string[end:endp1]}".')
return (num, endp1)
################################################################################
# This function is used to parse the lag time string returned by the
# ONTAP API and return the equivalent seconds it represents.
# The input string is assumed to follow this pattern "P#DT#H#M#S" where
# each of those "#" can be one to three digits long. Also, if the lag isn't
# more than 24 hours, then the "#D" isn't there and the string simply starts
# with "PT". Similarly, if the lag time isn't more than an hour then the "#H"
# string is missing.
################################################################################
def parseLagTime(string):
#
num=0
#
# First check to see if the Day field is there, by checking to see if the
# second character is a digit. If not, it is assumed to be 'T'.
includesDay=False
if re.search('[0-9]', string[1:2]):
includesDay=True
start=1
else:
start=2
data=getNumber(string, start)
num += data[0]
start=data[1]
#
# If there is a 'D', then there is a 'T' between the D and the # of hours
# so skip pass it.
if includesDay:
start += 1
data=getNumber(string, start)
num += data[0]
start=data[1]
data=getNumber(string, start)
num += data[0]
start=data[1]
data=getNumber(string, start)
num += data[0]
return(num)
################################################################################
# This function checks to see if an event is in the events array based on
# the unique Identifier passed in. It will also update the "refresh" field on
# any matches.
################################################################################
def eventExist (events, uniqueIdentifier):
for event in events:
if event["index"] == uniqueIdentifier:
event["refresh"] = eventResilience
return True
return False
################################################################################
# This function makes an API call to the FSxN to ensure it is up. If the
# errors out, then it sends an alert, and returns 'False'. Otherwise it returns
# 'True'.
################################################################################
def checkSystem():
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
changedEvents = False
#
# Get the previous status.
try:
data = s3Client.get_object(Key=config["systemStatusFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then this must be the
# first time this script has run against thie filesystem so create an
# initial status structure.
if err.response['Error']['Code'] == "NoSuchKey":
fsxStatus = {
"systemHealth": True,
"version" : initialVersion,
"numberNodes" : 2,
"downInterfaces" : []
}
changedEvents = True
else:
raise err
else:
fsxStatus = json.loads(data["Body"].read().decode('UTF-8'))
#
# Get the cluster name and ONTAP version from the FSxN.
# This is also a way to test that the FSxN cluster is accessible.
badHTTPStatus = False
try:
endpoint = f'https://{config["OntapAdminServer"]}/api/cluster?fields=version,name'
response = http.request('GET', endpoint, headers=headers, timeout=5.0)
if response.status == 200:
if not fsxStatus["systemHealth"]:
fsxStatus["systemHealth"] = True
changedEvents = True
data = json.loads(response.data)
if config["awsAccountId"] != None:
clusterName = f'{data["name"]}({config["awsAccountId"]})'
else:
clusterName = data['name']
#
# The following assumes that the format of the "full" version
# looks like: "NetApp Release 9.13.1P6: Tue Dec 05 16:06:25 UTC 2023".
# The reason for looking at the "full" instead of the individual
# keys (generation, major, minor) is because they don't provide
# the patch level. :-(
clusterVersion = data["version"]["full"].split()[2].replace(":", "")
if fsxStatus["version"] == initialVersion:
fsxStatus["version"] = clusterVersion
else:
print(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
badHTTPStatus = True
raise Exception(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
except:
if fsxStatus["systemHealth"]:
if config["awsAccountId"] != None:
clusterName = f'{config["OntapAdminServer"]}({config["awsAccountId"]})'
else:
clusterName = config["OntapAdminServer"]
if badHTTPStatus:
message = f'CRITICAL: Received a non 200 HTTP status code ({response.status}) when trying to access {clusterName}.'
else:
message = f'CRITICAL: Failed to issue API against {clusterName}. Cluster could be down.'
logger.critical(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
fsxStatus["systemHealth"] = False
changedEvents = True
if changedEvents:
s3Client.put_object(Key=config["systemStatusFilename"], Bucket=config["s3BucketName"], Body=json.dumps(fsxStatus).encode('UTF-8'))
#
# If the cluster is done, return false so the program can exit cleanly.
return(fsxStatus["systemHealth"])
################################################################################
# This function checks the following things:
# o If the ONTAP version has changed.
# o If one of the nodes are down.
# o If a network interface is down.
#
# ASSUMPTIONS: That checkSystem() has been called before it.
################################################################################
def checkSystemHealth(service):
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
changedEvents = False
#
# Get the previous status.
# Shouldn't have to check for status of the get_object() call, to see if the object exist or not,
# since "checkSystem()" should already have been called and it creates the object if it doesn't
# already exist. So, if there is a failure, it should be something else than "non-existent".
data = s3Client.get_object(Key=config["systemStatusFilename"], Bucket=config["s3BucketName"])
fsxStatus = json.loads(data["Body"].read().decode('UTF-8'))
for rule in service["rules"]:
for key in rule.keys():
lkey = key.lower()
if lkey == "versionchange":
if rule[key] and clusterVersion != fsxStatus["version"]:
message = f'NOTICE: The ONTAP vesion changed on cluster {clusterName} from {fsxStatus["version"]} to {clusterVersion}.'
logger.info(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
fsxStatus["version"] = clusterVersion
changedEvents = True
elif lkey == "failover":
#
# Check that both nodes are available.
# Using the CLI passthrough API because I couldn't find the equivalent API call.
if rule[key]:
endpoint = f'https://{config["OntapAdminServer"]}/api/private/cli/system/node/virtual-machine/instance/show-settings'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
if data["num_records"] != fsxStatus["numberNodes"]:
message = f'Alert: The number of nodes on cluster {clusterName} went from {fsxStatus["numberNodes"]} to {data["num_records"]}.'
logger.info(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
fsxStatus["numberNodes"] = data["num_records"]
changedEvents = True
else:
print(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
elif lkey == "networkinterfaces":
if rule[key]:
endpoint = f'https://{config["OntapAdminServer"]}/api/network/ip/interfaces?fields=state'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
#
# Decrement the refresh field to know if any events have really gone away.
for interface in fsxStatus["downInterfaces"]:
interface["refresh"] -= 1
data = json.loads(response.data)
for interface in data["records"]:
if interface.get("state") != None and interface["state"] != "up":
uniqueIdentifier = interface["name"]
if(not eventExist(fsxStatus["downInterfaces"], uniqueIdentifier)): # Resets the refresh key.
message = f'Alert: Network interface {interface["name"]} on cluster {clusterName} is down.'
logger.info(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
event = {
"index": uniqueIdentifier,
"refresh": eventResilience
}
fsxStatus["downInterfaces"].append(event)
changedEvents = True
#
# After processing the records, see if any events need to be removed.
i = 0
while i < len(fsxStatus["downInterfaces"]):
if fsxStatus["downInterfaces"][i]["refresh"] <= 0:
print(f'Deleting downed interface: {fsxStatus["downInterfaces"][i]["index"]}')
del fsxStatus["downInterfaces"][i]
changedEvents = True
else:
if fsxStatus["downInterfaces"][i]["refresh"] != eventResilience:
changedEvents = True
i += 1
else:
print(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
else:
print(f'Unknown System Health alert type: "{key}".')
if changedEvents:
s3Client.put_object(Key=config["systemStatusFilename"], Bucket=config["s3BucketName"], Body=json.dumps(fsxStatus).encode('UTF-8'))
################################################################################
# This function processes the EMS events.
################################################################################
def processEMSEvents(service):
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
changedEvents = False
#
# Get the saved events so we can ensure we are only reporting on new ones.
try:
data = s3Client.get_object(Key=config["emsEventsFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then it will get created once an alert it sent.
if err.response['Error']['Code'] == "NoSuchKey":
events = []
else:
raise err
else:
events = json.loads(data["Body"].read().decode('UTF-8'))
#
# Decrement the refresh field to know if any records have really gone away.
for event in events:
event["refresh"] -= 1
#
# Run the API call to get the current list of EMS events.
endpoint = f'https://{config["OntapAdminServer"]}/api/support/ems/events'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
#
# Process the events to see if there are any new ones.
print(f'Received {len(data["records"])} EMS records.')
logger.debug(f'Received {len(data["records"])} EMS records.')
for record in data["records"]:
for rule in service["rules"]:
if (re.search(rule["name"], record["message"]["name"]) and
re.search(rule["severity"], record["message"]["severity"]) and
re.search(rule["message"], record["log_message"])):
if (not eventExist (events, record["index"])): # This resets the "refresh" field if found.
message = f'{record["time"]} : {clusterName} {record["message"]["name"]}({record["message"]["severity"]}) - {record["log_message"]}'
useverity=record["message"]["severity"].upper()
if useverity == "EMERGENCY":
logger.critical(message)
elif useverity == "ALERT":
logger.error(message)
elif useverity == "ERROR":
logger.warning(message)
elif useverity == "NOTICE" or useverity == "INFORMATIONAL":
logger.info(message)
elif useverity == "DEBUG":
logger.debug(message)
else:
print(f'Received unknown severity from ONTAP "{record["message"]["severity"]}". The message received is next.')
logger.info(f'Received unknown severity from ONTAP "{record["message"]["severity"]}". The message received is next.')
logger.info(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents = True
event = {
"index": record["index"],
"time": record["time"],
"messageName": record["message"]["name"],
"message": record["log_message"],
"refresh": eventResilience
}
print(message)
events.append(event)
#
# Now that we have processed all the events, check to see if any events should be deleted.
i = 0
while i < len(events):
if events[i]["refresh"] <= 0:
print(f'Deleting event: {events[i]["time"]} : {events[i]["message"]}')
del events[i]
changedEvents = True
else:
# If an event wasn't refreshed, then we need to save the new refresh count.
if events[i]["refresh"] != eventResilience:
changedEvents = True
i += 1
#
# If the events array changed, save it.
if changedEvents:
s3Client.put_object(Key=config["emsEventsFilename"], Bucket=config["s3BucketName"], Body=json.dumps(events).encode('UTF-8'))
else:
print(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
logger.debug(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
################################################################################
# This function is used to find an existing SM relationship based on the source
# and destinatino path passed in. It returns None if one isn't found
################################################################################
def getPreviousSMRecord(relationShips, sourceCluster, sourcePath, destPath):
for relationship in relationShips:
if relationship['sourcePath'] == sourcePath and relationship['destPath'] == destPath and relationship['sourceCluster'] == sourceCluster:
relationship['refresh'] = True
return(relationship)
return(None)
################################################################################
# This function is used to check SnapMirror relationships.
################################################################################
def processSnapMirrorRelationships(service):
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
#
# Get the saved events so we can ensure we are only reporting on new ones.
try:
data = s3Client.get_object(Key=config["smEventsFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then it will get created once an alert it sent.
if err.response['Error']['Code'] == "NoSuchKey":
events = []
else:
raise err
else:
events = json.loads(data["Body"].read().decode('UTF-8'))
#
# Decrement the refresh field to know if any records have really gone away.
for event in events:
event["refresh"] -= 1
changedEvents=False
#
# Get the saved SM relationships.
try:
data = s3Client.get_object(Key=config["smRelationshipsFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then it will get created once an alert it sent.
if err.response['Error']['Code'] == "NoSuchKey":
smRelationships = []
else:
raise err
else:
smRelationships = json.loads(data["Body"].read().decode('UTF-8'))
#
# Set the refresh to False to know if any of the relationships still exist.
for relationship in smRelationships:
relationship["refresh"] = False
updateRelationships = False
#
# Get the current time in seconds since UNIX epoch 01/01/1970.
curTime = int(datetime.datetime.now().timestamp())
#
# Run the API call to get the current state of all the snapmirror relationships.
endpoint = f'https://{config["OntapAdminServer"]}/api/snapmirror/relationships?fields=*'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
for record in data["records"]:
for rule in service["rules"]:
for key in rule.keys():
lkey = key.lower()
#
# If the source cluster isn't defined, then assume it is a local SM relationship.
sourceCluster = record['source'].get('cluster')
if sourceCluster == None:
sourceClusterName = clusterName
else:
sourceClusterName = sourceCluster['name']
if lkey == "maxlagtime":
if record.get("lag_time") != None:
lagSeconds = parseLagTime(record["lag_time"])
if lagSeconds > rule["maxLagTime"]:
uniqueIdentifier = record["uuid"] + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
message = f'Snapmirror Lag Alert: {sourceClusterName}::{record["source"]["path"]} -> {clusterName}::{record["destination"]["path"]} has a lag time of {lagSeconds} seconds.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
elif lkey == "healthy":
if not record["healthy"]:
uniqueIdentifier = record["uuid"] + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
message = f'Snapmirror Health Alert: {sourceClusterName}::{record["source"]["path"]} {clusterName}::{record["destination"]["path"]} has a status of {record["healthy"]}'
logger.warning(message) # Intentionally put this before adding the reasons, since I'm not sure how syslog will handle a multi-line message.
for reason in record["unhealthy_reason"]:
message += "\n" + reason["message"]
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
elif lkey == "stalledtransferseconds":
if record.get('transfer') and record['transfer']['state'].lower() == "transferring":
sourcePath = record['source']['path']
destPath = record['destination']['path']
bytesTransferred = record['transfer']['bytes_transferred']
prevRec = getPreviousSMRecord(smRelationships, sourceClusterName, sourcePath, destPath)
if prevRec != None:
timeDiff=curTime - prevRec["time"]
print(f'transfer bytes last time:{prevRec["bytesTransferred"]} this time:{bytesTransferred} and {timeDiff} > {rule[key]}')
if prevRec['bytesTransferred'] == bytesTransferred:
if (curTime - prevRec['time']) > rule[key]:
uniqueIdentifier = record['uuid'] + "_" + "transfer"
if not eventExist(events, uniqueIdentifier):
message = f'Snapmiorror transfer has stalled: {sourceClusterName}::{sourcePath} -> {clusterName}::{destPath}.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject='Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
else:
prevRec['time'] = curTime
prevRec['refresh'] = True
prevRec['bytesTransferred'] = bytesTransferred
updateRelationships = True
else:
prevRec = {
"time": curTime,
"refresh": True,
"bytesTransferred": bytesTransferred,
"sourcePath": sourcePath,
"destPath": destPath,
"sourceCluster": sourceClusterName
}
updateRelationships = True
smRelationships.append(prevRec)
else:
message = f'Unknown snapmirror alert type: "{key}".'
logger.warning(message)
print(message)
#
# After processing the records, see if any SM relationships need to be removed.
i = 0
while i < len(smRelationships):
if not smRelationships[i]["refresh"]:
del smRelationships[i]
updateRelationships = True
else:
i += 1
#
# If any of the SM relationships changed, save it.
if(updateRelationships):
s3Client.put_object(Key=config["smRelationshipsFilename"], Bucket=config["s3BucketName"], Body=json.dumps(smRelationships).encode('UTF-8'))
#
# After processing the records, see if any events need to be removed.
i = 0
while i < len(events):
if events[i]["refresh"] <= 0:
print(f'Deleting event: {events[i]["message"]}')
del events[i]
changedEvents = True
else:
# If an event wasn't refreshed, then we need to save the new refresh count.
if events[i]["refresh"] != eventResilience:
changedEvents = True
i += 1
#
# If the events array changed, save it.
if(changedEvents):
s3Client.put_object(Key=config["smEventsFilename"], Bucket=config["s3BucketName"], Body=json.dumps(events).encode('UTF-8'))
else:
print(f'API call to {endpoint} failed. HTTP status code {response.status}.')
################################################################################
# This function is used to check all the volume and aggregate utlization.
################################################################################
def processStorageUtilization(service):
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
changedEvents=False
#
# Get the saved events so we can ensure we are only reporting on new ones.
try:
data = s3Client.get_object(Key=config["storageEventsFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then it will get created once an alert it sent.
if err.response['Error']['Code'] == "NoSuchKey":
events = []
else:
raise err
else:
events = json.loads(data["Body"].read().decode('UTF-8'))
#
# Decrement the refresh field to know if any records have really gone away.
for event in events:
event["refresh"] -= 1
for rule in service["rules"]:
for key in rule.keys():
lkey=key.lower()
if lkey == "aggrwarnpercentused" or lkey == 'aggrcriticalpercentused':
#
# Run the API call to get the physical storage used.
endpoint = f'https://{config["OntapAdminServer"]}/api/storage/aggregates?fields=space'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
for aggr in data["records"]:
if aggr["space"]["block_storage"]["used_percent"] >= rule[key]:
uniqueIdentifier = aggr["uuid"] + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
alertType = 'Warning' if lkey == "aggrwarnpercentused" else 'Critical'
message = f'Aggregate {alertType} Alert: Aggregate {aggr["name"]} on {clusterName} is {aggr["space"]["block_storage"]["used_percent"]}% full, which is more or equal to {rule[key]}% full.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents = True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(event)
events.append(event)
else:
print(f'API call to {endpoint} failed. HTTP status code {response.status}.')
elif lkey == "volumewarnpercentused" or lkey == "volumecriticalpercentused":
#
# Run the API call to get the volume information.
endpoint = f'https://{config["OntapAdminServer"]}/api/storage/volumes?fields=space,svm'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
for record in data["records"]:
if record["space"].get("percent_used"):
if record["space"]["percent_used"] >= rule[key]:
uniqueIdentifier = record["uuid"] + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
alertType = 'Warning' if lkey == "volumewarnpercentused" else 'Critical'
message = f'Volume Usage {alertType} Alert: volume {record["svm"]["name"]}:/{record["name"]} on {clusterName} is {record["space"]["percent_used"]}% full, which is more or equal to {rule[key]}% full.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents = True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
else:
print(f'API call to {endpoint} failed. HTTP status code {response.status}.')
else:
message = f'Unknown storage alert type: "{key}".'
logger.warning(message)
print(message)
#
# After processing the records, see if any events need to be removed.
i = 0
while i < len(events):
if events[i]["refresh"] <= 0:
print(f'Deleting event: {events[i]["message"]}')
del events[i]
changedEvents = True
else:
# If an event wasn't refreshed, then we need to save the new refresh count.
if events[i]["refresh"] != eventResilience:
changedEvents = True
i += 1
#
# If the events array changed, save it.
if(changedEvents):
s3Client.put_object(Key=config["storageEventsFilename"], Bucket=config["s3BucketName"], Body=json.dumps(events).encode('UTF-8'))
################################################################################
# This function is used to check utilization of quota limits.
################################################################################
def processQuotaUtilization(service):
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
changedEvents=False
#
# Get the saved events so we can ensure we are only reporting on new ones.
try:
data = s3Client.get_object(Key=config["quotaEventsFilename"], Bucket=config["s3BucketName"])
except botocore.exceptions.ClientError as err:
# If the error is that the object doesn't exist, then it will get created once an alert it sent.
if err.response['Error']['Code'] == "NoSuchKey":
events = []
else:
raise err
else:
events = json.loads(data["Body"].read().decode('UTF-8'))
#
# Decrement the refresh field to know if any records have really gone away.
for event in events:
event["refresh"] -= 1
#
# Run the API call to get the quota report.
endpoint = f'https://{config["OntapAdminServer"]}/api/storage/quota/reports?fields=*'
response = http.request('GET', endpoint, headers=headers)
if response.status == 200:
data = json.loads(response.data)
for record in data["records"]:
for rule in service["rules"]:
for key in rule.keys():
lkey = key.lower() # Convert to all lower case so the key can be case insensitive.
if lkey == "maxquotainodespercentused":
#
# Since the quota report might not have the files key, and even if it does, it might not have
# the hard_limit_percent" key, need to check for their existencae first.
if(record.get("files") != None and record["files"]["used"].get("hard_limit_percent") != None and
record["files"]["used"]["hard_limit_percent"] > rule[key]):
uniqueIdentifier = str(record["index"]) + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
if record.get("qtree") != None:
qtree=f' under qtree: {record["qtree"]["name"]} '
else:
qtree=' '
if record.get("users") != None:
users=None
for user in record["users"]:
if users == None:
users = user["name"]
else:
users += ',{user["name"]}'
user=f'associated with user(s) "{users}" '
else:
user=''
message = f'Quota Inode Usage Alert: Quota of type "{record["type"]}" on {record["svm"]["name"]}:/{record["volume"]["name"]}{qtree}{user}on {clusterName} is using {record["files"]["used"]["hard_limit_percent"]}% which is more than {rule[key]}% of its inodes.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
elif lkey == "maxhardquotaspacepercentused":
if(record.get("space") != None and record["space"]["used"].get("hard_limit_percent") and
record["space"]["used"]["hard_limit_percent"] >= rule[key]):
uniqueIdentifier = str(record["index"]) + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
if record.get("qtree") != None:
qtree=f' under qtree: {record["qtree"]["name"]} '
else:
qtree=" "
if record.get("users") != None:
users=None
for user in record["users"]:
if users == None:
users = user["name"]
else:
users += ',{user["name"]}'
user=f'associated with user(s) "{users}" '
else:
user=''
message = f'Quota Space Usage Alert: Hard quota of type "{record["type"]}" on {record["svm"]["name"]}:/{record["volume"]["name"]}{qtree}{user}on {clusterName} is using {record["space"]["used"]["hard_limit_percent"]}% which is more than {rule[key]}% of its allocaed space.'
logger.warning(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
elif lkey == "maxsoftquotaspacepercentused":
if(record.get("space") != None and record["space"]["used"].get("soft_limit_percent") and
record["space"]["used"]["soft_limit_percent"] >= rule[key]):
uniqueIdentifier = str(record["index"]) + "_" + key
if not eventExist(events, uniqueIdentifier): # This resets the "refresh" field if found.
if record.get("qtree") != None:
qtree=f' under qtree: {record["qtree"]["name"]} '
else:
qtree=" "
if record.get("users") != None:
users=None
for user in record["users"]:
if users == None:
users = user["name"]
else:
users += ',{user["name"]}'
user=f'associated with user(s) "{users}" '
else:
user=''
message = f'Quota Space Usage Alert: Soft quota of type "{record["type"]}" on {record["svm"]["name"]}:/{record["volume"]["name"]}{qtree}{user}on {clusterName} is using {record["space"]["used"]["soft_limit_percent"]}% which is more than {rule[key]}% of its allocaed space.'
logger.info(message)
snsClient.publish(TopicArn=config["snsTopicArn"], Message=message, Subject=f'Monitor ONTAP Services Alert for cluster {clusterName}')
changedEvents=True
event = {
"index": uniqueIdentifier,
"message": message,
"refresh": eventResilience
}
print(message)
events.append(event)
else:
message = f'Unknown quota matching condition type "{key}".'
logger.warning(message)
print(message)
#
# After processing the records, see if any events need to be removed.
i=0
while i < len(events):
if events[i]["refresh"] <= 0:
print(f'Deleting event: {events[i]["message"]}')
del events[i]
changedEvents = True
else:
# If an event wasn't refreshed, then we need to save the new refresh count.
if events[i]["refresh"] != eventResilience:
changedEvents = True
i += 1
#
# If the events array changed, save it.
if(changedEvents):
s3Client.put_object(Key=config["quotaEventsFilename"], Bucket=config["s3BucketName"], Body=json.dumps(events).encode('UTF-8'))
else:
print(f'API call to {endpoint} failed. HTTP status code {response.status}.')
################################################################################
# This function returns the index of the service in the conditions dictionary.
################################################################################
def getServiceIndex(targetService, conditions):
i = 0
while i < len(conditions["services"]):
if conditions["services"][i]["name"] == targetService:
return i
i += 1
return None
################################################################################
# This function builds a default matching conditions dictionary based on the
# environment variables passed in.
################################################################################
def buildDefaultMatchingConditions():
#
# Define global variables so we don't have to pass them to all the functions.
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
#
# Define an empty matching conditions dictionary.
conditions = { "services": [
{"name": "systemHealth", "rules": []},
{"name": "ems", "rules": []},
{"name": "snapmirror", "rules": []},
{"name": "storage", "rules": []},
{"name": "quota", "rules": []}
]}
#
# Now, add rules based on the environment variables.
for name, value in os.environ.items():
if name == "initialVersionChangeAlert":
if value == "true":
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"versionChange": True})
else:
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"versionChange": False})
elif name == "initialFailoverAlert":
if value == "true":
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"failover": True})
else:
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"failover": False})
elif name == "initialNetworkInterfacesAlert":
if value == "true":
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"networkInterfaces": True})
else:
conditions["services"][getServiceIndex("systemHealth", conditions)]["rules"].append({"networkInterfaces": False})
elif name == "initialEmsEventsAlert":
if value == "true":
conditions["services"][getServiceIndex("ems", conditions)]["rules"].append({"name": "", "severity": "error|alert|emergency", "message": ""})
elif name == "initialSnapMirrorHealthAlert":
if value == "true":
conditions["services"][getServiceIndex("snapmirror", conditions)]["rules"].append({"Healthy": False}) # This is what it matches on, so it is interesting when the health is false.
else:
conditions["services"][getServiceIndex("snapmirror", conditions)]["rules"].append({"Healthy": True})
elif name == "initialSnapMirrorLagTimeAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("snapmirror", conditions)]["rules"].append({"maxLagTime": value})
elif name == "initialSnapMirrorStalledAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("snapmirror", conditions)]["rules"].append({"stalledTransferSeconds": value})
elif name == "initialFileSystemUtilizationWarnAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("storage", conditions)]["rules"].append({"aggrWarnPercentUsed": value})
elif name == "initialFileSystemUtilizationCriticalAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("storage", conditions)]["rules"].append({"aggrCriticalPercentUsed": value})
elif name == "initialVolumeUtilizationWarnAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("storage", conditions)]["rules"].append({"volumeWarnPercentUsed": value})
elif name == "initialVolumeUtilizationCriticalAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("storage", conditions)]["rules"].append({"volumeCriticalPercentUsed": value})
elif name == "initialSoftQuotaUtilizationAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("quota", conditions)]["rules"].append({"maxSoftQuotaSpacePercentUsed": value})
elif name == "initialHardQuotaUtilizationAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("quota", conditions)]["rules"].append({"maxHardQuotaSpacePercentUsed": value})
elif name == "initialInodesQuotaUtilizationAlert":
value = int(value)
if value > 0:
conditions["services"][getServiceIndex("quota", conditions)]["rules"].append({"maxQuotaInodesPercentUsed": value})
return conditions
################################################################################
# This function is used to read in all the configuration parameters from the
# various places:
# Environment Variables
# Config File
# Calculated
################################################################################
def readInConfig():
#
# Define global variables so we don't have to pass them to all the functions.
global config, s3Client, snsClient, http, headers, clusterName, clusterVersion, logger
#
# Define a dictionary with all the required variables so we can
# easily add them and check for their existence.
requiredEnvVariables = {
"OntapAdminServer": None,
"s3BucketName": None,
"s3BucketRegion": None
}
optionalVariables = {
"configFilename": None,
"secretsManagerEndPointHostname": None,
"snsEndPointHostname": None,
"syslogIP": None,
"awsAccountId": None
}
filenameVariables = {
"emsEventsFilename": None,
"smEventsFilename": None,
"smRelationshipsFilename": None,
"conditionsFilename": None,
"storageEventsFilename": None,
"quotaEventsFilename": None,
"systemStatusFilename": None
}
config = {
"snsTopicArn": None,
"secretArn": None,
"secretUsernameKey": None,
"secretPasswordKey": None
}
config.update(filenameVariables)
config.update(optionalVariables)
config.update(requiredEnvVariables)
#
# Get the required, and any additional, paramaters from the environment.
for var in config:
config[var] = os.environ.get(var)
#
# Check to see if s3BacketArn was provided instead of s3BucketName.
if config["s3BucketName"] == None and os.environ.get("s3BucketArn") != None:
config["s3BucketName"] = os.environ.get("s3BucketArn").split(":")[-1]
#
# Check that required environmental variables are there.
for var in requiredEnvVariables:
if config[var] == None:
raise Exception (f'\n\nMissing required environment variable "{var}".')
#
# Open a client to the s3 service.
s3Client = boto3.client('s3', config["s3BucketRegion"])
#
# Calculate the config filename if it hasn't already been provided.
defaultConfigFilename = config["OntapAdminServer"] + "-config"
if config["configFilename"] == None: