forked from cloudfoundry-incubator/fissile
-
Notifications
You must be signed in to change notification settings - Fork 1
/
job.go
380 lines (321 loc) · 10.2 KB
/
job.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
package model
import (
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"sort"
"github.com/pivotal-golang/archiver/extractor"
"gopkg.in/yaml.v2"
)
// Job represents a BOSH job
type Job struct {
Name string
Description string
Templates []*JobTemplate
Packages Packages
Path string
Fingerprint string
SHA1 string
Properties []*JobProperty
Version string
Release *Release
jobReleaseInfo map[interface{}]interface{}
jobSpec map[interface{}]interface{}
}
// Jobs is an array of Job*
type Jobs []*Job
func newJob(release *Release, jobReleaseInfo map[interface{}]interface{}) (*Job, error) {
job := &Job{
Release: release,
jobReleaseInfo: jobReleaseInfo,
}
if err := job.loadJobInfo(); err != nil {
return nil, err
}
if err := job.loadJobSpec(); err != nil {
return nil, err
}
return job, nil
}
func (j *Job) getProperty(name string) (*JobProperty, error) {
for _, property := range j.Properties {
if property.Name == name {
return property, nil
}
}
return nil, fmt.Errorf("Property %s not found in job %s", name, j.Name)
}
// ValidateSHA1 validates that the SHA1 of the actual job archive is the same
// as the one from the release manifest
func (j *Job) ValidateSHA1() error {
file, err := os.Open(j.Path)
if err != nil {
return fmt.Errorf("Error opening the job archive %s for sha1 calculation", j.Path)
}
defer file.Close()
h := sha1.New()
_, err = io.Copy(h, file)
if err != nil {
return fmt.Errorf("Error copying job archive %s for sha1 calculation", j.Path)
}
computedSha1 := fmt.Sprintf("%x", h.Sum(nil))
if computedSha1 != j.SHA1 {
return fmt.Errorf("Computed sha1 (%s) is different than manifest sha1 (%s) for job archive %s", computedSha1, j.SHA1, j.Path)
}
return nil
}
// Extract will extract the contents of the job archive to destination
// It creates a directory with the name of the job
// Returns the full path of the extracted archive
func (j *Job) Extract(destination string) (string, error) {
targetDir := filepath.Join(destination, j.Name)
if err := os.MkdirAll(targetDir, 0755); err != nil {
return "", err
}
if err := extractor.NewTgz().Extract(j.Path, targetDir); err != nil {
return "", err
}
return targetDir, nil
}
func (j *Job) loadJobInfo() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error trying to load job information: %s", r)
}
}()
j.Name = j.jobReleaseInfo["name"].(string)
j.Version = j.jobReleaseInfo["version"].(string)
j.Fingerprint = j.jobReleaseInfo["fingerprint"].(string)
j.SHA1 = j.jobReleaseInfo["sha1"].(string)
j.Path = j.jobArchivePath()
return nil
}
func (j *Job) loadJobSpec() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error trying to load job spec: %s", r)
}
}()
tempJobDir, err := ioutil.TempDir("", "fissile-job-dir")
defer func() {
if cleanupErr := os.RemoveAll(tempJobDir); cleanupErr != nil && err != nil {
err = fmt.Errorf("Error loading job spec: %v, cleanup error: %v", err, cleanupErr)
} else if cleanupErr != nil {
err = fmt.Errorf("Error cleaning up after load job spec: %v", cleanupErr)
}
}()
if err != nil {
return err
}
jobDir, err := j.Extract(tempJobDir)
if err != nil {
return fmt.Errorf("Error extracting archive (%s) for job %s: %s", j.Path, j.Name, err.Error())
}
specFile := filepath.Join(jobDir, "job.MF")
specContents, err := ioutil.ReadFile(specFile)
if err != nil {
return err
}
if err := yaml.Unmarshal([]byte(specContents), &j.jobSpec); err != nil {
return err
}
if j.jobSpec["description"] != nil {
j.Description = j.jobSpec["description"].(string)
}
if j.jobSpec["packages"] != nil {
for _, pkg := range j.jobSpec["packages"].([]interface{}) {
pkgName := pkg.(string)
dependency, err := j.Release.LookupPackage(pkgName)
if err != nil {
return fmt.Errorf("Cannot find dependency for job %s: %v", j.Name, err.Error())
}
j.Packages = append(j.Packages, dependency)
}
}
if j.jobSpec["templates"] != nil {
for source, destination := range j.jobSpec["templates"].(map[interface{}]interface{}) {
templateFile := filepath.Join(jobDir, "templates", source.(string))
templateContent, err := ioutil.ReadFile(templateFile)
if err != nil {
return err
}
template := &JobTemplate{
SourcePath: source.(string),
DestinationPath: destination.(string),
Job: j,
Content: string(templateContent),
}
j.Templates = append(j.Templates, template)
}
}
if j.jobSpec["properties"] != nil {
// We want to load the properties in sorted order, so that we are
// consistent and avoid flaky tests
properties := j.jobSpec["properties"].(map[interface{}]interface{})
var propertyNames []string
for propertyName := range properties {
propertyNames = append(propertyNames, propertyName.(string))
}
sort.Strings(propertyNames)
for _, propertyName := range propertyNames {
property := &JobProperty{
Name: propertyName,
Job: j,
}
propertyDefinition := properties[propertyName]
if propertyDefinition != nil {
propertyDefinitionMap := propertyDefinition.(map[interface{}]interface{})
if propertyDefinitionMap["description"] != nil {
property.Description = propertyDefinitionMap["description"].(string)
}
if propertyDefinitionMap["default"] != nil {
property.Default = propertyDefinitionMap["default"]
}
}
j.Properties = append(j.Properties, property)
}
}
return nil
}
// MergeSpec is used to merge temporary spec patches into each job. otherJob should only be
// the hcf/patch-properties job. The code assumes package and property objects are immutable,
// as they're now being shared across jobs. Also, when specified packages or properties are
// specified in the "other" job, that one takes precedence.
func (j *Job) MergeSpec(otherJob *Job) {
// Ignore otherJob.Name, otherJob.Description
// Skip templates -- they're only in place to keep `create-release` happy.
j.Packages = append(j.Packages, otherJob.Packages...)
j.Properties = append(j.Properties, otherJob.Properties...)
}
// WriteConfigs merges the job's spec with the opinions and writes out the result as JSON to the specified path.
func (j *Job) WriteConfigs(role *Role, outputPath, lightOpinionsPath, darkOpinionsPath string) (err error) {
config, err := initializeConfigJSON()
if err != nil {
return err
}
config["job"].(map[string]interface{})["name"] = role.Name
var templates []map[string]string
for _, roleJob := range role.Jobs {
templates = append(templates, map[string]string{"name": roleJob.Name})
}
config["job"].(map[string]interface{})["templates"] = templates
opinions, err := newOpinions(lightOpinionsPath, darkOpinionsPath)
if err != nil {
return err
}
properties, err := j.getPropertiesForJob(opinions)
if err != nil {
return err
}
config["properties"] = properties
// Write out the configuration
err = os.MkdirAll(filepath.Dir(outputPath), 0755)
if err != nil {
return err
}
jobJSON, err := json.MarshalIndent(config, "", " ") // 4-space indent
if err != nil {
return err
}
if err = ioutil.WriteFile(outputPath, jobJSON, 0644); err != nil {
return err
}
return nil
}
// getPropertiesForJob returns the parameters for the given job, using its specs and opinions
func (j *Job) getPropertiesForJob(opinions *opinions) (map[string]interface{}, error) {
props := make(map[string]interface{})
lightOpinions, ok := opinions.Light["properties"]
if !ok {
return nil, fmt.Errorf("getPropertiesForJob: no 'properties' key in light opinions")
}
darkOpinions, ok := opinions.Dark["properties"]
if !ok {
return nil, fmt.Errorf("getPropertiesForJob: no 'properties' key in dark opinions")
}
lightOpinionsByString, ok := lightOpinions.(map[interface{}]interface{})
if !ok {
return nil, fmt.Errorf("getPropertiesForJob: can't convert lightOpinions into a string map")
}
darkOpinionsByString, ok := darkOpinions.(map[interface{}]interface{})
if !ok {
return nil, fmt.Errorf("getPropertiesForJob: can't convert darkOpinions into a string map")
}
for _, property := range j.Properties {
keyPieces, err := getKeyGrams(property.Name)
if err != nil {
return nil, err
}
// The check for darkness does not only test if the
// presented key is found in the dark opionions, but
// also the type of the associated value. Excluding a
// key like "a.b.c.d" does not mean that "a.b.c",
// etc. are excluded as well. Definitely not. So,
// finding a key we consider it to be an excluded leaf
// key only when the associated value, if any is
// neither map nor array. When finding a map or array,
// or no value at all we consider the key to be an
// inner node which is not excluded.
darkValue, ok := getOpinionValue(darkOpinionsByString, keyPieces)
if ok {
if darkValue == nil {
// Ignore dark opinions
continue
}
kind := reflect.TypeOf(darkValue).Kind()
if kind != reflect.Map && kind != reflect.Array {
// Ignore dark opinions
continue
}
}
lightValue, hasLightValue := getOpinionValue(lightOpinionsByString, keyPieces)
var finalValue interface{}
if hasLightValue && lightValue != nil {
finalValue = lightValue
} else {
finalValue = property.Default
}
if err := insertConfig(props, property.Name, finalValue); err != nil {
return nil, err
}
}
return props, nil
}
// initializeConfigJSON returns the scaffolding for the BOSH-style JSON structure
func initializeConfigJSON() (map[string]interface{}, error) {
var config map[string]interface{}
err := json.Unmarshal([]byte(`{
"job": {
"templates": []
},
"parameters": {},
"properties": {},
"networks": {
"default": {}
}
}`), &config)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal initial config: %+v", err)
}
return config, nil
}
// Len implements the Len function to satisfy sort.Interface
func (slice Jobs) Len() int {
return len(slice)
}
// Less implements the Less function to satisfy sort.Interface
func (slice Jobs) Less(i, j int) bool {
return slice[i].Name < slice[j].Name
}
// Swap implements the Swap function to satisfy sort.Interface
func (slice Jobs) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
func (j *Job) jobArchivePath() string {
return filepath.Join(j.Release.DevBOSHCacheDir, j.SHA1)
}