From 751b0ee986e0b8002b54d310d8728669ff9ff7b0 Mon Sep 17 00:00:00 2001 From: yy Date: Tue, 7 Nov 2023 17:30:49 +0800 Subject: [PATCH] use kube-system ns uid as cluster id. Signed-off-by: yy --- controllers/license/cmd/manager/main.go | 10 ++++- .../internal/util/clusterid/cluster_id.go | 37 ++++++++----------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/controllers/license/cmd/manager/main.go b/controllers/license/cmd/manager/main.go index 390702dce52..ddb0cb4ad06 100644 --- a/controllers/license/cmd/manager/main.go +++ b/controllers/license/cmd/manager/main.go @@ -35,6 +35,7 @@ import ( accountv1 "github.com/labring/sealos/controllers/account/api/v1" licensev1 "github.com/labring/sealos/controllers/license/api/v1" "github.com/labring/sealos/controllers/license/internal/controller" + utilid "github.com/labring/sealos/controllers/license/internal/util/clusterid" "github.com/labring/sealos/controllers/license/internal/util/database" //+kubebuilder:scaffold:imports ) @@ -101,7 +102,14 @@ func main() { } defer db.Disconnect(context.Background()) - if err = (&controller.LicenseReconciler{ClusterID: os.Getenv("CLUSTER_ID")}).SetupWithManager(mgr, db); err != nil { + clusterID, err := utilid.GetClusterID(context.Background(), mgr.GetClient()) + if err != nil { + setupLog.Error(err, "unable to get cluster id") + os.Exit(1) + } + setupLog.Info("cluster id", "id", clusterID) + + if err = (&controller.LicenseReconciler{ClusterID: clusterID}).SetupWithManager(mgr, db); err != nil { setupLog.Error(err, "unable to create controller", "controller", "License") os.Exit(1) } diff --git a/controllers/license/internal/util/clusterid/cluster_id.go b/controllers/license/internal/util/clusterid/cluster_id.go index cdd06125e94..c88198c9151 100644 --- a/controllers/license/internal/util/clusterid/cluster_id.go +++ b/controllers/license/internal/util/clusterid/cluster_id.go @@ -1,24 +1,17 @@ package clusterid -//import ( -// "context" -// "os" -// -// "github.com/labring/sealos/controllers/license/internal/util/database" -//) -// -//func GetClusterID(ctx context.Context, db *database.DataBase) (string, error) { -// // TODO get cluster id from database -// //id, err := db.GetClusterID(ctx) -// //if errors.Is(err, mongo.ErrNoDocuments) { -// // // if cluster id is not set, set it -// // envID := os.Getenv("CLUSTER_ID") -// // if envID == "" { -// // return "", errors.New("cluster id not set") -// // } -// // if err := db.StoreClusterID(ctx, os.Getenv("CLUSTER_ID")); err != nil { -// // return db.GetClusterID(ctx) -// // } -// //} -// return os.Getenv("CLUSTER_ID"), nil -//} +import ( + "context" + + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func GetClusterID(ctx context.Context, c client.Client) (string, error) { + ns := &corev1.Namespace{} + err := c.Get(ctx, client.ObjectKey{Name: "kube-system"}, ns) + if err != nil { + return "", err + } + return string(ns.UID), nil +}