-
Notifications
You must be signed in to change notification settings - Fork 38
/
parse.go
226 lines (185 loc) · 6.48 KB
/
parse.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
package config
import (
"bytes"
"context"
"fmt"
"regexp"
"strings"
"entgo.io/ent/dialect/sql"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/seal-io/walrus/pkg/dao/model"
"github.com/seal-io/walrus/pkg/dao/model/resource"
"github.com/seal-io/walrus/pkg/dao/model/resourcerelationship"
"github.com/seal-io/walrus/pkg/dao/types"
"github.com/seal-io/walrus/pkg/dao/types/crypto"
"github.com/seal-io/walrus/pkg/dao/types/object"
"github.com/seal-io/walrus/pkg/resources/interpolation"
"github.com/seal-io/walrus/pkg/resourcestate"
pkgvariable "github.com/seal-io/walrus/pkg/variable"
"github.com/seal-io/walrus/utils/json"
)
const (
// _variablePrefix the prefix of the variable name.
_variablePrefix = "_walrus_var_"
// _resourcePrefix the prefix of the resource output name.
_resourcePrefix = "_walrus_res_"
)
// _interpolationReg is the regular expression for matching non-reference or non-variable expressions.
// Reference: https://developer.hashicorp.com/terraform/language/expressions/strings#escape-sequences-1
// To handle escape sequences, ${xxx} is converted to $${xxx}.
// If there are more than two consecutive $ symbols, like $${xxx}, they are further converted to $$${xxx}.
// During Terraform processing, $${} is ultimately transformed back to ${};
// this interpolation is used to ensure a WYSIWYG user experience.
var _interpolationReg = regexp.MustCompile(`\$\{((var\.)?([^.}]+)(?:\.([^.}]+))?)[^\}]*\}`)
type RunOpts struct {
ResourceRun *model.ResourceRun
ResourceName string
ProjectID object.ID
EnvironmentID object.ID
}
// ParseModuleAttributes parse module variables and dependencies.
func ParseModuleAttributes(
ctx context.Context,
mc model.ClientSet,
attributes map[string]any,
onlyValidated bool,
opts RunOpts,
) (attrs map[string]any, variables model.Variables, outputs map[string]types.OutputValue, err error) {
var (
templateVariables []string
dependencyResourceOutputs []string
)
replaced := !onlyValidated
attrs, templateVariables, dependencyResourceOutputs, err = parseAttributeReplace(attributes, replaced)
if err != nil {
return
}
// If a resource run has variables that inherit from cloned run, use them directly.
if opts.ResourceRun != nil && len(opts.ResourceRun.Variables) > 0 {
for k, v := range opts.ResourceRun.Variables {
variables = append(variables, &model.Variable{
Name: k,
Value: crypto.String(v),
})
}
} else {
variables, err = pkgvariable.Get(ctx, mc, templateVariables, opts.ProjectID, opts.EnvironmentID)
if err != nil {
return nil, nil, nil, err
}
}
if !onlyValidated {
dependOutputMap := toDependOutputMap(dependencyResourceOutputs)
outputs, err = getResourceDependencyOutputsByID(
ctx,
mc,
opts.ResourceRun.ResourceID,
dependOutputMap)
if err != nil {
return nil, nil, nil, err
}
// Check if all dependency resource outputs are found.
for outputName := range dependOutputMap {
if _, ok := outputs[outputName]; !ok {
return nil, nil, nil, fmt.Errorf("resource %s dependency output %s not found",
opts.ResourceName, outputName)
}
}
}
return attrs, variables, outputs, nil
}
// toDependOutputMap splits the dependencyResourceOutputs from {resource}_{resource_name}_{output_name}
// to a map of {resource_name}_{output_name}:{resource}.
func toDependOutputMap(dependencyResourceOutputs []string) map[string]string {
dependOutputMap := make(map[string]string, 0)
for _, dependOutput := range dependencyResourceOutputs {
ss := strings.SplitN(dependOutput, "_", 2)
if len(ss) != 2 {
continue
}
dependOutputMap[ss[1]] = ss[0]
}
return dependOutputMap
}
// parseAttributeReplace parses attribute variable ${var.name} replaces it with ${var._variablePrefix+name},
// resource reference ${res.name.output} replaces it with ${var._resourcePrefix+name}
// and returns variable names and output names.
// Replaced flag indicates whether to replace the module attribute variable with prefix string.
func parseAttributeReplace(
attributes map[string]any,
replaced bool,
) (map[string]any, []string, []string, error) {
bs, err := json.Marshal(attributes)
if err != nil {
return nil, nil, nil, err
}
variableMatches := interpolation.VariableReg.FindAllSubmatch(bs, -1)
resourceMatches := interpolation.ResourceReg.FindAllSubmatch(bs, -1)
variableMatched := sets.NewString()
for _, match := range variableMatches {
if len(match) > 1 {
variableMatched.Insert(string(match[1]))
}
}
resourceMatched := sets.NewString()
for _, match := range resourceMatches {
if len(match) > 1 {
// Resource outputs are in the form:
// - res_{resource_name}_{output_name}.
resourceMatched.Insert("res_" + string(match[1]) + "_" + string(match[2]))
}
}
variableRepl := "${var." + _variablePrefix + "${1}}"
bs = interpolation.VariableReg.ReplaceAll(bs, []byte(variableRepl))
resourceRepl := "${var." + _resourcePrefix + "${1}_${2}}"
bs = interpolation.ResourceReg.ReplaceAll(bs, []byte(resourceRepl))
// Replace interpolation from ${} to $${} to avoid escape sequences.
bs = _interpolationReg.ReplaceAllFunc(bs, func(match []byte) []byte {
m := _interpolationReg.FindSubmatch(match)
if len(m) != 5 {
return match
}
// If it is a variable or resource reference, do not replace.
if string(m[2]) == "var." {
return match
}
var b bytes.Buffer
b.WriteString("$")
b.Write(match)
return b.Bytes()
})
if replaced {
err = json.Unmarshal(bs, &attributes)
if err != nil {
return nil, nil, nil, err
}
}
return attributes, variableMatched.List(), resourceMatched.List(), nil
}
// getResourceDependencyOutputsByID gets the dependency outputs of the resource by resource id.
func getResourceDependencyOutputsByID(
ctx context.Context,
client model.ClientSet,
resourceID object.ID,
dependOutputs map[string]string,
) (map[string]types.OutputValue, error) {
entity, err := client.Resources().Query().
Where(resource.ID(resourceID)).
WithDependencies(func(sq *model.ResourceRelationshipQuery) {
sq.Where(func(s *sql.Selector) {
s.Where(sql.ColumnsNEQ(resourcerelationship.FieldResourceID, resourcerelationship.FieldDependencyID))
})
}).
Only(ctx)
if err != nil {
return nil, err
}
dependencyResourceIDs := make([]object.ID, 0, len(entity.Edges.Dependencies))
for _, d := range entity.Edges.Dependencies {
if d.Type != types.ResourceRelationshipTypeImplicit {
continue
}
dependencyResourceIDs = append(dependencyResourceIDs, d.DependencyID)
}
return resourcestate.GetDependencyOutputs(ctx, client, dependencyResourceIDs, dependOutputs)
}