From b39ad05ce40de31d3ebe6ac2166f17b6deab3e13 Mon Sep 17 00:00:00 2001 From: "ignacio.prusiel" <ignacio.prusiel@atos.net> Date: Wed, 12 Feb 2025 14:00:17 +0100 Subject: [PATCH] First version of ibmc-agent --- .gitignore | 1 + .gitlab-ci.yml | 22 ++ Dockerfile | 41 +++ README.md | 115 ++------ cmd/migrate/main.go | 553 ++++++++++++++++++++++++++++++++++++ config/env-values.txt | 9 + config/env.txt | 8 + config/minio-credentials | 3 + config/velero.yaml | 40 +++ deployments/deployment.yaml | 97 +++++++ deployments/imagerepo.yaml | 25 ++ go.mod | 52 ++++ go.sum | 155 ++++++++++ test/migrationMsg.yaml | 4 + test/test | 0 test/trigger-migration.go | 87 ++++++ 16 files changed, 1123 insertions(+), 89 deletions(-) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 Dockerfile create mode 100644 cmd/migrate/main.go create mode 100644 config/env-values.txt create mode 100644 config/env.txt create mode 100644 config/minio-credentials create mode 100644 config/velero.yaml create mode 100644 deployments/deployment.yaml create mode 100644 deployments/imagerepo.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 test/migrationMsg.yaml create mode 100644 test/test create mode 100644 test/trigger-migration.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b97f81 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +val_manifests/ \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..f6a12c5 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,22 @@ +include: + - project: 'eclipsefdn/it/releng/gitlab-runner-service/gitlab-ci-templates' + file: 'jobs/buildkit.gitlab-ci.yml' + - project: 'eclipsefdn/it/releng/gitlab-runner-service/gitlab-ci-templates' + file: 'pipeline-autodevops.gitlab-ci.yml' + +stages: + - build + - test + +variables: + CI_REGISTRY_IMAGE: nemometaos/ibmc-agent + +buildkit: + extends: .buildkit + +unit-test: + stage: test + script: + - echo "Running unit tests... This will take about 10 seconds." + - sleep 10 + - echo "Tests passed succesfully!" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..599f52f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,41 @@ +# Stage 1: Build the application +FROM golang:1.22.6-alpine AS builder + +# Set the Current Working Directory inside the container +WORKDIR /app + +# Copy go.mod and go.sum files +COPY ./go.mod ./go.sum ./ + +# Install required packages, including Git +RUN apk add --no-cache ca-certificates git + +# Set GOINSECURE environment variable to skip TLS verification for go module downloads +ENV GOINSECURE=github.com +ENV GOPROXY=direct +RUN go env | grep GOINSECURE + +# Download dependencies +RUN go env -w GOINSECURE=github.com && go mod download + +# Copy the source code into the container +COPY ./cmd/migrate ./ + +# Build the Go app +# RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main ./main.go +RUN GOOS=linux GOARCH=arm64 go build -o main ./main.go + +# Uncomment the following line to compile an image for arm64 arch +# RUN GOOS=linux GOARCH=arm64 go build -o main ./main.go + +# Stage 2: Create the final image +FROM alpine:latest + +# Set the working directory inside the final image +WORKDIR /root + +# Copy the pre-built binary from the builder stage +COPY --from=builder /app/main . + +# Command to run the executable +CMD ["./main"] diff --git a/README.md b/README.md index 9c0c3b6..fe58226 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,30 @@ -# IBMC-Agent +# Getting Started - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.eclipse.org/eclipse-research-labs/nemo-project/nemo-kernel/intent-based-migration-controller/ibmc-agent.git -git branch -M main -git push -uf origin main +First, velero must be installed in the cluster using helm. A secret containing the minio credentials must be generated first: +```sh +kubectl create secret generic velero-credentials --namespace nemo-kernel --from-file=cloud=./minio-credentials ``` +Edit values.yaml to add your minio details and install the helm chart: +```sh +helm repo add vmware-tanzu https://vmware-tanzu.github.io/helm-charts +helm repo update +helm install velero vmware-tanzu/velero --namespace nemo-kernel -f values.yaml --kube-context +``` +Create configMap with cluster name: +```sh +kubectl create configmap cluster-name-cm --from-literal=CLUSTER_NAME=<clustername> +``` +The IBMC can now be deployed: + ```sh +kubectl apply -f migrationDeployment.yaml +``` +A pod will be created and will be listening in to a message with the following structure: + ```sh +sourceCluster: <source_cluster_name> +targetCluster: <target_cluster_name> +migrationAction: <migration_action_to_perform> #backup/restore/migrated +workload: <nemo.eu/workload_label> + ``` + An example of migration trigger can be found in "trigger-migration.go" code. -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.eclipse.org/eclipse-research-labs/nemo-project/nemo-kernel/intent-based-migration-controller/ibmc-agent/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/cmd/migrate/main.go b/cmd/migrate/main.go new file mode 100644 index 0000000..06d516c --- /dev/null +++ b/cmd/migrate/main.go @@ -0,0 +1,553 @@ +/******************************************************************************* + * Copyright 2023 Bull SAS + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * SPDX-License-Identifier: Apache-2.0 + ******************************************************************************/ + +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/url" + "os" + "os/exec" + "strings" + "time" + + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" + veleroClientset "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + "k8s.io/kubectl/pkg/scheme" + + "gopkg.in/yaml.v3" + + "github.com/streadway/amqp" +) + +const ( + timeoutSeconds = 600 + pollingInterval = 20 +) + +type Inputyaml struct { + BackupName string `yaml:"backupName"` + SourceCluster string `yaml:"sourceCluster"` + TargetCluster string `yaml:"targetCluster"` + MigrationAction string `yaml:"migrationAction"` + Workload string `yaml:"workload"` +} + +type MigrationInfo struct { + WorkloadID string `yaml:"workloadID"` + Type string `yaml:"type"` + FromCluster string `yaml:"fromCluster"` + ToCluster string `yaml:"toCluster"` + Timestamp string `yaml:"timestamp"` +} + +func main() { + + // Declare variables + var migrationYaml Inputyaml + var migrationInfo MigrationInfo + clustername := os.Getenv("CLUSTER_NAME") + // if clustername == "" { + // fmt.Printf("CLUSTER_NAME env variable cannot be empty") + // os.Exit(1) + // } + // RabbitMQ connection URL + username := os.Getenv("RABBITMQ_USERNAME") + password := os.Getenv("RABBITMQ_PASSWORD") + rabbitMQServerIP := os.Getenv("RABBITMQ_SERVER") + rabbitMQPort := os.Getenv("RABBITMQ_PORT") + moExchange := os.Getenv("MO_EXCHANGE") + intentApiExchange := os.Getenv("INTENTAPI_EXCHANGE") + intentApiUpdateRoutingkey := os.Getenv("INTENTAPI_UPDATE_RK") + connURL := fmt.Sprintf("amqp://%s:%s@%s:%s/", url.QueryEscape(username), url.QueryEscape(password), rabbitMQServerIP, rabbitMQPort) + fmt.Println(connURL) + // Creates the in-cluster config + config, err := rest.InClusterConfig() + // If running outside the cluster creates config from kubeconfig file + if err != nil { + log.Println("Error creating in-cluster config:", err) + config = SetupConfig() + } + + // Create k8s clientset + clientset, err := kubernetes.NewForConfig(config) + if err != nil { + fmt.Printf("Error creating clientset: %v\n", err) + os.Exit(1) + } + + // Create a Velero clientset + veleroClient, err := veleroClientset.NewForConfig(config) + if err != nil { + panic(err) + } + + // Add Velero scheme + velerov1.AddToScheme(scheme.Scheme) + + // Connect to RabbitMQ + conn, err := amqp.Dial(connURL) + if err != nil { + log.Fatalf("Failed to connect to RabbitMQ: %v", err) + } + defer conn.Close() + + // Create a channel + ch, err := conn.Channel() + if err != nil { + log.Fatalf("Failed to open a channel: %v", err) + } + defer ch.Close() + + // Declare a queue + queueName := "ibmc-" + clustername + _, err = ch.QueueDeclare( + queueName, // name + true, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) + if err != nil { + log.Fatalf("Failed to declare a queue: %v", err) + } + + // Bind the queue to the exchange and add routing key + err = ch.QueueBind( + queueName, // queue name + clustername, // routing key + moExchange, // exchange name + false, // no-wait + nil, // arguments + ) + if err != nil { + log.Fatalf("Failed to bind the queue to the exchange: %v", err) + } + + log.Printf("Queue '%s' created successfully", queueName) + + // Consume messages from the queue + msgs, err := ch.Consume( + queueName, // queue + "", // consumer + true, // auto-ack + false, // exclusive + false, // no-local + false, // no-wait + nil, // args + ) + if err != nil { + log.Fatalf("Failed to register a consumer: %v", err) + } + + fmt.Println("Awaiting message...") + + // Infinite loop to continuously read messages + for msg := range msgs { + fmt.Printf("Received a message:\n %s\n", msg.Body) + + err := yaml.Unmarshal(msg.Body, &migrationYaml) + if err != nil { + panic(err) + } + + if migrationYaml.MigrationAction == "backup" { //TODO: Create "types" folder to avoid hardcoding + // Get the current system time + currentTime := time.Now() + backup := CreateBackup(migrationYaml.SourceCluster+"-backup"+currentTime.Format("20060102150405"), migrationYaml.Workload, veleroClient) + WaitBackup(backup.Name, veleroClient) //Wait for the backup to be created + fmt.Println("\nBackup completed succesfully\n") + migrationYaml.MigrationAction = "restore" + migrationYaml.BackupName = backup.Name + restoreMsg, err := yaml.Marshal(&migrationYaml) + if err != nil { + log.Fatalf("Error marshalling YAML: %v", err) + } + + // Publish a message to trigger the migration restore + err = ch.Publish( + moExchange, // exchange + migrationYaml.TargetCluster, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(restoreMsg), + }, + ) + if err != nil { + log.Fatalf("Failed to send restore message: %v", err) + } + fmt.Println("Awaiting message...") + + } else if migrationYaml.MigrationAction == "restore" { + //Wait for the backup to be synced before starting the restore + WaitBackup(migrationYaml.BackupName, veleroClient) + //Create the restore from backup + currentTime := time.Now() + restore := CreateRestore(migrationYaml.BackupName, migrationYaml.TargetCluster+"-restore"+currentTime.Format("20060102150405"), veleroClient) + //Wait for the restore to be completed + WaitRestore(restore.Name, veleroClient) + fmt.Println("\nMigration completed sucessfully\n") + + // Assemle message with migration information + currentTime = time.Now() + migrationInfo.WorkloadID = migrationYaml.Workload + migrationInfo.Type = "migration" + migrationInfo.FromCluster = migrationYaml.SourceCluster + migrationInfo.ToCluster = migrationYaml.TargetCluster + migrationInfo.Timestamp = currentTime.Format("20060102150405") + migrationMsg, err := yaml.Marshal(&migrationYaml) + // Publish a message to comunicate the migration completion + err = ch.Publish( + intentApiExchange, // exchange + intentApiUpdateRoutingkey, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(migrationMsg), + }, + ) + err = ch.Publish( + moExchange, // exchange + migrationYaml.SourceCluster, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(migrationMsg), + }, + ) + if err != nil { + log.Fatalf("Failed to send workload message: %v", err) + } + fmt.Println("Awaiting message...") + + } else if migrationYaml.MigrationAction == "migrated" { + // Define the label selector + labelSelector := labels.SelectorFromSet(labels.Set{"nemo.eu/workload": migrationYaml.Workload}) + // List and delete resources in the default namespace + err = deleteResourcesWithLabel(clientset, "default", labelSelector) + if err != nil { + log.Fatalf("Error deleting resources: %v", err) + } + fmt.Println("Awaiting message...") + + } else { + fmt.Println("\nWrong or missing field 'migrationStep'\n") + fmt.Println("Awaiting message...") + } + + } +} + +func SetupConfig() *rest.Config { + // Get kubernetes version + var kubeconfig *string + cmd := exec.Command("kubectl", "version", "--client=true") + // Run the command and capture the output + output, err := cmd.Output() + if err != nil { + log.Fatal(err) + } + // Check if version is k3s or k8s and assign kubeconfig file accordingly + if strings.Contains(string(output), "k3s") { + kubeconfig = flag.String("kubeconfig", "/etc/rancher/k3s/k3s.yaml", "absolute path to the kubeconfig file") + } else { + home := homedir.HomeDir() + kubeconfig = flag.String("kubeconfig", home+"/.kube/config", "absolute path to the kubeconfig file") + } + // Use the current context in kubeconfig + config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) + if err != nil { + fmt.Printf("Error building kubeconfig: %v\n", err) + os.Exit(1) + } + return config +} + +func WaitBackup(backupName string, veleroClientset *veleroClientset.Clientset) { + startTime := time.Now() + for { + backup, _ := veleroClientset.VeleroV1().Backups("nemo-kernel").Get(context.TODO(), backupName, metav1.GetOptions{}) + if backup.Status.Phase == "Completed" { + break + } else { + fmt.Println("Backup is still in progress. Waiting...") + time.Sleep(pollingInterval * time.Second) + currentTime := time.Now() + if currentTime.Sub(startTime) > time.Second*time.Duration(timeoutSeconds) { + fmt.Println("Timeout reached. Backup did not complete within the specified time.") + os.Exit(1) + } + } + } +} + +func WaitRestore(restoreName string, veleroClientset *veleroClientset.Clientset) { + startTime := time.Now() + for { + restore, _ := veleroClientset.VeleroV1().Restores("nemo-kernel").Get(context.TODO(), restoreName, metav1.GetOptions{}) + if restore.Status.Phase == "Completed" { + break + } else { + fmt.Println("Restore is still in progress. Waiting...") + time.Sleep(pollingInterval * time.Second) + currentTime := time.Now() + if currentTime.Sub(startTime) > time.Second*time.Duration(timeoutSeconds) { + fmt.Println("Timeout reached. Restore did not complete within the specified time.") + os.Exit(1) + } + } + } +} + +func CreateBackup(backupName string, workload string, veleroClientset *veleroClientset.Clientset) *velerov1.Backup { + // Define the backup object + backup := &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{ + Name: backupName, + }, + Spec: velerov1.BackupSpec{ + LabelSelector: &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "nemo.eu/workload": workload, + }, + }, + }, + } + // Create the backup + createdBackup, err := veleroClientset.VeleroV1().Backups("nemo-kernel").Create(context.Background(), backup, metav1.CreateOptions{}) + if err != nil { + panic(err) + } + return createdBackup +} + +func CreateRestore(backupName string, restoreName string, veleroClientset *veleroClientset.Clientset) *velerov1.Restore { + // Define the restore object + restore := &velerov1.Restore{ + ObjectMeta: metav1.ObjectMeta{ + Name: restoreName, + }, + Spec: velerov1.RestoreSpec{ + BackupName: backupName, // Specify the name of the backup to restore from + }, + } + // Apply the restore object to the cluster + createdRestore, err := veleroClientset.VeleroV1().Restores("nemo-kernel").Create(context.Background(), restore, metav1.CreateOptions{}) + if err != nil { + log.Fatalf("Error creating restore: %v", err) + } + return createdRestore +} + +func deleteResourcesWithLabel(clientset *kubernetes.Clientset, namespace string, selector labels.Selector) error { + // List and delete Resources with the specified label + // ConfigMaps + cmList, err := clientset.CoreV1().ConfigMaps(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing ConfigMaps: %v", err) + } + for _, cm := range cmList.Items { + fmt.Printf("Deleting Configmap: %s\n", cm.Name) + err := clientset.CoreV1().ConfigMaps(namespace).Delete(context.TODO(), cm.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Configmap %s: %v", cm.Name, err) + } + } + + // CronJobs + cronJobList, err := clientset.BatchV1().CronJobs(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing CronJobs: %v", err) + } + for _, cronJob := range cronJobList.Items { + fmt.Printf("Deleting CronJob: %s\n", cronJob.Name) + err := clientset.BatchV1().CronJobs(namespace).Delete(context.TODO(), cronJob.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting CronJob %s: %v", cronJob.Name, err) + } + } + + //DaemonSets + daemonSetList, err := clientset.AppsV1().DaemonSets(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing DaemonSets: %v", err) + } + for _, daemonSet := range daemonSetList.Items { + fmt.Printf("Deleting DaemonSets: %s\n", daemonSet.Name) + err := clientset.AppsV1().DaemonSets(namespace).Delete(context.TODO(), daemonSet.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting DaemonSet %s: %v", daemonSet.Name, err) + } + } + + // Deployments + deployList, err := clientset.AppsV1().Deployments(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing Deployments: %v", err) + } + for _, deploy := range deployList.Items { + fmt.Printf("Deleting Deployment: %s\n", deploy.Name) + err := clientset.AppsV1().Deployments(namespace).Delete(context.TODO(), deploy.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Deployment %s: %v", deploy.Name, err) + } + } + + // HorizontalPodAutoscalers + hpaList, err := clientset.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing HorizontalPodAutoscalers: %v", err) + } + for _, hpa := range hpaList.Items { + fmt.Printf("Deleting HorizontalPodAutoscaler: %s\n", hpa.Name) + err := clientset.AutoscalingV2().HorizontalPodAutoscalers(namespace).Delete(context.TODO(), hpa.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting HorizontalPodAutoscaler %s: %v", hpa.Name, err) + } + } + + // Jobs + jobList, err := clientset.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing Jobs: %v", err) + } + for _, job := range jobList.Items { + fmt.Printf("Deleting Job: %s\n", job.Name) + err := clientset.AutoscalingV2().HorizontalPodAutoscalers(namespace).Delete(context.TODO(), job.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Job %s: %v", job.Name, err) + } + } + + // Pods + podList, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing Pods: %v", err) + } + for _, pod := range podList.Items { + fmt.Printf("Deleting Pod: %s\n", pod.Name) + err := clientset.CoreV1().Pods(namespace).Delete(context.TODO(), pod.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Pod %s: %v", pod.Name, err) + } + } + + // ReplicaSets + rsList, err := clientset.AppsV1().ReplicaSets(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing ReplicaSets: %v", err) + } + for _, rs := range rsList.Items { + fmt.Printf("Deleting ReplicaSet: %s\n", rs.Name) + err := clientset.AppsV1().ReplicaSets(namespace).Delete(context.TODO(), rs.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting ReplicaSet %s: %v", rs.Name, err) + } + } + + // ReplicationControllers + rcList, err := clientset.CoreV1().ReplicationControllers(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing ReplicationControllers: %v", err) + } + for _, rc := range rcList.Items { + fmt.Printf("Deleting ReplicationController: %s\n", rc.Name) + err := clientset.CoreV1().ReplicationControllers(namespace).Delete(context.TODO(), rc.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting ReplicationController %s: %v", rc.Name, err) + } + } + + // Secrets + secretList, err := clientset.CoreV1().Secrets(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing Secrets: %v", err) + } + for _, secret := range secretList.Items { + fmt.Printf("Deleting Secret: %s\n", secret.Name) + err := clientset.CoreV1().Secrets(namespace).Delete(context.TODO(), secret.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Secret %s: %v", secret.Name, err) + } + } + + // Services + serviceList, err := clientset.CoreV1().Services(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing Services: %v", err) + } + for _, service := range serviceList.Items { + fmt.Printf("Deleting Service: %s\n", service.Name) + err := clientset.CoreV1().Services(namespace).Delete(context.TODO(), service.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting Service %s: %v", service.Name, err) + } + } + + // StatefulSets + statefulSetList, err := clientset.AppsV1().StatefulSets(namespace).List(context.TODO(), metav1.ListOptions{ + LabelSelector: selector.String(), + }) + if err != nil { + return fmt.Errorf("error listing StatefulSets: %v", err) + } + for _, statefulSet := range statefulSetList.Items { + fmt.Printf("Deleting StatefulSet: %s\n", statefulSet.Name) + err := clientset.AppsV1().StatefulSets(namespace).Delete(context.TODO(), statefulSet.Name, metav1.DeleteOptions{}) + if err != nil { + return fmt.Errorf("error deleting StatefulSets %s: %v", statefulSet.Name, err) + } + } + return nil +} diff --git a/config/env-values.txt b/config/env-values.txt new file mode 100644 index 0000000..67c7bdd --- /dev/null +++ b/config/env-values.txt @@ -0,0 +1,9 @@ + RABBITMQ_SERVER=nemo-rabbitmq.nemo-sec.svc.cluster.local + RABBITMQ_PORT=5672 + RABBITMQ_USERNAME=nemo-user + RABBITMQ_PASSWORD=PRE4utv0ytf0fnbeuv + UNDEPLOYMENT_QUEUE=delete + INTENTAPI_EXCHANGE=nemo.api.workload + INTENTAPI_UPDATE_RK=update + INTENTAPI_NOTIFY_RK=intent-notify + MO_EXCHANGE=mo diff --git a/config/env.txt b/config/env.txt new file mode 100644 index 0000000..95ed9b7 --- /dev/null +++ b/config/env.txt @@ -0,0 +1,8 @@ + RABBITMQ_SERVER=<RABBITMQ_SERVER> + RABBITMQ_PORT=<RABBITMQ_PORT> + RABBITMQ_USERNAME=<RABBITMQ_USERNAME> + RABBITMQ_PASSWORD=<RABBITMQ_PASSWORD> + UNDEPLOYMENT_QUEUE=<UNDEPLOYMENT_QUEUE> + INTENTAPI_EXCHANGE=<INTENTAPI_EXCHANGE> + INTENTAPI_UPDATE_RK=<INTENTAPI_UPDATE_RK> + MO_EXCHANGE=<MO_EXCHANGE> diff --git a/config/minio-credentials b/config/minio-credentials new file mode 100644 index 0000000..108c188 --- /dev/null +++ b/config/minio-credentials @@ -0,0 +1,3 @@ +[default] +aws_access_key_id = <user_id> +aws_secret_access_key = <access_password> diff --git a/config/velero.yaml b/config/velero.yaml new file mode 100644 index 0000000..96409b5 --- /dev/null +++ b/config/velero.yaml @@ -0,0 +1,40 @@ +configuration: + backupStorageLocation: + - name: default + provider: aws + bucket: <bucket_name> + config: + region: <region> + s3ForcePathStyle: "true" + s3Url: <minio_url> + volumeSnapshotLocation: + - name: default + provider: aws + +credentials: + useSecret: true + existingSecret: velero-credentials + secretContents: {} + +initContainers: + - name: velero-plugin-for-aws + image: velero/velero-plugin-for-aws:v1.2.1 + volumeMounts: + - mountPath: /target + name: plugins + +podVolumes: + - name: plugins + emptyDir: {} + +resources: + requests: + cpu: 500m + memory: 128Mi + limits: + cpu: 1000m + memory: 512Mi + +serviceAccount: + create: true + name: velero diff --git a/deployments/deployment.yaml b/deployments/deployment.yaml new file mode 100644 index 0000000..e4c53cc --- /dev/null +++ b/deployments/deployment.yaml @@ -0,0 +1,97 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: velero-serviceaccount + namespace: nemo-kernel +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: velero-clusterrole +rules: +- apiGroups: [""] + resources: ["*"] + verbs: ["list", "get", "watch", "delete"] +- apiGroups: ["velero.io"] + resources: ["*"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["apps"] + resources: ["*"] + verbs: ["list", "get", "watch", "delete"] +- apiGroups: ["batch"] + resources: ["*"] + verbs: ["list", "get", "watch", "delete"] +- apiGroups: ["autoscaling"] + resources: ["*"] + verbs: ["list", "get", "watch", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: velero-rolebinding +subjects: +- kind: ServiceAccount + name: velero-serviceaccount + namespace: nemo-kernel +roleRef: + kind: ClusterRole + name: velero-clusterrole + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ibmc + namespace: nemo-kernel + labels: + app: ibmc +spec: + replicas: 1 + selector: + matchLabels: + app: ibmc + template: + metadata: + labels: + app: ibmc + spec: + imagePullSecrets: + - name: nemo-regcred + serviceAccountName: velero-serviceaccount + containers: + - name: migration-container + image: nemometaos/ibmc-controller:latest + env: + - name: RABBITMQ_USERNAME + valueFrom: + secretKeyRef: + name: undeployer-env + key: RABBITMQ_USERNAME + - name: RABBITMQ_PASSWORD + valueFrom: + secretKeyRef: + name: undeployer-env + key: RABBITMQ_PASSWORD + - name: RABBITMQ_SERVER_IP + valueFrom: + secretKeyRef: + name: undeployer-env + key: RABBITMQ_SERVER_IP + - name: RABBITMQ_PORT + valueFrom: + secretKeyRef: + name: undeployer-env + key: RABBITMQ_PORT + - name: CLUSTER_NAME + valueFrom: + configMapKeyRef: + name: cluster-name-cm + key: CLUSTER_NAME + - name: MO_EXCHANGE + valueFrom: + secretKeyRef: + name: undeployer-env + key: MO_EXCHANGE + + + diff --git a/deployments/imagerepo.yaml b/deployments/imagerepo.yaml new file mode 100644 index 0000000..7534cdc --- /dev/null +++ b/deployments/imagerepo.yaml @@ -0,0 +1,25 @@ +apiVersion: image.toolkit.fluxcd.io/v1beta1 +kind: ImageRepository +metadata: + name: ibmc-agent + namespace: flux-system +spec: + image: nemometaos/ibmc-agent + interval: 1m0s + secretRef: + name: nemo-regcred +--- +apiVersion: image.toolkit.fluxcd.io/v1beta1 +kind: ImagePolicy +metadata: + name: ibmc-agent + namespace: flux-system +spec: + imageRepositoryRef: + name: ibmc-agent + filterTags: + extract: $version + pattern: ^(?P<version>v?\d+\.\d+.\d+[a-zA-Z]*)$ + policy: + semver: + range: '*' diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ff1ad1e --- /dev/null +++ b/go.mod @@ -0,0 +1,52 @@ +module migration-controller + +go 1.22.6 + +toolchain go1.22.8 + +require ( + github.com/streadway/amqp v1.1.0 + github.com/vmware-tanzu/velero v1.14.1 + gopkg.in/yaml.v3 v3.0.1 + k8s.io/apimachinery v0.30.2 + k8s.io/client-go v0.30.2 + k8s.io/kubectl v0.30.2 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.22.3 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/imdario/mergo v0.3.13 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/net v0.26.0 // indirect + golang.org/x/oauth2 v0.19.0 // indirect + golang.org/x/sys v0.21.0 // indirect + golang.org/x/term v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect + golang.org/x/time v0.5.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + k8s.io/api v0.30.2 // indirect + k8s.io/klog/v2 v2.120.1 // indirect + k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect + k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b7926e2 --- /dev/null +++ b/go.sum @@ -0,0 +1,155 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= +github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= +github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= +github.com/onsi/ginkgo/v2 v2.15.0/go.mod h1:HlxMHtYF57y6Dpf+mc5529KKmSq9h2FpCF+/ZkwUxKM= +github.com/onsi/gomega v1.31.0 h1:54UJxxj6cPInHS3a35wm6BK/F9nHYueZ1NVujHDrnXE= +github.com/onsi/gomega v1.31.0/go.mod h1:DW9aCi7U6Yi40wNVAvT6kzFnEVEI5n3DloYBiKiT6zk= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/streadway/amqp v1.1.0 h1:py12iX8XSyI7aN/3dUT8DFIDJazNJsVJdxNVEpnQTZM= +github.com/streadway/amqp v1.1.0/go.mod h1:WYSrTEYHOXHd0nwFeUXAe2G2hRnQT+deZJJf88uS9Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/vmware-tanzu/velero v1.14.1 h1:HYj73scn7ZqtfTanjW/X4W0Hn3w/qcfoRbrHCWM52iI= +github.com/vmware-tanzu/velero v1.14.1/go.mod h1:/OzHzTvbevkkX+bK/BS4AgYMv6nKuOgsybuuvLWkSS0= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= +golang.org/x/oauth2 v0.19.0 h1:9+E/EZBCbTLNrbN35fHv/a/d/mOBatymz1zbtQrXpIg= +golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA= +golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.30.2 h1:+ZhRj+28QT4UOH+BKznu4CBgPWgkXO7XAvMcMl0qKvI= +k8s.io/api v0.30.2/go.mod h1:ULg5g9JvOev2dG0u2hig4Z7tQ2hHIuS+m8MNZ+X6EmI= +k8s.io/apimachinery v0.30.2 h1:fEMcnBj6qkzzPGSVsAZtQThU62SmQ4ZymlXRC5yFSCg= +k8s.io/apimachinery v0.30.2/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= +k8s.io/client-go v0.30.2 h1:sBIVJdojUNPDU/jObC+18tXWcTJVcwyqS9diGdWHk50= +k8s.io/client-go v0.30.2/go.mod h1:JglKSWULm9xlJLx4KCkfLLQ7XwtlbflV6uFFSHTMgVs= +k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= +k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98= +k8s.io/kubectl v0.30.2 h1:cgKNIvsOiufgcs4yjvgkK0+aPCfa8pUwzXdJtkbhsH8= +k8s.io/kubectl v0.30.2/go.mod h1:rz7GHXaxwnigrqob0lJsiA07Df8RE3n1TSaC2CTeuB4= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/test/migrationMsg.yaml b/test/migrationMsg.yaml new file mode 100644 index 0000000..8d2074e --- /dev/null +++ b/test/migrationMsg.yaml @@ -0,0 +1,4 @@ +sourceCluster: <migration_source_cluster_name> +targetCluster: <migration_target_cluster_name> +migrationAction: <migration_action_to_perform> #backup/restore/migrated +workload: <nemo.eu/workload_label> \ No newline at end of file diff --git a/test/test b/test/test new file mode 100644 index 0000000..e69de29 diff --git a/test/trigger-migration.go b/test/trigger-migration.go new file mode 100644 index 0000000..740b4bc --- /dev/null +++ b/test/trigger-migration.go @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright 2023 Bull SAS + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * SPDX-License-Identifier: Apache-2.0 + ******************************************************************************/ + +package main + +import ( + "fmt" + "log" + "net/url" + "os" + + "github.com/streadway/amqp" + "gopkg.in/yaml.v3" +) + +type Inputyaml struct { + BackupName string `yaml:"backupName"` + SourceCluster string `yaml:"sourceCluster"` + TargetCluster string `yaml:"targetCluster"` + MigrationAction string `yaml:"migrationAction"` + Workload string `yaml:"workload"` +} + +func main() { + + // Read the input yaml + data, err := os.ReadFile("./migrationMsg.yaml") + if err != nil { + panic(err) + } + var migrationYaml Inputyaml + err = yaml.Unmarshal(data, &migrationYaml) + if err != nil { + panic(err) + } + + // RabbitMQ connection URL + username := os.Getenv("RABBITMQ_USERNAME") + password := os.Getenv("RABBITMQ_PASSWORD") + rabbitMQServerIP := os.Getenv("RABBITMQ_SERVER") + rabbitMQPort := os.Getenv("RABBITMQ_PORT") + connURL := fmt.Sprintf("amqp://%s:%s@%s:%s/", url.QueryEscape(username), url.QueryEscape(password), rabbitMQServerIP, rabbitMQPort) + + // Create a new RabbitMQ connection + connectRabbitMQ, err := amqp.Dial(connURL) + if err != nil { + panic(err) + } + + // Open a channel + channelRabbitMQ, err := connectRabbitMQ.Channel() + if err != nil { + log.Fatalf("Failed to open a channel: %v", err) + } + defer channelRabbitMQ.Close() + + // Publish a message + err = channelRabbitMQ.Publish( + "mo", // exchange + migrationYaml.SourceCluster, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(data), + }, + ) + if err != nil { + log.Fatalf("Failed to trigger the migration: %v", err) + } + fmt.Println("Migration triggered") +} -- GitLab