|
| 1 | +/* |
| 2 | +Copyright 2022 The KubeVela Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package cmd |
| 18 | + |
| 19 | +import ( |
| 20 | + "bytes" |
| 21 | + "compress/gzip" |
| 22 | + "context" |
| 23 | + "fmt" |
| 24 | + "log" |
| 25 | + "os" |
| 26 | + "os/exec" |
| 27 | + "path/filepath" |
| 28 | + |
| 29 | + "github.com/oam-dev/terraform-controller/api/v1beta2" |
| 30 | + "github.com/oam-dev/terraform-controller/controllers/configuration/backend" |
| 31 | + "github.com/spf13/cobra" |
| 32 | + v1 "k8s.io/api/core/v1" |
| 33 | + kerrors "k8s.io/apimachinery/pkg/api/errors" |
| 34 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 35 | + "k8s.io/apimachinery/pkg/runtime" |
| 36 | + "k8s.io/apimachinery/pkg/runtime/serializer/json" |
| 37 | + "k8s.io/cli-runtime/pkg/genericclioptions" |
| 38 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 39 | +) |
| 40 | + |
| 41 | +var ( |
| 42 | + stateJSONPath string |
| 43 | + configurationPath string |
| 44 | + k8sClient client.Client |
| 45 | +) |
| 46 | + |
| 47 | +// newRestoreCmd represents the restore command |
| 48 | +func newRestoreCmd(kubeFlags *genericclioptions.ConfigFlags) *cobra.Command { |
| 49 | + restoreCmd := &cobra.Command{ |
| 50 | + Use: "restore", |
| 51 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 52 | + var err error |
| 53 | + k8sClient, err = buildClientSet(kubeFlags) |
| 54 | + if err != nil { |
| 55 | + return err |
| 56 | + } |
| 57 | + pwd, err := os.Getwd() |
| 58 | + if err != nil { |
| 59 | + return err |
| 60 | + } |
| 61 | + stateJSONPath = filepath.Join(pwd, stateJSONPath) |
| 62 | + configurationPath = filepath.Join(pwd, configurationPath) |
| 63 | + return restore(context.Background()) |
| 64 | + }, |
| 65 | + } |
| 66 | + restoreCmd.Flags().StringVar(&stateJSONPath, "state", "state.json", "the path of the backed up Terraform state file") |
| 67 | + restoreCmd.Flags().StringVar(&configurationPath, "configuration", "configuration.yaml", "the path of the backed up configuration objcet yaml file") |
| 68 | + return restoreCmd |
| 69 | +} |
| 70 | + |
| 71 | +func buildClientSet(kubeFlags *genericclioptions.ConfigFlags) (client.Client, error) { |
| 72 | + config, err := kubeFlags.ToRESTConfig() |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + return client.New(config, client.Options{}) |
| 77 | +} |
| 78 | + |
| 79 | +func restore(ctx context.Context) error { |
| 80 | + configuration, err := getConfiguration() |
| 81 | + if err != nil { |
| 82 | + return err |
| 83 | + } |
| 84 | + backendInterface, err := backend.ParseConfigurationBackend(configuration, k8sClient) |
| 85 | + if err != nil { |
| 86 | + return err |
| 87 | + } |
| 88 | + |
| 89 | + // restore the backend |
| 90 | + if err := resumeK8SBackend(ctx, backendInterface); err != nil { |
| 91 | + return err |
| 92 | + } |
| 93 | + |
| 94 | + // apply the configuration yaml |
| 95 | + // FIXME (loheagn) use the restClient to do this |
| 96 | + applyCmd := exec.Command("bash", "-c", fmt.Sprintf("kubectl apply -f %s", configurationPath)) |
| 97 | + if err := applyCmd.Run(); err != nil { |
| 98 | + return err |
| 99 | + } |
| 100 | + return nil |
| 101 | +} |
| 102 | + |
| 103 | +func getConfiguration() (*v1beta2.Configuration, error) { |
| 104 | + configurationYamlBytes, err := os.ReadFile(configurationPath) |
| 105 | + if err != nil { |
| 106 | + return nil, err |
| 107 | + } |
| 108 | + configuration := &v1beta2.Configuration{} |
| 109 | + scheme := runtime.NewScheme() |
| 110 | + serializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme, scheme, json.SerializerOptions{Yaml: true}) |
| 111 | + if _, _, err := serializer.Decode(configurationYamlBytes, nil, configuration); err != nil { |
| 112 | + return nil, err |
| 113 | + } |
| 114 | + return configuration, nil |
| 115 | +} |
| 116 | + |
| 117 | +func resumeK8SBackend(ctx context.Context, backendInterface backend.Backend) error { |
| 118 | + k8sBackend, ok := backendInterface.(*backend.K8SBackend) |
| 119 | + if !ok { |
| 120 | + log.Println("the configuration doesn't use the kubernetes backend, no need to restore the Terraform state") |
| 121 | + return nil |
| 122 | + } |
| 123 | + |
| 124 | + tfState, err := compressedTFState() |
| 125 | + if err != nil { |
| 126 | + return err |
| 127 | + } |
| 128 | + |
| 129 | + var gotSecret v1.Secret |
| 130 | + |
| 131 | + configureSecret := func() { |
| 132 | + if gotSecret.Annotations == nil { |
| 133 | + gotSecret.Annotations = make(map[string]string) |
| 134 | + } |
| 135 | + gotSecret.Annotations["encoding"] = "gzip" |
| 136 | + |
| 137 | + if gotSecret.Labels == nil { |
| 138 | + gotSecret.Labels = make(map[string]string) |
| 139 | + } |
| 140 | + gotSecret.Labels["app.kubernetes.io/managed-by"] = "terraform" |
| 141 | + gotSecret.Labels["tfstate"] = "true" |
| 142 | + gotSecret.Labels["tfstateSecretSuffix"] = k8sBackend.SecretSuffix |
| 143 | + gotSecret.Labels["tfstateWorkspace"] = "default" |
| 144 | + |
| 145 | + gotSecret.Type = v1.SecretTypeOpaque |
| 146 | + } |
| 147 | + |
| 148 | + if err := k8sClient.Get(ctx, client.ObjectKey{Name: "tfstate-default-" + k8sBackend.SecretSuffix, Namespace: k8sBackend.SecretNS}, &gotSecret); err != nil { |
| 149 | + if !kerrors.IsNotFound(err) { |
| 150 | + return err |
| 151 | + } |
| 152 | + // is not found, create the secret |
| 153 | + gotSecret = v1.Secret{ |
| 154 | + ObjectMeta: metav1.ObjectMeta{ |
| 155 | + Name: "tfstate-default-" + k8sBackend.SecretSuffix, |
| 156 | + Namespace: k8sBackend.SecretNS, |
| 157 | + }, |
| 158 | + Type: v1.SecretTypeOpaque, |
| 159 | + Data: map[string][]byte{ |
| 160 | + "tfstate": tfState, |
| 161 | + }, |
| 162 | + } |
| 163 | + configureSecret() |
| 164 | + if err := k8sClient.Create(ctx, &gotSecret); err != nil { |
| 165 | + return err |
| 166 | + } |
| 167 | + } else { |
| 168 | + // update the secret |
| 169 | + configureSecret() |
| 170 | + gotSecret.Data["tfstate"] = tfState |
| 171 | + if err := k8sClient.Update(ctx, &gotSecret); err != nil { |
| 172 | + return err |
| 173 | + } |
| 174 | + } |
| 175 | + return nil |
| 176 | +} |
| 177 | + |
| 178 | +func compressedTFState() ([]byte, error) { |
| 179 | + srcBytes, err := os.ReadFile(stateJSONPath) |
| 180 | + var buf bytes.Buffer |
| 181 | + writer := gzip.NewWriter(&buf) |
| 182 | + _, err = writer.Write(srcBytes) |
| 183 | + if err != nil { |
| 184 | + return nil, err |
| 185 | + } |
| 186 | + if err := writer.Close(); err != nil { |
| 187 | + return nil, err |
| 188 | + } |
| 189 | + return buf.Bytes(), nil |
| 190 | +} |
0 commit comments