forked from poseidon/matchbox
/
ignition.go
86 lines (78 loc) · 2.34 KB
/
ignition.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
package http
import (
"bytes"
"encoding/json"
"gopkg.in/yaml.v2"
"net/http"
"strings"
ignition "github.com/coreos/ignition/src/config"
"golang.org/x/net/context"
"github.com/coreos/coreos-baremetal/bootcfg/server"
pb "github.com/coreos/coreos-baremetal/bootcfg/server/serverpb"
)
// ignitionHandler returns a handler that responds with the Ignition config
// for the requester. The Ignition file referenced in the Profile is rendered
// with metadata and parsed and validated as either YAML or JSON based on the
// extension. The Ignition config is served as an HTTP JSON response.
func ignitionHandler(srv server.Server) ContextHandler {
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
group, err := groupFromContext(ctx)
if err != nil || group.Profile == "" {
http.NotFound(w, req)
return
}
profile, err := srv.ProfileGet(ctx, &pb.ProfileGetRequest{Id: group.Profile})
if err != nil || profile.IgnitionId == "" {
http.NotFound(w, req)
return
}
contents, err := srv.IgnitionGet(ctx, profile.IgnitionId)
if err != nil {
http.NotFound(w, req)
return
}
// collect data for rendering Ignition Config
data := make(map[string]interface{})
if group.Metadata != nil {
err = json.Unmarshal(group.Metadata, &data)
if err != nil {
log.Errorf("error unmarshalling metadata: %v", err)
http.NotFound(w, req)
return
}
}
data["query"] = req.URL.RawQuery
for key, value := range group.Selector {
data[strings.ToLower(key)] = value
}
// render the template for an Ignition config with data
var buf bytes.Buffer
err = renderTemplate(&buf, data, contents)
if err != nil {
http.NotFound(w, req)
return
}
// Unmarshal YAML or JSON Ignition config
var cfg ignition.Config
if isYAML(profile.IgnitionId) {
if err := yaml.Unmarshal(buf.Bytes(), &cfg); err != nil {
log.Errorf("error parsing YAML Ignition config: %v", err)
http.NotFound(w, req)
return
}
} else {
cfg, err = ignition.Parse(buf.Bytes())
if err != nil {
log.Errorf("error parsing JSON Ignition config: %v", err)
http.NotFound(w, req)
return
}
}
// Marshal Ignition config as JSON HTTP response
renderJSON(w, cfg)
}
return ContextHandlerFunc(fn)
}
func isYAML(filename string) bool {
return strings.HasSuffix(filename, ".yaml") || strings.HasSuffix(filename, ".yml")
}