-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdag.go
195 lines (166 loc) · 4.41 KB
/
dag.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
package herd
import (
"context"
"fmt"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"github.com/kendru/darwin/go/depgraph"
"github.com/samber/lo"
)
// Graph represents a directed graph.
type Graph struct {
*depgraph.Graph
ops map[string]*OpState
init bool
orphans *sync.WaitGroup
collectOrphans bool
}
// GraphEntry is the external representation of
// the operation to execute (OpState).
type GraphEntry struct {
WithCallback bool
Background bool
Callback []func(context.Context) error
Error error
Ignored, Fatal, WeakDeps, Executed bool
Name string
Dependencies []string
WeakDependencies []string
Duration time.Duration
}
// DAG creates a new instance of a runnable Graph.
// A DAG is a Direct Acyclic Graph.
// The graph is walked, and depending on the dependencies it will run the jobs as requested.
// The Graph can be explored with `Analyze()`, extended with new operations with Add(),
// and finally being run with Run(context.Context).
func DAG(opts ...GraphOption) *Graph {
g := &Graph{Graph: depgraph.New(), ops: make(map[string]*OpState), orphans: &sync.WaitGroup{}}
for _, o := range opts {
o(g)
}
if g.init {
if err := g.Add("init"); err != nil {
return nil
}
}
return g
}
// Add adds a new operation to the graph.
// Requires a name (string), and accepts a list of options.
func (g *Graph) Add(name string, opts ...OpOption) error {
state := &OpState{Mutex: sync.Mutex{}}
for _, o := range opts {
if err := o(name, state, g); err != nil {
return err
}
}
g.ops[name] = state
if g.init && len(g.Graph.Dependents(name)) == 0 && name != "init" {
if err := g.Graph.DependOn(name, "init"); err != nil {
return err
}
}
return nil
}
// Stage returns the DAG item state.
// Note: it locks to be thread-safe.
func (g *Graph) State(name string) GraphEntry {
g.ops[name].Lock()
defer g.ops[name].Unlock()
return g.ops[name].toGraphEntry(name)
}
func (g *Graph) buildStateGraph() (graph [][]GraphEntry) {
for _, layer := range g.TopoSortedLayers() {
states := []GraphEntry{}
for _, r := range layer {
g.ops[r].Lock()
states = append(states, g.ops[r].toGraphEntry(r))
g.ops[r].Unlock()
}
graph = append(graph, states)
}
return
}
// Analyze returns the DAG and the Graph in the execution order.
// It will also return eventual updates if called after Run().
func (g *Graph) Analyze() (graph [][]GraphEntry) {
return g.buildStateGraph()
}
// Run starts the jobs defined in the DAG with a context.
// It returns error in case of failure.
func (g *Graph) Run(ctx context.Context) error {
checkFatal := func(layer []GraphEntry) error {
for _, s := range layer {
if s.Fatal && g.ops[s.Name].err != nil {
return g.ops[s.Name].err
}
}
return nil
}
for _, layer := range g.buildStateGraph() {
var wg sync.WaitGroup
LAYER:
for _, r := range layer {
if !r.WithCallback || r.Ignored {
continue
}
fns := r.Callback
if !r.WeakDeps {
for k := range g.Graph.Dependencies(r.Name) {
if len(r.WeakDependencies) != 0 && lo.Contains(r.WeakDependencies, k) {
continue
}
g.ops[r.Name].Lock()
g.ops[k].Lock()
unlock := func() {
g.ops[r.Name].Unlock()
g.ops[k].Unlock()
}
if g.ops[k].err != nil {
g.ops[r.Name].err = fmt.Errorf("'%s' deps %s failed", r.Name, k)
unlock()
continue LAYER
}
unlock()
}
}
for i := range fns {
if !r.Background {
wg.Add(1)
} else if g.collectOrphans {
g.orphans.Add(1)
}
go func(ctx context.Context, g *Graph, key string, f func(context.Context) error) {
now := time.Now()
err := f(ctx)
g.ops[key].Lock()
if err != nil {
g.ops[key].err = multierror.Append(g.ops[key].err, err)
}
g.ops[key].executed = true
if !g.ops[key].background {
wg.Done()
} else if g.collectOrphans {
g.orphans.Done()
}
g.ops[key].duration = time.Since(now)
g.ops[key].Unlock()
}(ctx, g, r.Name, fns[i])
}
}
wg.Wait()
if err := checkFatal(layer); err != nil {
return err
}
}
if g.collectOrphans {
g.orphans.Wait()
for _, layer := range g.buildStateGraph() {
if err := checkFatal(layer); err != nil {
return err
}
}
}
return nil
}