-
Notifications
You must be signed in to change notification settings - Fork 2
/
closer.go
113 lines (97 loc) · 2.29 KB
/
closer.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
package dilithium
import (
"github.com/openziti/dilithium/util"
"github.com/sirupsen/logrus"
"time"
)
// Closer manages the state machine for the shutdown of a TxPortal and RxPortal pair (one side of a communication).
//
type Closer struct {
seq *util.Sequence
rxCloseSeq int32
rxCloseSeqIn chan int32
txCloseSeq int32
txCloseSeqIn chan int32
txp *TxPortal
rxp *RxPortal
lastEvent time.Time
closeHook func()
}
func NewCloser(seq *util.Sequence, closeHook func()) *Closer {
return &Closer{
seq: seq,
rxCloseSeq: notClosed,
rxCloseSeqIn: make(chan int32, 1),
txCloseSeq: notClosed,
txCloseSeqIn: make(chan int32, 1),
closeHook: closeHook,
}
}
func (c *Closer) EmergencyStop() {
logrus.Info("broken glass")
c.txp.close()
c.rxp.Close()
c.txp.ii.Closed(c.txp.adapter)
if c.closeHook != nil {
c.closeHook()
}
}
func (c *Closer) timeout() {
logrus.Info("timeout")
c.txp.close()
c.rxp.Close()
if c.closeHook != nil {
c.closeHook()
}
}
func (c *Closer) run() {
logrus.Info("started")
defer logrus.Info("exited")
closeWait:
for {
select {
case rxCloseSeq, ok := <-c.rxCloseSeqIn:
if !ok {
logrus.Info("!rx close seq")
break closeWait
}
c.rxCloseSeq = rxCloseSeq
c.lastEvent = time.Now()
logrus.Infof("got rx close seq [%d]", rxCloseSeq)
if c.txCloseSeq == notClosed {
if err := c.txp.sendClose(c.seq); err != nil {
logrus.Errorf("error sending close (%v)", err)
}
}
if c.readyToClose() {
break closeWait
}
case txCloseSeq, ok := <-c.txCloseSeqIn:
if !ok {
logrus.Infof("!tx close seq")
break closeWait
}
c.txCloseSeq = txCloseSeq
c.lastEvent = time.Now()
logrus.Infof("got tx close seq [%d]", txCloseSeq)
if c.readyToClose() {
break closeWait
}
case <-time.After(time.Duration(c.txp.alg.Profile().CloseCheckMs) * time.Millisecond):
if c.readyToClose() {
break closeWait
}
}
}
logrus.Info("ready to close")
c.txp.close()
c.rxp.Close()
if c.closeHook != nil {
c.closeHook()
}
logrus.Info("close complete")
}
func (c *Closer) readyToClose() bool {
return (c.txCloseSeq != notClosed && c.rxCloseSeq != notClosed) || time.Since(c.lastEvent).Milliseconds() > int64(c.txp.alg.Profile().ConnectionTimeout)
}
const notClosed = int32(-99)