-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
110 lines (94 loc) · 2.46 KB
/
Copy pathmain.go
File metadata and controls
110 lines (94 loc) · 2.46 KB
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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
const (
ExitOk = 0
ExitWarning = 1
ExitCritical = 2
ExitUnknown = 3
)
func getStatusNamed(code int) string {
switch code {
case ExitOk:
return "OK"
case ExitWarning:
return "WARNING"
case ExitCritical:
return "CRITICAL"
case ExitUnknown:
return "UNKNOWN"
default:
return "UNKNOWN"
}
}
const GithubAPI = "https://api.github.com/repos/cloudflare/cloudflared/releases/latest"
const Timeout = 10 * time.Second
func exitWith(msg string, code int) {
newMsg := fmt.Sprintf("%s - %s", getStatusNamed(code), msg)
fmt.Println(newMsg)
os.Exit(code)
}
func getInstalledVersion() string {
cmd := exec.Command("cloudflared", "--version")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
exitWith("cloudflared not installed", ExitUnknown)
}
lines := strings.Split(out.String(), "\n")
if len(lines) == 0 {
exitWith("cloudflared version output empty", ExitUnknown)
}
parts := strings.Fields(lines[0])
if len(parts) < 3 {
exitWith("cloudflared version output malformed", ExitUnknown)
}
return strings.TrimPrefix(parts[2], "v")
}
func getLatestVersion(token string) string {
client := &http.Client{Timeout: Timeout}
req, err := http.NewRequest("GET", GithubAPI, nil)
if err != nil {
exitWith("Failed to create HTTP request", ExitUnknown)
}
if token != "" {
req.Header.Set("Authorization", "token "+token)
}
resp, err := client.Do(req)
if err != nil {
exitWith("Failed to fetch Github API:"+err.Error(), ExitUnknown)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
exitWith(fmt.Sprintf("Failed to fetch Github API: %s", resp.Status), ExitUnknown)
}
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
exitWith("Failed to decode Github API response: "+err.Error(), ExitUnknown)
}
tag, ok := data["tag_name"].(string)
if !ok || tag == "" {
exitWith("Failed to parse Github API response: tag_name not found", ExitUnknown)
}
return strings.TrimPrefix(tag, "v")
}
func main() {
token := flag.String("token", "", "Github API token")
flag.Parse()
installed := getInstalledVersion()
latest := getLatestVersion(*token)
if installed != latest {
exitWith(fmt.Sprintf("Installed version: %s, Latest version: %s", installed, latest), ExitWarning)
}
exitWith(fmt.Sprintf("Installed version: %s, Latest version: %s", installed, latest), ExitOk)
}