diff --git a/pkg/model/model.go b/pkg/model/model.go index a7947103..bd780efe 100644 --- a/pkg/model/model.go +++ b/pkg/model/model.go @@ -17,6 +17,7 @@ type Object struct { ObjectMeta *ResourceObjectMeta `json:"metadata" gorm:"foreignkey:ID;references:id;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` Spec *ResourceSpec `json:"spec,omitempty" gorm:"foreignkey:ID;references:id;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` Status *ResourceStatus `json:"status,omitempty" gorm:"foreignkey:ID;references:id;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` + ClusterID string `json:"cluster_id"` PatternResource *uuid.UUID `json:"pattern_resource"` // Secondary fields for configsmaps and secrets diff --git a/pkg/model/model_converter.go b/pkg/model/model_converter.go index f180ea6c..8c3c1fee 100644 --- a/pkg/model/model_converter.go +++ b/pkg/model/model_converter.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/layer5io/meshkit/utils" "github.com/layer5io/meshsync/internal/config" + iutils "github.com/layer5io/meshsync/pkg/utils" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -86,6 +87,8 @@ func ParseList(object unstructured.Unstructured) Object { result.Type = string(objType) } + result.ClusterID = iutils.GetClusterID() + return result } @@ -96,7 +99,7 @@ func IsObject(obj Object) bool { func SetID(obj *Object) { if obj != nil { id := base64.StdEncoding.EncodeToString([]byte( - fmt.Sprintf("%s.%s.%s.%s", obj.Kind, obj.APIVersion, obj.ObjectMeta.Namespace, obj.ObjectMeta.Name), + fmt.Sprintf("%s.%s.%s.%s.%s", obj.ClusterID, obj.Kind, obj.APIVersion, obj.ObjectMeta.Namespace, obj.ObjectMeta.Name), )) obj.ID = id obj.ObjectMeta.ID = id diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go new file mode 100644 index 00000000..279a3ce9 --- /dev/null +++ b/pkg/utils/utils.go @@ -0,0 +1,42 @@ +package utils + +import ( + "context" + + "github.com/layer5io/meshkit/utils/kubernetes" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// clusterID is a unique identifier for the cluster +// in which MeshSync is running +var clusterID *string = nil + +// GetClusterID returns a unique identifier for the cluster in which +// meshsync is running +// +// Notes: +// 1. If MeshSync is running out of cluster then the function will return +// an empty string +// 2. Function caches the cluster ID whenever it is invoked for the first time +// assuming that the cluster ID cannot and will not change throughout MeshSync's +// lifecycle +func GetClusterID() string { + if clusterID != nil { + return *clusterID + } + + client, err := kubernetes.New(nil) + if err != nil { + return "" + } + + ksns, err := client.KubeClient.CoreV1().Namespaces().Get(context.TODO(), "kube-system", v1.GetOptions{}) + if err != nil { + return "" + } + + uid := string(ksns.ObjectMeta.GetUID()) + clusterID = &uid + + return *clusterID +}