/
state.go
232 lines (192 loc) · 7.32 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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.
package terraformer
import (
"context"
"encoding/json"
"fmt"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/gardener/gardener/pkg/controllerutils"
kubernetesutils "github.com/gardener/gardener/pkg/utils/kubernetes"
)
const (
// TerraformerFinalizer is the finalizer key set by the terraformer on the configmaps and secrets
TerraformerFinalizer = "gardener.cloud/terraformer"
)
type terraformStateV3 struct {
Modules []struct {
Outputs map[string]outputState `json:"outputs"`
} `json:"modules"`
}
type outputState struct {
Type string `json:"type"`
Value interface{} `json:"value"`
}
type terraformStateV4 struct {
Outputs map[string]outputState `json:"outputs"`
}
// GetState returns the Terraform state as byte slice.
func (t *terraformer) GetState(ctx context.Context) ([]byte, error) {
configMap := &corev1.ConfigMap{}
if err := t.client.Get(ctx, kubernetesutils.Key(t.namespace, t.stateName), configMap); err != nil {
return nil, err
}
return []byte(configMap.Data[StateKey]), nil
}
// GetStateOutputVariables returns the given <variable> from the given Terraform <stateData>.
// In case the variable was not found, an error is returned.
func (t *terraformer) GetStateOutputVariables(ctx context.Context, variables ...string) (map[string]string, error) {
var (
output = make(map[string]string)
wantedVariables = sets.New(variables...)
foundVariables = sets.New[string]()
)
stateConfigMap, err := t.GetState(ctx)
if err != nil {
return nil, err
}
if len(stateConfigMap) == 0 {
return nil, &variablesNotFoundError{sets.List(wantedVariables)}
}
outputVariables, err := getOutputVariables(stateConfigMap)
if err != nil {
return nil, err
}
for _, variable := range variables {
if outputVariable, ok := outputVariables[variable]; ok {
output[variable] = fmt.Sprint(outputVariable.Value)
foundVariables.Insert(variable)
}
}
if wantedVariables.Len() != foundVariables.Len() {
return nil, &variablesNotFoundError{sets.List(wantedVariables.Difference(foundVariables))}
}
return output, nil
}
// IsStateEmpty returns true if the Terraform state is empty and the terraformer finalizer
// is not present on any of the used configmaps and secrets. Otherwise, it returns false.
func (t *terraformer) IsStateEmpty(ctx context.Context) bool {
for _, obj := range []client.Object{
&corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: t.namespace, Name: t.configName}},
&corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: t.namespace, Name: t.stateName}},
&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: t.namespace, Name: t.variablesName}},
} {
resourceName := obj.GetName()
if err := t.client.Get(ctx, kubernetesutils.Key(t.namespace, resourceName), obj); client.IgnoreNotFound(err) != nil {
t.logger.Error(err, "Failed to get resource", "name", resourceName)
return false
}
if controllerutil.ContainsFinalizer(obj, TerraformerFinalizer) {
return false
}
}
state, err := t.GetState(ctx)
if err != nil {
return apierrors.IsNotFound(err)
}
return len(state) == 0
}
type variablesNotFoundError struct {
variables []string
}
// Error prints the error message of the variablesNotFound error.
func (e *variablesNotFoundError) Error() string {
return fmt.Sprintf("could not find all requested variables: %+v", e.variables)
}
// IsVariablesNotFoundError returns true if the error indicates that not all variables have been found.
func IsVariablesNotFoundError(err error) bool {
switch err.(type) {
case *variablesNotFoundError:
return true
}
return false
}
func getOutputVariables(stateConfigMap []byte) (map[string]outputState, error) {
version, err := sniffJSONStateVersion(stateConfigMap)
if err != nil {
return nil, err
}
var outputVariables map[string]outputState
switch {
case version == 2 || version == 3:
var state terraformStateV3
if err := json.Unmarshal(stateConfigMap, &state); err != nil {
return nil, err
}
outputVariables = state.Modules[0].Outputs
case version == 4:
var state terraformStateV4
if err := json.Unmarshal(stateConfigMap, &state); err != nil {
return nil, err
}
outputVariables = state.Outputs
default:
return nil, fmt.Errorf("the state file uses format version %d, which is not supported by Terraformer", version)
}
return outputVariables, nil
}
func sniffJSONStateVersion(stateConfigMap []byte) (uint64, error) {
type VersionSniff struct {
Version *uint64 `json:"version"`
}
var sniff VersionSniff
if err := json.Unmarshal(stateConfigMap, &sniff); err != nil {
return 0, fmt.Errorf("the state file could not be parsed as JSON: %w", err)
}
if sniff.Version == nil {
return 0, fmt.Errorf("the state file does not have a \"version\" attribute, which is required to identify the format version")
}
return *sniff.Version, nil
}
// Initialize implements StateConfigMapInitializer
func (f StateConfigMapInitializerFunc) Initialize(ctx context.Context, c client.Client, namespace, name string, ownerRef *metav1.OwnerReference) error {
return f(ctx, c, namespace, name, ownerRef)
}
// CreateState create terraform state config map and use empty state.
// It does not create or update state ConfigMap if already exists,
func CreateState(ctx context.Context, c client.Client, namespace, name string, ownerRef *metav1.OwnerReference) error {
configMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name},
Data: map[string]string{
StateKey: "",
},
}
if ownerRef != nil {
configMap.SetOwnerReferences(kubernetesutils.MergeOwnerReferences(configMap.OwnerReferences, *ownerRef))
}
return client.IgnoreAlreadyExists(c.Create(ctx, configMap))
}
// Initialize implements StateConfigMapInitializer
func (cus CreateOrUpdateState) Initialize(ctx context.Context, c client.Client, namespace, name string, ownerRef *metav1.OwnerReference) error {
if cus.State == nil {
return fmt.Errorf("missing state when creating or updating terraform state ConfigMap %s/%s", namespace, name)
}
configMap := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}}
_, err := controllerutils.GetAndCreateOrStrategicMergePatch(ctx, c, configMap, func() error {
if configMap.Data == nil {
configMap.Data = make(map[string]string)
}
configMap.Data[StateKey] = *cus.State
if ownerRef != nil {
configMap.SetOwnerReferences(kubernetesutils.MergeOwnerReferences(configMap.OwnerReferences, *ownerRef))
}
return nil
})
return err
}