Blob


1 package icinga
3 import (
4 "encoding/json"
5 "strings"
6 "time"
7 )
9 func (s Service) name() string {
10 return s.Name
11 }
13 func (s Service) path() string {
14 return "/objects/services/" + s.Name
15 }
17 // Service represents a Service object.
18 type Service struct {
19 Name string `json:"-"`
20 Groups []string `json:"groups,omitempty"`
21 State ServiceState `json:"state,omitempty"`
22 StateType StateType `json:"state_type,omitempty"`
23 CheckCommand string `json:"check_command"`
24 DisplayName string `json:"display_name,omitempty"`
25 LastCheck time.Time `json:",omitempty"`
26 LastCheckResult CheckResult `json:"last_check_result,omitempty"`
27 Acknowledgement bool `json:",omitempty"`
28 Notes string `json:"notes,omitempty"`
29 NotesURL string `json:"notes_url,omitempty"`
30 }
32 type CheckResult struct {
33 CheckSource string `json:"check_source"`
34 Command interface{}
35 Output string
36 }
38 type ServiceState int
40 const (
41 ServiceOK ServiceState = 0 + iota
42 ServiceWarning
43 ServiceCritical
44 ServiceUnknown
45 )
47 func (state ServiceState) String() string {
48 switch state {
49 case ServiceOK:
50 return "OK"
51 case ServiceWarning:
52 return "Warning"
53 case ServiceCritical:
54 return "Critical"
55 }
56 return "Unknown"
57 }
59 // UnmarshalJSON unmarshals service attributes into more meaningful Service field types.
60 func (s *Service) UnmarshalJSON(data []byte) error {
61 type alias Service
62 aux := &struct {
63 Acknowledgement interface{} `json:"acknowledgement"`
64 State interface{} `json:"state"`
65 StateType interface{} `json:"state_type"`
66 LastCheck float64 `json:"last_check"`
67 *alias
68 }{
69 alias: (*alias)(s),
70 }
71 if err := json.Unmarshal(data, &aux); err != nil {
72 return err
73 }
74 switch v := aux.Acknowledgement.(type) {
75 case int:
76 if v != 0 {
77 s.Acknowledgement = true
78 }
79 case float64:
80 if int(v) != 0 {
81 s.Acknowledgement = true
82 }
83 }
84 switch v := aux.State.(type) {
85 case int:
86 s.State = ServiceState(v)
87 case float64:
88 s.State = ServiceState(v)
89 }
90 switch v := aux.StateType.(type) {
91 case int:
92 s.StateType = StateType(v)
93 case float64:
94 s.StateType = StateType(v)
95 }
96 s.LastCheck = time.Unix(int64(aux.LastCheck), 0)
97 return nil
98 }
100 func (s Service) Host() string {
101 return strings.SplitN(s.Name, "!", 2)[0]
104 func (cr CheckResult) RawCommand() string {
105 switch v := cr.Command.(type) {
106 case string:
107 return v
108 case []interface{}:
109 var cmd []string
110 for i := range v {
111 if arg, ok := v[i].(string); ok {
112 cmd = append(cmd, arg)
115 return strings.Join(cmd, " ")
117 return "no command"