Blob


1 package icinga
3 import "encoding/json"
5 // Host represents a Host object. To create a Host, the Name and CheckCommand
6 // fields must be set.
7 type Host struct {
8 Name string `json:"name"`
9 Address string `json:"address"`
10 Address6 string `json:"address6"`
11 Groups []string `json:"groups"`
12 State HostState `json:"state"`
13 StateType StateType `json:"state_type"`
14 CheckCommand string `json:"check_command"`
15 DisplayName string `json:"display_name"`
16 Acknowledgement bool
17 }
19 type HostGroup struct {
20 Name string `json:"name"`
21 DisplayName string `json:"display_name"`
22 }
24 type HostState int
26 const (
27 HostUp HostState = 0 + iota
28 HostDown
29 HostUnreachable
30 )
32 func (s HostState) String() string {
33 switch s {
34 case HostUp:
35 return "HostUp"
36 case HostDown:
37 return "HostDown"
38 case HostUnreachable:
39 return "HostUnreachable"
40 }
41 return "unhandled host state"
42 }
44 func (h Host) name() string {
45 return h.Name
46 }
48 func (h Host) path() string {
49 return "/objects/hosts/" + h.Name
50 }
52 func (hg HostGroup) name() string {
53 return hg.Name
54 }
56 func (hg HostGroup) path() string {
57 return "/objects/hostgroups/" + hg.Name
58 }
60 func (h Host) MarshalJSON() ([]byte, error) {
61 attrs := make(map[string]interface{})
62 attrs["address"] = h.Address
63 attrs["address6"] = h.Address6
64 if len(h.Groups) > 0 {
65 attrs["groups"] = h.Groups
66 }
67 attrs["check_command"] = h.CheckCommand
68 attrs["display_name"] = h.DisplayName
69 m := make(map[string]interface{})
70 m["attrs"] = attrs
71 return json.Marshal(m)
72 }
74 // UnmarhsalJSON unmarshals host attributes into more meaningful Host field types.
75 func (h *Host) UnmarshalJSON(data []byte) error {
76 type alias Host
77 aux := &struct {
78 Acknowledgement int
79 *alias
80 }{
81 alias: (*alias)(h),
82 }
83 if err := json.Unmarshal(data, &aux); err != nil {
84 return err
85 }
86 if aux.Acknowledgement != 0 {
87 h.Acknowledgement = true
88 }
89 return nil
90 }
92 func (hg HostGroup) MarshalJSON() ([]byte, error) {
93 type attrs struct {
94 DisplayName string `json:"display_name"`
95 }
96 type group struct {
97 Attrs attrs `json:"attrs"`
98 }
99 return json.Marshal(&group{
100 Attrs: attrs{
101 DisplayName: hg.DisplayName,
102 },
103 })