forked from hyperhq/runv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fanout.go
118 lines (102 loc) · 2.29 KB
/
fanout.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
package hypervisor
import (
"sync"
"github.com/hyperhq/runv/hypervisor/types"
)
type Fanout struct {
size int
upstream chan *types.VmResponse
clients []chan *types.VmResponse
closeSignal chan *types.VmResponse
running bool
lock sync.RWMutex
}
// CreateFanout create a new fanout, and if it is non-blocked, it will start
// the fanout goroutine at once, otherwise it will start the goroutine when it
// get the first client
func CreateFanout(upstream chan *types.VmResponse, size int, block bool) *Fanout {
fo := &Fanout{
size: size,
upstream: upstream,
clients: []chan *types.VmResponse{},
closeSignal: make(chan *types.VmResponse, 1),
running: !block,
lock: sync.RWMutex{},
}
if !block {
fo.start()
}
return fo
}
func (fo *Fanout) Acquire() (chan *types.VmResponse, error) {
client := make(chan *types.VmResponse, fo.size)
fo.lock.Lock()
first := !fo.running
fo.running = true
fo.clients = append(fo.clients, client)
fo.lock.Unlock()
if first {
fo.start()
}
return client, nil
}
func (fo *Fanout) Release(client chan *types.VmResponse) error {
fo.lock.Lock()
defer fo.lock.Unlock()
remains := []chan *types.VmResponse{}
for _, c := range fo.clients {
if c != client {
remains = append(remains, c)
continue
}
close(client)
}
fo.clients = remains
return nil
}
func (fo *Fanout) Close() {
if fo == nil {
return
}
UnblockSend(fo.closeSignal, nil)
close(fo.closeSignal)
}
func (fo *Fanout) start() {
go func() {
next := true
for next {
// exit goroutine in case upstream closed or get close signal
select {
case rsp, ok := <-fo.upstream:
if !ok {
next = false
} else {
fo.lock.RLock()
for _, c := range fo.clients {
UnblockSend(c, rsp)
}
fo.lock.RUnlock()
}
case _, _ = <-fo.closeSignal:
next = false
}
// all cleints check and operation should protected
fo.lock.Lock()
if !next {
for _, c := range fo.clients {
close(c)
}
fo.clients = []chan *types.VmResponse{}
fo.running = false
}
fo.lock.Unlock() // don't change this to defer, it is inside loop
}
}()
}
func UnblockSend(ch chan *types.VmResponse, u *types.VmResponse) {
defer func() { recover() }() // in case has closed by someone
select {
case ch <- u:
default:
}
}