-
Notifications
You must be signed in to change notification settings - Fork 23
/
fields.go
260 lines (238 loc) · 7.01 KB
/
fields.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
/*
* === This file is part of ALICE O² ===
*
* Copyright 2018-2020 CERN and copyright holders of ALICE O².
* Author: Teo Mrnjavac <teo.mrnjavac@cern.ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In applying this license CERN does not waive the privileges and
* immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
package template
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"text/template"
"github.com/AliceO2Group/Control/common/gera"
"github.com/AliceO2Group/Control/common/logger"
"github.com/AliceO2Group/Control/configuration/componentcfg"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"github.com/sirupsen/logrus"
"github.com/valyala/fasttemplate"
)
const DEBUG_TEMPLATE_SYSTEM=false
var log = logger.New(logrus.StandardLogger(),"template")
type Sequence map[Stage]Fields
type BuildObjectStackFunc func(stage Stage) map[string]interface{}
type ComponentConfigurationService interface {
GetComponentConfiguration(query *componentcfg.Query) (payload string, err error)
GetAndProcessComponentConfiguration(query *componentcfg.Query, varStack map[string]string) (payload string, err error)
}
func (sf Sequence) Execute(confSvc ComponentConfigurationService, parentPath string, varStack VarStack, buildObjectStack BuildObjectStackFunc, stringTemplateCache map[string]template.Template) (err error) {
for i := 0; i < int(_STAGE_MAX); i++ {
currentStage := Stage(i)
var stagedStack map[string]string
stagedStack, err = varStack.consolidated(currentStage)
if err != nil {
return
}
objectStack := buildObjectStack(currentStage)
if fields, ok := sf[currentStage]; ok {
if DEBUG_TEMPLATE_SYSTEM {
log.WithFields(logrus.Fields{
"path": parentPath,
"stage": currentStage,
"fields": func() string {
accumulator := make([]string, len(fields))
for i, v := range fields {
accumulator[i] = v.Get()
}
return strings.Join(accumulator, ", ")
}(),
}).Trace("about to process fields for stage")
}
err = fields.Execute(confSvc, parentPath, stagedStack, objectStack, stringTemplateCache)
if err != nil {
log.WithError(err).Errorf("template processing error")
return
}
}
}
return
}
type Fields []Field
type Stage int
const (
// RESOLUTION STAGE ↓ VALUES AVAILABLE ↓
STAGE0 Stage = iota // parent stack only + locals
STAGE1 // parent stack + defaults + locals
STAGE2 // parent stack + defaults + vars + locals
STAGE3 // parent stack + defaults + vars + uservars + locals
STAGE4 // parent stack + defaults + vars + uservars + locals + full self-object = full stack
_STAGE_MAX
)
type VarStack struct {
Locals map[string]string
Defaults *gera.StringWrapMap
Vars *gera.StringWrapMap
UserVars *gera.StringWrapMap
}
func (vs *VarStack) consolidated(stage Stage) (consolidatedStack map[string]string, err error) {
var defaults, vars, userVars map[string]string
vars, err = vs.Vars.Flattened()
if err != nil {
return
}
userVars, err = vs.UserVars.Flattened()
if err != nil {
return
}
switch stage {
case STAGE0:
defaults, err = vs.Defaults.FlattenedParent()
if err != nil {
return
}
vars, err = vs.Vars.FlattenedParent()
if err != nil {
return
}
userVars, err = vs.UserVars.FlattenedParent()
if err != nil {
return
}
case STAGE1:
defaults, err = vs.Defaults.Flattened()
if err != nil {
return
}
vars, err = vs.Vars.FlattenedParent()
if err != nil {
return
}
userVars, err = vs.UserVars.FlattenedParent()
if err != nil {
return
}
case STAGE2:
defaults, err = vs.Defaults.Flattened()
if err != nil {
return
}
vars, err = vs.Vars.Flattened()
if err != nil {
return
}
userVars, err = vs.UserVars.FlattenedParent()
if err != nil {
return
}
case STAGE3: fallthrough
case STAGE4:
defaults, err = vs.Defaults.Flattened()
if err != nil {
return
}
vars, err = vs.Vars.Flattened()
if err != nil {
return
}
userVars, err = vs.UserVars.Flattened()
if err != nil {
return
}
}
consolidated := gera.MakeStringMapWithMap(vs.Locals).Wrap(gera.MakeStringMapWithMap(userVars).Wrap(gera.MakeStringMapWithMap(vars).Wrap(gera.MakeStringMapWithMap(defaults))))
consolidatedStack, err = consolidated.Flattened()
if err != nil {
return
}
return
}
func (fields Fields) Execute(confSvc ComponentConfigurationService, parentPath string, varStack map[string]string, objStack map[string]interface{}, stringTemplateCache map[string]template.Template) (err error) {
environment := make(map[string]interface{}, len(varStack))
strOpStack := MakeStrOperationFuncMap()
for k, v := range varStack {
environment[k] = v
}
for k, v := range objStack {
environment[k] = v
}
for k, v := range strOpStack {
environment[k] = v
}
configAccessFuncs := MakeConfigAccessFuncs(confSvc, varStack)
for k, v := range configAccessFuncs {
environment[k] = v
}
for _, field := range fields {
buf := new(bytes.Buffer)
// FIXME: the line below implements the cache
//tmpl, ok := stringTemplateCache[*str]
var tmpl *fasttemplate.Template // dummy
ok := false // dummy
if !ok {
tmpl, err = fasttemplate.NewTemplate(field.Get(), "{{", "}}")
if err != nil {
log.WithError(err).WithField("role", parentPath).Warn("template processing error (bad workflow file)")
return
}
}
_, err = tmpl.ExecuteFunc(buf, func(w io.Writer, tag string) (i int, err error) {
var(
program *vm.Program
rawOutput interface{}
)
program, err = expr.Compile(tag)
if err != nil {
return
}
rawOutput, err = expr.Run(program, environment)
if err != nil {
return
}
switch rawOutput.(type) {
case []interface{}, []string:
var jsonOutput []byte
jsonOutput, err = json.Marshal(rawOutput)
if err != nil {
return
}
return w.Write(jsonOutput)
default:
return w.Write([]byte(fmt.Sprintf("%v", rawOutput)))
}
})
if DEBUG_TEMPLATE_SYSTEM {
log.WithFields(logrus.Fields{
"path": parentPath,
"fieldBefore": field.Get(),
"fieldAfter": buf.String(),
"error": err,
}).Trace("processed field for stage")
}
if err != nil {
log.WithError(err).WithField("role", parentPath).Warn("template processing error (bad variable or workflow file)")
return
}
field.Set(buf.String())
}
return
}