-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstack.go
386 lines (328 loc) · 8.38 KB
/
stack.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package stack
import (
"encoding/json"
"fmt"
"sort"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/ast/astutil"
"cuelang.org/go/cue/cuecontext"
cueflow "cuelang.org/go/tools/flow"
log "github.com/sirupsen/logrus"
"github.com/stakpak/devx/pkg/auth"
"github.com/stakpak/devx/pkg/gitrepo"
"github.com/stakpak/devx/pkg/utils"
)
type Stack struct {
ID string
DepIDs []string
BuildSource string
components cue.Value
tasks []string
dependencies map[string][]string
}
func NewStack(value cue.Value, stackId string, depIds []string) (*Stack, error) {
components := value.LookupPath(cue.ParsePath("components"))
if components.Err() != nil {
return nil, components.Err()
}
stack := &Stack{
ID: stackId,
DepIDs: depIds,
components: components,
dependencies: make(map[string][]string),
}
cfg := &cueflow.Config{
FindHiddenTasks: true,
Root: cue.ParsePath(""),
}
flow := cueflow.New(
cfg,
components,
taskFunc,
)
tasks := flow.Tasks()
for _, task := range tasks {
id := utils.GetLastPathFragment(task.Value())
parents := task.Dependencies()
stack.dependencies[id] = make([]string, 0)
for _, parent := range parents {
parentId := utils.GetLastPathFragment(parent.Value())
stack.addDependency(id, parentId)
}
}
stack.tasks = computeOrderedTasks(stack)
return stack, nil
}
func (s *Stack) Print() {
log.Info(s.components)
}
func (s *Stack) GetDependencies(id string) ([]string, error) {
val, ok := s.dependencies[id]
if !ok {
return nil, fmt.Errorf("Id %s not found in dependencies map", id)
}
return val, nil
}
func (s *Stack) UpdateComponent(id string, value cue.Value) error {
// s.components.
s.components = s.components.FillPath(cue.ParsePath(id), value)
if s.components.Err() != nil {
return s.components.Err()
}
return nil
}
func (s *Stack) GetComponent(id string) (cue.Value, error) {
result := s.components.LookupPath(cue.ParsePath(id))
return result, result.Err()
}
func (s *Stack) IsConcreteComponent(component cue.Value) bool {
err := component.Validate(cue.Concrete(true))
return err == nil
}
func (s *Stack) HasConcreteResourceDrivers(component cue.Value) bool {
resources := component.LookupPath(cue.ParsePath("$resource"))
if resources.Exists() {
resourceIter, _ := resources.Fields()
for resourceIter.Next() {
driver := resourceIter.Value().LookupPath(cue.ParsePath("$metadata.labels.driver"))
if !driver.Exists() {
return false
}
err := driver.Validate(cue.Concrete(true))
if err != nil {
return false
}
}
}
return true
}
func (s *Stack) GetContext() *cue.Context {
return s.components.Context()
}
func (s *Stack) GetTasks() []string {
return s.tasks
}
func (s *Stack) AddComponents(value cue.Value) {
s.components = s.components.FillPath(cue.ParsePath(""), value)
cfg := &cueflow.Config{
FindHiddenTasks: true,
Root: cue.ParsePath(""),
}
flow := cueflow.New(
cfg,
s.components,
taskFunc,
)
tasks := flow.Tasks()
for _, task := range tasks {
id := utils.GetLastPathFragment(task.Value())
parents := task.Dependencies()
s.dependencies[id] = make([]string, 0)
for _, parent := range parents {
parentId := utils.GetLastPathFragment(parent.Value())
s.addDependency(id, parentId)
}
}
s.tasks = computeOrderedTasks(s)
}
func (s *Stack) addDependency(id string, depId string) {
s.dependencies[id] = append(s.dependencies[id], depId)
}
// cue flow already checks for cycles, so we don't have to
func computeOrderedTasks(s *Stack) []string {
result := make([]string, 0)
// initialize data structures
visited := make(map[string]bool)
stack := make([]string, 0)
for id := range s.dependencies {
stack = append(stack, id)
visited[id] = false
}
// make scheduling deterministic
sort.Strings(stack)
for len(stack) > 0 {
current := stack[len(stack)-1]
if isVisited, _ := visited[current]; isVisited {
stack = stack[:len(stack)-1]
continue
}
parents, _ := s.GetDependencies(current)
isReady := true
for _, parent := range parents {
if isVisited, _ := visited[parent]; !isVisited {
isReady = false
stack = append(stack, parent)
}
}
if !isReady {
continue
}
visited[current] = true
result = append(result, current)
stack = stack[:len(stack)-1]
}
return result
}
func taskFunc(v cue.Value) (cueflow.Runner, error) {
idPath := cue.ParsePath("$metadata.id")
componentId := v.LookupPath(idPath)
if !componentId.Exists() {
// Not a task
return nil, nil
}
return cueflow.RunnerFunc(func(t *cueflow.Task) error {
return nil
}), nil
}
func (s *Stack) GetComponents() cue.Value {
return s.components
}
type BuildData struct {
Stack string `json:"stack"`
Identity string `json:"identity,omitempty"`
Result cue.Value `json:"result"`
Imports []string `json:"imports"`
References map[string][]Reference `json:"references"`
Environment string `json:"environment"`
Git *gitrepo.GitData `json:"git,omitempty"`
Error *string `json:"error"`
Source string `json:"source"`
}
type Reference struct {
Source string `json:"source"`
Target string `json:"target"`
}
func (s *Stack) SendBuild(configDir string, server auth.ServerConfig, environment string, buildError *string) (string, error) {
build := BuildData{
Stack: s.ID,
Identity: "",
Imports: s.DepIDs,
Environment: environment,
Git: nil,
Error: buildError,
Source: s.BuildSource,
}
if buildError == nil {
build.Result = s.GetComponents()
build.References = s.GetReferences()
} else {
build.Result = cuecontext.New().CompileString("{}")
build.References = map[string][]Reference{}
}
gitData, err := gitrepo.GetGitData(configDir)
if err != nil {
return "", err
}
build.Git = gitData
data, err := utils.SendData(server, "builds", &build)
if err != nil {
return "", err
}
buildResponse := make(map[string]string)
err = json.Unmarshal(data, &buildResponse)
if err != nil {
return "", err
}
return buildResponse["id"], nil
}
func (s *Stack) GetReferences() map[string][]Reference {
refMap := map[string][]Reference{}
refs := removeDuplicates(GetRef(s.components.Syntax()))
for _, r := range refs {
if r.Target == "" {
continue
}
parts := strings.SplitN(r.Target, ".", 2)
refMap[parts[0]] = append(refMap[parts[0]], r)
}
return refMap
}
func GetRef(node ast.Node) []Reference {
refs := []Reference{}
if node == nil {
return refs
}
astutil.Apply(node, func(c astutil.Cursor) bool {
path := GetPath(c)
if strings.Contains(path, "#") || strings.Contains(path, "$") {
return false
}
switch n := c.Node().(type) {
case *ast.SelectorExpr:
sourcePath := GetName(n)
if strings.Contains(sourcePath, "#") || strings.Contains(sourcePath, "?") {
return false
}
refs = append(refs, Reference{
Source: sourcePath,
Target: path,
})
return false
case *ast.IndexExpr:
sourcePath := GetName(n)
if strings.Contains(sourcePath, "#") || strings.Contains(sourcePath, "?") {
return false
}
refs = append(refs, Reference{
Source: sourcePath,
Target: path,
})
return false
}
return true
}, nil)
return refs
}
func GetPath(c astutil.Cursor) string {
if c == nil {
return ""
}
path := GetPath(c.Parent())
if c.Parent() != nil {
switch p := c.Parent().Node().(type) {
case *ast.ListLit:
for i, e := range p.Elts {
if e == c.Node() {
path = path + fmt.Sprintf("[%d]", i)
break
}
}
}
}
switch n := c.Node().(type) {
case *ast.Field:
path = path + "." + GetName(n.Label)
case *ast.Ident:
path = path + "." + GetName(n)
}
return strings.TrimPrefix(path, ".")
}
func GetName(n ast.Node) string {
switch n := n.(type) {
case *ast.Ident:
return n.Name
case *ast.Field:
return GetName(n.Label)
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", GetName(n.X), GetName(n.Sel))
case *ast.IndexExpr:
return fmt.Sprintf("%s[%s]", GetName(n.X), GetName(n.Index))
case *ast.BasicLit:
return n.Value
}
return "?"
}
func removeDuplicates(refs []Reference) []Reference {
allKeys := make(map[string]bool)
list := []Reference{}
for _, item := range refs {
key := fmt.Sprintf(item.Source, item.Target)
if _, value := allKeys[key]; !value {
allKeys[key] = true
list = append(list, item)
}
}
return list
}