-
Notifications
You must be signed in to change notification settings - Fork 51
/
heartbeat.go
120 lines (100 loc) · 2.2 KB
/
heartbeat.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
package main
import (
"bufio"
"io"
"strings"
"sync"
"time"
"github.com/reconquest/hierr-go"
"github.com/reconquest/runcmd"
)
const (
heartbeatPing = "PING"
)
// heartbeat runs infinite process of sending test messages to the connected
// node. All heartbeats to all nodes are connected to each other, so if one
// heartbeat routine exits, all heartbeat routines will exit, because in that
// case orgalorg can't guarantee global lock.
func heartbeat(
period time.Duration,
node *distributedLockNode,
canceler *sync.Cond,
) {
abort := make(chan struct{}, 0)
// Internal go-routine for listening abort broadcast and finishing current
// heartbeat process.
go func() {
canceler.L.Lock()
canceler.Wait()
canceler.L.Unlock()
abort <- struct{}{}
}()
// Finish finishes current go-routine and send abort broadcast to all
// connected go-routines.
finish := func(code int) {
canceler.L.Lock()
canceler.Broadcast()
canceler.L.Unlock()
<-abort
if remote, ok := node.runner.(*runcmd.Remote); ok {
tracef("%s closing connection", node.String())
err := remote.CloseConnection()
if err != nil {
warningf(
"%s",
hierr.Errorf(
err,
"%s error while closing connection",
node.String(),
),
)
}
}
exit(code)
}
ticker := time.Tick(period)
// Infinite loop of heartbeating. It will send heartbeat message, wait
// fraction of send timeout time and try to receive heartbeat response.
// If no response received, heartbeat process aborts.
for {
_, err := io.WriteString(node.connection.stdin, heartbeatPing+"\n")
if err != nil {
errorf(
"%s",
hierr.Errorf(
err,
`%s can't send heartbeat`,
node.String(),
),
)
finish(2)
}
select {
case <-abort:
return
case <-ticker:
// pass
}
ping, err := bufio.NewReader(node.connection.stdout).ReadString('\n')
if err != nil {
errorf(
"%s",
hierr.Errorf(
err,
`%s can't receive heartbeat`,
node.String(),
),
)
finish(2)
}
if strings.TrimSpace(ping) != heartbeatPing {
errorf(
`%s received unexpected heartbeat ping: '%s'`,
node.String(),
ping,
)
finish(2)
}
tracef(`%s heartbeat`, node.String())
}
}