/
templateHelper.go
105 lines (86 loc) · 2.47 KB
/
templateHelper.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
package monitoring
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"text/template"
"github.com/ghodss/yaml"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
monitoring "github.com/integr8ly/application-monitoring-operator/pkg/apis/applicationmonitoring/v1alpha1"
)
type Parameters struct {
Params map[string]string
}
type TemplateHelper struct {
Parameters Parameters
TemplatePath string
}
// Creates a new templates helper and populates the values for all
// templates properties. Some of them (like the hostname) are set
// by the user in the custom resource
func NewTemplateHelper(extraParams map[string]string) *TemplateHelper {
param := Parameters{
Params: extraParams,
}
templatePath := "./templates/monitoring"
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
templatePath = "../../../templates/monitoring"
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
templatePath = "/usr/local/bin/templates/monitoring"
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
panic("cannot find templates")
}
}
}
return &TemplateHelper{
Parameters: param,
TemplatePath: templatePath,
}
}
// Takes a list of strings, wraps each string in double quotes and joins them
// Used for building yaml arrays
func joinQuote(values []monitoring.BlackboxtargetData) string {
var result []string
for _, s := range values {
result = append(result, fmt.Sprintf("\"%v@%v@%v\"", s.Module, s.Service, s.Url))
}
return strings.Join(result, ", ")
}
// load a templates from a given resource name. The templates must be located
// under ./templates and the filename must be <resource-name>.yaml
func (h *TemplateHelper) loadTemplate(name string) ([]byte, error) {
path := fmt.Sprintf("%s/%s", h.TemplatePath, name)
tpl, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
parser := template.New("application-monitoring")
parser.Funcs(template.FuncMap{
"JoinQuote": joinQuote,
})
parsed, err := parser.Parse(string(tpl))
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = parsed.Execute(&buffer, h.Parameters)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func (h *TemplateHelper) CreateResource(template string) (runtime.Object, error) {
tpl, err := h.loadTemplate(template)
if err != nil {
return nil, err
}
resource := unstructured.Unstructured{}
err = yaml.Unmarshal(tpl, &resource)
if err != nil {
return nil, err
}
return &resource, nil
}