forked from goharbor/harbor-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
91 lines (68 loc) · 1.48 KB
/
node.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
package graph
import (
"context"
"sync"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
)
type node struct {
resource Resource
fn RunFunc
parent chan error
parentLock *sync.Mutex
parentCount int
children []chan<- error
childrenLock []*sync.Mutex
}
var errParentChannelClosed = errors.New("parent channel closed")
func (no *node) Wait(ctx context.Context) error {
defer close(no.parent)
if no.parentCount == 0 {
return nil
}
span, _ := opentracing.StartSpanFromContext(ctx, "waitNode")
defer span.Finish()
received := 0
for parentErr := range no.parent {
if parentErr != nil {
// a parent failed
return parentErr
}
received++
if received >= no.parentCount {
return nil
}
}
if received < no.parentCount {
// parents closed the channel
return errParentChannelClosed
}
return nil
}
func (no *node) Terminates(err error) (result error) {
for _, c := range no.children {
c := c
go func() {
no.parentLock.Lock()
defer no.parentLock.Unlock()
defer func() {
// recover from panic caused by writing to a closed channel
if r := recover(); r != nil {
result = errors.Errorf("%v", r)
}
}()
c <- err
}()
}
return result
}
func (no *node) AddChild(child *node) {
if no == nil {
// Parent is nil -> not a blocker
return
}
no.parentLock.Lock()
defer no.parentLock.Unlock()
no.children = append(no.children, child.parent)
no.childrenLock = append(no.childrenLock, child.parentLock)
}