File size: 7,462 Bytes
1e92f2d |
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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
package remotemonitor
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"net/mail"
"net/smtp"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/target/goalert/config"
"github.com/target/goalert/notification/twilio"
"github.com/target/goalert/retry"
)
// Monitor will check for functionality and communication between itself and one or more instances.
// Each monitor should have a unique phone number and location.
type Monitor struct {
appCfg config.Config
cfg Config
tw twilio.Config
shutdownCh chan struct{}
startCh chan string
finishCh chan string
pendingCh chan int
pending map[string]time.Time
srv *http.Server
}
func setRequestScheme(scheme string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// required for Twilio sig validation to work
req.URL.Host = req.Host
req.URL.Scheme = scheme
h.ServeHTTP(w, req)
})
}
// NewMonitor creates and starts a new Monitor with the given Config.
func NewMonitor(cfg Config) (*Monitor, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
http.DefaultTransport.(*http.Transport).DisableKeepAlives = true
http.DefaultTransport = &requestIDTransport{
RoundTripper: http.DefaultTransport,
}
u, err := url.Parse(cfg.PublicURL)
if err != nil {
return nil, err
}
m := &Monitor{
cfg: cfg,
tw: twilio.Config{},
shutdownCh: make(chan struct{}),
startCh: make(chan string),
finishCh: make(chan string),
pendingCh: make(chan int),
pending: make(map[string]time.Time),
}
l, err := net.Listen("tcp", cfg.ListenAddr)
if err != nil {
return nil, err
}
h := twilio.WrapValidation(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, u.Path)
m.ServeHTTP(w, req)
}), m.tw)
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, req *http.Request) {
_, _ = io.WriteString(w, "ok")
})
m.appCfg.General.PublicURL = cfg.PublicURL
m.appCfg.Twilio.Enable = true
m.appCfg.Twilio.AccountSID = cfg.Twilio.AccountSID
m.appCfg.Twilio.AuthToken = cfg.Twilio.AuthToken
m.appCfg.Twilio.FromNumber = cfg.Twilio.FromNumber
m.appCfg.Twilio.MessagingServiceSID = cfg.Twilio.MessageSID
mux.Handle("/", twilio.WrapHeaderHack(h))
m.srv = &http.Server{
Handler: config.Handler(
setRequestScheme(u.Scheme, mux),
config.Static(m.appCfg),
),
IdleTimeout: 15 * time.Second,
ReadHeaderTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
MaxHeaderBytes: 1024 * 1024,
}
m.srv.SetKeepAlivesEnabled(false)
log.Println("Listening:", l.Addr())
go m.serve(l)
go m.loop()
go m.waitLoop()
return m, nil
}
func logClose(close func() error) {
if err := close(); err != nil {
log.Println("ERROR: close: ", err)
}
}
func (m *Monitor) serve(l net.Listener) {
err := m.srv.Serve(l)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalln("ERROR:", err)
}
}
func (m *Monitor) reportErr(i Instance, err error, action string) {
if err == nil {
return
}
summary := fmt.Sprintf("Remote Monitor in %s failed to %s in %s", m.cfg.Location, action, i.Location)
details := fmt.Sprintf("Monitor Location: %s\nInstance Location: %s\nAction: %s\nError: %s", m.cfg.Location, i.Location, action, err.Error())
for _, ins := range m.cfg.Instances {
if ins.ErrorAPIKey == "" {
log.Println("No ErrorAPIKey for", ins.Location)
continue
}
ins := ins // copy
go func() {
if err := ins.createGenericAlert(ins.ErrorAPIKey, "", summary, details); err != nil {
log.Printf("ERROR: create generic alert: %v", err)
}
}()
}
log.Println("ERROR:", summary)
}
func (m *Monitor) waitLoop() {
t := time.NewTicker(100 * time.Millisecond)
for {
select {
case <-t.C:
for k, v := range m.pending {
if time.Since(v) > time.Minute {
delete(m.pending, k)
}
}
case name := <-m.startCh:
m.pending[name] = time.Now()
case name := <-m.finishCh:
delete(m.pending, name)
}
select {
case m.pendingCh <- len(m.pending):
default:
}
}
}
func (m *Monitor) createEmailAlert(i Instance, dedup, summary, details string) error {
addr, err := mail.ParseAddress(i.EmailAPIKey)
if err != nil {
return err
}
key, domain, found := strings.Cut(addr.Address, "@")
if !found {
return fmt.Errorf("invalid email address: %s", i.EmailAPIKey)
}
addr.Address = key + "+" + dedup + "@" + domain
msg := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\r\n"
msg += fmt.Sprintf("From: %s\r\n", m.cfg.SMTP.From)
msg += fmt.Sprintf("To: %s\r\n", addr.String())
msg += fmt.Sprintf("Subject: %s\r\n", summary)
msg += fmt.Sprintf("\r\n%s\r\n", details)
host, _, err := net.SplitHostPort(m.cfg.SMTP.ServerAddr)
if err != nil {
return err
}
var auth smtp.Auth
if m.cfg.SMTP.User != "" || m.cfg.SMTP.Pass != "" {
auth = smtp.PlainAuth("", m.cfg.SMTP.User, m.cfg.SMTP.Pass, host)
}
err = retry.DoTemporaryError(func(_ int) error {
err = smtp.SendMail(m.cfg.SMTP.ServerAddr, auth, m.cfg.SMTP.From, []string{addr.Address}, []byte(msg))
if err == nil {
return nil
}
if strings.HasPrefix(err.Error(), "4") { // SMTP server return codes beginning with 4 are considered transient
err = retry.TemporaryError(err)
}
return errors.Wrap(err, "send email")
},
retry.Log(m.context()),
retry.Limit(m.cfg.SMTP.Retries),
retry.FibBackoff(time.Second),
)
return err
}
func (m *Monitor) loop() {
delay := time.Duration(m.cfg.CheckMinutes) * time.Minute
t := time.NewTicker(delay)
dedup := fmt.Sprintf("RM-%s", m.cfg.Location)
summary := fmt.Sprintf("Remote Monitor Communication Test from %s", m.cfg.Location)
details := fmt.Sprintf(`This alert was generated by a GoAlert Remote Monitor running in %s.
These alerts are generated periodically to monitor actual system functionality and communication.
If it is not automatically closed within a minute, there may be a problem with SMS or network connectivity.
`, m.cfg.Location)
doCheck := func(preferEmail bool) {
for _, i := range m.cfg.Instances {
if i.ErrorsOnly {
continue
}
m.startCh <- i.Location
go func(i Instance) {
var err error
switch {
case i.EmailAPIKey != "" && (i.GenericAPIKey == "" || preferEmail):
err = m.createEmailAlert(i, dedup, summary, details)
case i.GenericAPIKey != "" && (i.EmailAPIKey == "" || !preferEmail):
err = i.createGenericAlert(i.GenericAPIKey, dedup, summary, details)
}
if err != nil {
m.reportErr(i, err, "create new alert")
}
}(i)
}
}
var preferEmail bool
doCheck(preferEmail)
for {
select {
case <-m.shutdownCh:
return
case <-t.C:
preferEmail = !preferEmail
doCheck(preferEmail)
}
}
}
// context will return a new background context with config applied.
func (m *Monitor) context() context.Context {
return m.appCfg.Context(context.Background())
}
// Shutdown gracefully shuts down the monitor, waiting for any in-flight checks to complete.
func (m *Monitor) Shutdown(ctx context.Context) error {
log.Println("Beginning shutdown...")
close(m.shutdownCh)
wait:
for {
select {
case n := <-m.pendingCh:
if n == 0 {
// wait for all pending operations to finish or timeout
break wait
}
case <-ctx.Done():
return ctx.Err()
}
}
return m.srv.Shutdown(ctx)
}
|