summaryrefslogtreecommitdiff
path: root/http.go
blob: f0b5e07409b80ee7d87ed587393bb0ca9f6eac6e (plain)
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
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"go.wit.com/log"
)

// remove '?' part and trailing '/'
func cleanURL(url string) string {
	url = "/" + strings.Trim(url, "/")
	return url
}

func okHandler(w http.ResponseWriter, r *http.Request) {
	// log.Info("Got URL Path: ", r.URL.Path)
	route := cleanURL(r.URL.Path)

	hostname := r.URL.Query().Get("hostname")
	// flag := r.URL.Query().Get("flag")

	msg, err := ioutil.ReadAll(r.Body) // Read the body as []byte
	if err != nil {
		log.Info("ReadAll() error =", err)
		return
	}

	if route == "/" {
		return
	}

	if route == "/machine" {
		handleMachine(r, w, hostname, msg)
		return
	}

	if route == "/uptime" {
		if me.zood == nil {
			fmt.Fprintf(w, "BAD zood == nil\n")
			return
		}
		var count int
		var bad int
		for m := range me.machines.IterAll() {
			count += 1
			if m.FindVersion("zood") != me.zood.version {
				if m.SinceLastUpdate() > 10*time.Minute {
					// skip machines that have not been updated in the last 10 minutes
					log.Info("ignoring old machine", m.Hostname)
					continue
				}
				bad += 1
			}
		}
		if bad == 0 {
			fmt.Fprintf(w, "GOOD machine count=(%d) all machines are version %s\n", count, me.zood.version)
		} else {
			fmt.Fprintf(w, "BAD machine count=(%d) upgrade=(%d) to %s\n", count, bad, me.zood.version)
		}
		return
	}

	log.Warn("BAD URL =", route)
}

// starts and sits waiting for HTTP requests
func startHTTP() {
	http.HandleFunc("/", okHandler)

	p := fmt.Sprintf(":%d", argv.Port)
	log.Println("Running on port", p)

	err := http.ListenAndServe(p, nil)
	if err != nil {
		log.Println("Error starting server:", err)
		badExit(err)
	}
}