-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_alive.go
46 lines (39 loc) · 1.09 KB
/
client_alive.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
package sshx
import (
"context"
"fmt"
"time"
)
// CheckLivenessUntilNotAlive checks liveness every aliveCheckInterval, if consecutive liveness failure count reach notAliveCountExit, an error is returned.
func (c *Client) CheckLivenessUntilNotAlive(ctx context.Context, aliveCheckInterval time.Duration, notAliveCountExit uint) error {
ticker := time.NewTicker(aliveCheckInterval)
defer ticker.Stop()
var (
notAliveCount uint
lastError error
)
for {
if notAliveCount >= notAliveCountExit {
return fmt.Errorf("%s liveness check failed %d time consecutively (last error: %v)", c.addr, notAliveCount, lastError)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := c.IsAlive(); err != nil {
notAliveCount++
lastError = err
} else {
notAliveCount = 0
}
ticker.Reset(aliveCheckInterval)
}
}
}
// IsAlive sends a keepalive ssh request.
func (c *Client) IsAlive() error {
if _, _, err := c.Client.SendRequest("[email protected]", true, nil); err != nil {
return fmt.Errorf("unable to send keepalive request: %w", err)
}
return nil
}