This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
template_functions.go
266 lines (235 loc) · 6.79 KB
/
template_functions.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
package main
import (
"errors"
"fmt"
"os"
"path"
"reflect"
"regexp"
"strings"
"text/template"
"time"
log "github.com/Sirupsen/logrus"
)
func newFuncMap(ctx *TemplateContext) template.FuncMap {
return template.FuncMap{
// Utility funcs
"base": path.Base,
"dir": path.Dir,
"env": os.Getenv,
"timestamp": time.Now,
"split": strings.Split,
"join": strings.Join,
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"contains": strings.Contains,
"replace": strings.Replace,
"where": where,
"exists": exists,
"dict": dict,
// Service funcs
"host": hostFunc(ctx),
"hosts": hostsFunc(ctx),
"service": serviceFunc(ctx),
"services": servicesFunc(ctx),
"whereLabelExists": whereLabelExists,
"whereLabelEquals": whereLabelEquals,
"whereLabelMatches": whereLabelEquals,
"groupByLabel": groupByLabel,
}
}
// serviceFunc returns a single service given a string argument in the form
// <service-name>[.<stack-name>].
func serviceFunc(ctx *TemplateContext) func(...string) (interface{}, error) {
return func(s ...string) (result interface{}, err error) {
result, err = ctx.GetService(s...)
if _, ok := err.(NotFoundError); ok {
log.Debug(err)
return nil, nil
}
return
}
}
// servicesFunc returns all available services, optionally filtered by stack
// name or label values.
func servicesFunc(ctx *TemplateContext) func(...string) (interface{}, error) {
return func(s ...string) (interface{}, error) {
return ctx.GetServices(s...)
}
}
// hostFunc returns a single host given it's UUID.
func hostFunc(ctx *TemplateContext) func(...string) (interface{}, error) {
return func(s ...string) (result interface{}, err error) {
result, err = ctx.GetHost(s...)
if _, ok := err.(NotFoundError); ok {
log.Debug(err)
return nil, nil
}
return
}
}
// hostsFunc returns all available hosts, optionally filtered by label value.
func hostsFunc(ctx *TemplateContext) func(...string) (interface{}, error) {
return func(s ...string) (interface{}, error) {
return ctx.GetHosts(s...)
}
}
// groupByLabel takes a label key and a slice of services or hosts and returns a map based
// on the values of the label.
//
// The map key is a string representing the label value. The map value is a
// slice of services or hosts that have the corresponding label value.
// Example:
// {{range $labelValue, $containers := svc.Containers | groupByLabel "foo"}}
func groupByLabel(label string, in interface{}) (map[string][]interface{}, error) {
m := make(map[string][]interface{})
if in == nil {
return m, fmt.Errorf("(groupByLabel) input is nil")
}
switch typed := in.(type) {
case []Service:
for _, s := range typed {
value, ok := s.Labels[label]
if ok && len(value) > 0 {
m[value] = append(m[value], s)
}
}
case []Container:
for _, c := range typed {
value, ok := c.Labels[label]
if ok && len(value) > 0 {
m[value] = append(m[value], c)
}
}
case []Host:
for _, h := range typed {
value, ok := h.Labels[label]
if ok && len(value) > 0 {
m[value] = append(m[value], h)
}
}
default:
return m, fmt.Errorf("(groupByLabel) invalid input type %T", in)
}
return m, nil
}
func whereLabel(funcName string, in interface{}, label string, test func(string, bool) bool) ([]interface{}, error) {
result := make([]interface{}, 0)
if in == nil {
return result, fmt.Errorf("(%s) input is nil", funcName)
}
if label == "" {
return result, fmt.Errorf("(%s) label is empty", funcName)
}
switch typed := in.(type) {
case []Service:
for _, s := range typed {
value, ok := s.Labels[label]
if test(value, ok) {
result = append(result, s)
}
}
case []Container:
for _, c := range typed {
value, ok := c.Labels[label]
if test(value, ok) {
result = append(result, c)
}
}
case []Host:
for _, s := range typed {
value, ok := s.Labels[label]
if test(value, ok) {
result = append(result, s)
}
}
default:
return result, fmt.Errorf("(%s) invalid input type %T", funcName, in)
}
return result, nil
}
// selects services or hosts from the input that have the given label
func whereLabelExists(label string, in interface{}) ([]interface{}, error) {
return whereLabel("whereLabelExists", in, label, func(_ string, ok bool) bool {
return ok
})
}
// selects services or hosts from the input that have the given label and value
func whereLabelEquals(label, labelValue string, in interface{}) ([]interface{}, error) {
return whereLabel("whereLabelEquals", in, label, func(value string, ok bool) bool {
return ok && strings.EqualFold(value, labelValue)
})
}
// selects services or hosts from the input that have the given label whose value matches the regex
func whereLabelMatches(label, pattern string, in interface{}) ([]interface{}, error) {
rx, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return whereLabel("whereLabelMatches", in, label, func(value string, ok bool) bool {
return ok && rx.MatchString(value)
})
}
func getArrayValues(funcName string, entries interface{}) (*reflect.Value, error) {
entriesVal := reflect.ValueOf(entries)
kind := entriesVal.Kind()
if kind == reflect.Ptr {
entriesVal = reflect.Indirect(entriesVal)
kind = entriesVal.Kind()
}
switch kind {
case reflect.Array, reflect.Slice:
break
default:
return nil, fmt.Errorf("Must pass an array or slice to '%v'; received %v; kind %v", funcName, entries, kind)
}
return &entriesVal, nil
}
// Generalized where function
func generalizedWhere(funcName string, entries interface{}, key string, test func(interface{}) bool) (interface{}, error) {
entriesVal, err := getArrayValues(funcName, entries)
if err != nil {
return nil, err
}
selection := make([]interface{}, 0)
for i := 0; i < entriesVal.Len(); i++ {
v := reflect.Indirect(entriesVal.Index(i)).Interface()
value := deepGet(v, key)
if test(value) {
selection = append(selection, v)
}
}
return selection, nil
}
// selects entries based on key
func where(entries interface{}, key string, cmp interface{}) (interface{}, error) {
return generalizedWhere("where", entries, key, func(value interface{}) bool {
return reflect.DeepEqual(value, cmp)
})
}
// detects whether file or path exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// Creates a map from a list of pairs
func dict(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
}