-
Notifications
You must be signed in to change notification settings - Fork 87
/
gitops.go
435 lines (373 loc) · 12.8 KB
/
gitops.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package gitops
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/kotsadm/pkg/kotsutil"
"github.com/replicatedhq/kots/kotsadm/pkg/logger"
"github.com/replicatedhq/kots/pkg/crypto"
"golang.org/x/crypto/ssh"
"gopkg.in/src-d/go-git.v4"
go_git_config "gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
go_git_ssh "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
v1 "k8s.io/api/core/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
type GitOpsConfig struct {
Provider string `json:"provider"`
RepoURI string `json:"repoUri"`
Hostname string `json:"hostname"`
Path string `json:"path"`
Branch string `json:"branch"`
Format string `json:"format"`
Action string `json:"action"`
PublicKey string `json:"publicKey"`
PrivateKey string `json:"-"`
LastError string `json:"lastError"`
}
func (g *GitOpsConfig) CommitURL(hash string) string {
switch g.Provider {
case "github", "github_enterprise":
return fmt.Sprintf("%s/commit/%s", g.RepoURI, hash)
case "gitlab":
return fmt.Sprintf("%s/commit/%s", g.RepoURI, hash)
case "bitbucket":
return fmt.Sprintf("%s/commits/%s", g.RepoURI, hash)
default:
return fmt.Sprintf("%s/commit/%s", g.RepoURI, hash)
}
}
func (g *GitOpsConfig) CloneURL() string {
// copied this logic from node js api
// this feels incomplete and fragile.... needs enterprise support
uriParts := strings.Split(g.RepoURI, "/")
switch g.Provider {
case "github":
return fmt.Sprintf("git@github.com:%s/%s.git", uriParts[3], uriParts[4])
case "github_enterprise":
return fmt.Sprintf("git@%s:%s/%s.git", uriParts[2], uriParts[3], uriParts[4])
case "gitlab":
return fmt.Sprintf("git@gitlab.com:%s/%s.git", uriParts[3], uriParts[4])
case "bitbucket":
return fmt.Sprintf("git@bitbucket.org:%s/%s.git", uriParts[3], uriParts[4])
}
return ""
}
// GetDownstreamGitOps will return the gitops config for a downstrea,
// This implementation copies how it works in typescript.
func GetDownstreamGitOps(appID string, clusterID string) (*GitOpsConfig, error) {
cfg, err := config.GetConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to get cluster config")
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, errors.Wrap(err, "failed to create kubernetes clientset")
}
secret, err := clientset.CoreV1().Secrets(os.Getenv("POD_NAMESPACE")).Get(context.TODO(), "kotsadm-gitops", metav1.GetOptions{})
if kuberneteserrors.IsNotFound(err) {
return nil, nil
}
configMap, err := clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Get(context.TODO(), "kotsadm-gitops", metav1.GetOptions{})
if kuberneteserrors.IsNotFound(err) {
return nil, nil
}
configMapDataKey := fmt.Sprintf("%s-%s", appID, clusterID)
configMapDataEncoded, ok := configMap.Data[configMapDataKey]
if !ok {
return nil, nil
}
configMapDataDecoded, err := base64.StdEncoding.DecodeString(configMapDataEncoded)
if err != nil {
return nil, errors.Wrap(err, "failed to decode configmap data")
}
configMapData := map[string]string{}
if err := json.Unmarshal(configMapDataDecoded, &configMapData); err != nil {
return nil, errors.Wrap(err, "faield to unmarshal configmap data")
}
repoURI := configMapData["repoUri"]
for key, val := range secret.Data {
splitKey := strings.Split(key, ".")
if len(splitKey) != 3 {
continue
}
if splitKey[2] == "repoUri" {
if string(val) == repoURI {
// this is the provider we want
idx, err := strconv.ParseInt(splitKey[1], 10, 64)
if err != nil {
}
provider, publicKey, privateKey, repoURI, err := gitOpsConfigFromSecretData(idx, secret.Data)
cipher, err := crypto.AESCipherFromString(os.Getenv("API_ENCRYPTION_KEY"))
if err != nil {
return nil, errors.Wrap(err, "failed to create aes cipher")
}
decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
if err != nil {
return nil, errors.Wrap(err, "failed to decode")
}
decryptedPrivateKey, err := cipher.Decrypt([]byte(decodedPrivateKey))
if err != nil {
return nil, errors.Wrap(err, "failed to decrypt")
}
gitOpsConfig := GitOpsConfig{
Provider: provider,
PublicKey: publicKey,
PrivateKey: string(decryptedPrivateKey),
RepoURI: repoURI,
Branch: configMapData["branch"],
Path: configMapData["path"],
Format: configMapData["format"],
Action: configMapData["action"],
LastError: configMapData["lastError"],
}
return &gitOpsConfig, nil
}
}
}
return nil, nil
}
func DisableDownstreamGitOps(appID string, clusterID string) error {
cfg, err := config.GetConfig()
if err != nil {
return errors.Wrap(err, "failed to get cluster config")
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return errors.Wrap(err, "failed to create kubernetes clientset")
}
configMap, err := clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Get(context.TODO(), "kotsadm-gitops", metav1.GetOptions{})
if kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "gitops config map not found")
}
configMapDataKey := fmt.Sprintf("%s-%s", appID, clusterID)
_, ok := configMap.Data[configMapDataKey]
if ok {
delete(configMap.Data, configMapDataKey)
}
_, err = clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Update(context.TODO(), configMap, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update config map")
}
return nil
}
func UpdateDownstreamGitOps(appID, clusterID, uri, branch, path, format, action string) error {
cfg, err := config.GetConfig()
if err != nil {
return errors.Wrap(err, "failed to get cluster config")
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return errors.Wrap(err, "failed to create kubernetes clientset")
}
configMap, err := clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Get(context.TODO(), "kotsadm-gitops", metav1.GetOptions{})
if err != nil && !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get configmap")
}
configMapExists := true
if kuberneteserrors.IsNotFound(err) {
configMapExists = false
}
configMapData := map[string]string{}
if configMapExists && configMap.Data != nil {
configMapData = configMap.Data
}
appKey := fmt.Sprintf("%s-%s", appID, clusterID)
newAppData := map[string]string{
"repoUri": uri,
"branch": branch,
"path": path,
"format": format,
"action": action,
}
// check if to reset or keep last error
appDataEncoded, ok := configMapData[appKey]
if ok {
appDataDecoded, err := base64.StdEncoding.DecodeString(appDataEncoded)
if err != nil {
return errors.Wrap(err, "failed to decode configmap data")
}
appDataUnmarshalled := map[string]string{}
if err := json.Unmarshal(appDataDecoded, &appDataUnmarshalled); err != nil {
return errors.Wrap(err, "failed to unmarshal configmap data")
}
oldUri, _ := appDataUnmarshalled["repoUri"]
oldBranch, _ := appDataUnmarshalled["branch"]
if oldBranch == branch && oldUri == uri {
lastError, ok := appDataUnmarshalled["lastError"]
if ok {
newAppData["lastError"] = lastError // keep last error
}
}
}
// update/set app data in config map
newAppDataMarshalled, err := json.Marshal(newAppData)
if err != nil {
return errors.Wrap(err, "failed to marshal new app data")
}
newAppDataEncoded := base64.StdEncoding.EncodeToString([]byte(newAppDataMarshalled))
configMapData[appKey] = newAppDataEncoded
if configMapExists {
configMap.Data = configMapData
_, err = clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Update(context.TODO(), configMap, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update config map")
}
} else {
configMap = &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kotsadm-gitops",
Namespace: os.Getenv("POD_NAMESPACE"),
},
Data: configMapData,
}
_, err = clientset.CoreV1().ConfigMaps(os.Getenv("POD_NAMESPACE")).Create(context.TODO(), configMap, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create config map")
}
}
return nil
}
func gitOpsConfigFromSecretData(idx int64, secretData map[string][]byte) (string, string, string, string, error) {
provider := ""
publicKey := ""
privateKey := ""
repoURI := ""
providerDecoded, ok := secretData[fmt.Sprintf("provider.%d.type", idx)]
if ok {
provider = string(providerDecoded)
}
publicKeyDecoded, ok := secretData[fmt.Sprintf("provider.%d.publicKey", idx)]
if ok {
publicKey = string(publicKeyDecoded)
}
privateKeyDecoded, ok := secretData[fmt.Sprintf("provider.%d.privateKey", idx)]
if ok {
privateKey = string(privateKeyDecoded)
}
repoURIDecoded, ok := secretData[fmt.Sprintf("provider.%d.repoUri", idx)]
if ok {
repoURI = string(repoURIDecoded)
}
return provider, publicKey, privateKey, repoURI, nil
}
func CreateGitOpsCommit(gitOpsConfig *GitOpsConfig, appSlug string, appName string, newSequence int, archiveDir string, downstreamName string) (string, error) {
kotsKinds, err := kotsutil.LoadKotsKindsFromPath(archiveDir)
if err != nil {
return "", errors.Wrap(err, "failed to load kots kinds")
}
// we use the kustomize binary here...
cmd := exec.Command(fmt.Sprintf("kustomize%s", kotsKinds.KustomizeVersion()), "build", filepath.Join(archiveDir, "overlays", "downstreams", downstreamName))
out, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
logger.Errorf("kustomize stderr: %q", string(ee.Stderr))
}
return "", errors.Wrap(err, "failed to run kustomize")
}
// using the deploy key, create the commit in a new branch
var auth transport.AuthMethod
signer, err := ssh.ParsePrivateKey([]byte(gitOpsConfig.PrivateKey))
if err != nil {
return "", errors.Wrap(err, "failed to parse deploy key")
}
auth = &go_git_ssh.PublicKeys{User: "git", Signer: signer}
auth.(*go_git_ssh.PublicKeys).HostKeyCallback = ssh.InsecureIgnoreHostKey()
workDir, err := ioutil.TempDir("", "kotsadm")
if err != nil {
return "", errors.Wrap(err, "failed to create temp dir")
}
defer os.RemoveAll(workDir)
cloned, err := git.PlainClone(workDir, false, &git.CloneOptions{
URL: gitOpsConfig.CloneURL(),
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
Auth: auth,
})
if err != nil {
return "", errors.Wrap(err, "failed to clone repo")
}
workTree, err := cloned.Worktree()
if err != nil {
return "", errors.Wrap(err, "failed to get worktree")
}
err = cloned.Fetch(&git.FetchOptions{
RefSpecs: []go_git_config.RefSpec{"refs/*:refs/*", "HEAD:refs/heads/HEAD"},
Auth: auth,
})
if err != nil {
return "", errors.Wrap(err, "failed to fetch from repo")
}
// try to check out the branch if it exists
err = workTree.Checkout(&git.CheckoutOptions{
Create: false,
Force: false,
Branch: plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", gitOpsConfig.Branch)),
})
if err != nil {
err := workTree.Checkout(&git.CheckoutOptions{
Create: true,
Force: false,
Branch: plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", gitOpsConfig.Branch)),
})
if err != nil {
return "", errors.Wrap(err, "failed to get or create branch")
}
}
filePath := filepath.Join(workDir, gitOpsConfig.Path, fmt.Sprintf("%s.yaml", appSlug))
_, err = os.Stat(filePath)
if err == nil { // if the file has not changed, end now
currentRevision, err := ioutil.ReadFile(filePath)
if err != nil {
return "", errors.Wrap(err, "failed to read current file")
}
if string(currentRevision) == string(out) {
return "", nil
}
} else if os.IsNotExist(err) { // create subdirectory if not exist
err := os.MkdirAll(filepath.Join(workDir, gitOpsConfig.Path), 0644)
if err != nil {
return "", errors.Wrap(err, "failed to mkdir for file")
}
}
err = ioutil.WriteFile(filePath, out, 0644)
if err != nil {
return "", errors.Wrap(err, "failed to write updated app yaml")
}
_, err = workTree.Add(strings.TrimPrefix(filepath.Join(gitOpsConfig.Path, fmt.Sprintf("%s.yaml", appSlug)), "/"))
if err != nil {
return "", errors.Wrap(err, "failed to add to worktree")
}
// commit it
updatedHash, err := workTree.Commit(fmt.Sprintf("Updating %s to version %d", appName, newSequence), &git.CommitOptions{
Author: &object.Signature{
Name: "KOTS Admin Console",
Email: "help@replicated.com",
When: time.Now(),
},
})
if err != nil {
return "", errors.Wrap(err, "failed to commit")
}
err = cloned.Push(&git.PushOptions{
Auth: auth,
})
if err != nil {
return "", errors.Wrap(err, "failed to push")
}
return gitOpsConfig.CommitURL(updatedHash.String()), nil
}