forked from lightninglabs/lndinit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
254 lines (209 loc) · 6.81 KB
/
k8s.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package main
import (
"context"
"encoding/base64"
"fmt"
api "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
defaultK8sNamespace = "default"
defaultK8sResourcePolicy = "keep"
)
type k8sSecretOptions struct {
Namespace string `long:"namespace" description:"The Kubernetes namespace the secret is located in"`
SecretName string `long:"secret-name" description:"The name of the Kubernetes secret"`
SecretKeyName string `long:"secret-key-name" description:"The name of the key/entry within the secret"`
Base64 bool `long:"base64" description:"Encode as base64 when storing and decode as base64 when reading"`
}
func (s *k8sSecretOptions) AnySet() bool {
return s.Namespace != defaultK8sNamespace || s.SecretName != "" ||
s.SecretKeyName != ""
}
type helmOptions struct {
Annotate bool `long:"annotate" description:"Whether Helm annotations should be added to the created secret"`
ReleaseName string `long:"release-name" description:"The value for the meta.helm.sh/release-name annotation"`
ResourcePolicy string `long:"resource-policy" description:"The value for the helm.sh/resource-policy annotation"`
}
type jsonK8sObject struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
}
func saveK8s(content string, opts *k8sSecretOptions, overwrite bool,
helm *helmOptions) error {
client, err := getClientK8s()
if err != nil {
return err
}
secret, exists, err := getSecretK8s(
client, opts.Namespace, opts.SecretName,
)
if err != nil {
return err
}
if exists {
return updateSecretValueK8s(
client, secret, opts, overwrite, content,
)
}
return createSecretK8s(client, opts, helm, content)
}
func readK8s(opts *k8sSecretOptions) (string, *jsonK8sObject, error) {
client, err := getClientK8s()
if err != nil {
return "", nil, err
}
secret, exists, err := getSecretK8s(
client, opts.Namespace, opts.SecretName,
)
if err != nil {
return "", nil, err
}
if !exists {
return "", nil, fmt.Errorf("secret %s does not exist in "+
"namespace %s", opts.SecretName, opts.Namespace)
}
if len(secret.Data) == 0 {
return "", nil, fmt.Errorf("secret %s exists but contains no "+
"data", opts.SecretName)
}
if len(secret.Data[opts.SecretKeyName]) == 0 {
return "", nil, fmt.Errorf("secret %s exists but does not "+
"contain the key %s", opts.SecretName,
opts.SecretKeyName)
}
// There is an additional layer of base64 encoding applied to each of
// the secrets. Try to de-code it now.
content, err := secretToString(
secret.Data[opts.SecretKeyName], opts.Base64,
)
if err != nil {
return "", nil, fmt.Errorf("failed to decode raw secret %s "+
"key %s: %v", opts.SecretName, opts.SecretKeyName, err)
}
return content, &jsonK8sObject{
TypeMeta: secret.TypeMeta,
ObjectMeta: secret.ObjectMeta,
}, nil
}
func getClientK8s() (*kubernetes.Clientset, error) {
log("Creating k8s cluster config")
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("unable to grab cluster config: %v", err)
}
log("Creating k8s cluster client")
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("error creating cluster config: %v", err)
}
log("Cluster client created successfully")
return client, nil
}
func getSecretK8s(client *kubernetes.Clientset, namespace,
name string) (*api.Secret, bool, error) {
log("Attempting to load secret %s from namespace %s", name, namespace)
secret, err := client.CoreV1().Secrets(namespace).Get(
context.Background(), name, metav1.GetOptions{},
)
switch {
case err == nil:
log("Secret %s loaded successfully", name)
return secret, true, nil
case errors.IsNotFound(err):
log("Secret %s not found in namespace %s", name, namespace)
return nil, false, nil
default:
return nil, false, fmt.Errorf("error querying secret "+
"existence: %v", err)
}
}
func updateSecretValueK8s(client *kubernetes.Clientset, secret *api.Secret,
opts *k8sSecretOptions, overwrite bool, content string) error {
if len(secret.Data) == 0 {
log("Data of secret %s is empty, initializing", opts.SecretName)
secret.Data = make(map[string][]byte)
}
if len(secret.Data[opts.SecretKeyName]) > 0 && !overwrite {
return fmt.Errorf("key %s in secret %s already exists: %v",
opts.SecretKeyName, opts.SecretName,
errTargetExists)
}
// Do we need to add an extra layer of base64?
if opts.Base64 {
content = base64.StdEncoding.EncodeToString([]byte(content))
}
secret.Data[opts.SecretKeyName] = []byte(content)
log("Attempting to update key %s of secret %s in namespace %s",
opts.SecretKeyName, opts.SecretName, opts.Namespace)
updatedSecret, err := client.CoreV1().Secrets(opts.Namespace).Update(
context.Background(), secret, metav1.UpdateOptions{},
)
if err != nil {
return fmt.Errorf("error updating secret %s in namespace %s: "+
"%v", opts.SecretName, opts.Namespace, err)
}
jsonSecret, _ := asJSON(jsonK8sObject{
TypeMeta: updatedSecret.TypeMeta,
ObjectMeta: updatedSecret.ObjectMeta,
})
log("Updated secret: %s", jsonSecret)
return nil
}
func createSecretK8s(client *kubernetes.Clientset, opts *k8sSecretOptions,
helm *helmOptions, content string) error {
meta := metav1.ObjectMeta{
Name: opts.SecretName,
}
if helm != nil && helm.Annotate {
meta.Labels = map[string]string{
"app.kubernetes.io/managed-by": "Helm",
}
meta.Annotations = map[string]string{
"helm.sh/resource-policy": helm.ResourcePolicy,
"meta.helm.sh/release-name": helm.ReleaseName,
"meta.helm.sh/release-namespace": opts.Namespace,
}
}
// Do we need to add an extra layer of base64?
if opts.Base64 {
content = base64.StdEncoding.EncodeToString([]byte(content))
}
newSecret := &api.Secret{
Type: api.SecretTypeOpaque,
ObjectMeta: meta,
Data: map[string][]byte{
opts.SecretKeyName: []byte(content),
},
}
updatedSecret, err := client.CoreV1().Secrets(opts.Namespace).Create(
context.Background(), newSecret, metav1.CreateOptions{},
)
if err != nil {
return fmt.Errorf("error creating secret %s in namespace %s: "+
"%v", opts.SecretName, opts.Namespace, err)
}
jsonSecret, _ := asJSON(jsonK8sObject{
TypeMeta: updatedSecret.TypeMeta,
ObjectMeta: updatedSecret.ObjectMeta,
})
log("Created secret: %s", jsonSecret)
return nil
}
// secretToString turns the raw bytes of a secret into a string, removing the
// additional layer of base64 encoding if there is expected to be one.
func secretToString(rawSecret []byte, doubleBase64 bool) (string, error) {
content := string(rawSecret)
if doubleBase64 {
decoded, err := base64.StdEncoding.DecodeString(content)
if err != nil {
return "", fmt.Errorf("failed to base64 decode: %v",
err)
}
content = string(decoded)
}
return content, nil
}