/
serviceextinfo.go
351 lines (294 loc) · 7.84 KB
/
serviceextinfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package nrc
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"regexp"
"sort"
"strings"
)
type serviceextinfo struct {
hostname string
svcdesc string
notes string
notes_url string
action_url string
icon_image string
icon_image_alt string
disable string
}
type Serviceextinfo struct {
serviceextinfo []serviceextinfo
username string
password string
}
func (h Serviceextinfo) RequiredOptions() []string {
return []string{}
}
func (h *Serviceextinfo) Options() (arr []string) {
n := reflect.TypeOf(h.serviceextinfo).Elem().NumField()
for i := 0; i < n; i++ {
f := reflect.TypeOf(h.serviceextinfo).Elem().Field(i)
arr = append(arr, f.Name)
}
sort.Strings(arr)
return arr
}
func (h Serviceextinfo) OptionsJson() (s string) {
f := h.Options()
s = "["
c := ""
for _, j := range f {
s += c + `"` + j + `"`
c = ","
}
s += "]"
return s
}
func (h *Serviceextinfo) filterServiceextinfo(filter string) {
f := NewFilter(filter)
newh := []serviceextinfo{}
for _, k := range h.serviceextinfo {
t := &k // Must be a pointer or interface for reflection
foundCount := 0
for i := 0; i < len(f.names); i++ {
_, found := reflect.TypeOf(t).Elem().FieldByName(f.names[i])
if found == true {
val := reflect.ValueOf(t).Elem().FieldByName(f.names[i])
userRegx, _ := UrlDecodeForce(f.regex[i])
regex := regexp.MustCompile(userRegx)
if regex.MatchString(val.String()) {
foundCount += 1
continue
}
/*
val := reflect.ValueOf(t).Elem().FieldByName(f.names[i])
if val.String() == f.regex[i] {
foundCount += 1
continue
}
*/
}
}
if foundCount == len(f.names) {
newh = append(newh, k)
}
}
// Replace the list we got with this filtered list
h.serviceextinfo = newh
}
func (h Serviceextinfo) Show(brief bool, filter string) {
if filter != "" {
h.filterServiceextinfo(filter)
}
var ind4 = " " // big indent
fmt.Printf("\n")
for _, r := range h.serviceextinfo {
t := &r // Reflection is only allowed on ptr or interface
n := reflect.TypeOf(t).Elem().NumField()
for i := 0; i < n; i++ {
f := reflect.TypeOf(t).Elem().Field(i)
g := reflect.ValueOf(t).Elem().Field(i)
if brief == true || (brief == false && g.String() != "") {
fmt.Printf("%s%s:%s\n",
ind4, f.Name, g)
}
}
fmt.Printf("\n")
}
}
func (h Serviceextinfo) ShowJson(newline, brief bool, filter string) {
if filter != "" {
h.filterServiceextinfo(filter)
}
var nl = "" // newline
var ind4 = "" // big indent
var ind2 = "" // small indent
if newline == false {
nl = "\n"
ind4 = " "
ind2 = " "
}
fmt.Printf("[")
objcomma := ""
for _, r := range h.serviceextinfo {
comma := ""
nli := ""
fmt.Printf("%s%s%s{%s", objcomma, nl, ind2, nl)
t := &r // Reflection is only allowed on ptr or interface
n := reflect.TypeOf(t).Elem().NumField()
for i := 0; i < n; i++ {
f := reflect.TypeOf(t).Elem().Field(i)
g := reflect.ValueOf(t).Elem().Field(i)
if brief == true || (brief == false && g.String() != "") {
fmt.Printf("%s%s%s\"%s\":\"%s\"",
comma, nli, ind4, f.Name, g)
comma = ","
nli = nl
}
}
fmt.Printf("%s%s}", nl, ind2)
objcomma = ","
}
fmt.Printf("%s]\n", nl)
}
func NewNrcServiceextinfo(username, password string) *Serviceextinfo {
h := &Serviceextinfo{}
h.username = username
h.password = password
return h
}
/*
* Send HTTP GET request
*/
func (h *Serviceextinfo) Get(url, endpoint, folder string, data []string) (e error) {
// accept bad certs
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
}
client := &http.Client{Transport: tr}
// Not available in Go<1.3
//client.Timeout = 8 * 1e9
for strings.HasSuffix(url, "/") {
url = strings.TrimSuffix(url, "/")
}
for strings.HasSuffix(endpoint, "/") {
url = strings.TrimSuffix(endpoint, "/")
}
// Construct url, http://1.2.3.4/rest/show/hosts?json={"folder":"local",...}
fullUrl := url + "/" + endpoint + "?json={\"folder\":\"" + folder + "\""
dataStr, err := FormatData(data, "services")
if err != nil {
txt := fmt.Sprintf("Could not format data. Check the '-d' option.")
return HttpError{txt}
}
if dataStr != "" {
fullUrl += "," + dataStr
}
fullUrl += "}"
//fmt.Printf("URL=%s\n", fullUrl)
//fmt.Printf("%s\n", url+"/"+endpoint)
//resp, err := client.Get(fullUrl)
req, err := http.NewRequest("GET", fullUrl, nil)
if len(h.username) > 0 {
req.SetBasicAuth(h.username, h.password)
}
resp, err := client.Do(req)
if err != nil {
txt := fmt.Sprintf("Could not send REST request ('%s').", err.Error())
return HttpError{txt}
}
defer resp.Body.Close()
var body []byte
if b, err := ioutil.ReadAll(resp.Body); err != nil {
txt := fmt.Sprintf("Error reading Body ('%s').", err.Error())
return HttpError{txt}
} else {
body = b
}
if resp.StatusCode != 200 {
response, _ := UrlDecode(string(body))
txt := fmt.Sprintf("Status (%d): %s", resp.StatusCode, response)
return HttpError{txt}
} else {
var generic interface{}
if err := json.Unmarshal(body, &generic); err != nil {
txt := fmt.Sprintf("Status (%d) Error decoding JSON (%s).",
resp.StatusCode, err.Error())
return HttpError{txt}
}
genericReply := generic.([]interface{})
//fmt.Printf("%s\n", body)
for _, j := range genericReply {
serviceextinfo := serviceextinfo{}
for _, j2 := range j.([]interface{}) {
content := j2.(map[string]interface{})
for k, v := range content {
switch k {
case "hostname":
serviceextinfo.hostname = v.(string)
case "svcdesc":
serviceextinfo.svcdesc = v.(string)
case "notes":
serviceextinfo.notes = v.(string)
case "notes_url":
serviceextinfo.notes_url = v.(string)
case "action_url":
serviceextinfo.action_url = v.(string)
case "icon_image":
serviceextinfo.icon_image = v.(string)
case "icon_image_alt":
serviceextinfo.icon_image_alt = v.(string)
case "disable":
serviceextinfo.disable = v.(string)
}
}
}
h.serviceextinfo = append(h.serviceextinfo, serviceextinfo)
}
return nil
}
}
/*
* Send HTTP POST request
*/
func (h Serviceextinfo) Post(url, endpoint, folder string, data []string) (e error) {
for strings.HasSuffix(url, "/") {
url = strings.TrimSuffix(url, "/")
}
for strings.HasSuffix(endpoint, "/") {
url = strings.TrimSuffix(endpoint, "/")
}
fullUrl := url + "/" + endpoint
// Format data
dataStr := "json={\"folder\":\"" + folder + "\""
dataInr, err := FormatData(data, "serviceextinfo")
if err != nil {
txt := fmt.Sprintf("Could not format data. Check the '-d' option.")
return HttpError{txt}
}
if dataInr != "" {
dataStr += "," + dataInr
}
dataStr += "}"
//fmt.Printf("URL=%s\n", fullUrl)
//fmt.Printf("Data=%s\n", dataStr)
buf := bytes.NewBuffer([]byte(dataStr))
//fmt.Printf("json=%s\n", buf)
// accept bad certs
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
//resp, err := client.Post(fullUrl, "application/x-www-form-urlencoded", buf)
req, err := http.NewRequest("POST", fullUrl, buf)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if len(h.username) > 0 {
req.SetBasicAuth(h.username, h.password)
}
resp, err := client.Do(req)
if err != nil {
txt := fmt.Sprintf("Could not send REST request ('%s').", err.Error())
return HttpError{txt}
}
defer resp.Body.Close()
var body []byte
if b, err := ioutil.ReadAll(resp.Body); err != nil {
txt := fmt.Sprintf("Error reading Body ('%s').", err.Error())
return HttpError{txt}
} else {
body = b
}
if resp.StatusCode != 200 {
response, _ := UrlDecode(string(body))
txt := fmt.Sprintf("Status (%d): %s", resp.StatusCode, response)
return HttpError{txt}
}
// If we get here then it was a success
return nil
}