-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go.go
109 lines (92 loc) · 2.71 KB
/
main.go.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strings"
"github.com/alekstet/linux_service_checker/conf"
)
type Req struct {
Command string `json:"command"`
Name string `json:"name"`
}
type Data struct {
ServicesNames []string
ServerName string
}
func (d *Data) Datas(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
services_works := []string{}
services_statuses := []string{}
services_journals := []string{}
services_infos := make(map[string][]string)
for _, j := range d.ServicesNames {
cmd_status := exec.Command("ssh", d.ServerName, "sudo", "systemctl", "status", j)
stdout_status, err := cmd_status.CombinedOutput()
if err != nil {
w.WriteHeader(500)
}
cmd_journal := exec.Command("ssh", d.ServerName, "sudo", "journalctl", "-u", j, "-e", "-n")
stdout_journal, err := cmd_journal.CombinedOutput()
if err != nil {
w.WriteHeader(500)
}
services_statuses = append(services_statuses, string(stdout_status))
services_journals = append(services_journals, string(stdout_journal))
words := strings.Split(string(stdout_status), " ")
for _, word := range words {
contain_run := strings.Contains(word, "(running)")
contain_exit := strings.Contains(word, "(exited)")
contain_dead := strings.Contains(word, "(dead)")
contain_rest := strings.Contains(word, "(auto-restart)")
if contain_run {
services_works = append(services_works, "running")
}
if contain_exit {
services_works = append(services_works, "exited")
}
if contain_dead {
services_works = append(services_works, "dead")
}
if contain_rest {
services_works = append(services_works, "auto-restart")
}
}
}
for i, j := range d.ServicesNames {
info := []string{services_statuses[i], services_works[i], services_journals[i]}
services_infos[j] = info
}
jsonResp, err := json.Marshal(services_infos)
if err != nil {
w.WriteHeader(500)
}
w.Write(jsonResp)
}
func Action(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(500)
}
var req Req
json.Unmarshal(body, &req)
cmd := exec.Command("sudo", "systemctl", req.Command, req.Name)
_, err = cmd.CombinedOutput()
if err != nil {
w.WriteHeader(500)
}
}
func main() {
services_names, server_url, server_name := conf.ReadConfig()
d := Data{services_names, server_name}
html := http.FileServer(http.Dir("./dist"))
http.HandleFunc("/datas", d.Datas)
http.HandleFunc("/action", Action)
http.Handle("/", html)
err := http.ListenAndServe(server_url, nil)
if err != nil {
log.Fatal(err)
}
}