-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcloudformation.yaml
More file actions
2239 lines (2099 loc) · 120 KB
/
cloudformation.yaml
File metadata and controls
2239 lines (2099 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Description: "Deploy monitor-ontap-services."
#
# This just formats the page that prompts for the parameters when using the AWS Console to deploy your stack.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Configuration Parameters"
Parameters:
- OntapAdminSever
- s3BucketName
- subNetIds
- securityGroupIds
- snsTopicArn
- cloudWatchLogGroupArn
- secretArn
- secretUsernameKey
- secretPasswordKey
- checkInterval
- createWatchdogAlarm
- createSecretsManagerEndpoint
- createSNSEndpoint
- createCloudWatchLogsEndpoint
- createS3Endpoint
- routeTableIds
- vpcId
- endpointSecurityGroupIds
- LambdaRoleArn
- SchedulerRoleArn
- watchdogRoleArn
- Label:
default: "Alert Parameters"
Parameters:
- versionChangeAlert
- failoverAlert
- emsEventsAlert
- snapMirrorLagTimeAlert
- snapMirrorLagTimePercentAlert
- snapMirrorStalledAlert
- snapMirrorHealthAlert
- fileSystemUtilizationWarnAlert
- fileSystemUtilizationCriticalAlert
- volumeUtilizationWarnAlert
- volumeUtilizationCriticalAlert
- volumeFileUtilizationWarnAlert
- volumeFileUtilizationCriticalAlert
- volumeOfflineAlert
- softQuotaUtilizationAlert
- hardQuotaUtilizationAlert
- inodesQuotaUtilizationAlert
- vserverStateAlert
- vserverNFSProtocolStateAlert
- vserverCIFSProtocolStateAlert
Parameters:
OntapAdminSever:
Description: "The DNS name, or IP address, of the management endpoint of the FSxN file system to be monitored."
Type: String
s3BucketName:
Description: "The name of the S3 bucket to use to store the status and configuration files. Must also be holding the lambda_layer.zip file."
Type: String
subNetIds:
Description: "The subnet IDs where you want to deploy the Lambda function. Must have connectivity to the FSxN file system to be monitored."
Type: "List<AWS::EC2::Subnet::Id>"
securityGroupIds:
Description: "The security group IDs to associate with the Lambda function. Must allow outbound traffic over TCP port 443 to the FSxN file system, and the AWS service endpoints."
Type: "List<AWS::EC2::SecurityGroup::Id>"
Default: ""
snsTopicArn:
Description: "The ARN of the SNS topic where you want alerts sent to."
Type: String
cloudWatchLogGroupArn:
Description: "The ARN of the CloudWatch log group to send alerts to. If left blank, alerts will not be sent to CloudWatch. Note that the log group must already exist. Also note that the ARN should end with ':*'."
Type: String
Default: ""
secretArn:
Description: "The ARN of the Secrets Manager secret that holds the FSxN credentials to use."
Type: String
secretUsernameKey:
Description: "The key in the secret that holds the username."
Type: String
Default: "username"
secretPasswordKey:
Description: "The key in the secret that holds the password."
Type: String
Default: "password"
createWatchdogAlarm:
Description: "Create a CloudWatch alarm to monitor the Lambda function. It will alert you if the function fails to run successfully."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
watchdogRoleArn:
Description: "The ARN of the role to use for the Lambda function that will publish messages to the SNS topic if the monitoring function doesn't run properly. This is only needed if you are having the CloudWatch alarm created and if you want to provide an existing role, otherwise an appropriate one will be created for you."
Type: String
Default: ""
createSecretsManagerEndpoint:
Description: "Create a Secrets Manager endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
createSNSEndpoint:
Description: "Create an SNS endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
createCloudWatchLogsEndpoint:
Description: "Create a CloudWatch logs endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
createS3Endpoint:
Description: "Create an S3 endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
routeTableIds:
Description: "The route table IDs, comma separated, to update to use the S3 endpoint. Since the S3 endpoint is of type 'Gateway' route tables have to be updated to use it. This parameter is only needed if createS3Endpoint is set to 'true'."
Type: CommaDelimitedList
Default: ""
vpcId:
Description: "The VPC ID where the FSxN file system is located. This is only needed if you are creating an endpoint."
Type: String
Default: ""
endpointSecurityGroupIds:
Description: "The security group IDs, comma separated list, to associate with the SNS, SecretsManager and/or CloudWatch Logs endpoints. Must allow traffic from from the Lambda function over TCP port 443. This parameter is only needed if you are creating the SNS, SecretsManager, or CloudWatch Logs endpoint."
Type: CommaDelimitedList
Default: ""
LambdaRoleArn:
Description: "The ARN of the role to use for the Lambda function. This is only needed if you want to provide an existing role, otherwise an appropriate one will be created for you."
Type: String
Default: ""
SchedulerRoleArn:
Description: "The ARN of the role to use for the Lambda scheduler. This is only needed if you want to provide an existing role, otherwise an appropriate one will be created for you."
Type: String
Default: ""
checkInterval:
Description: "The interval, in minutes, between checks."
Type: Number
Default: 15
MinValue: 1
versionChangeAlert:
Description: "Alert when the ONTAP version changes."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
failoverAlert:
Description: "Alert when a failover occurs."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
emsEventsAlert:
Description: "Alert for EMS messages."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
snapMirrorLagTimeAlert:
Description: "Alert when a SnapMirror update time is more than the specified seconds. Set to 0 to disable this alert. Recommended to set both snapMirrorLagTimeAlert and snapMirrorLagTimePercentAlert."
Type: Number
Default: 86400
snapMirrorLagTimePercentAlert:
Description: "Alert when the last succesful SnapMirror update time is more than this percent of the amount of time since the last scheduled update. Must be more than 100. A value of 200 means 2 times the update interval. Set to 0 to disable this alert."
Type: Number
MinValue: 100
Default: 200
snapMirrorStalledAlert:
Description: "Alert when a SnapMirror update hasn't transferred any new data in the specified seconds. Set to 0 to disable this alert."
Type: Number
Default: 600
MinValue: 60
snapMirrorHealthAlert:
Description: "Alert when the SnapMirror relationship is not healthy."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
fileSystemUtilizationWarnAlert:
Description: "Alert when the file system utilization exceeds this threshold in percentage."
Type: Number
Default: 80
fileSystemUtilizationCriticalAlert:
Description: "Alert when the file system utilization exceeds this threshold in percentage."
Type: Number
Default: 90
volumeUtilizationWarnAlert:
Description: "Alert when a volume utilization exceeds this threshold in percentage."
Type: Number
Default: 90
volumeUtilizationCriticalAlert:
Description: "Alert when a volume utilization exceeds this threshold in percentage."
Type: Number
Default: 95
volumeFileUtilizationWarnAlert:
Description: "Alert when a volume inode utilization exceeds this threshold in percentage."
Type: Number
Default: 90
volumeFileUtilizationCriticalAlert:
Description: "Alert when a volume inode utilization exceeds this threshold in percentage."
Type: Number
Default: 95
volumeOfflineAlert:
Description: "Alert when a volume goes offline."
Type: String
AllowedValues: ["true", "false"]
Default: "true"
softQuotaUtilizationAlert:
Description: "Alert when a soft quota exceeds this threshold in percentage."
Type: Number
Default: 100
hardQuotaUtilizationAlert:
Description: "Alert when a hard quota exceeds this threshold in percentage."
Type: Number
Default: 80
inodesQuotaUtilizationAlert:
Description: "Alert when an inode quota exceeds this threshold in percentage."
Type: Number
Default: 80
vserverStateAlert:
Description: "Alert when a vserver goes offline."
Type: String
AllowedValues: ["true", "false"]
Default: "true"
vserverNFSProtocolStateAlert:
Description: "Alert when a vserver's NFS protocol goes offline."
Type: String
AllowedValues: ["true", "false"]
Default: "true"
vserverCIFSProtocolStateAlert:
Description: "Alert when a vserver's CIFS protocol goes offline."
Type: String
AllowedValues: ["true", "false"]
Default: "true"
Conditions:
CreateSecretsManagerEndpoint: !Equals [!Ref createSecretsManagerEndpoint, "true"]
CreateSNSEndpoint: !Equals [!Ref createSNSEndpoint, "true"]
CreateS3Endpoint: !Equals [!Ref createS3Endpoint, "true"]
CreateCloudWatchLogsEndpoint: !Equals [!Ref createCloudWatchLogsEndpoint, "true"]
CreateWatchdogAlarm: !Equals [!Ref createWatchdogAlarm, "true"]
CreateLambdaRoleWithCW: !And [!Equals [!Ref LambdaRoleArn, ""], !Not [!Equals [!Ref cloudWatchLogGroupArn, ""]]]
CreateLambdaRoleWithoutCW: !And [!Equals [!Ref LambdaRoleArn, ""], !Equals [!Ref cloudWatchLogGroupArn, ""]]
CreateSchedulerRole: !Equals [!Ref SchedulerRoleArn, ""]
CreateWatchdogRole: !Equals [!Ref watchdogRoleArn, ""]
Resources:
SecretManagerEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateSecretsManagerEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.secretsmanager"
VpcEndpointType: 'Interface'
PrivateDnsEnabled: true
SubnetIds: !Ref subNetIds
SecurityGroupIds: !Ref endpointSecurityGroupIds
CWEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateCloudWatchLogsEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.logs"
VpcEndpointType: 'Interface'
PrivateDnsEnabled: true
SubnetIds: !Ref subNetIds
SecurityGroupIds: !Ref endpointSecurityGroupIds
SNSEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateSNSEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.sns"
VpcEndpointType: 'Interface'
PrivateDnsEnabled: true
SubnetIds: !Ref subNetIds
SecurityGroupIds: !Ref endpointSecurityGroupIds
S3Endpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateS3Endpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.s3"
VpcEndpointType: 'Gateway'
RouteTableIds: !Ref routeTableIds
#
# Allow the Watchdog Lambda function to publish to the SNS topic.
LambdaRoleWatchdog:
Type: "AWS::IAM::Role"
Condition: CreateWatchdogRole
Properties:
RoleName: !Sub "mon-ontap-services-watchdog-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "lambda.amazonaws.com"
Action: "sts:AssumeRole"
Policies:
- PolicyName: "LambdaPolicyWatchdog"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "sns:Publish"
Resource: !Ref snsTopicArn
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
#
# This allows the Watchdog CloudWatch alarm to invoke the Lambda function.
resourceBasedPermission:
Type: "AWS::Lambda::Permission"
Condition: CreateWatchdogAlarm
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !Sub "monitor-ontap-services-watchdog-${AWS::StackName}"
Principal: "lambda.alarms.cloudwatch.amazonaws.com"
SourceArn: !GetAtt watchdogAlarm.Arn
#
# Use a Lambda function to publish to an SNS topic so it can reside in a different region.
watchdogLambdaFunction:
Type: "AWS::Lambda::Function"
Condition: CreateWatchdogAlarm
Properties:
FunctionName: !Sub "monitor-ontap-services-watchdog-${AWS::StackName}"
PackageType: "Zip"
Runtime: "python3.12"
Handler: "index.lambda_handler"
Timeout: 10
Role: !If [CreateWatchdogRole, !GetAtt LambdaRoleWatchdog.Arn, !Ref watchdogRoleArn]
Environment:
Variables:
snsTopicArn: !Ref snsTopicArn
Code:
ZipFile: |
import boto3
import os
def lambda_handler(event, context):
snsTopicArn = os.environ.get('snsTopicArn')
if snsTopicArn is not None:
region = snsTopicArn.split(":")[3]
snsClient = boto3.client('sns', region_name=region)
#
# This is for future developement when the monitor-ontap-services
# Lambda function will be able to send messages to the SNS topic.
cmd = event.get("cmd")
#
# If the cmd is None, then assume a CloudWatch alarm triggered this function.
if cmd is None:
message = f'Error! Lambda function {event["alarmData"]["alarmName"].replace("-watchdog-", "")} failed to execute properly.'
snsClient.publish(
TopicArn = snsTopicArn,
Subject = 'Error! Monitoring ONTAP services has failed to execute',
Message = message
)
elif cmd == "sendSns":
message = event.get("message")
subject = event.get("subject")
snsClient.publish(
TopicArn = snsTopicArn,
Subject = subject,
Message = message
)
#
# This is the CloudWatch alarm that will trigger when the monitor-ontap-services
# Lambda function fails to run successfully. It will invoke the watchdogLambdaFunction
# to send a message to the SNS topic.
watchdogAlarm:
Type: "AWS::CloudWatch::Alarm"
Condition: CreateWatchdogAlarm
Properties:
AlarmName: !Sub "monitor-ontap-services-watchdog-${AWS::StackName}"
AlarmDescription: !Sub "Watchdog alarm for the monitor-ontap-services-${AWS::StackName} Lambda function."
Namespace: "AWS/Lambda"
MetricName: "Errors"
Dimensions:
- Name: "FunctionName"
Value: !Sub "monitor-ontap-services-${AWS::StackName}"
Statistic: "Maximum"
Period: 300
EvaluationPeriods: 1
TreatMissingData: "ignore"
Threshold: 0.5
ComparisonOperator: "GreaterThanThreshold"
AlarmActions:
- !GetAtt watchdogLambdaFunction.Arn
LambdaRoleWithoutCW:
Type: "AWS::IAM::Role"
Condition: CreateLambdaRoleWithoutCW
Properties:
RoleName: !Sub "mon-ontap-services-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "lambda.amazonaws.com"
Action: "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
Policies:
- PolicyName: "LambdaPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "secretsManager:GetSecretValue"
- "sns:Publish"
- "s3:GetObject"
- "s3:PutObject"
- "s3:ListBucket"
Resource:
- !Ref secretArn
- !Ref snsTopicArn
- !Sub "arn:aws:s3:::${s3BucketName}"
- !Sub "arn:aws:s3:::${s3BucketName}/*"
LambdaRoleWithCW:
Type: "AWS::IAM::Role"
Condition: CreateLambdaRoleWithCW
Properties:
RoleName: !Sub "mon-ontap-services-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "lambda.amazonaws.com"
Action: "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
Policies:
- PolicyName: "LambdaPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "secretsManager:GetSecretValue"
- "sns:Publish"
- "logs:PutLogEvents"
- "logs:DescribeLogStreams"
- "logs:CreateLogStream"
- "s3:GetObject"
- "s3:PutObject"
- "s3:ListBucket"
Resource:
- !Ref secretArn
- !Ref snsTopicArn
- !Sub "arn:aws:s3:::${s3BucketName}"
- !Sub "arn:aws:s3:::${s3BucketName}/*"
- !Ref cloudWatchLogGroupArn
SchedulerRole:
Type: "AWS::IAM::Role"
Condition: CreateSchedulerRole
Properties:
RoleName: !Sub "SchedulerRole-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "scheduler.amazonaws.com"
Action: "sts:AssumeRole"
Policies:
- PolicyName: "SchedulerPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "lambda:InvokeFunction"
Resource: !GetAtt LambdaFunction.Arn
LambdaScheduler:
Type: "AWS::Scheduler::Schedule"
Properties:
Description: "Schedule the monitor-ontap-services Lambda function."
Name: !Sub "monitor-ontap-services-scheduler-${AWS::StackName}"
FlexibleTimeWindow:
Mode: "OFF"
ScheduleExpression: !Sub "rate(${checkInterval} minutes)"
Target:
Arn: !GetAtt LambdaFunction.Arn
RoleArn: !If [CreateSchedulerRole, !GetAtt SchedulerRole.Arn, !Ref SchedulerRoleArn]
LambdaLayer:
Type: "AWS::Lambda::LayerVersion"
Properties:
LayerName: !Sub "MOS-${AWS::StackName}"
Content:
S3Bucket: !Ref s3BucketName
S3Key: "lambda_layer.zip"
CompatibleRuntimes:
- "python3.12"
LambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
FunctionName: !Sub "monitor-ontap-services-${AWS::StackName}"
Role: !If [CreateLambdaRoleWithCW, !GetAtt LambdaRoleWithCW.Arn, !If [CreateLambdaRoleWithoutCW, !GetAtt LambdaRoleWithoutCW.Arn, !Ref LambdaRoleArn]]
VpcConfig:
SecurityGroupIds: !Ref securityGroupIds
SubnetIds: !Ref subNetIds
PackageType: "Zip"
Runtime: "python3.12"
Layers:
- !GetAtt LambdaLayer.LayerVersionArn
Handler: "index.lambda_handler"
Timeout: 60
Environment:
Variables:
s3BucketRegion: !Ref AWS::Region
s3BucketName: !Ref s3BucketName
OntapAdminServer: !Ref OntapAdminSever
secretArn: !Ref secretArn
secretUsernameKey: !Ref secretUsernameKey
secretPasswordKey: !Ref secretPasswordKey
snsTopicArn: !Ref snsTopicArn
sendSnsFunctionName: !Sub "monitor-ontap-services-watchdog-${AWS::StackName}"
cloudWatchLogGroupArn: !Ref cloudWatchLogGroupArn
initialVersionChangeAlert: !Ref versionChangeAlert
initialFailoverAlert: !Ref failoverAlert
initialEmsEventsAlert: !Ref emsEventsAlert
initialSnapMirrorLagTimeAlert: !Ref snapMirrorLagTimeAlert
initialSnapMirrorLagTimePercentAlert: !Ref snapMirrorLagTimePercentAlert
initialSnapMirrorStalledAlert: !Ref snapMirrorStalledAlert
initialSnapMirrorHealthAlert: !Ref snapMirrorHealthAlert
initialFileSystemUtilizationWarnAlert: !Ref fileSystemUtilizationWarnAlert
initialFileSystemUtilizationCriticalAlert: !Ref fileSystemUtilizationCriticalAlert
initialVolumeUtilizationWarnAlert: !Ref volumeUtilizationWarnAlert
initialVolumeUtilizationCriticalAlert: !Ref volumeUtilizationCriticalAlert
initialVolumeFileUtilizationWarnAlert: !Ref volumeFileUtilizationWarnAlert
initialVolumeFileUtilizationCriticalAlert: !Ref volumeFileUtilizationCriticalAlert
initialVolumeOfflineAlert: !Ref volumeOfflineAlert
initialSoftQuotaUtilizationAlert: !Ref softQuotaUtilizationAlert
initialHardQuotaUtilizationAlert: !Ref hardQuotaUtilizationAlert
initialInodesQuotaUtilizationAlert: !Ref inodesQuotaUtilizationAlert
initialVserverStateAlert: !Ref vserverStateAlert
initialVserverNFSProtocolStateAlert: !Ref vserverNFSProtocolStateAlert
initialVserverCIFSProtocolStateAlert: !Ref vserverCIFSProtocolStateAlert
Code:
ZipFile: |
#!/bin/python3
#
################################################################################
# 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: v2.16
# Date: 2025-05-19-21:24:55
################################################################################
import json
import re
import os
import datetime
import pytz
import logging
from logging.handlers import SysLogHandler
from cronsim import CronSim
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":
logger.warning(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, clusterTimezone
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, ONTAP version and timezone 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,timezone'
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
#
# Get the Timezone for SnapMirror lag time calculations.
clusterTimezone = data["timezone"]["name"]
else:
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.'
sendAlert(message, "CRITICAL")
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}.'
sendAlert(message, "INFO")
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"]}.'
sendAlert(message, "INFO")
fsxStatus["numberNodes"] = data["num_records"]
changedEvents = True
else:
logger.warning(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.'
sendAlert(message, "WARNING")
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:
logger.debug(f'Deleting interface: {fsxStatus["downInterfaces"][i]["index"]}')
del fsxStatus["downInterfaces"][i]
changedEvents = True
else:
if fsxStatus["downInterfaces"][i]["refresh"] != eventResilience:
changedEvents = True
i += 1
else:
logger.warning(f'API call to {endpoint} failed. HTTP status code: {response.status}.')
else:
logger.warning(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?return_timeout=15'
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"]:
messageFilter = rule.get("filter")
if messageFilter == None or messageFilter == "":
messageFilter = "ThisShouldn'tMatchAnything"
if (not re.search(messageFilter, record["log_message"]) and
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":
sendAlert(message, "CRITICAL")
elif useverity == "ALERT":
sendAlert(message, "ERROR")
elif useverity == "ERROR":
sendAlert(message, "WARNING")
elif useverity == "NOTICE" or useverity == "INFORMATIONAL":
sendAlert(message, "INFO")
elif useverity == "DEBUG":
sendAlert(message, "DEBUG")
else:
sendAlert(f'Received unknown severity from ONTAP "{record["message"]["severity"]}". The message received is next.', "INFO")
sendAlert(message, "INFO")
changedEvents = True
event = {
"index": record["index"],
"time": record["time"],
"messageName": record["message"]["name"],
"message": record["log_message"],
"refresh": eventResilience
}
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:
logger.debug(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:
logger.warning(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
################################################################################