-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle-writer.go
410 lines (362 loc) · 11.7 KB
/
bundle-writer.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
package bundle
import (
"encoding/json"
"fmt"
"github.com/cloud66-oss/starter/common"
"io/ioutil"
"os"
"path/filepath"
"time"
)
type ManifestBundle struct {
Version string `json:"version"`
Metadata *Metadata `json:"metadata"`
UID string `json:"uid"`
Name string `json:"name"`
StencilGroups []*BundleStencilGroup `json:"stencil_groups"`
BaseTemplates []*BundleBaseTemplates `json:"base_template"`
Tags []string `json:"tags"`
HelmReleases []*BundleHelmRelease `json:"helm_releases"`
Configurations []string `json:"configuration"`
}
type BundleHelmRelease struct {
UID string `json:"uid"`
ChartName string `json:"chart_name"`
DisplayName string `json:"display_name"`
Version string `json:"version"`
RepositoryURL string `json:"repository_url"`
ValuesFile string `json:"values_file"`
}
type BundleBaseTemplates struct {
Name string `json:"name"`
Repo string `json:"repo"`
Branch string `json:"branch"`
Stencils []*BundleStencil `json:"stencils"`
Policies []*BundlePolicy `json:"policies"`
Transformers []*BundleTransformer `json:"transformers"`
}
type Metadata struct {
App string `json:"app"`
Timestamp time.Time `json:"timestamp"`
Annotations []string `json:"annotations"`
}
type BundleStencil struct {
UID string `json:"uid"`
Filename string `json:"filename"`
TemplateFilename string `json:"template_filename"`
ContextID string `json:"context_id"`
Status int `json:"status"`
Tags []string `json:"tags"`
Sequence int `json:"sequence"`
}
type BundleStencilGroup struct {
UID string `json:"uid"`
Name string `json:"name"`
Tags []string `json:"tags"`
}
type BundlePolicy struct {
UID string `json:"uid"`
Name string `json:"name"`
Selector string `json:"selector"`
Sequence int `json:"sequence"`
Tags []string `json:"tags"`
}
type BundleTransformer struct { // this is just a placeholder for now
UID string `json:"uid"`
Name string `json:"name"`
Tags []string `json:"tags"`
}
type TemplateJSON struct {
Version string `json:"version"`
Public bool `json:"public"`
Name string `json:"name"`
Icon string `json:"icon"`
LongName string `json:"long_name"`
Description string `json:"description"`
Templates *TemplatesStruct `json:"templates"`
}
type TemplatesStruct struct {
Stencils []*StencilTemplate `json:"stencils"`
Policies []*PolicyTemplate `json:"policies"`
Transformers []*TransformersTemplate `json:"transformers"`
}
type StencilTemplate struct {
Name string `json:"name"`
FilenamePattern string `json:"filename_pattern"`
Filename string `json:"filename"`
Description string `json:"description"`
ContextType string `json:"context_type"`
Tags []string `json:"tags"`
PreferredSequence int `json:"preferred_sequence"`
Suggested bool `json:"suggested"`
MinUsage int `json:"min_usage"`
MaxUsage int `json:"max_usage"`
}
type PolicyTemplate struct{}
type TransformersTemplate struct{}
func CreateSkycapFiles(outputDir string,
templateRepository string,
branch string,
packName string,
githubURL string,
services []*common.Service,
databases []common.Database) error {
if templateRepository == "" {
//no stencil template defined for this pack, print an error and do nothing
fmt.Printf("Sorry but there is no stencil template for this language/framework yet\n")
return nil
}
//Create .bundle directory structure if it doesn't exist
tempFolder := os.TempDir()
bundleFolder := filepath.Join(tempFolder, "bundle")
defer os.RemoveAll(bundleFolder)
err := createBundleFolderStructure(bundleFolder)
if err != nil {
return err
}
//create manifest.json file and start filling
manifestFile, err := loadManifest()
if err != nil {
return err
}
manifestFile, err = saveEnvVars(packName, getEnvVars(services, databases), manifestFile, bundleFolder)
if err != nil {
return err
}
manifestFile, err = addDatabase(manifestFile, databases)
manifestFile, err = getRequiredStencils(
templateRepository,
branch,
outputDir,
services,
bundleFolder,
manifestFile,
githubURL)
if err != nil {
return err
}
manifestFile, err = addMetadata(manifestFile)
if err != nil {
return err
}
err = saveManifest(bundleFolder, manifestFile)
if err != nil {
return err
}
// tarball
err = os.RemoveAll(filepath.Join(bundleFolder, "temp"))
if err != nil {
common.PrintError(err.Error())
}
err = common.Tar(bundleFolder, filepath.Join(outputDir, "starter.bundle"))
if err != nil {
common.PrintError(err.Error())
}
fmt.Printf("Bundle is saved to starter.bundle\n")
return err
}
// downloading templates from github and putting them into homedir
func getStencilTemplateFile(templateRepository string, tempFolder string, filename string, branch string) (string, error) {
//Download templates.json file
manifestPath := templateRepository + filename // don't need to use filepath since it's a URL
downErr := common.DownloadSingleFile(tempFolder, common.DownloadFile{URL: manifestPath, Name: filename}, branch)
if downErr != nil {
return "", downErr
}
return filepath.Join(tempFolder, filename), nil
}
func getEnvVars(servs []*common.Service, databases []common.Database) map[string]string {
var envas = make(map[string]string)
for _, envVarArray := range servs {
for _, envs := range envVarArray.EnvVars {
envas[envs.Key] = envs.Value
}
}
return envas
}
func createBundleFolderStructure(baseFolder string) error {
var folders = [5]string{"stencils", "policies", "stencil_groups", "helm_releases", "configurations"}
for _, subfolder := range folders {
folder := filepath.Join(baseFolder, subfolder)
err := os.MkdirAll(folder, 0777)
if err != nil {
return err
}
}
return nil
}
func getRequiredStencils(templateRepository string,
branch string,
outputDir string,
services []*common.Service,
bundleFolder string,
manifestFile *ManifestBundle,
githubURL string) (*ManifestBundle, error) {
templateFolder := filepath.Join(os.TempDir(), "temp")
err := os.MkdirAll(templateFolder, 0777)
defer os.RemoveAll(templateFolder)
if err != nil {
return nil, err
}
//start download the template.json file
tjPathfile, err := getStencilTemplateFile(templateRepository, templateFolder, "templates.json", branch)
if err != nil {
fmt.Printf("Error while downloading the templates.json. err: %s", err)
return nil, err
}
// open the template.json file and start downloading the stencils
templateJSON, err := os.Open(tjPathfile)
if err != nil {
return nil, err
}
templatesJSONData, err := ioutil.ReadAll(templateJSON)
if err != nil {
return nil, err
}
var templJSON TemplateJSON
err = json.Unmarshal([]byte(templatesJSONData), &templJSON)
if err != nil {
return nil, err
}
var manifestStencils = make([]*BundleStencil, 0)
for _, stencil := range templJSON.Templates.Stencils {
if stencil.MinUsage > 0 {
if stencil.ContextType == "service" {
for _, service := range services {
manifestFile, manifestStencils, err = downloadAndAddStencil(
service.Name,
stencil,
manifestFile,
bundleFolder,
templateRepository,
branch,
manifestStencils)
// create entry in manifest file with formatted name
// download and rename stencil file
}
} else {
manifestFile, manifestStencils, err = downloadAndAddStencil(
"",
stencil,
manifestFile,
bundleFolder,
templateRepository,
branch,
manifestStencils)
}
}
}
var newTemplate BundleBaseTemplates
newTemplate.Name = templJSON.Name
newTemplate.Repo = githubURL
newTemplate.Branch = branch
newTemplate.Stencils = manifestStencils
newTemplate.Policies = make([]*BundlePolicy, 0)
newTemplate.Transformers = make([]*BundleTransformer, 0)
manifestFile.BaseTemplates = append(manifestFile.BaseTemplates, &newTemplate)
return manifestFile, nil
}
func loadManifest() (*ManifestBundle, error) {
manifest := &ManifestBundle{
Version: "1",
Metadata: nil,
UID: "",
Name: "",
StencilGroups: make([]*BundleStencilGroup, 0),
BaseTemplates: make([]*BundleBaseTemplates, 0),
Tags: make([]string, 0),
HelmReleases: make([]*BundleHelmRelease, 0),
Configurations: make([]string, 0),
}
return manifest, nil
}
func saveManifest(bundleFolder string, content *ManifestBundle) error {
out, err := json.MarshalIndent(content, "", " ")
if err != nil {
return err
}
manifestPath := filepath.Join(bundleFolder, "manifest.json")
return ioutil.WriteFile(manifestPath, out, 0600)
}
func saveEnvVars(prefix string, envVars map[string]string, manifestFile *ManifestBundle, bundleFolder string) (*ManifestBundle, error) {
filename := prefix + "-config"
varsPath := filepath.Join(filepath.Join(bundleFolder, "configurations"), prefix+"-config")
var fileOut string
for key, value := range envVars {
fileOut = fileOut + key + "=" + value + "\n"
}
err := ioutil.WriteFile(varsPath, []byte(fileOut), 0600)
if err != nil {
return nil, err
}
var configs = manifestFile.Configurations
manifestFile.Configurations = append(configs, filename)
return manifestFile, nil
}
func downloadAndAddStencil(context string,
stencil *StencilTemplate,
manifestFile *ManifestBundle,
bundleFolder string,
templateRepository string,
branch string,
manifestStencils []*BundleStencil) (*ManifestBundle, []*BundleStencil, error) {
var filename = ""
if context != "" {
filename = context + "_"
}
filename = filename + stencil.Filename
//download the stencil file
stencilPath := templateRepository + "stencils/" + stencil.Filename // don't need to use filepath since it's a URL
stencilsFolder := filepath.Join(bundleFolder, "stencils")
downErr := common.DownloadSingleFile(stencilsFolder, common.DownloadFile{URL: stencilPath, Name: filename}, branch)
if downErr != nil {
return nil, nil, downErr
}
// Add the entry to the manifest file
var tempStencil BundleStencil
tempStencil.UID = ""
tempStencil.Filename = filename
tempStencil.TemplateFilename = stencil.Filename
tempStencil.ContextID = context
tempStencil.Status = 2 // it means that the stencils still need to be deployed
tempStencil.Tags = []string{"starter"}
tempStencil.Sequence = stencil.PreferredSequence
manifestStencils = append(manifestStencils, &tempStencil)
return manifestFile, manifestStencils, nil
}
func addMetadata(manifestFile *ManifestBundle) (*ManifestBundle, error) {
var metadata = &Metadata{
Annotations: []string{"Generated by Cloud 66 starter"},
App: "starter",
Timestamp: time.Now().UTC(),
}
manifestFile.Metadata = metadata
manifestFile.Name = "starter-formation"
manifestFile.Tags = []string{"starter"}
return manifestFile, nil
}
func addDatabase(manifestFile *ManifestBundle, databases []common.Database) (*ManifestBundle, error) {
var helmReleases = make([]*BundleHelmRelease, 0)
var release BundleHelmRelease
for _, db := range databases {
switch db.Name {
case "mysql":
release.ChartName = db.Name
release.DisplayName = db.Name
release.Version = "0.10.2"
case "postgresql":
release.ChartName = db.Name
release.DisplayName = db.Name
release.Version = "3.1.0"
default:
common.PrintlnWarning("Database %s not supported\n", db.Name)
continue
}
release.UID = ""
release.RepositoryURL = "https://kubernetes-charts.storage.googleapis.com/"
release.ValuesFile = ""
helmReleases = append(helmReleases, &release)
}
manifestFile.HelmReleases = helmReleases
return manifestFile, nil
}