aboutsummaryrefslogtreecommitdiff
path: root/cmd/main/main.go
blob: 9210d44b75fb7bd19447552b7f85dc08d0e318cc (plain) (blame)
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package main

import (
	"bytes"
	"flag"
	"fmt"
	"gopkg.in/yaml.v3"
	"os"
	"time"

	"riedstra.dev/go/checkup"
)

var Version = "Development"

// jobResponse lets us return a bit more info from each of the jobs
// and track how the response has changed
type jobResponse struct {
	Id      string
	Message string
	Err     error
	Time    time.Time
}

type Config struct {
	RocketChatURL      string             `yaml:"RocketChatURL"`
	DiscordURL         string             `yaml:"DiscordURL"`
	DefaultCertPort    string             `yaml:"DefaultCertPort"`
	CertWindow         int                `yaml:"CertWindow"`
	CheckCerts         map[string]*string `yaml:"CheckCerts"`
	ExpectedStatusCode int                `yaml:"ExpectedStatusCode"`
	StatusChecks       map[string]*int    `yaml:"StatusChecks"`
	StatusChecksNoRdr  map[string]*int    `yaml:"StatusChecksNoRedirect"`
	Workers            int                `yaml:"Workers"`
	Interval           int                `yaml:"Interval"`
	RenotifyInterval   int                `yaml:"RenotifyInterval"`
	HTTPTimeout        int                `yaml:"HTTPTimeout"`
}

func ReadConfig(fn string, conf *Config) error {
	fh, err := os.Open(fn)
	if err != nil {
		return err
	}

	dec := yaml.NewDecoder(fh)
	err = dec.Decode(conf)
	return err
}

func jobNotifyDedup(conf *Config, prevJobs, newJobs map[string]*jobResponse) {
	buf := &bytes.Buffer{}

	for id, resp := range newJobs {
		oldresp, ok := prevJobs[id]
		if !ok {
			buf.Write([]byte(resp.Message))
			buf.Write([]byte{'\n'})
			continue
		}

		if oldresp.Message == resp.Message {
			// This isn't new, adjust accordingly
			newJobs[id] = prevJobs[id]

			if time.Now().After(
				oldresp.Time.Add(time.Duration(conf.RenotifyInterval) * time.Second)) {

				// Reset the time
				newJobs[id] = resp

				buf.Write([]byte(
					"still active --> " + resp.Message,
				))
				buf.Write([]byte{'\n'})
			}

			continue
		}

		buf.Write([]byte(
			oldresp.Message + " now --> " + resp.Message,
		))
		buf.Write([]byte{'\n'})
	}

	for id, resp := range prevJobs {
		_, ok := newJobs[id]
		if !ok {
			buf.Write([]byte(
				"[CLEARED]: " + resp.Message + "\n",
			))
		}
	}

	fmt.Print(string(buf.Bytes()))
	notify(conf, buf.Bytes())
}

func jobNotify(conf *Config, jobs map[string]*jobResponse) {
	buf := &bytes.Buffer{}

	for _, resp := range jobs {
		buf.Write([]byte(resp.Message))
		buf.Write([]byte{'\n'})
	}

	notify(conf, buf.Bytes())
}

func notify(conf *Config, b []byte) {
	if len(b) >= 1 {

		if conf.RocketChatURL != "" {
			err := checkup.SendRocketChatAlert(conf.RocketChatURL, string(b))
			if err != nil {
				fmt.Fprintln(os.Stderr, string(b))
				fmt.Fprintf(os.Stderr,
					"When sending webhook for rocketchat: %s\n", err)
			}

		}
		if conf.DiscordURL != "" {
			err := checkup.SendDiscordAlert(conf.DiscordURL, string(b))
			if err != nil {
				fmt.Fprintln(os.Stderr, string(b))
				fmt.Fprintf(os.Stderr,
					"When sending webhook for discord: %s\n", err)
			}
		}
	}
}

func main() {
	fl := flag.NewFlagSet("checkup", flag.ExitOnError)

	confFn := fl.String("c", "config.yml", "Configuration file path")
	version := fl.Bool("v", false, "Print version and exit")
	once := fl.Bool("o", false, "Run once then exit")
	debug := fl.Bool("d", false, "Dump the config to stderr")

	_ = fl.Parse(os.Args[1:])

	if *version {
		fmt.Println(Version)
		os.Exit(0)
	}

	// Defaults to be overridden by config
	conf := &Config{
		Workers:            1,
		DefaultCertPort:    "443",
		CertWindow:         15,
		ExpectedStatusCode: 200,
		Interval:           60,
		RenotifyInterval:   900,
	}

	err := ReadConfig(*confFn, conf)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	if *debug {
		enc := yaml.NewEncoder(os.Stderr)

		err := enc.Encode(conf)
		if err != nil {
			panic(err)
		}
	}

	if *once {
		jobNotify(conf, checkCerts(conf))
		jobNotify(conf, checkStatus(conf, conf.StatusChecks, checkup.HttpStatusOK))
		jobNotify(conf, checkStatus(conf, conf.StatusChecksNoRdr, checkup.HttpNoRedirectStatusOK))
		os.Exit(0)
	}

	certsPrev := map[string]*jobResponse{}
	statusPrev := map[string]*jobResponse{}
	statusPrevNoRdr := map[string]*jobResponse{}
	for {
		cert := checkCerts(conf)
		status := checkStatus(conf, conf.StatusChecks, checkup.HttpStatusOK)
		statusNoRdr := checkStatus(conf, conf.StatusChecksNoRdr, checkup.HttpNoRedirectStatusOK)

		jobNotifyDedup(conf, certsPrev, cert)
		jobNotifyDedup(conf, statusPrev, status)
		jobNotifyDedup(conf, statusPrevNoRdr, statusNoRdr)

		certsPrev = cert
		statusPrev = status
		statusPrevNoRdr = statusNoRdr

		time.Sleep(time.Duration(conf.Interval) * time.Second)
	}

}