/
main.go
86 lines (72 loc) · 1.86 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
var pollingInterval = 2 * time.Second
func main() {
addr := os.Args[1]
username := os.Args[2]
privateKey := os.Getenv("CHECKER_SSH_PRIVATE_KEY")
if len(strings.Split(addr, ":")) == 1 {
addr = fmt.Sprintf("%s:22", addr)
}
signer, err := ssh.ParsePrivateKey([]byte(privateKey))
if err != nil {
log.Fatal(err)
}
for {
time.Sleep(pollingInterval)
client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint: gosec
Timeout: 1 * time.Second,
})
if err != nil {
// SSH connection failed, indicating the server might still be rebooting
fmt.Printf("SSH connection failed: %s, waiting... \n", err.Error())
continue
}
// SSH connection successful, check uptime
session, err := client.NewSession()
if err != nil {
fmt.Printf("SSH connection failed: %s, waiting... \n", err.Error())
continue
}
defer session.Close()
// Run the uptime command
output, err := session.CombinedOutput("cat /proc/uptime")
if err != nil {
fmt.Printf("SSH command failed: %s, waiting... \n", err.Error())
continue
}
// Check if the output contains information about server uptime
if rebooted(output) {
fmt.Println("Server rebooted and accessible via SSH")
break
}
fmt.Println("Server is not yet rebooted, waiting...")
}
}
func rebooted(output []byte) bool {
// The uptime command returns two values, the first is the uptime in seconds
// 84.03 153.29
// Let's just check if the first value is less than 180 (3 min)
sec := strings.Split(strings.Split(string(output), " ")[0], ".")[0]
i, err := strconv.Atoi(sec)
if err != nil {
log.Fatal(err)
}
if i < 600 {
return true
}
return false
}