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) filterObjects(objpath, expr string) ([]object, error) {
39 resp, err := c.get(objpath, expr)
40 if err != nil {
41 return nil, err
42 }
43 defer resp.Body.Close()
44 if expr != "" && resp.StatusCode == http.StatusNotFound {
45 return nil, ErrNoMatch
47 }
48 iresp, err := parseResponse(resp.Body)
49 if err != nil {
50 return nil, fmt.Errorf("parse response: %v", err)
51 } else if iresp.Error != nil {
52 return nil, iresp.Error
53 } else if resp.StatusCode != http.StatusOK {
54 return nil, errors.New(resp.Status)
55 }
56 return iresp.Results, nil
57 }
59 func (c *Client) createObject(obj object) error {
60 buf := &bytes.Buffer{}
61 switch v := obj.(type) {
62 case Host, Service, User:
63 if err := json.NewEncoder(buf).Encode(v); err != nil {
64 return err
65 }
66 default:
67 return fmt.Errorf("create type %T unsupported", v)
68 }
69 resp, err := c.put(obj.path(), buf)
70 if err != nil {
71 return err
72 }
73 if resp.StatusCode == http.StatusOK {
74 return nil
75 }
76 defer resp.Body.Close()
77 iresp, err := parseResponse(resp.Body)
78 if err != nil {
79 return fmt.Errorf("parse response: %v", err)
80 }
81 if strings.Contains(iresp.Error.Error(), "already exists") {
82 return ErrExist
83 }
84 return iresp.Error
85 }
87 func (c *Client) deleteObject(objpath string) error {
88 resp, err := c.delete(objpath)
89 if err != nil {
90 return err
91 }
92 defer resp.Body.Close()
93 if resp.StatusCode == http.StatusOK {
94 return nil
95 } else if resp.StatusCode == http.StatusNotFound {
96 return ErrNotExist
97 }
98 iresp, err := parseResponse(resp.Body)
99 if err != nil {
100 return fmt.Errorf("parse response: %v", err)
102 return iresp.Error