-
Notifications
You must be signed in to change notification settings - Fork 1
/
install-hopsworks.py
1440 lines (1251 loc) · 64 KB
/
install-hopsworks.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
# This file is part of Hopsworks
# Copyright (C) 2024, Hopsworks AB. All rights reserved
#
# Hopsworks is free software: you can redistribute it and/or modify it under the terms of
# the GNU Affero General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# Hopsworks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
import subprocess
import time
import sys
import os
import uuid
import shutil
import argparse
from datetime import datetime
import urllib.request
import urllib.error
import ssl
import threading
import boto3
import json
import tempfile
import yaml
HOPSWORKS_LOGO = """
██╗ ██╗ ██████╗ ██████╗ ███████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗ ███████╗
██║ ██║ ██╔═══██╗ ██╔══██╗ ██╔════╝ ██║ ██║ ██╔═══██╗ ██╔══██╗ ██║ ██╔╝ ██╔════╝
███████║ ██║ ██║ ██████╔╝ ███████╗ ██║ █╗ ██║ ██║ ██║ ██████╔╝ █████╔╝ ███████╗
██╔══██║ ██║ ██║ ██╔═══╝ ╚════██║ ██║███╗██║ ██║ ██║ ██╔══██╗ ██╔═██╗ ╚════██║
██║ ██║ ╚██████╔╝ ██║ ███████║ ╚███╔███╔╝ ╚██████╔╝ ██║ ██║ ██║ ██╗ ███████║
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝
"""
SERVER_URL = "https://magiclex--hopsworks-installation-hopsworks-installation.modal.run/"
STARTUP_LICENSE_URL = "https://www.hopsworks.ai/startup-license"
EVALUATION_LICENSE_URL = "https://www.hopsworks.ai/evaluation-license"
KNOWN_NONFATAL_ERRORS = [
"invalid ingress class: IngressClass.networking.k8s.io",
]
""" All the helm stuff here ⬇ """
HELM_BASE_CONFIG = {
"hopsworks.service.worker.external.https.type": "LoadBalancer",
"global._hopsworks.externalLoadBalancers.enabled": "true",
"global._hopsworks.imagePullPolicy": "Always",
"hopsworks.replicaCount.worker": "1",
"rondb.clusterSize.activeDataReplicas": "1",
"hopsfs.datanode.count": "2"
}
CLOUD_SPECIFIC_VALUES = {
"AWS": {
"global._hopsworks.cloudProvider": "AWS",
"global._hopsworks.ingressController.type": "none",
"global._hopsworks.managedDockerRegistery.enabled": "true",
"global._hopsworks.managedDockerRegistery.credHelper.enabled": "true",
"global._hopsworks.managedDockerRegistery.credHelper.secretName": "awsregcred",
"global._hopsworks.storageClassName": "ebs-gp3",
"hopsworks.variables.docker_operations_managed_docker_secrets": "awsregcred",
"hopsworks.variables.docker_operations_image_pull_secrets": "awsregcred",
"hopsworks.dockerRegistry.preset.secrets[0]": "awsregcred",
"externalLoadBalancers": {
"enabled": True,
"class": None,
"annotations": {
"service.beta.kubernetes.io/aws-load-balancer-scheme": "internet-facing"
}
}
},
"GCP": {
"global._hopsworks.cloudProvider": "GCP",
"global._hopsworks.managedDockerRegistery.enabled": "true",
"global._hopsworks.managedDockerRegistery.credHelper.enabled": "true",
"global._hopsworks.managedDockerRegistery.credHelper.configMap": "docker-config",
"global._hopsworks.managedDockerRegistery.credHelper.secretName": "gcrregcred",
"hopsworks.variables.docker_operations_managed_docker_secrets": "gcrregcred",
"hopsworks.variables.docker_operations_image_pull_secrets": "gcrregcred",
"hopsworks.dockerRegistry.preset.secrets[0]": "gcrregcred",
"serviceAccount.name": "hopsworks-sa"
},
"Azure": {
"global._hopsworks.cloudProvider": "AZURE",
"global._hopsworks.managedDockerRegistery.enabled": "true",
"global._hopsworks.ingressController.type": "none",
"global._hopsworks.imagePullSecretName": "regcred",
"global._hopsworks.minio.enabled": "true",
"serviceAccount.name": "hopsworks-sa",
"serviceAccount.create": "false",
"hopsworks.service.worker.external.https.type": "LoadBalancer",
"hopsworks.service.worker.external.https.annotations.service\\.beta\\.kubernetes\\.io/azure-load-balancer-internal": "false"
},
"OVH": {
"global._hopsworks.cloudProvider": "OVH"
}
}
# Utilities
def print_colored(message, color, **kwargs):
colors = {
"red": "\033[91m", "green": "\033[92m", "yellow": "\033[93m",
"blue": "\033[94m", "magenta": "\033[95m", "cyan": "\033[96m",
"white": "\033[97m", "reset": "\033[0m"
}
print(f"{colors.get(color, '')}{message}{colors['reset']}", **kwargs)
def run_command(command, verbose=True):
if verbose:
print_colored(f"Running: {command}", "cyan")
try:
result = subprocess.run(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if verbose:
if result.stdout:
print(result.stdout)
if result.stderr:
print_colored(result.stderr, "yellow")
return result.returncode == 0, result.stdout, result.stderr
except Exception as e:
return False, "", str(e)
def get_user_input(prompt, options=None):
while True:
response = input(prompt + " ").strip()
if options is None or response.lower() in [option.lower() for option in options]:
return response
print_colored(f"Invalid input. Expected one of: {', '.join(options)}", "yellow")
# Main installer
class HopsworksInstaller:
def __init__(self):
# Common attributes
self.environment = None
self.kubeconfig_path = None
self.cluster_name = None
self.region = None
self.zone = None
self.namespace = 'hopsworks'
self.installation_id = None
self.args = None
# GCP specific
self.project_id = None
self.sa_email = None
self.role_name = None
# Registry handling
self.use_managed_registry = False
self.managed_registry_info = None
# AWS specific
self.aws_profile = None
self.aws_account_id = None
self.policy_name = None
# Azure specific (if we need it later)
self.resource_group = None
def run(self):
print_colored(HOPSWORKS_LOGO, "white")
self.parse_arguments()
self.check_required_tools()
self.get_deployment_environment()
if not self.args.loadbalancer_only:
if self.environment == "GCP":
self.setup_gke_prerequisites()
elif self.environment == "AWS":
self.setup_aws_prerequisites()
elif self.environment == "Azure":
self.setup_aks_prerequisites() # This will create the cluster
else:
self.setup_and_verify_kubeconfig() # Only for other environments
self.handle_managed_registry()
self.handle_license_and_user_data()
if self.install_hopsworks():
print_colored("\nHopsworks installation completed.", "green")
self.finalize_installation()
else:
print_colored("Hopsworks installation failed. Please check the logs and try again.", "red")
sys.exit(1)
else:
# For loadbalancer-only, we need to set up the necessary variables
self.namespace = self.args.namespace
self.setup_and_verify_kubeconfig()
self.finalize_installation()
def construct_helm_command(self):
"""Constructs the helm command with proper configuration"""
# Base helm command
helm_command = [
"helm upgrade --install hopsworks-release hopsworks/hopsworks",
f"--namespace={self.namespace}",
"--create-namespace",
"--values hopsworks/values.yaml"
]
# Helper function to flatten nested dictionaries
def flatten_dict(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
# Start with base config
helm_values = HELM_BASE_CONFIG.copy()
# Add cloud-specific values
if self.environment in CLOUD_SPECIFIC_VALUES:
cloud_config = CLOUD_SPECIFIC_VALUES[self.environment].copy()
# Handle registry values for each cloud provider
if self.environment == "AWS" and self.managed_registry_info:
cloud_config.update({
"global._hopsworks.managedDockerRegistery.domain": self.managed_registry_info['domain'],
"global._hopsworks.managedDockerRegistery.namespace": self.managed_registry_info['namespace']
})
elif self.environment == "GCP" and self.managed_registry_info:
cloud_config.update({
"global._hopsworks.managedDockerRegistery.domain": self.managed_registry_info['domain'],
"global._hopsworks.managedDockerRegistery.namespace": self.managed_registry_info['namespace'],
"serviceAccount.annotations.iam\\.gke\\.io/gcp-service-account": self.sa_email
})
elif self.environment == "Azure" and hasattr(self, 'registry_secrets_created'):
# Azure uses regcred secret which is already configured in base cloud config
# We only need to verify the secret exists, which we track with registry_secrets_created
if not self.registry_secrets_created:
print_colored("Warning: Azure registry secrets not properly configured", "yellow")
helm_values.update(cloud_config)
# Flatten nested structures
flat_values = flatten_dict(helm_values)
# Add each value with proper escaping and formatting
for key, value in flat_values.items():
if value is None:
value = "null"
elif isinstance(value, bool):
value = str(value).lower()
elif isinstance(value, (int, float)):
value = str(value)
else:
# Escape special characters in string values
value = f'"{str(value)}"'
helm_command.append(f"--set {key}={value}")
# Add timeout and devel flag
helm_command.extend([
"--timeout 60m",
"--devel"
])
return " ".join(helm_command)
def setup_aws_prerequisites(self):
"""Setup AWS prerequisites including metrics server"""
print_colored("\nSetting up AWS prerequisites...", "blue")
# 1. Basic AWS setup and verification
self.aws_profile = input("Enter your AWS profile name (default: default): ").strip() or "default"
os.environ['AWS_PROFILE'] = self.aws_profile
# Verify AWS credentials
cmd = f"aws sts get-caller-identity --profile {self.aws_profile}"
if not run_command(cmd, verbose=False)[0]:
print_colored("AWS CLI not properly configured. Please run 'aws configure' first.", "red")
sys.exit(1)
# Get basic info
self.region = self.get_aws_region()
self.cluster_name = input("Enter your EKS cluster name: ").strip()
# Get AWS account ID
cmd = f"aws sts get-caller-identity --query Account --output text --profile {self.aws_profile}"
success, account_id, _ = run_command(cmd)
if not success:
print_colored("Failed to get AWS account ID.", "red")
sys.exit(1)
self.aws_account_id = account_id.strip()
# 2. Create S3 bucket
bucket_name = input("Enter S3 bucket name for Hopsworks data: ").strip()
cmd = f"aws s3 mb s3://{bucket_name} --region {self.region} --profile {self.aws_profile}"
if not run_command(cmd)[0]:
print_colored("Failed to create S3 bucket", "red")
sys.exit(1)
# Enable versioning on the bucket
cmd = f"aws s3api put-bucket-versioning --bucket {bucket_name} --versioning-configuration Status=Enabled --profile {self.aws_profile}"
if not run_command(cmd)[0]:
print_colored("Failed to enable bucket versioning", "red")
sys.exit(1)
# 3. Create ECR repository
print_colored("\nCreating ECR repository...", "cyan")
repo_name = f"{self.cluster_name}/hopsworks-base"
cmd = f"aws ecr create-repository --repository-name {repo_name} --profile {self.aws_profile} --region {self.region}"
if not run_command(cmd)[0]:
print_colored("Failed to create ECR repository", "red")
sys.exit(1)
# 4. Create IAM policy
print_colored("\nCreating IAM policies...", "cyan")
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "HopsworksS3Access",
"Effect": "Allow",
"Action": [
"S3:PutObject", "S3:ListBucket", "S3:GetObject", "S3:DeleteObject",
"S3:AbortMultipartUpload", "S3:ListBucketMultipartUploads",
"S3:PutLifecycleConfiguration", "S3:GetLifecycleConfiguration",
"S3:PutBucketVersioning", "S3:GetBucketVersioning",
"S3:ListBucketVersions", "S3:DeleteObjectVersion"
],
"Resource": [
f"arn:aws:s3:::{bucket_name}/*",
f"arn:aws:s3:::{bucket_name}"
]
},
{
"Sid": "HopsworksECRAccess",
"Effect": "Allow",
"Action": [
"ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage",
"ecr:CompleteLayerUpload", "ecr:UploadLayerPart",
"ecr:InitiateLayerUpload", "ecr:BatchCheckLayerAvailability",
"ecr:PutImage", "ecr:ListImages", "ecr:BatchDeleteImage",
"ecr:GetLifecyclePolicy", "ecr:PutLifecyclePolicy",
"ecr:TagResource"
],
"Resource": [f"arn:aws:ecr:{self.region}:{self.aws_account_id}:repository/*/hopsworks-base"]
},
{
"Sid": "HopsworksECRAuthToken",
"Effect": "Allow",
"Action": ["ecr:GetAuthorizationToken"],
"Resource": "*"
},
{
"Sid": "LoadBalancerAccess",
"Effect": "Allow",
"Action": [
"elasticloadbalancing:*", "ec2:CreateTags", "ec2:DeleteTags",
"ec2:DescribeAccountAttributes", "ec2:DescribeAddresses",
"ec2:DescribeInstances", "ec2:DescribeInternetGateways",
"ec2:DescribeNetworkInterfaces", "ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets", "ec2:DescribeTags", "ec2:DescribeVpcs",
"ec2:ModifyNetworkInterfaceAttribute",
"ec2:DescribeInstanceTypes", # Added for RSS management
"ec2:DescribeInstanceTypeOfferings", # Added for RSS management
"iam:CreateServiceLinkedRole", "iam:ListServerCertificates",
"cognito-idp:DescribeUserPoolClient",
"acm:ListCertificates", "acm:DescribeCertificate",
"waf-regional:*", "wafv2:*", "shield:*"
],
"Resource": "*"
}
]
}
timestamp = int(time.time())
with open(f'policy-{timestamp}.json', 'w') as f:
json.dump(policy, f, indent=2)
self.policy_name = f"hopsworks-policy-{timestamp}"
cmd = f"aws iam create-policy --policy-name {self.policy_name} --policy-document file://policy-{timestamp}.json --profile {self.aws_profile}"
if not run_command(cmd)[0]:
print_colored("Failed to create IAM policy", "red")
sys.exit(1)
print_colored("Waiting for policy to propagate...", "yellow")
time.sleep(10)
# 5. Create EKS cluster configuration
print_colored("\nCreating EKS cluster configuration...", "cyan")
instance_type = input("Enter instance type (default: m6i.2xlarge): ").strip() or "m6i.2xlarge"
node_count = input("Enter number of nodes (default: 4): ").strip() or "4"
cluster_config = {
"apiVersion": "eksctl.io/v1alpha5",
"kind": "ClusterConfig",
"metadata": {
"name": self.cluster_name,
"region": self.region,
"version": "1.29"
},
"iam": {
"withOIDC": True,
},
"addons": [{
"name": "aws-ebs-csi-driver",
"wellKnownPolicies": {
"ebsCSIController": True
}
}],
"managedNodeGroups": [{
"name": "ng-1",
"amiFamily": "AmazonLinux2023",
"instanceType": instance_type,
"minSize": int(node_count),
"maxSize": int(node_count),
"volumeSize": 100,
"ssh": {
"allow": True
},
"iam": {
"attachPolicyARNs": [
"arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy",
"arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy",
"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
f"arn:aws:iam::{self.aws_account_id}:policy/{self.policy_name}"
],
"withAddonPolicies": {
"awsLoadBalancerController": True
}
}
}]
}
with open(f'eksctl-{timestamp}.yaml', 'w') as f:
yaml.dump(cluster_config, f)
# 6. Create EKS cluster
print_colored("\nCreating EKS cluster (this will take 15-20 minutes)...", "cyan")
cmd = f"eksctl create cluster -f eksctl-{timestamp}.yaml --profile {self.aws_profile}"
if not run_command(cmd)[0]:
print_colored("Failed to create EKS cluster", "red")
sys.exit(1)
# 7. Create GP3 storage class
print_colored("\nCreating GP3 storage class...", "cyan")
storage_class = {
"apiVersion": "storage.k8s.io/v1",
"kind": "StorageClass",
"metadata": {
"name": "ebs-gp3"
},
"provisioner": "ebs.csi.aws.com",
"parameters": {
"type": "gp3",
"csi.storage.k8s.io/fstype": "xfs"
},
"volumeBindingMode": "WaitForFirstConsumer",
"reclaimPolicy": "Delete"
}
with open(f'storage-class-{timestamp}.yaml', 'w') as f:
yaml.dump(storage_class, f)
if not run_command(f"kubectl apply -f storage-class-{timestamp}.yaml")[0]:
print_colored("Failed to create GP3 storage class", "red")
sys.exit(1)
# 8. Set up AWS Load Balancer Controller
print_colored("\nSetting up AWS Load Balancer Controller...", "cyan")
# Download and create ALB policy
cmd = "curl -o iam_policy_alb.json https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.7.2/docs/install/iam_policy.json"
if not run_command(cmd)[0]:
print_colored("Failed to download ALB policy", "red")
sys.exit(1)
alb_policy_name = f"AWSLoadBalancerControllerIAMPolicy-{self.cluster_name}-{timestamp}"
cmd = f"aws iam create-policy --policy-name {alb_policy_name} --policy-document file://iam_policy_alb.json --profile {self.aws_profile}"
run_command(cmd) # Ignore if policy exists
# Create service account with explicit role
print_colored("\nCreating service account for Load Balancer Controller...", "cyan")
cmd = (f"eksctl create iamserviceaccount "
f"--cluster={self.cluster_name} "
f"--namespace=kube-system "
f"--name=aws-load-balancer-controller "
f"--role-name=AmazonEKSLoadBalancerControllerRole-{self.cluster_name} "
f"--attach-policy-arn=arn:aws:iam::{self.aws_account_id}:policy/{alb_policy_name} "
f"--override-existing-serviceaccounts "
f"--approve "
f"--region={self.region}")
if not run_command(cmd)[0]:
print_colored("Failed to create service account for ALB controller", "red")
sys.exit(1)
# Install AWS Load Balancer Controller
print_colored("\nInstalling AWS Load Balancer Controller...", "cyan")
cmd = (f"helm install aws-load-balancer-controller eks/aws-load-balancer-controller "
f"-n kube-system "
f"--set clusterName={self.cluster_name} "
f"--set serviceAccount.create=false "
f"--set serviceAccount.name=aws-load-balancer-controller "
f"--set region={self.region} "
f"--set vpcId=$(aws eks describe-cluster --name {self.cluster_name} --query \"cluster.resourcesVpcConfig.vpcId\" --output text --region {self.region}) "
f"--set image.repository=602401143452.dkr.ecr.{self.region}.amazonaws.com/amazon/aws-load-balancer-controller "
"--set enableServiceMutatorWebhook=false")
if not run_command(cmd)[0]:
print_colored("Failed to install AWS Load Balancer Controller", "red")
sys.exit(1)
# 9. Install and configure metrics server
print_colored("\nInstalling metrics server...", "cyan")
metrics_cmd = """
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/high-availability-1.21+.yaml && \
kubectl patch deployment metrics-server -n kube-system --type=json \
-p='[{"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--kubelet-insecure-tls"}]'
"""
if not run_command(metrics_cmd)[0]:
print_colored("Failed to install metrics server. Some monitoring features might be limited.", "yellow")
else:
print_colored("Metrics server installed and patched for EKS.", "green")
# 10. Verify final deployment
print_colored("\nVerifying AWS Load Balancer Controller deployment...", "cyan")
max_retries = 12
for i in range(max_retries):
cmd = "kubectl get deployment -n kube-system aws-load-balancer-controller"
success, output, _ = run_command(cmd, verbose=False)
if success and "1/1" in output:
print_colored("AWS Load Balancer Controller is ready!", "green")
break
if i < max_retries - 1:
print_colored(f"Waiting for controller to be ready (attempt {i+1}/{max_retries})...", "yellow")
time.sleep(10)
# 11. Cleanup temporary files
for file in [f'policy-{timestamp}.json', f'eksctl-{timestamp}.yaml', f'storage-class-{timestamp}.yaml', 'iam_policy_alb.json']:
if os.path.exists(file):
os.remove(file)
print_colored("\nAWS prerequisites setup completed successfully!", "green")
return True
def setup_gke_prerequisites(self):
"""Setup everything needed before cluster creation"""
print_colored("\nSetting up GKE prerequisites...", "blue")
# 1. Get essential info first
self.project_id = input("Enter your GCP project ID: ").strip()
zone_input = input("Enter your GCP zone (e.g., europe-west1-b). Note: If you select a region like europe-west1, deployments will include all sub-zones (a, b, c), potentially multiplying node counts. Proceed with caution: ").strip()
self.zone = zone_input
self.region = '-'.join(zone_input.split('-')[:-1]) # extract region from zone
# 2. Create role with timestamp to avoid collision
timestamp = int(time.time())
self.role_name = f"hopsworksai.instances.{timestamp}" # Unique role name
print_colored(f"Creating role '{self.role_name}'...", "cyan")
role_file = tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False)
try:
role_def = {
"title": "Hopsworks AI Instances",
"description": "Role for Hopsworks instances",
"stage": "GA",
"includedPermissions": [
# Artifact Registry permissions
"artifactregistry.repositories.create",
"artifactregistry.repositories.get",
"artifactregistry.repositories.uploadArtifacts",
"artifactregistry.repositories.downloadArtifacts",
"artifactregistry.tags.list",
"artifactregistry.repositories.list"
]
}
yaml.dump(role_def, role_file)
role_file.close()
success, _, error = run_command(
f"gcloud iam roles create {self.role_name} --project={self.project_id} --file={role_file.name}"
)
if not success:
print_colored(f"Failed to create role: {error}", "red")
sys.exit(1)
else:
print_colored(f"Role '{self.role_name}' created successfully.", "green")
finally:
os.unlink(role_file.name)
# 3. Create/update service account
sa_name = "hopsworksai-instances"
self.sa_email = f"{sa_name}@{self.project_id}.iam.gserviceaccount.com"
# Check if SA exists first
success, _, _ = run_command(
f"gcloud iam service-accounts describe {self.sa_email} --project={self.project_id}",
verbose=False
)
if not success:
success, _, error = run_command(
f"gcloud iam service-accounts create {sa_name} "
f"--project={self.project_id} "
f"--description='Service account for Hopsworks' "
f"--display-name='Hopsworks Service Account'"
)
if not success and "already exists" not in error:
print_colored(f"Failed to create service account: {error}", "red")
sys.exit(1)
else:
print_colored(f"Service account '{self.sa_email}' created.", "green")
else:
print_colored(f"Service account '{self.sa_email}' already exists.", "green")
# 4. Update role binding
print_colored("Updating role binding...", "cyan")
# Remove existing binding if it exists
run_command(
f"gcloud projects remove-iam-policy-binding {self.project_id} "
f"--member=serviceAccount:{self.sa_email} "
f"--role=projects/{self.project_id}/roles/{self.role_name}",
verbose=False
)
success, _, error = run_command(
f"gcloud projects add-iam-policy-binding {self.project_id} "
f"--member=serviceAccount:{self.sa_email} "
f"--role=projects/{self.project_id}/roles/{self.role_name}"
)
if not success:
print_colored(f"Failed to bind role: {error}", "red")
sys.exit(1)
else:
print_colored(f"Role '{self.role_name}' bound to service account '{self.sa_email}'.", "green")
# 5. NOW we can create the cluster with the service account
self.cluster_name = input("Enter your GKE cluster name: ").strip() or "hopsworks-cluster"
node_count = input("Enter number of nodes (default: 5): ").strip() or "5"
machine_type = input("Enter machine type (default: n2-standard-8): ").strip() or "n2-standard-8"
cluster_cmd = (f"gcloud container clusters create {self.cluster_name} "
f"--zone={self.zone} "
f"--machine-type={machine_type} "
f"--num-nodes={node_count} "
f"--enable-ip-alias "
f"--service-account={self.sa_email}")
print_colored("Creating GKE cluster...", "cyan")
if not run_command(cluster_cmd)[0]:
print_colored("Failed to create GKE cluster.", "red")
sys.exit(1)
else:
print_colored(f"GKE cluster '{self.cluster_name}' created.", "green")
# 6. Configure kubectl
print_colored("Configuring kubectl...", "cyan")
run_command(f"gcloud container clusters get-credentials {self.cluster_name} "
f"--zone={self.zone} "
f"--project={self.project_id}")
# 7. Setup Artifact Registry
registry_name = f"hopsworks-{self.cluster_name}-{timestamp}"
print_colored("Creating Artifact Registry repository...", "cyan")
success, _, error = run_command(f"gcloud artifacts repositories create {registry_name} "
f"--repository-format=docker "
f"--location={self.region} "
f"--project={self.project_id}")
if not success and "already exists" not in error:
print_colored(f"Failed to create Artifact Registry: {error}", "red")
sys.exit(1)
else:
print_colored(f"Artifact Registry repository '{registry_name}' created or already exists.", "green")
# Now, set up GKE authentication
self.setup_gke_authentication()
def setup_gke_authentication(self):
"""Setup GKE auth with proper Workload Identity"""
# 1. Create and bind Kubernetes service account
print_colored("Setting up Kubernetes service account...", "cyan")
run_command(f"kubectl create namespace {self.namespace} --dry-run=client -o yaml | kubectl apply -f -")
run_command(f"kubectl create serviceaccount -n {self.namespace} hopsworks-sa")
# Bind the GCP SA to K8s SA
workload_binding = (
f"gcloud iam service-accounts add-iam-policy-binding {self.sa_email} "
f"--role roles/iam.workloadIdentityUser "
f"--member \"serviceAccount:{self.project_id}.svc.id.goog[{self.namespace}/hopsworks-sa]\""
)
run_command(workload_binding)
# Annotate the K8s SA
run_command(
f"kubectl annotate serviceaccount -n {self.namespace} hopsworks-sa "
f"iam.gke.io/gcp-service-account={self.sa_email}"
)
# 2. Setup Docker config for both GCP and hops.works registries
docker_config = {
"credHelpers": {
f"{self.region}-docker.pkg.dev": "gcloud",
"docker.hops.works": "gcloud"
}
}
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump(docker_config, f)
config_file = f.name
run_command(f"kubectl create configmap docker-config -n {self.namespace} "
f"--from-file=config.json={config_file} "
f"--dry-run=client -o yaml | kubectl apply -f -")
os.unlink(config_file)
return True
def setup_aks_prerequisites(self):
"""Setup AKS prerequisites and cluster from scratch"""
print_colored("\nSetting up AKS prerequisites...", "blue")
# Verify Azure CLI auth
if not run_command("az account show", verbose=False)[0]:
print_colored("Please run 'az login' first.", "red")
sys.exit(1)
# Get resource group - create if doesn't exist
self.resource_group = input("Enter your Azure resource group name: ").strip()
location = input("Enter Azure region (eg. eastus): ").strip() or "eastus"
# Check if resource group exists, create if it doesn't
if not run_command(f"az group show --name {self.resource_group}", verbose=False)[0]:
print_colored(f"Creating resource group {self.resource_group}...", "cyan")
if not run_command(f"az group create --name {self.resource_group} --location {location}")[0]:
print_colored("Failed to create resource group.", "red")
sys.exit(1)
# Get cluster details
self.cluster_name = input("Enter your AKS cluster name: ").strip()
node_count = input("Enter number of nodes (default: 5): ").strip() or "5"
machine_type = input("Enter machine type (default: Standard_D8_v4): ").strip() or "Standard_D8_v4"
# Create AKS cluster with minimal config but all we need
print_colored("\nCreating AKS cluster (this will take 5-10 minutes)...", "cyan")
cluster_cmd = (
f"az aks create "
f"--resource-group {self.resource_group} "
f"--name {self.cluster_name} "
f"--node-count {node_count} "
f"--node-vm-size {machine_type} "
f"--location {location} "
f"--network-plugin azure "
f"--generate-ssh-keys "
f"--load-balancer-sku standard "
f"--enable-managed-identity "
f"--network-policy azure "
f"--no-wait"
)
if not run_command(cluster_cmd)[0]:
print_colored("Failed to start AKS cluster creation.", "red")
sys.exit(1)
# Wait for cluster to be ready
print_colored("\nWaiting for cluster to be ready...", "cyan")
while True:
success, output, _ = run_command(
f"az aks show --resource-group {self.resource_group} --name {self.cluster_name} --query provisioningState -o tsv",
verbose=False
)
if success and "Succeeded" in output:
break
print_colored("Still creating cluster...", "yellow")
time.sleep(30)
# Get credentials
print_colored("\nGetting kubectl credentials...", "cyan")
cmd = f"az aks get-credentials --resource-group {self.resource_group} --name {self.cluster_name} --overwrite-existing"
if not run_command(cmd)[0]:
print_colored("Failed to get AKS credentials.", "red")
sys.exit(1)
# Create namespace and setup basic RBAC
print_colored(f"\nCreating namespace {self.namespace} and setting up RBAC...", "cyan")
run_command(f"kubectl create namespace {self.namespace}")
# Create a more permissive service account for Hopsworks
sa_yaml = f"""apiVersion: v1
kind: ServiceAccount
metadata:
name: hopsworks-sa
namespace: {self.namespace}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: hopsworks-admin
namespace: {self.namespace}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: admin
subjects:
- kind: ServiceAccount
name: hopsworks-sa
namespace: {self.namespace}"""
with open('sa.yaml', 'w') as f:
f.write(sa_yaml)
run_command("kubectl apply -f sa.yaml")
print_colored("\nAKS prerequisites setup completed successfully!", "green")
return True
def handle_azure_registry(self):
"""Setup Docker registry auth for Azure with proper error handling and verification"""
print_colored("\nSetting up Docker registry credentials...", "blue")
# Get Docker registry credentials with basic validation
while True:
docker_user = input("Enter your Hopsworks Docker registry username: ").strip()
if docker_user:
break
print_colored("Username cannot be empty.", "yellow")
while True:
docker_pass = input("Enter your Hopsworks Docker registry password: ").strip()
if docker_pass:
break
print_colored("Password cannot be empty.", "yellow")
# Define our secrets configuration
registry_secrets = [
{
"name": "regcred", # Primary secret referenced in Helm values
"server": "docker.hops.works",
"required": True # This one must succeed
},
{
"name": "hopsworks-registry-secret", # Backup secret for additional components
"server": "docker.hops.works",
"required": False # This one can fail if it exists
}
]
# Track if we've successfully created the required secrets
required_secrets_created = False
for secret_config in registry_secrets:
print_colored(f"\nCreating secret {secret_config['name']}...", "cyan")
# First try to delete any existing secret
cleanup_cmd = f"kubectl delete secret {secret_config['name']} -n {self.namespace} --ignore-not-found=true"
run_command(cleanup_cmd, verbose=False)
# Create the new secret
create_cmd = (
f"kubectl create secret docker-registry {secret_config['name']} "
f"--namespace={self.namespace} "
f"--docker-server={secret_config['server']} "
f"--docker-username={docker_user} "
f"--docker-password={docker_pass} "
)
success, output, error = run_command(create_cmd)
if success:
print_colored(f"Successfully created secret {secret_config['name']}", "green")
if secret_config['required']:
required_secrets_created = True
else:
error_msg = f"Failed to create secret {secret_config['name']}"
if "already exists" in error:
print_colored(f"{error_msg} (already exists)", "yellow")
if secret_config['required']:
required_secrets_created = True
else:
print_colored(f"{error_msg}: {error}", "red")
if secret_config['required'] and not required_secrets_created:
print_colored("Failed to create required registry secret. Cannot proceed.", "red")
sys.exit(1)
# Verify the secrets were created
print_colored("\nVerifying registry secrets...", "cyan")
verify_cmd = f"kubectl get secrets -n {self.namespace} | grep -E 'regcred|hopsworks-registry-secret'"
success, output, _ = run_command(verify_cmd, verbose=False)
if success and 'regcred' in output:
print_colored("\nRegistry secrets setup completed successfully.", "green")
# Store this for potential use in other methods
self.registry_secrets_created = True
return True
else:
print_colored("Warning: Registry secrets verification failed.", "yellow")
print_colored("This might cause issues with pulling images.", "yellow")
# Don't exit here - let the installation continue and potentially fail later
self.registry_secrets_created = False
return False
def setup_and_verify_kubeconfig(self):
while True:
self.kubeconfig_path, self.cluster_name, self.region = self.setup_kubeconfig()
if self.kubeconfig_path:
# Set the provided config as current context
run_command(f"kubectl config use-context $(kubectl config current-context --kubeconfig={self.kubeconfig_path})")
if self.verify_kubeconfig():
break
else:
print_colored("Failed to set up a valid kubeconfig.", "red")
if not get_user_input("Do you want to try again? (yes/no):", ["yes", "no"]).lower() == "yes":
sys.exit(1)
def setup_kubeconfig(self):
print_colored(f"\nSetting up kubeconfig for {self.environment}...", "blue")
kubeconfig_path = None
cluster_name = None
region = None
if self.environment == "AWS":
# Existing AWS logic
cluster_name = input("Enter your EKS cluster name: ").strip()
region = self.get_aws_region()
cmd = f"aws eks get-token --cluster-name {cluster_name} --region {region}"
if not run_command(cmd)[0]:
print_colored("Failed to get EKS token. Updating kubeconfig...", "yellow")
cmd = f"aws eks update-kubeconfig --name {cluster_name} --region {region}"
if not run_command(cmd)[0]:
print_colored("Failed to update kubeconfig.", "red")
return None, None, None
kubeconfig_path = os.path.expanduser("~/.kube/config")
elif self.environment == "GCP":
if self.args.loadbalancer_only:
cluster_name = input("Enter your GKE cluster name: ").strip()
self.project_id = input("Enter your GCP project ID: ").strip()
zone_input = input("Enter your GCP zone (e.g. europe-west1-b): ").strip()
self.zone = zone_input
self.region = '-'.join(zone_input.split('-')[:-1]) # extract region from zone
else:
# Since we handle GCP kubeconfig in setup_gke_prerequisites, skip here
cluster_name = self.cluster_name
cmd = f"gcloud container clusters get-credentials {cluster_name} --project {self.project_id} --zone {self.zone}"
if not run_command(cmd)[0]:
print_colored("Failed to get GKE credentials. Check your gcloud setup.", "red")
return None, None, None
run_command("gcloud auth configure-docker", verbose=False)
kubeconfig_path = os.path.expanduser("~/.kube/config")
elif self.environment == "Azure":
self.resource_group = input("Enter your Azure resource group name: ").strip()
cluster_name = input("Enter your AKS cluster name: ").strip()
cmd = f"az aks get-credentials --resource-group {self.resource_group} --name {cluster_name} --overwrite-existing"
if not run_command(cmd)[0]:
print_colored("Failed to get AKS credentials. Check your Azure CLI configuration and permissions.", "red")
return None, None, None
kubeconfig_path = os.path.expanduser("~/.kube/config")
else:
# Other environments
kubeconfig_path = input("Enter the path to your kubeconfig file: ").strip()
kubeconfig_path = os.path.expanduser(kubeconfig_path)
if not os.path.exists(kubeconfig_path):
print_colored(f"The file {kubeconfig_path} does not exist. Check the path and try again.", "red")
return None, None, None
if kubeconfig_path:
os.environ['KUBECONFIG'] = kubeconfig_path
with open('set_kubeconfig.sh', 'w') as f:
f.write(f"export KUBECONFIG={kubeconfig_path}\n")
print("\nTo use kubectl in your current shell, run:")
print("source set_kubeconfig.sh")
return kubeconfig_path, cluster_name, region
def verify_kubeconfig(self):
print_colored("\nVerifying kubeconfig...", "cyan")
# Check current context
cmd = "kubectl config current-context"
success, output, error = run_command(cmd, verbose=True)
if not success:
print_colored(f"Failed to get current context. Error: {error}", "red")
return False
# Try to list namespaces
cmd = "kubectl get namespaces"
success, output, error = run_command(cmd, verbose=True)
if not success:
print_colored(f"Failed to list namespaces. Error: {error}", "red")
return False
print_colored("Kubeconfig verified successfully.", "green")