-
Notifications
You must be signed in to change notification settings - Fork 37
/
init.go
268 lines (243 loc) · 6.29 KB
/
init.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
/*
Copyright 2019 Splunk Inc.
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 commands
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"github.com/ghodss/yaml"
"github.com/spf13/cobra"
"github.com/splunk/qbec/internal/cmd"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/remote"
"github.com/splunk/qbec/internal/sio"
)
type initCommandConfig struct {
cmd.AppContext
withExample bool // create a hello world example
}
var baseParamsTemplate = template.Must(template.New("base").Parse(`
// this file has the baseline default parameters
{
components: { {{- if .AddExample}}
hello: {
indexData: 'hello baseline\n',
replicas: 1,
}, {{- end}}
},
}
`))
var envParamsTemplate = template.Must(template.New("env").Parse(`
// this file has the param overrides for the default environment
local base = import './base.libsonnet';
base {
components +: { {{- if .AddExample}}
hello +: {
indexData: 'hello default\n',
replicas: 2,
}, {{- end}}
}
}
`))
var paramsTemplate = template.Must(template.New("any-env").Parse(`
// this file returns the params for the current qbec environment
local env = std.extVar('qbec.io/env');
local paramsMap = import 'glob-import:environments/*.libsonnet';
local baseFile = if env == '_' then 'base' else env;
local key = 'environments/%s.libsonnet' % baseFile;
if std.objectHas(paramsMap, key)
then paramsMap[key]
else error 'no param file %s found for environment %s' % [key, env]
`))
var componentExampleTemplate = template.Must(template.New("comp").Parse(`
local p = import '../params.libsonnet';
local params = p.components.hello;
[
{
apiVersion: 'v1',
kind: 'ConfigMap',
metadata: {
name: 'demo-config',
},
data: {
'index.html': params.indexData,
},
},
{
apiVersion: 'apps/v1',
kind: 'Deployment',
metadata: {
name: 'demo-deploy',
labels: {
app: 'demo-deploy',
},
},
spec: {
replicas: params.replicas,
selector: {
matchLabels: {
app: 'demo-deploy',
},
},
template: {
metadata: {
labels: {
app: 'demo-deploy',
},
},
spec: {
containers: [
{
name: 'main',
image: 'nginx:stable',
imagePullPolicy: 'Always',
volumeMounts: [
{
name: 'web',
mountPath: '/usr/share/nginx/html',
},
],
},
],
volumes: [
{
name: 'web',
configMap: {
name: 'demo-config',
},
},
],
},
},
},
},
]
`))
func writeTemplateFile(file string, t *template.Template, data interface{}) error {
var w bytes.Buffer
if err := t.Execute(&w, data); err != nil {
return fmt.Errorf("unable to expand template for file %s, %v", file, err)
}
if err := ioutil.WriteFile(file, w.Bytes(), 0644); err != nil {
return err
}
sio.Noticeln("wrote", file)
return nil
}
func writeFiles(dir string, app model.QbecApp, config initCommandConfig) error {
if err := os.Mkdir(app.Metadata.Name, 0755); err != nil {
return err
}
templateData := struct {
AddExample bool
}{config.withExample}
type templateFile struct {
t *template.Template
f string
}
compsDir, envDir := filepath.Join(dir, "components"), filepath.Join(dir, "environments")
for _, dir := range []string{compsDir, envDir} {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
}
files := []templateFile{
{
t: paramsTemplate,
f: filepath.Join(dir, "params.libsonnet"),
},
{
t: baseParamsTemplate,
f: filepath.Join(envDir, "base.libsonnet"),
},
{
t: envParamsTemplate,
f: filepath.Join(envDir, "default.libsonnet"),
},
}
if config.withExample {
files = append(files, templateFile{
t: componentExampleTemplate,
f: filepath.Join(compsDir, "hello.jsonnet"),
})
}
for _, tf := range files {
if err := writeTemplateFile(tf.f, tf.t, templateData); err != nil {
return err
}
}
b, err := yaml.Marshal(app)
if err != nil {
return fmt.Errorf("yaml marshal: %v", err)
}
file := filepath.Join(dir, "qbec.yaml")
if err := ioutil.WriteFile(file, b, 0644); err != nil {
return err
}
sio.Noticeln("wrote", file)
return nil
}
func doInit(args []string, config initCommandConfig) error {
if len(args) != 1 {
return fmt.Errorf("a single app name argument must be supplied")
}
name := args[0]
_, err := os.Stat(name)
if err == nil {
return fmt.Errorf("directory %s already exists", name)
}
if !os.IsNotExist(err) {
return err
}
ctx, err := config.KubeContextInfo()
if err != nil {
sio.Warnf("could not get current K8s context info, %v\n", err)
sio.Warnln("using fake parameters for the default environment")
ctx = &remote.ContextInfo{
ServerURL: "https://minikube",
}
}
sio.Noticef("using server URL %q and default namespace %q for the default environment\n", ctx.ServerURL, ctx.Namespace)
app := model.QbecApp{
Kind: "App",
APIVersion: model.LatestAPIVersion,
Metadata: model.AppMeta{
Name: name,
},
Spec: model.AppSpec{
Environments: map[string]model.Environment{
"default": {
Server: ctx.ServerURL,
DefaultNamespace: ctx.Namespace,
},
},
},
}
return writeFiles(name, app, config)
}
func newInitCommand(cp ctxProvider) *cobra.Command {
c := &cobra.Command{
Use: "init <app-name>",
Short: "initialize a qbec app",
}
config := initCommandConfig{}
c.Flags().BoolVar(&config.withExample, "with-example", false, "create a hello world sample component")
c.RunE = func(c *cobra.Command, args []string) error {
config.AppContext = cp()
return cmd.WrapError(doInit(args, config))
}
return c
}