Blob


1 package icinga
3 import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net/http"
9 "strings"
10 )
12 type object interface {
13 name() string
14 attrs() map[string]interface{}
15 path() string
16 }
18 func (c *Client) lookupObject(objpath string) (object, error) {
19 resp, err := c.get(objpath)
20 if err != nil {
21 return nil, err
22 }
23 defer resp.Body.Close()
24 if resp.StatusCode == http.StatusNotFound {
25 return nil, ErrNotExist
26 }
27 iresp, err := parseResponse(resp.Body)
28 if err != nil {
29 return nil, fmt.Errorf("parse response: %v", err)
30 } else if iresp.Error != nil {
31 return nil, iresp.Error
32 } else if resp.StatusCode != http.StatusOK {
33 return nil, errors.New(resp.Status)
34 }
35 return objectFromLookup(iresp)
36 }
38 func (c *Client) allObjects(objpath string) ([]object, error) {
39 resp, err := c.get(objpath)
40 if err != nil {
41 return nil, err
42 }
43 defer resp.Body.Close()
44 iresp, err := parseResponse(resp.Body)
45 if err != nil {
46 return nil, err
47 } else if iresp.Error != nil {
48 return nil, iresp.Error
49 } else if resp.StatusCode != http.StatusOK {
50 return nil, errors.New(resp.Status)
51 }
52 return iresp.Results, nil
53 }
55 func (c *Client) filterObjects(objpath, expr string) ([]object, error) {
56 resp, err := c.getFilter(objpath, expr)
57 if err != nil {
58 return nil, err
59 }
60 defer resp.Body.Close()
61 if resp.StatusCode == http.StatusNotFound {
62 return nil, ErrNoMatch
63 }
64 iresp, err := parseResponse(resp.Body)
65 if err != nil {
66 return nil, err
67 } else if iresp.Error != nil {
68 return nil, iresp.Error
69 } else if resp.StatusCode != http.StatusOK {
70 return nil, errors.New(resp.Status)
71 }
72 return iresp.Results, nil
73 }
75 func (c *Client) createObject(obj object) error {
76 buf := &bytes.Buffer{}
77 switch v := obj.(type) {
78 case Host:
79 if err := json.NewEncoder(buf).Encode(v); err != nil {
80 return err
81 }
82 case Service:
83 if err := json.NewEncoder(buf).Encode(v); err != nil {
84 return err
85 }
86 case User:
87 if err := json.NewEncoder(buf).Encode(v); err != nil {
88 return err
89 }
90 default:
91 return fmt.Errorf("create type %T unsupported", v)
92 }
93 resp, err := c.put(obj.path(), buf)
94 if err != nil {
95 return err
96 }
97 if resp.StatusCode == http.StatusOK {
98 return nil
99 }
100 defer resp.Body.Close()
101 iresp, err := parseResponse(resp.Body)
102 if err != nil {
103 return fmt.Errorf("parse response: %v", err)
105 if strings.Contains(iresp.Error.Error(), "already exists") {
106 return ErrExist
108 return iresp.Error
111 func (c *Client) deleteObject(objpath string) error {
112 resp, err := c.delete(objpath)
113 if err != nil {
114 return err
116 defer resp.Body.Close()
117 if resp.StatusCode == http.StatusOK {
118 return nil
119 } else if resp.StatusCode == http.StatusNotFound {
120 return ErrNotExist
122 iresp, err := parseResponse(resp.Body)
123 if err != nil {
124 return fmt.Errorf("parse response: %v", err)
126 return iresp.Error