/
server.go
90 lines (85 loc) · 2.43 KB
/
server.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
87
88
89
90
package main
import (
"flag"
"fmt"
"github.com/coreos/go-systemd/dbus"
"net/http"
"strconv"
)
type UnitAction struct {
Action string
Unit string
}
var ConfigData = map[string][]UnitAction{
"ptw/nodename-DELETE": []UnitAction{
UnitAction{Action: "stop", Unit: "ptw-protonet.service"},
UnitAction{Action: "restart", Unit: "dokku-protonet.service"},
},
"ptw/nodename-PUT": []UnitAction{
UnitAction{Action: "restart", Unit: "ptw-protonet.service"},
UnitAction{Action: "restart", Unit: "dokku-protonet.service"},
},
"ptw/enabled-DELETE": []UnitAction{
UnitAction{Action: "stop", Unit: "ptw-protonet.service"},
},
"ptw/enabled-PUT": []UnitAction{
UnitAction{Action: "restart", Unit: "ptw-protonet.service"},
},
"ssh-DELETE": []UnitAction{
UnitAction{Action: "restart", Unit: "dokku-protonet.service"},
},
"ssh-PUT": []UnitAction{
UnitAction{Action: "restart", Unit: "dokku-protonet.service"},
},
}
func createHandler(connection *dbus.Conn) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.PostForm.Get("key")
action := r.PostForm.Get("action")
http_status := http.StatusOK
if unit_actions, action_exists := ConfigData[key+"-"+action]; action_exists {
for _, unit_action := range unit_actions {
result_channel := make(chan string, 1)
var err error
var result string
switch unit_action.Action {
case "restart", "start":
_, err = connection.RestartUnit(unit_action.Unit, "fail", result_channel)
case "stop":
_, err = connection.StopUnit(unit_action.Unit, "fail", result_channel)
}
if err == nil {
result = <-result_channel
} else {
fmt.Printf("Systemd Unit ERROR: %s", err.Error())
w.Write([]byte(err.Error()))
http_status = http.StatusInternalServerError
}
if result != "done" {
fmt.Printf("Unexpected API result: %s", result)
w.Write([]byte(result))
http_status = http.StatusInternalServerError
}
}
} else {
http_status = http.StatusNotFound
fmt.Printf("NO ACTION WAS GIVEN.")
w.Write([]byte("NO ACTION WAS GIVEN."))
}
w.WriteHeader(http_status)
}
}
func main() {
var port int
flag.IntVar(&port, "port", 3001, "server port")
flag.Parse()
fmt.Println("Port: ", port)
var connection, err = dbus.New()
if err != nil {
panic(err)
}
var handler = createHandler(connection)
http.HandleFunc("/", handler)
http.ListenAndServe(":"+strconv.Itoa(port), nil)
}