-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathcluster_validators.py
More file actions
1640 lines (1400 loc) · 71.6 KB
/
Copy pathcluster_validators.py
File metadata and controls
1640 lines (1400 loc) · 71.6 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
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
import math
import re
from collections import defaultdict
from enum import Enum
from ipaddress import collapse_addresses, ip_network
from itertools import combinations, product
from typing import List
from pcluster.aws.aws_api import AWSApi
from pcluster.aws.aws_resources import InstanceTypeInfo
from pcluster.aws.common import AWSClientError
from pcluster.cli.commands.dcv_util import get_supported_dcv_os
from pcluster.config.common import CapacityType, SharedStorageType
from pcluster.constants import (
CIDR_ALL_IPS,
DELETE_POLICY,
EFS_PORT,
FSX_PORTS,
PCLUSTER_IMAGE_BUILD_STATUS_TAG,
PCLUSTER_NAME_MAX_LENGTH,
PCLUSTER_NAME_MAX_LENGTH_SLURM_ACCOUNTING,
PCLUSTER_NAME_REGEX,
PCLUSTER_TAG_VALUE_REGEX,
PCLUSTER_VERSION_TAG,
PRIVATE_OSES,
RETAIN_POLICY,
SUPPORTED_OSES,
SUPPORTED_SCHEDULERS,
)
from pcluster.launch_template_utils import _LaunchTemplateBuilder
from pcluster.utils import (
get_installed_version,
get_supported_os_for_architecture,
remove_none_values,
retrieve_supported_regions,
)
from pcluster.validators.common import FailureLevel, Validator
# pylint: disable=C0302
NAME_MAX_LENGTH = 25
SHARED_STORAGE_NAME_MAX_LENGTH = 30
NAME_REGEX = r"^[a-z][a-z0-9\-]*$"
EFA_UNSUPPORTED_ARCHITECTURES_OSES = {
"x86_64": ["almalinux8"],
"arm64": ["almalinux8"],
}
EFS_MESSAGES = {
"errors": {
"ignored_param_with_efs_fs_id": "{efs_param} cannot be specified when an existing EFS file system is used.",
}
}
FSX_SUPPORTED_ARCHITECTURES_OSES = {
"x86_64": SUPPORTED_OSES,
"arm64": SUPPORTED_OSES,
}
FSX_MESSAGES = {
"errors": {
"unsupported_os": "On {architecture} instance types, FSx Lustre can be used with one of the following operating"
" systems: {supported_oses}. Please double check the os configuration.",
"unsupported_architecture": "FSx Lustre can be used only with instance types and AMIs that support these "
"architectures: {supported_architectures}. Please double check the head node instance type, "
"compute instance type and/or custom AMI configurations.",
"unsupported_backup_param": "When restoring an FSx Lustre file system from backup, '{name}' "
"cannot be specified.",
"ignored_param_with_fsx_fs_id": "{fsx_param} cannot be specified when an existing Lustre file system is used.",
}
}
HOST_NAME_MAX_LENGTH = 64
# Max fqdn size is 255 characters, the first 64 are used for the hostname (e.g. queuename-st|dy-computeresourcename-N),
# then we need to add an extra ., so we have 190 characters to be used for the clustername + domain-name.
CLUSTER_NAME_AND_CUSTOM_DOMAIN_NAME_MAX_LENGTH = 255 - HOST_NAME_MAX_LENGTH - 1
class ClusterNameValidator(Validator):
"""Cluster name validator."""
def _validate(self, name, scheduling):
if scheduling.settings.database is not None or scheduling.settings.external_slurmdbd is not None:
if not re.match(PCLUSTER_NAME_REGEX % (PCLUSTER_NAME_MAX_LENGTH_SLURM_ACCOUNTING - 1), name):
self._add_failure(
(
"Error: The cluster name can contain only alphanumeric characters (case-sensitive) and "
"hyphens. "
"It must start with an alphabetic character and when using Slurm accounting it can't be longer "
f"than {PCLUSTER_NAME_MAX_LENGTH_SLURM_ACCOUNTING} characters."
),
FailureLevel.ERROR,
)
else:
if not re.match(PCLUSTER_NAME_REGEX % (PCLUSTER_NAME_MAX_LENGTH - 1), name):
self._add_failure(
(
"Error: The cluster name can contain only alphanumeric characters (case-sensitive) and "
"hyphens. "
"It must start with an alphabetic character and can't be longer "
f"than {PCLUSTER_NAME_MAX_LENGTH} characters."
),
FailureLevel.ERROR,
)
class RegionValidator(Validator):
"""Region validator."""
def _validate(self, region):
if region not in retrieve_supported_regions():
self._add_failure(
f"Region '{region}' is not yet officially supported by ParallelCluster", FailureLevel.ERROR
)
class OsCustomAmiValidator(Validator):
"""For some OSes we don't publish official AMIs, so CustomAmi parameter is required."""
def _validate(self, os: str, custom_ami: str):
if not custom_ami and os in PRIVATE_OSES:
self._add_failure(
(
f"ParallelCluster has no official AMI for {os}. "
"Please build your own AMI using pcluster build-image command, "
"as explained in the documentation: "
"https://docs.aws.amazon.com/parallelcluster/latest/ug/building-custom-ami-v3.html"
),
FailureLevel.ERROR,
)
class CustomAmiTagValidator(Validator):
"""Custom AMI tag validator to check if the AMI was created by pcluster to avoid runtime baking."""
def _validate(self, custom_ami: str):
tags = AWSApi.instance().ec2.describe_image(custom_ami).tags
tags_dict = {}
if tags: # tags can be None if there is no tag
for tag in tags:
tags_dict[tag["Key"]] = tag["Value"]
current_version = get_installed_version()
if PCLUSTER_VERSION_TAG not in tags_dict:
self._add_failure(
(
"The custom AMI may not have been created by pcluster. "
"You can ignore this warning if the AMI is shared or copied from another pcluster AMI. "
"If the AMI is indeed not created by pcluster, cluster creation will fail. "
"If the cluster creation fails, please go to "
"https://docs.aws.amazon.com/parallelcluster/latest/ug/troubleshooting.html"
"#troubleshooting-stack-creation-failures for troubleshooting."
),
FailureLevel.WARNING,
)
elif tags_dict[PCLUSTER_VERSION_TAG] != current_version:
self._add_failure(
(
f"The custom AMI was created with pcluster {tags_dict[PCLUSTER_VERSION_TAG]}, "
f"but is trying to be used with pcluster {current_version}. "
f"Please either use an AMI created with {current_version} or"
f" change your ParallelCluster to {tags_dict[PCLUSTER_VERSION_TAG]}"
),
FailureLevel.ERROR,
)
elif PCLUSTER_IMAGE_BUILD_STATUS_TAG not in tags_dict:
self._add_failure(
(
"Unable to retrieve custom AMI build status. "
"Please check build-image CloudFormation stack for details."
),
FailureLevel.ERROR,
)
class ComputeResourceSizeValidator(Validator):
"""
Slurm compute resource size validator.
Validate min count and max count combinations.
"""
def _validate(self, min_count: int, max_count: int, capacity_type: CapacityType):
if max_count < min_count:
self._add_failure("Max count must be greater than or equal to min count.", FailureLevel.ERROR)
if capacity_type == CapacityType.CAPACITY_BLOCK:
if max_count != min_count:
self._add_failure(
"Max count must be set to the same value of min count when using Capacity Block reservation.",
FailureLevel.ERROR,
)
if min_count == 0:
self._add_failure(
"Min count must be a value > 0 when using Capacity Block reservation.", FailureLevel.ERROR
)
class EfaOsArchitectureValidator(Validator):
"""OS and architecture combination validator if EFA is enabled."""
def _validate(self, efa_enabled: bool, os: str, architecture: str):
if efa_enabled and os in EFA_UNSUPPORTED_ARCHITECTURES_OSES.get(architecture):
self._add_failure(
f"EFA is currently not supported on {os} for {architecture} architecture.", FailureLevel.ERROR
)
class SchedulableMemoryValidator(Validator):
"""Validate SchedulableMemory parameter passed by user."""
def _validate(self, schedulable_memory, ec2memory, instance_type):
if schedulable_memory is not None:
if schedulable_memory < 1:
self._add_failure("SchedulableMemory must be at least 1 MiB.", FailureLevel.ERROR)
if ec2memory is None:
self._add_failure(
f"SchedulableMemory was set but EC2 memory is not available for selected instance type "
f"{instance_type}. Defaulting to 1 MiB.",
FailureLevel.WARNING,
)
else:
if schedulable_memory > ec2memory:
self._add_failure(
f"SchedulableMemory cannot be larger than EC2 Memory for selected instance type "
f"{instance_type} ({ec2memory} MiB).",
FailureLevel.ERROR,
)
if schedulable_memory < math.floor(0.95 * ec2memory):
self._add_failure(
f"SchedulableMemory was set lower than 95% of EC2 Memory for selected instance type "
f"{instance_type} ({ec2memory} MiB).",
FailureLevel.INFO,
)
class ArchitectureOsValidator(Validator):
"""
Validate OS and architecture combination.
ARM AMIs are only available for a subset of the supported OSes.
"""
def _validate(self, os: str, architecture: str):
allowed_oses = get_supported_os_for_architecture(architecture)
if os not in allowed_oses:
self._add_failure(
f"The architecture {architecture} is only supported "
f"for the following operating systems: {allowed_oses}.",
FailureLevel.ERROR,
)
class InstanceArchitectureCompatibilityValidator(Validator):
"""
Validate instance type and architecture combination.
Verify that head node and compute instance types imply compatible architectures.
"""
def _validate(self, instance_type_info_list: List[InstanceTypeInfo], architecture: str):
head_node_architecture = architecture
for instance_type_info in instance_type_info_list:
compute_architectures = instance_type_info.supported_architecture()
if head_node_architecture not in instance_type_info.supported_architecture():
self._add_failure(
"The specified compute instance type ({0}) supports the architectures {1}, none of which are "
"compatible with the architecture supported by the head node instance type ({2}).".format(
instance_type_info.instance_type(), compute_architectures, head_node_architecture
),
FailureLevel.ERROR,
)
class NameValidator(Validator):
"""Validate queue name length and format."""
def _validate(self, name):
match = re.match(NAME_REGEX, name)
if not match:
self._add_failure(
(
f"Invalid name '{name}'. "
"Name must begin with a letter and only contain lowercase letters, digits and hyphens."
),
FailureLevel.ERROR,
)
if len(name) > NAME_MAX_LENGTH:
self._add_failure(
f"Invalid name '{name}'. Name can be at most {NAME_MAX_LENGTH} chars long.", FailureLevel.ERROR
)
if re.match("^default$", name):
self._add_failure(f"It is forbidden to use '{name}' as a name.", FailureLevel.ERROR)
class MaxCountValidator(Validator):
"""Validate whether the number of resource exceeds the limits."""
def _validate(self, resources_length, max_length, resource_name):
if resources_length > max_length:
self._add_failure(
"Invalid number of {resource_name} ({resources_length}) specified. Currently only supports "
"up to {max_length} {resource_name}.".format(
resource_name=resource_name, resources_length=resources_length, max_length=max_length
),
FailureLevel.ERROR,
)
# --------------- EFA validators --------------- #
class EfaValidator(Validator):
"""Check if EFA and EFA GDR are supported features in the given instance type."""
def _validate(self, instance_type, efa_enabled, gdr_support, multiaz_enabled):
instance_type_supports_efa = AWSApi.instance().ec2.get_instance_type_info(instance_type).is_efa_supported()
if efa_enabled and not instance_type_supports_efa:
self._add_failure(f"Instance type '{instance_type}' does not support EFA.", FailureLevel.ERROR)
if instance_type_supports_efa and not efa_enabled and not multiaz_enabled:
self._add_failure(
f"The EC2 instance selected ({instance_type}) supports enhanced networking capabilities using "
"Elastic Fabric Adapter (EFA). EFA enables you to run applications requiring high levels of "
"inter-node communications at scale on AWS at no additional charge. You can update the cluster's "
"configuration to enable EFA (https://docs.aws.amazon.com/parallelcluster/latest/ug/efa-v3.html)",
FailureLevel.WARNING,
)
if gdr_support and not efa_enabled:
self._add_failure("The EFA GDR Support can be used only if EFA is enabled.", FailureLevel.ERROR)
class EfaPlacementGroupValidator(Validator):
"""Validate placement group if EFA is enabled."""
def _validate(
self,
efa_enabled: bool,
placement_group_key: str,
placement_group_disabled: bool,
multi_az_enabled: bool,
capacity_type: str,
queue_name: str,
):
# Capacity Blocks do not require the configuration of a Placement Group
if capacity_type == CapacityType.CAPACITY_BLOCK:
return
# if multi_az is enabled suggestions about PlacementGroups will be suppressed
if efa_enabled and placement_group_disabled and not multi_az_enabled:
self._add_failure(
f"Placement group is disabled for queue '{queue_name}'. "
"This is expected when using a capacity reservation with its own placement group. "
"Otherwise, enabling a placement group may improve network performance.",
FailureLevel.WARNING,
)
elif efa_enabled and placement_group_key is None and not multi_az_enabled:
self._add_failure(
f"The placement group for EFA-enabled compute resources in queue '{queue_name}' must be explicit. "
"You may see better performance using a placement group, but if you don't wish to use one or "
"the compute resources in the queue use a capacity reservation with its own placement group, "
"please add 'Enabled: false' to the compute resource's configuration section.",
FailureLevel.ERROR,
)
class EfaSecurityGroupValidator(Validator):
"""Validate Security Group if EFA is enabled."""
def _validate(self, efa_enabled, security_groups, additional_security_groups):
if efa_enabled and security_groups:
# Check security groups associated to the EFA
efa_sg_found = self._check_in_out_rules(security_groups)
if additional_security_groups:
efa_sg_found = efa_sg_found or self._check_in_out_rules(additional_security_groups)
if not efa_sg_found:
self._add_failure(
"An EFA requires a security group that allows all inbound and outbound traffic "
"to and from the security group itself. See "
"https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security",
FailureLevel.ERROR,
)
def _check_in_out_rules(self, security_groups):
efa_sg_found = False
for security_group in security_groups:
try:
sec_group = AWSApi.instance().ec2.describe_security_group(security_group)
# check inbound rules
allowed_in = self._all_traffic_allowed(security_group, sec_group.get("IpPermissions"))
# check outbound rules
allowed_out = self._all_traffic_allowed(security_group, sec_group.get("IpPermissionsEgress"))
if allowed_in and allowed_out:
efa_sg_found = True
break
except AWSClientError as e:
self._add_failure(str(e), FailureLevel.WARNING)
return efa_sg_found
def _all_traffic_allowed(self, security_group_id, security_group_permission):
for rule in security_group_permission:
if rule.get("IpProtocol") == "-1" and rule.get("UserIdGroupPairs"):
for group in rule.get("UserIdGroupPairs"):
if group.get("GroupId") == security_group_id:
return True
return False
class EfaMultiAzValidator(Validator):
"""Validate MultiAZ if EFA is enabled."""
def _validate(
self, queue_name: str, multi_az_enabled: bool, compute_resource_name: str, compute_resource_efa_enabled: bool
):
if multi_az_enabled and compute_resource_efa_enabled:
message = (
f"You have enabled the Elastic Fabric Adapter (EFA) for the '{compute_resource_name}' Compute Resource"
f" on the '{queue_name}' queue. EFA is not supported across Availability zones. Either disable EFA "
"to use multiple subnets on the queue or specify only one subnet to enable EFA on "
"the compute resources."
)
self._add_failure(
message,
FailureLevel.ERROR,
)
# --------------- Storage validators --------------- #
def _is_access_allowed(
security_groups_ids, subnets, port, security_groups_by_nodes, protocol="tcp", check_outbound=True
):
"""
Verify given list of security groups to check if they allow in and out access on the given port.
:param security_groups_ids: list of security groups to verify
:param port: port to verify
:param security_groups_by_nodes: all security groups from cluster. This is a set of frozen sets.
Each frozen set contains sg combination of a queue.
:param protocol: the IP protocol to be checked.
:return: True if both in and out access are allowed
:raise: ClientError if a given security group doesn't exist
"""
in_access = False
out_access = False
src_ip_ranges = []
dst_ip_ranges = []
src_security_groups = set()
dst_security_groups = set()
for sec_group in AWSApi.instance().ec2.describe_security_groups(security_groups_ids):
# Check all inbound rules
for rule in sec_group.get("IpPermissions"):
if in_access:
break
if _is_port_allowed_by_sg_rule(rule, port, protocol):
in_access = _populate_allowed_src_or_dst(rule, src_ip_ranges, src_security_groups)
# Check all outbound rules
for rule in sec_group.get("IpPermissionsEgress"):
if out_access:
break
if _is_port_allowed_by_sg_rule(rule, port, protocol):
out_access = _populate_allowed_src_or_dst(rule, dst_ip_ranges, dst_security_groups)
if in_access and out_access:
return True
# If in_access or out_access is still False, check allowed ip ranges and security groups.
# The in_access or out_access could only have been true, if previous logics had found prefix list in SG rules.
# Rules of ip ranges have to be checked at the end because the union of all ip ranges may cover the subnets,
# even when individual ip ranges do not cover the subnets. The same reason applies to allowed security groups.
in_access = in_access or _are_ip_ranges_and_sg_accessible(
security_groups_by_nodes, src_ip_ranges, src_security_groups, subnets
)
out_access = out_access or _are_ip_ranges_and_sg_accessible(
security_groups_by_nodes, dst_ip_ranges, dst_security_groups, subnets
)
if check_outbound:
return in_access and out_access
return in_access
def _are_ip_ranges_and_sg_accessible(security_groups_by_nodes, allowed_ip_ranges, allowed_security_groups, subnets):
# For all cluster nodes, at least one of the security groups attached need to be in the UserIdGroupPairs.
return all(
node_security_groups & allowed_security_groups for node_security_groups in security_groups_by_nodes
) or _are_subnets_covered_by_cidrs(allowed_ip_ranges, subnets)
def _populate_allowed_src_or_dst(rule, ip_ranges, allowed_security_groups):
"""
Collect Ip ranges or security groups allowed by the rule.
:param rule: A rule of a security group
:param ip_ranges: A list of ip ranges.
:param allowed_security_groups: A list of allowed security group.
:return: True if we can determine the current rule allows connection.
False if it does not allow connection or cannot be determined.
"""
if rule.get("PrefixListIds"):
return True # Always assume prefix list is properly set for code simplicity
if rule.get("IpRanges"):
ip_ranges.extend(rule.get("IpRanges"))
# Ip Ranges have to be checked later. Return False because the rule allowance is not determined.
if rule.get("Ipv4Ranges"):
# Currently the describe_security_groups API response syntax contains "IpRanges".
# This check is added for future compatibility if API changes to use "Ipv4Ranges"
ip_ranges.extend(rule.get("Ipv4Ranges"))
if rule.get("UserIdGroupPairs"):
allowed_security_groups.update(
{user_id_group_pair.get("GroupId") for user_id_group_pair in rule.get("UserIdGroupPairs")}
)
# Security groups have to be checked later. Return False because the rule allowance is not determined.
return False
def _is_port_allowed_by_sg_rule(rule, port_to_check, protocol):
"""
Verify if the security group rule accepts connections on the given port.
:param rule: The rule to check
:param port_to_check: The port to check
:param protocol: the IP protocol to be checked.
:return: True if the rule accepts connection, False otherwise
"""
from_port = rule.get("FromPort")
to_port = rule.get("ToPort")
ip_protocol = rule.get("IpProtocol")
# if ip_protocol is -1, all ports are allowed
if ip_protocol == "-1":
return True
# Add protocol number in addition to the protocol name
if protocol == "tcp":
expected_protocol = [protocol, "6"]
elif protocol == "udp":
expected_protocol = [protocol, "17"]
else:
# ToDo: When adding new checks for other protocols, change the code to include the protocol number too.
expected_protocol = [protocol]
if (ip_protocol in expected_protocol) and (from_port <= port_to_check <= to_port):
return True
return False
def _are_subnets_covered_by_cidrs(ip_ranges, subnets):
"""Verify given list of security groups to check if they allow in and out access on cluster subnet CIDRs."""
# Collapse ip ranges for better performance and correctness
collapsed_ip_ranges = list(collapse_addresses([ip_network(ip_range["CidrIp"]) for ip_range in ip_ranges]))
for subnet in subnets:
subnet_cidr = ip_network(AWSApi.instance().ec2.get_subnet_cidr(subnet))
covered = False
for ip_range in collapsed_ip_ranges:
if ip_range.supernet_of(subnet_cidr):
covered = True
break
if not covered:
return False
return True
class ExistingFsxNetworkingValidator(Validator):
"""
FSx networking validator.
Validate file system mount point according to the head node subnet.
The reason to have this structure is to make boto3 calls as few as possible.
"""
def _describe_network_interfaces(self, file_systems):
all_network_interfaces = []
for file_system in file_systems:
all_network_interfaces.extend(file_system.network_interface_ids)
if all_network_interfaces:
response = AWSApi.instance().ec2.describe_network_interfaces(all_network_interfaces)
network_interfaces_data = {}
for network_interface in response:
network_interfaces_data[network_interface["NetworkInterfaceId"]] = network_interface
return network_interfaces_data
else:
return {}
def _validate(self, file_storage_ids, subnet_ids, security_groups_by_nodes):
try:
file_cache_ids = [file_cache_id for file_cache_id in file_storage_ids if file_cache_id.startswith("fc-")]
if file_cache_ids:
file_storage_ids = [id for id in file_storage_ids if id not in file_cache_ids]
file_caches = AWSApi.instance().fsx.describe_file_caches(file_cache_ids)
self._check_file_storage(security_groups_by_nodes, file_caches, subnet_ids)
file_systems = AWSApi.instance().fsx.get_file_systems_info(file_storage_ids)
self._check_file_storage(security_groups_by_nodes, file_systems, subnet_ids)
except AWSClientError as e:
self._add_failure(str(e), FailureLevel.ERROR)
def _check_file_storage(self, security_groups_by_nodes, file_storages, subnet_ids):
vpc_id = AWSApi.instance().ec2.get_subnet_vpc(subnet_ids[0])
network_interfaces_data = self._describe_network_interfaces(file_storages)
for file_storage in file_storages:
# Check to see if fs is in the same VPC as the stack
file_storage_id = file_storage.file_system_id if file_storage.file_system_id else file_storage.file_cache_id
if file_storage.vpc_id != vpc_id:
self._add_failure(
"Currently only support using FSx file storage that is in the same VPC as the cluster. "
f"The file system {file_storage_id} is in {file_storage.vpc_id}.",
FailureLevel.ERROR,
)
# If there is an existing mt in the az, check the inbound and outbound rules of the security groups
network_interface_ids = file_storage.network_interface_ids
if not network_interface_ids:
self._add_failure(
f"Unable to validate FSx security groups. The given FSx file storage '{file_storage_id}'"
" doesn't have Elastic Network Interfaces attached to it.",
FailureLevel.ERROR,
)
else:
network_interface_responses = []
for network_interface_id in network_interface_ids:
network_interface_responses.append(network_interfaces_data[network_interface_id])
network_interfaces = [ni for ni in network_interface_responses if ni.get("VpcId") == vpc_id]
for protocol, ports in FSX_PORTS[file_storage.file_storage_type].items():
missing_ports = self._get_missing_ports(
security_groups_by_nodes,
subnet_ids,
network_interfaces,
ports,
protocol,
file_storage.file_storage_type,
)
if missing_ports:
direction = "inbound and outbound"
if file_storage.file_storage_type == "OPENZFS":
direction = "inbound"
self._add_failure(
f"The current security group settings on file storage '{file_storage_id}' does not"
" satisfy mounting requirement. The file storage must be associated to a security group"
f" that allows {direction} {protocol.upper()} traffic through ports {ports}. "
f"Missing ports: {missing_ports}",
FailureLevel.ERROR,
)
def _get_missing_ports(
self, security_groups_by_nodes, subnet_ids, network_interfaces, ports, protocol, storage_type
):
missing_ports = []
for port in ports:
fs_access = False
for network_interface in network_interfaces:
# Get list of security group IDs
sg_ids = [sg.get("GroupId") for sg in network_interface.get("Groups")]
check_outbound = True
if storage_type == "OPENZFS":
check_outbound = False
if _is_access_allowed(
sg_ids,
subnet_ids,
port=port,
security_groups_by_nodes=security_groups_by_nodes,
protocol=protocol,
check_outbound=check_outbound,
):
fs_access = True
break
if not fs_access:
missing_ports.append(port)
return missing_ports
class FsxArchitectureOsValidator(Validator):
"""
FSx architecture and OS validator.
Validate that OS and architecture are compatible with FSx.
"""
def _validate(self, architecture: str, os):
if architecture not in FSX_SUPPORTED_ARCHITECTURES_OSES:
self._add_failure(
FSX_MESSAGES["errors"]["unsupported_architecture"].format(
supported_architectures=list(FSX_SUPPORTED_ARCHITECTURES_OSES.keys())
),
FailureLevel.ERROR,
)
elif os not in FSX_SUPPORTED_ARCHITECTURES_OSES.get(architecture):
self._add_failure(
FSX_MESSAGES["errors"]["unsupported_os"].format(
architecture=architecture, supported_oses=FSX_SUPPORTED_ARCHITECTURES_OSES.get(architecture)
),
FailureLevel.ERROR,
)
def _find_duplicate_params(param_list):
param_set = set()
duplicated_params = []
if param_list:
for param in param_list:
if param in param_set:
duplicated_params.append(param)
else:
param_set.add(param)
return duplicated_params
def _find_overlapping_paths(shared_paths_list, local_paths_list):
overlapping_paths = []
if shared_paths_list:
for path1, path2 in list(combinations(shared_paths_list, 2)) + list(
product(shared_paths_list, local_paths_list)
): # Check all pairs in shared paths list and all pairs between shared paths list and local paths list
is_overlapping = path1.startswith(path2 + "/") or path2.startswith(path1 + "/")
if is_overlapping:
overlapping_paths.extend([path1, path2])
return overlapping_paths
class DuplicateMountDirValidator(Validator):
"""
Mount dir validator.
Verify if there are duplicated mount dirs between shared storage and ephemeral volumes.
"""
def _validate(self, shared_storage_name_mount_dir_tuple_list, local_mount_dir_instance_types_dict):
mount_dir_to_names = defaultdict(list)
for shared_storage_name, shared_mount_dir in shared_storage_name_mount_dir_tuple_list:
mount_dir_to_names[shared_mount_dir].append(shared_storage_name)
for mount_dir, names in mount_dir_to_names.items():
if len(names) > 1:
self._add_failure(
f"The mount directory `{mount_dir}` is used for multiple shared storage: {names}. "
"Shared storage mount directories should be unique. "
"Please change the mount directory configuration of the shared storage.",
FailureLevel.ERROR,
)
for local_mount_dir, instance_types in local_mount_dir_instance_types_dict.items():
shared_storage_names = mount_dir_to_names.get(local_mount_dir)
if shared_storage_names:
self._add_failure(
f"The mount directory `{local_mount_dir}` used for shared storage {shared_storage_names} "
f"clashes with the one used for ephemeral volumes of the instances {list(instance_types)}. "
f"Please change the mount directory configuration of either the shared storage or the ephemeral "
f"volume of the impacted nodes.",
FailureLevel.WARNING,
)
class OverlappingMountDirValidator(Validator):
"""
Mount dir validator.
Verify if there are overlap mount dirs.
1. Shared storage directories can not overlap with each other.
2. Shared storage directories can not overlap with ephemeral storage directories.
3. Ephemeral storage directories can overlap with each other, because they are local to compute nodes.
Two mount dirs are overlapped if one is contained into the other.
"""
def _validate(self, shared_mount_dir_list, local_mount_dir_list):
overlapping_mount_dirs = _find_overlapping_paths(shared_mount_dir_list, local_mount_dir_list)
if overlapping_mount_dirs:
self._add_failure(
"Mount directories {0} cannot overlap".format(
", ".join(mount_dir for mount_dir in overlapping_mount_dirs),
),
FailureLevel.ERROR,
)
class NumberOfStorageValidator(Validator):
"""
Number of storage validator.
Validate the number of storage specified is lower than maximum supported.
"""
def _validate(self, storage_type: str, max_number: int, storage_count: int):
if storage_count > max_number:
self._add_failure(
f"Too many {storage_type} shared storage specified in the configuration. "
f"ParallelCluster supports {max_number} {storage_type}.",
FailureLevel.ERROR,
)
class ManagedFsxMultiAzValidator(Validator):
"""
Managed FSx Storage Vs Multiple Subnets validator.
Validate if managed storage of type FSx is set when using multiple subnets in queues configuration.
"""
def _validate(self, compute_subnet_ids, new_storage_count):
if len(compute_subnet_ids) > 1 and new_storage_count.get("fsx") > 0:
self._add_failure(
"Managed FSx storage created by ParallelCluster is not supported when specifying multiple subnet Ids "
"under the SubnetIds configuration of a queue. Please make sure to provide an existing FSx shared "
"storage, properly configured to work across the target subnets or remove the managed FSx storage to "
"use multiple subnets for a queue.",
FailureLevel.ERROR,
)
class UnmanagedFsxMultiAzValidator(Validator):
"""
Unmanaged FSx Storage Vs Multiple Subnets validator.
Unmanaged FSx volumes can exist in AZ that are different from the ones defined in queues configuration.
In these cases we notify customers that they may incur in increased latency and costs.
"""
def _validate(self, queues, fsx_az_list):
for queue in queues:
queue_az_set = set(queue.networking.az_list)
fs_az_set = set(fsx_az_list)
# we want to ensure that all the az defined in the queue are supported by the FS
if not queue_az_set.issubset(fs_az_set):
self._add_failure(
"Your configuration for Queue '{0}' includes multiple subnets and external shared storage "
"configuration. Accessing a shared storage from different AZs can lead to increased storage "
"networking latency and added inter-AZ data transfer costs.".format(queue.name),
FailureLevel.INFO,
)
class EfsIdValidator(Validator): # TODO add tests
"""
EFS id validator.
Validate if there are existing mount target in the cluster (head and computes) availability zone
"""
def _validate(self, efs_id, avail_zones_mapping: dict, security_groups_by_nodes):
availability_zones = avail_zones_mapping.keys()
if len(availability_zones) > 1 and not AWSApi.instance().efs.is_efs_standard(efs_id):
self._add_failure(
f"Cluster has subnets located in different availability zones but EFS ({efs_id}) uses OneZone EFS "
"storage class which works within a single Availability Zone. Please use subnets located in one "
"Availability Zone or use a standard storage class EFS.",
FailureLevel.ERROR,
)
avail_zones_missing_mount_target_for_efs_standard = []
for avail_zone, subnets in avail_zones_mapping.items():
head_node_target_id = AWSApi.instance().efs.get_efs_mount_target_id(efs_id, avail_zone)
# If there is an existing mt in the az, need to check the inbound and outbound rules of the security groups
if head_node_target_id:
# Get list of security group IDs of the mount target
sg_ids = AWSApi.instance().efs.get_efs_mount_target_security_groups(head_node_target_id)
if not _is_access_allowed(
sg_ids, subnets, port=EFS_PORT, security_groups_by_nodes=security_groups_by_nodes
):
self._add_failure(
"There is an existing Mount Target {0} in the Availability Zone {1} for EFS {2}, "
"but it does not have a security group that allows inbound and outbound rules to support NFS. "
"Please modify the Mount Target's security group, to allow traffic on port 2049.".format(
head_node_target_id, avail_zone, efs_id
),
FailureLevel.ERROR,
)
else:
if AWSApi.instance().efs.is_efs_standard(efs_id):
avail_zones_missing_mount_target_for_efs_standard.append(avail_zone)
if avail_zones_missing_mount_target_for_efs_standard:
self._add_failure(
"There is no existing Mount Target for EFS '{0}' in these Availability Zones: '{1}'. "
"Please create an EFS Mount Target for those availability zones.".format(
efs_id, avail_zones_missing_mount_target_for_efs_standard
),
FailureLevel.ERROR,
)
class SharedStorageNameValidator(Validator):
"""
Shared storage name validator.
Validate if the provided name for the shared storage complies with the acceptable pattern.
Since the storage name is used as a tag, the provided name must comply with the tag pattern.
"""
def _validate(self, name: str):
if not re.match(PCLUSTER_TAG_VALUE_REGEX, name):
self._add_failure(
(
f"Error: The shared storage name {name} is not valid. "
"Allowed characters are letters, numbers and white spaces that can be represented in UTF-8 "
"and the following characters: '+' '-' '=' '.' '_' ':' '/', "
f"and it can't be longer than 256 characters."
),
FailureLevel.ERROR,
)
if len(name) > SHARED_STORAGE_NAME_MAX_LENGTH:
self._add_failure(
f"Invalid name '{name}'. Name can be at most {SHARED_STORAGE_NAME_MAX_LENGTH} chars long.",
FailureLevel.ERROR,
)
if re.match("^default$", name):
self._add_failure(f"It is forbidden to use '{name}' as a name.", FailureLevel.ERROR)
class SharedStorageMountDirValidator(Validator):
"""
Shared storage mount directory validator.
Make sure the mount directory is not the same as any reserved directory.
"""
def _validate(self, mount_dir: str):
reserved_directories = [
"/bin",
"/boot",
"/dev",
"/etc",
"/lib",
"/lib64",
"/media",
"/mnt",
"/opt",
"/opt/parallelcluster",
"/opt/parallelcluster/shared",
"/opt/parallelcluster/shared_login_nodes",
"/opt/slurm",
"/opt/intel",
"/proc",
"/root",
"/run",
"/sbin",
"/srv",
"/sys",
# A nosec comment is appended to the following line in order to disable the B108 check.
# It is a false positive since is a list to check folder name
# [B108:hardcoded_tmp_directory] Probable insecure usage of temp file/directory.
"/tmp", # nosec B108
"/usr",
"/var",
]
if not mount_dir.startswith("/"):
mount_dir = "/" + mount_dir
if mount_dir in reserved_directories:
self._add_failure(
f"Error: The shared storage mount directory {mount_dir} is reserved. Please use another directory",
FailureLevel.ERROR,
)
class SharedFileCacheNotHomeValidator(Validator):
"""
Shared FileCache Not Home Validator.
Validate if the provided name for the shared storage is not /home for FileCache
"""
def _validate(self, mount_dir: str):
if mount_dir in ("/home", "home"):
self._add_failure(
(
f"Error: FileCache cannot be used to mount the shared storage directory '{mount_dir}'. Please "
f"select a supported filesystem."
),
FailureLevel.ERROR,
)
class DeletionPolicyValidator(Validator):
"""Print warning message when deletion policy is set to Delete or Retain."""
def _validate(self, deletion_policy: str, name: str):
if deletion_policy == DELETE_POLICY:
self._add_failure(
f"The DeletionPolicy is set to {DELETE_POLICY}. The storage '{name}' will be deleted when you remove "
"it from the configuration when performing a cluster update or deleting the cluster.",
FailureLevel.INFO,
)
elif deletion_policy == RETAIN_POLICY:
self._add_failure(
f"The DeletionPolicy is set to {RETAIN_POLICY}. The storage '{name}' will be retained when you remove "
"it from the configuration when performing a cluster update or deleting the cluster.",
FailureLevel.INFO,