|
| 1 | +package clusteruid |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 7 | + "k8s.io/client-go/kubernetes" |
| 8 | +) |
| 9 | + |
| 10 | +// clusterUIDKey is the context key for storing the cluster UID |
| 11 | +type clusterUIDKey struct{} |
| 12 | + |
| 13 | +// GetClusterUID retrieves the UID of the kube-system namespace using the given Kubernetes clientset. |
| 14 | +// This UID can be used as a unique identifier for the Kubernetes cluster. |
| 15 | +// The UID is stored in the given context for later retrieval; use ClusterUIDFromContext to get it. |
| 16 | +func GetClusterUID(ctx context.Context, clientset kubernetes.Interface) (context.Context, error) { |
| 17 | + namespace, err := clientset.CoreV1().Namespaces().Get(ctx, "kube-system", metav1.GetOptions{}) |
| 18 | + if err != nil { |
| 19 | + return ctx, err |
| 20 | + } |
| 21 | + |
| 22 | + ctx = withClusterUID(ctx, string(namespace.ObjectMeta.UID)) |
| 23 | + return ctx, nil |
| 24 | +} |
| 25 | + |
| 26 | +// ClusterUIDFromContext retrieves the cluster UID from the context. |
| 27 | +// Panics if the value is not found or if the value is not a string. |
| 28 | +func ClusterUIDFromContext(ctx context.Context) string { |
| 29 | + value := ctx.Value(clusterUIDKey{}) |
| 30 | + if value == nil { |
| 31 | + panic("cluster UID not found in context") |
| 32 | + } |
| 33 | + |
| 34 | + uid, ok := value.(string) |
| 35 | + if !ok { |
| 36 | + panic("cluster UID in context is not a string") |
| 37 | + } |
| 38 | + |
| 39 | + return uid |
| 40 | +} |
| 41 | + |
| 42 | +// withClusterUID adds the given cluster UID to the context |
| 43 | +func withClusterUID(ctx context.Context, clusterUID string) context.Context { |
| 44 | + return context.WithValue(ctx, clusterUIDKey{}, clusterUID) |
| 45 | +} |
0 commit comments