Blob


1 package icinga
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "strings"
9 )
11 type checker interface {
12 object
13 Check(*Client) error
14 }
16 type StateType int
18 const (
19 StateSoft StateType = 0 + iota
20 StateHard
21 )
23 func (st StateType) String() string {
24 switch st {
25 case StateSoft:
26 return "StateSoft"
27 case StateHard:
28 return "StateHard"
29 }
30 return "unsupported state type"
31 }
33 // Check reschedules the check for s via the provided Client.
34 func (s Service) Check(c *Client) error {
35 return c.check(s)
36 }
38 // Check reschedules the check for h via the provided Client.
39 func (h Host) Check(c *Client) error {
40 return c.check(h)
41 }
43 func splitServiceName(name string) []string {
44 return strings.SplitN(name, "!", 2)
45 }
47 func (c *Client) check(ch checker) error {
48 var filter struct {
49 Type string `json:"type"`
50 Expr string `json:"filter"`
51 }
52 switch v := ch.(type) {
53 case Host:
54 filter.Type = "Host"
55 filter.Expr = fmt.Sprintf("host.name == %q", v.Name)
56 case Service:
57 filter.Type = "Service"
58 a := splitServiceName(v.Name)
59 if len(a) != 2 {
60 return fmt.Errorf("check %s: invalid service name", v.Name)
61 }
62 host := a[0]
63 service := a[1]
64 filter.Expr = fmt.Sprintf("host.name == %q && service.name == %q", host, service)
65 default:
66 return fmt.Errorf("cannot check %T", v)
67 }
69 buf := &bytes.Buffer{}
70 if err := json.NewEncoder(buf).Encode(filter); err != nil {
71 return err
72 }
73 resp, err := c.post("/actions/reschedule-check", buf)
74 if err != nil {
75 return fmt.Errorf("check %s: %w", ch.name(), err)
76 }
77 switch resp.StatusCode {
78 case http.StatusOK:
79 return nil
80 case http.StatusNotFound:
81 return fmt.Errorf("check %s: %w", ch.name(), ErrNotExist)
82 default:
83 return fmt.Errorf("check %s: %s", ch.name(), resp.Status)
84 }
85 }