forked from fallais/go-nagrapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (77 loc) · 2.16 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"net/http"
"strconv"
"github.com/cxfcxf/nagtomaps"
"github.com/zenazn/goji"
)
// Response ...
type Response struct {
Hosts []*Host `json:"hosts,omitempty"`
}
// Host ...
type Host struct {
Name string `json:"name,omitempty"`
Services []*Service `json:"services,omitempty"`
}
// Service ...
type Service struct {
Name string `json:"name,omitempty"`
//modified to *int in order to have json correctly identify the 0 value as a real value and not nil
CurrentState *int `json:"current_state,omitempty"`
}
var statusFile = flag.String("s", "/data/status.dat", "Specify the location of the status file")
//added the n flag to have as output only services with that level of issue
var nagiosstate = flag.Int("n", 0, "Specify the number Nagios uses to describe the status [0, 1, 2, 3]")
// GetState ...
func GetState(w http.ResponseWriter, r *http.Request) {
// Parse the status file
sdata := nagtomaps.ParseStatus(*statusFile)
//needed to have a int value to check it against nagios status level
nagstatus := *nagiosstate
hostResponse := &Response{
Hosts: nil,
}
for name := range sdata.Hoststatuslist {
host := &Host{
Name: name,
Services: nil,
}
for name2, object2 := range sdata.Servicestatuslist[name] {
//if the state of the service does not match with the one in input interrupts the loop
currstateint, _ := strconv.Atoi(object2["current_state"])
if currstateint != nagstatus {
continue
}
if object2["host_name"] == host.Name {
service := &Service{
Name: name2,
CurrentState: &currstateint,
}
host.Services = append(host.Services, service)
}
}
hostResponse.Hosts = append(hostResponse.Hosts, host)
}
// Marshal the result
response, err := json.Marshal(hostResponse)
if err != nil {
panic("Impossible to marshal")
}
// Write the response
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(response)
}
func main() {
// Parse the flags
flag.Parse()
// Routes for API
goji.Get("/state", GetState)
// Set the port
flag.Set("bind", ":8080")
// Start the server
goji.Serve()
}