diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..0f8103e --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/argohandler/argohandler.go b/argohandler/argohandler.go index 70d24cf..20be6cf 100644 --- a/argohandler/argohandler.go +++ b/argohandler/argohandler.go @@ -4,7 +4,9 @@ import ( "context" "fmt" "log" + "math/rand" "sync" + "time" "github.com/argoproj/argo-cd/v2/pkg/apiclient" "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" @@ -19,6 +21,7 @@ type ApplicationValues struct { Cluster string `yaml:"cluster"` RepoURL string `yaml:"repoURL"` Server string `yaml:"server"` + UserID string `yaml:"userID"` } var ( @@ -46,7 +49,17 @@ func InitializeClient() { }) } -func CreateApp(clustername string) { +func generateRandomString(length int) string { + const charset = "abcdefghijklmnopqrstuvwxyz0123456789" + seededRand := rand.New(rand.NewSource(time.Now().UnixNano())) + b := make([]byte, length) + for i := range b { + b[i] = charset[seededRand.Intn(len(charset))] + } + return string(b) +} + +func CreateApp(clustername string, ControlPlane string, PlatformVersion string, Cpu string, Memory string, userID string) { InitializeClient() @@ -56,13 +69,17 @@ func CreateApp(clustername string) { log.Fatalf("Failed to create application client: %v", err) } + // Generate unique cluster name with user prefix + uniqueClusterName := "test" + app := ApplicationValues{ - Name: clustername, - Namespace: "vc-bhrz-n", + Name: uniqueClusterName, + Namespace: "ns-" + generateRandomString(4), Path: "vcluster-0.21.1", Cluster: "in-cluster", Server: "https://kubernetes.default.svc", RepoURL: "http://192.168.2.20:8015/root/application.git", + UserID: userID, } // Define the ArgoCD application @@ -70,6 +87,10 @@ func CreateApp(clustername string) { ObjectMeta: metav1.ObjectMeta{ Name: app.Name, Namespace: "argocd", + Labels: map[string]string{ + "user-id": userID, + "type": "vcluster", + }, Finalizers: []string{ "resources-finalizer.argocd.argoproj.io", }, @@ -84,7 +105,32 @@ func CreateApp(clustername string) { RepoURL: app.RepoURL, TargetRevision: "HEAD", Helm: &argoprojv1alpha1.ApplicationSourceHelm{ - ValueFiles: []string{"vcluster.yaml"}, + Parameters: []argoprojv1alpha1.HelmParameter{ + { + Name: "controlPlane.advanced.defaultImageRegistry", + Value: "192.168.2.43:31898", + }, + { + Name: "controlPlane.distro.k8s.version", + Value: ControlPlane, + }, + { + Name: "controlPlane.distro.k8s.resources.limits.cpu", + Value: Cpu, + }, + { + Name: "controlPlane.distro.k8s.resources.limits.memory", + Value: Memory, + }, + { + Name: "controlPlane.distro.k8s.resources.requests.cpu", + Value: Cpu, + }, + { + Name: "controlPlane.distro.k8s.resources.requests.memory", + Value: Memory, + }, + }, }, }, Project: "default", @@ -129,3 +175,28 @@ func SyncApp(appName string) { fmt.Printf("Application synced successfully: %s\n", appName) } + +func ListUserClusters(userID string) ([]string, error) { + InitializeClient() + + _, appClient, err := client.NewApplicationClient() + if err != nil { + return nil, fmt.Errorf("failed to create application client: %v", err) + } + + // List all applications with the user's label + selector := fmt.Sprintf("user-id=%s", userID) + apps, err := appClient.List(context.Background(), &application.ApplicationQuery{ + Selector: &selector, + }) + if err != nil { + return nil, fmt.Errorf("failed to list applications: %v", err) + } + + var clusterNames []string + for _, app := range apps.Items { + clusterNames = append(clusterNames, app.Name) + } + + return clusterNames, nil +} diff --git a/db/db.go b/db/db.go index 753ffec..7f979ca 100644 --- a/db/db.go +++ b/db/db.go @@ -14,7 +14,7 @@ var ( ) func InitDB() { - clientOptions := options.Client().ApplyURI("mongodb://root:example@192.168.1.10:27017/") + clientOptions := options.Client().ApplyURI("mongodb://root:example@172.20.158.234:27017/") client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) diff --git a/handler/handler.go b/handler/handler.go index ba837ea..f92371c 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -5,9 +5,10 @@ import ( "encoding/json" "main/argohandler" "main/db" - "net/http" + "net/http" + "log" - "github.com/gorilla/mux" +// "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) @@ -24,11 +25,22 @@ type Cluster struct { UserID primitive.ObjectID `json:"userId"` } -func createClusterHandler(w http.ResponseWriter, r *http.Request) { +type Header struct { + Authorization string `bson:"token"` +} + +func CreateClusterHandler(w http.ResponseWriter, r *http.Request) { var cluster Cluster _ = json.NewDecoder(r.Body).Decode(&cluster) + var header Header + header.Authorization = r.Header.Get("Authorization") + + log.Fatal("--------------") + log.Fatal(r.Header.Get("Authorization")) + log.Fatal("--------------") + // vclusterCollection := db.Vclusters_details.FindOne(context.TODO(), bson.M{"name": Cluster.Name}).Decode(&existsCluster) if cluster.Name == "" || cluster.ControlPlane == "" || cluster.PlatformVersion == "" || cluster.Cpu == "" || cluster.Memory == "" { @@ -49,7 +61,7 @@ func createClusterHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, `{"message": "Could not create cluster"}`, http.StatusInternalServerError) } - argohandler.CreateApp(cluster.Name) + argohandler.CreateApp(cluster.Name, cluster.ControlPlane, cluster.PlatformVersion, cluster.Cpu, cluster.Memory, "userid") response := map[string]string{"message": "Cluster created"} @@ -58,6 +70,6 @@ func createClusterHandler(w http.ResponseWriter, r *http.Request) { } -func RegsiterClusterRoute(r *mux.Router) { - r.HandleFunc("/createcluster", createClusterHandler).Methods("POST") -} +// func RegsiterClusterRoute(r *mux.Router) { +// r.HandleFunc("/createcluster", createClusterHandler).Methods("POST", "OPTIONS") +// } diff --git a/main.go b/main.go index a5c1068..6a0cbb0 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "fmt" - "log" + "main/db" "main/handler" @@ -125,15 +125,17 @@ func main() { router.HandleFunc("/register", registerHnadler) router.HandleFunc("/login", loginHandler) - - handler.RegsiterClusterRoute(router) + router.HandleFunc("/createcluster", handler.CreateClusterHandler) + //handler.RegsiterClusterRoute(router) // Enable CORS c := cors.New(cors.Options{ - AllowedOrigins: []string{"http://localhost:4200", "*"}, // Angular app's origin - AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"}, - AllowedHeaders: []string{"Content-Type"}, + AllowedOrigins: []string{"*"}, // Allow all origins + AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowedHeaders: []string{"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin"}, + ExposedHeaders: []string{"Content-Length"}, AllowCredentials: true, + Debug: true, // Enable debug logging }) - log.Fatal(http.ListenAndServe(":8082", c.Handler((router)))) + http.ListenAndServe("0.0.0.0:8082", c.Handler(router)) }