/
mixin.go
84 lines (73 loc) · 2.13 KB
/
mixin.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
//go:generate packr2
package qliksense
import (
"bufio"
"github.com/deislabs/porter/pkg/context"
"github.com/ghodss/yaml" // We are not using go-yaml because of serialization problems with jsonschema, don't use this library elsewhere
"github.com/gobuffalo/packr/v2"
"github.com/pkg/errors"
"github.com/xeipuuv/gojsonschema"
"io/ioutil"
"strings"
)
type Mixin struct {
*context.Context
//add whatever other context/state is needed here
schema *packr.Box
}
// New azure mixin client, initialized with useful defaults.
func New() (*Mixin, error) {
return &Mixin{
schema: packr.New("schema", "./schema"),
Context: context.New(),
}, nil
}
func (m *Mixin) getPayloadData() ([]byte, error) {
reader := bufio.NewReader(m.In)
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, errors.Wrap(err, "could not read the payload from STDIN")
}
// hack to convert " to " due to the bug https://github.com/deislabs/porter/issues/846
// once the bug fixed we dont' need this hack
strData := string(data)
strData = strings.ReplaceAll(strData, """, "\"")
data = []byte(strData)
err = m.ValidatePayload(data)
if err != nil {
return nil, err
}
return data, nil
}
func (m *Mixin) ValidatePayload(b []byte) error {
// Load the step as a go dump
s := make(map[string]interface{})
err := yaml.Unmarshal(b, &s)
if err != nil {
return errors.Wrap(err, "could not marshal payload as yaml")
}
manifestLoader := gojsonschema.NewGoLoader(s)
// Load the step schema
schema, err := m.GetSchema()
if err != nil {
return err
}
schemaLoader := gojsonschema.NewStringLoader(schema)
validator, err := gojsonschema.NewSchema(schemaLoader)
if err != nil {
return errors.Wrap(err, "unable to compile the mixin step schema")
}
// Validate the manifest against the schema
result, err := validator.Validate(manifestLoader)
if err != nil {
return errors.Wrap(err, "unable to validate the mixin step schema")
}
if !result.Valid() {
errs := make([]string, 0, len(result.Errors()))
for _, err := range result.Errors() {
errs = append(errs, err.String())
}
return errors.New(strings.Join(errs, "\n\t* "))
}
return nil
}