forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
220 lines (204 loc) · 6.02 KB
/
common.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
package helm
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"encoding/base64"
"github.com/pkg/errors"
"github.com/rancher/rancher/pkg/controllers/user/helm/common"
"github.com/rancher/rancher/pkg/templatecontent"
mgmtv3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
helmName = "helm"
kubectl = "kubectl"
appLabel = "io.cattle.field/appId"
kcEnv = "KUBECONFIG"
)
func WriteTempDir(rootDir string, files map[string]string) (string, error) {
for name, content := range files {
fp := filepath.Join(rootDir, name)
if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil {
return "", err
}
if err := ioutil.WriteFile(fp, []byte(content), 0755); err != nil {
return "", err
}
}
for name := range files {
parts := strings.Split(name, "/")
if len(parts) > 0 {
return filepath.Join(rootDir, parts[0]), nil
}
}
return "", nil
}
func kubectlApply(template, kubeconfig string, app *v3.App) error {
file, err := ioutil.TempFile("", "app-template")
if err != nil {
return err
}
defer os.RemoveAll(file.Name())
if err := ioutil.WriteFile(file.Name(), []byte(template), 0755); err != nil {
return err
}
command := []string{"apply", "--all", "--overwrite", "-n", app.Spec.TargetNamespace, "-f", file.Name()}
if app.Spec.Prune {
command = append(command, "--prune")
}
cmd := exec.Command(kubectl, command...)
cmd.Env = []string{fmt.Sprintf("%s=%s", kcEnv, kubeconfig)}
sbErr := &bytes.Buffer{}
cmd.Stdout = os.Stdout
cmd.Stderr = sbErr
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return errors.Wrapf(err, fmt.Sprintf("Kubectl apply failed. Error: %s", sbErr.String()))
}
// wait for resources to be created and try 5 times
// todo: there is a bug around rolebindings that are being deleted if created outside rancher
start := 250 * time.Millisecond
for i := 0; i < 5; i++ {
time.Sleep(start)
command = []string{"label", "-n", app.Spec.TargetNamespace, "--overwrite", "-f", file.Name(), fmt.Sprintf("%s=%s", appLabel, app.Name)}
cmd = exec.Command(kubectl, command...)
cmd.Env = []string{fmt.Sprintf("%s=%s", kcEnv, kubeconfig)}
buf := &bytes.Buffer{}
cmd.Stdout = os.Stdout
cmd.Stderr = buf
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
if i == 4 {
logrus.Warnf("tried 4 times and kubectl label failed. Error: %s", buf.String())
break
}
start = start * 2
continue
}
break
}
return nil
}
func kubectlDelete(template, kubeconfig, namespace string) error {
file, err := ioutil.TempFile("", "app-template")
if err != nil {
return err
}
defer os.RemoveAll(file.Name())
if err := ioutil.WriteFile(file.Name(), []byte(template), 0755); err != nil {
return err
}
command := []string{"delete", "--all", "-n", namespace, "-f", file.Name()}
// try three times and succeed
start := time.Second * 1
for i := 0; i < 3; i++ {
cmd := exec.Command(kubectl, command...)
cmd.Env = []string{fmt.Sprintf("%s=%s", kcEnv, kubeconfig)}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
time.Sleep(start)
start = start * 2
continue
}
break
}
return nil
}
func convertTemplates(files map[string]string, templateContentClient mgmtv3.TemplateContentInterface) (map[string]string, error) {
templates := map[string]string{}
for name, tag := range files {
data, err := templatecontent.GetTemplateFromTag(tag, templateContentClient)
if err != nil {
continue
}
templates[name] = data
}
return templates, nil
}
func generateTemplates(obj *v3.App, templateVersionClient mgmtv3.TemplateVersionInterface, templateContentClient mgmtv3.TemplateContentInterface) (string, string, error) {
files := map[string]string{}
if obj.Spec.ExternalID != "" {
templateVersionID, err := common.ParseExternalID(obj.Spec.ExternalID)
if err != nil {
return "", "", err
}
templateVersion, err := templateVersionClient.Get(templateVersionID, metav1.GetOptions{})
if err != nil {
return "", "", err
}
files, err = convertTemplates(templateVersion.Spec.Files, templateContentClient)
if err != nil {
return "", "", err
}
} else {
for k, v := range obj.Spec.Files {
content, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return "", "", err
}
files[k] = string(content)
}
}
tempDir, err := ioutil.TempDir("", "helm-")
if err != nil {
return "", "", err
}
dir, err := WriteTempDir(tempDir, files)
defer os.RemoveAll(dir)
if err != nil {
return "", "", err
}
setValues := []string{}
if obj.Spec.Answers != nil {
answers := obj.Spec.Answers
result := []string{}
for k, v := range answers {
result = append(result, fmt.Sprintf("%s=%s", k, v))
}
setValues = append([]string{"--set"}, strings.Join(result, ","))
}
commands := append([]string{"template", dir, "--name", obj.Name, "--namespace", obj.Spec.TargetNamespace}, setValues...)
cmd := exec.Command(helmName, commands...)
sbOut := &bytes.Buffer{}
sbErr := &bytes.Buffer{}
cmd.Stdout = sbOut
cmd.Stderr = sbErr
if err := cmd.Start(); err != nil {
return "", "", errors.Wrapf(err, "helm template failed. %s", sbErr.String())
}
if err := cmd.Wait(); err != nil {
return "", "", errors.Wrapf(err, "helm template failed. %s", sbErr.String())
}
// notes.txt
commands = []string{"template", dir, "--name", obj.Name, "--namespace", obj.Spec.TargetNamespace, "--notes"}
cmd = exec.Command(helmName, commands...)
noteOut := &bytes.Buffer{}
sbErr = &bytes.Buffer{}
cmd.Stdout = noteOut
cmd.Stderr = sbErr
if err := cmd.Start(); err != nil {
return "", "", errors.Wrapf(err, "helm template --notes failed. %s", sbErr.String())
}
if err := cmd.Wait(); err != nil {
return "", "", errors.Wrapf(err, "helm template --notes failed. %s", sbErr.String())
}
template := sbOut.String()
notes := noteOut.String()
return template, notes, nil
}