|
1 | 1 | package utils |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + corev1 "k8s.io/api/core/v1" |
| 7 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 8 | + "sigs.k8s.io/controller-runtime/pkg/client/config" |
| 9 | + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" |
| 10 | + |
4 | 11 | "github.com/wandb/operator/pkg/wandb/spec" |
5 | 12 | ) |
6 | 13 |
|
7 | 14 | func GetLicense(specs ...*spec.Spec) string { |
| 15 | + log := ctrllog.Log.WithName("GetLicense") |
| 16 | + |
| 17 | + kubeClient, err := createKubeClient() |
| 18 | + if err != nil { |
| 19 | + log.Error(err, "Error creating Kubernetes client") |
| 20 | + return "" |
| 21 | + } |
| 22 | + |
8 | 23 | for _, s := range specs { |
9 | | - if s == nil { |
10 | | - continue |
11 | | - } |
12 | | - if s.Values == nil { |
| 24 | + if s == nil || s.Values == nil { |
13 | 25 | continue |
14 | 26 | } |
15 | 27 |
|
16 | 28 | license := s.Values.GetString("global.license") |
17 | 29 | if license != "" { |
| 30 | + log.Info("License retrieved from values.yaml") |
18 | 31 | return license |
19 | 32 | } |
| 33 | + |
| 34 | + secretName := s.Values.GetString("global.licenseSecret.name") |
| 35 | + secretKey := s.Values.GetString("global.licenseSecret.key") |
| 36 | + |
| 37 | + if secretName != "" && secretKey != "" { |
| 38 | + license := getLicenseFromSecret(kubeClient, secretName, secretKey) |
| 39 | + if license != "" { |
| 40 | + log.Info("License retrieved from Kubernetes secret", "secretName", secretName) |
| 41 | + return license |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + return "" |
| 46 | +} |
| 47 | + |
| 48 | +func createKubeClient() (client.Client, error) { |
| 49 | + kubeConfig := config.GetConfigOrDie() |
| 50 | + kubeClient, err := client.New(kubeConfig, client.Options{}) |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + return kubeClient, nil |
| 55 | +} |
| 56 | + |
| 57 | +func getLicenseFromSecret(kubeClient client.Client, secretName, secretKey string) string { |
| 58 | + log := ctrllog.Log.WithName("getLicenseFromSecret") |
| 59 | + secret := &corev1.Secret{} |
| 60 | + ctx := context.TODO() |
| 61 | + |
| 62 | + err := kubeClient.Get(ctx, client.ObjectKey{Name: secretName, Namespace: "default"}, secret) |
| 63 | + if err != nil { |
| 64 | + log.Error(err, "Error retrieving secret", "secretName", secretName) |
| 65 | + return "" |
| 66 | + } |
| 67 | + |
| 68 | + if secret.Data == nil { |
| 69 | + log.Info("Secret has no data", "secretName", secretName) |
| 70 | + return "" |
| 71 | + } |
| 72 | + license, exists := secret.Data[secretKey] |
| 73 | + if !exists { |
| 74 | + log.Info("Key not found in secret", "secretKey", secretKey, "secretName", secretName) |
| 75 | + return "" |
20 | 76 | } |
21 | | - return "" |
| 77 | + log.Info("Successfully retrieved license from secret", "secretName", secretName) |
| 78 | + return string(license) |
22 | 79 | } |
0 commit comments