forked from FXinnovation/alertmanager-webhook-servicenow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
servicenow.go
254 lines (206 loc) · 7.47 KB
/
servicenow.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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/prometheus/common/log"
)
const (
serviceNowBaseURL = "https://%s.service-now.com"
tableAPI = "%s/api/now/v2/table/%s"
hibernatingInstance = "Hibernating Instance"
)
// Incident is a model of the ServiceNow incident table
type Incident map[string]interface{}
// GetSysID returns the sys_id of the incident
func (i Incident) GetSysID() string {
return i["sys_id"].(string)
}
// GetNumber returns the number of the incident
func (i Incident) GetNumber() string {
return i["number"].(string)
}
// GetState returns the state of the incident
func (i Incident) GetState() json.Number {
return json.Number(i["state"].(string))
}
// IncidentResponse is a model of an API response contaning one incident
type IncidentResponse map[string]interface{}
// GetResult returns the incident from the IncidentResponse
func (ir IncidentResponse) GetResult() Incident {
var incident Incident = ir["result"].(map[string]interface{})
return incident
}
// IncidentsResponse is a model of an API response contaning multiple incidents
type IncidentsResponse map[string]interface{}
// GetResults returns the incidents from the IncidentsResponse
func (ir IncidentsResponse) GetResults() []Incident {
results := ir["result"].([]interface{})
incidents := make([]Incident, len(results))
for i, result := range results {
incidents[i] = result.(map[string]interface{})
}
return incidents
}
// ServiceNow interface
type ServiceNow interface {
CreateIncident(tableName string, incidentParam Incident) (Incident, error)
GetIncidents(tableName string, params map[string]string) ([]Incident, error)
UpdateIncident(tableName string, incidentParam Incident, sysID string) (Incident, error)
}
// ServiceNowClient is the interface to a ServiceNow instance
type ServiceNowClient struct {
baseURL string
authHeader string
client *http.Client
}
// NewServiceNowClient will create a new ServiceNow client
func NewServiceNowClient(instanceName string, userName string, password string) (*ServiceNowClient, error) {
if instanceName == "" {
return nil, errors.New("Missing instanceName")
}
if userName == "" {
return nil, errors.New("Missing userName")
}
if password == "" {
return nil, errors.New("Missing password")
}
return &ServiceNowClient{
baseURL: fmt.Sprintf(serviceNowBaseURL, instanceName),
authHeader: fmt.Sprintf("Basic %s", base64.URLEncoding.EncodeToString([]byte(userName+":"+password))),
client: http.DefaultClient,
}, nil
}
// Create a table item in ServiceNow from a post body
func (snClient *ServiceNowClient) create(table string, body []byte) ([]byte, error) {
url := fmt.Sprintf(tableAPI, snClient.baseURL, table)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
log.Errorf("Error creating the request. %s", err)
return nil, err
}
return snClient.doRequest(req)
}
// get a table item from ServiceNow using a map of arguments
func (snClient *ServiceNowClient) get(table string, params map[string]string) ([]byte, error) {
url := fmt.Sprintf(tableAPI, snClient.baseURL, table)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Errorf("Error creating the request. %s", err)
return nil, err
}
q := req.URL.Query()
for key, val := range params {
q.Add(key, val)
}
req.URL.RawQuery = q.Encode()
return snClient.doRequest(req)
}
// update a table item in ServiceNow from a post body and a sys_id
func (snClient *ServiceNowClient) update(table string, body []byte, sysID string) ([]byte, error) {
url := fmt.Sprintf(tableAPI+"/%s", snClient.baseURL, table, sysID)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(body))
if err != nil {
log.Errorf("Error creating the request. %s", err)
return nil, err
}
return snClient.doRequest(req)
}
// doRequest will do the given ServiceNow request and return response as byte array
func (snClient *ServiceNowClient) doRequest(req *http.Request) ([]byte, error) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", snClient.authHeader)
resp, err := snClient.client.Do(req)
if err != nil {
log.Errorf("Error sending the request. %s", err)
return nil, err
}
defer resp.Body.Close()
serviceNowRequests.WithLabelValues(req.URL.Host, req.Method, strconv.Itoa(resp.StatusCode)).Inc()
serviceNowLastRequest.SetToCurrentTime()
if resp.StatusCode >= 400 {
errorMsg := fmt.Sprintf("ServiceNow returned the HTTP error code: %v", resp.StatusCode)
log.Error(errorMsg)
return nil, errors.New(errorMsg)
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Error reading the body. %s", err)
return nil, err
}
if !json.Valid(responseBody) {
if strings.Contains(string(responseBody), hibernatingInstance) {
return nil, errors.New("ServiceNow is in sleeping mode and is unavailable (Hibernating Instance)")
}
return nil, errors.New("ServiceNow is unavailable (API return format is not valid JSON)")
}
return responseBody, nil
}
// CreateIncident will create an incident in ServiceNow from a given Incident, and return the created incident
func (snClient *ServiceNowClient) CreateIncident(tableName string, incidentParam Incident) (Incident, error) {
log.Info("Create a ServiceNow incident")
postBody, err := json.Marshal(incidentParam)
if err != nil {
log.Errorf("Error while marshalling the incident. %s", err)
return nil, err
}
response, err := snClient.create(tableName, postBody)
if err != nil {
log.Errorf("Error while creating the incident. %s", err)
return nil, err
}
incidentResponse := IncidentResponse{}
err = json.Unmarshal(response, &incidentResponse)
if err != nil {
log.Errorf("Error while unmarshalling the incident. %s", err)
return nil, err
}
createdIncident := incidentResponse.GetResult()
log.Infof("Incident %s created", createdIncident.GetNumber())
return createdIncident, nil
}
// GetIncidents will retrieve an incident from ServiceNow
func (snClient *ServiceNowClient) GetIncidents(tableName string, params map[string]string) ([]Incident, error) {
log.Infof("Get ServiceNow incidents with params: %v", params)
response, err := snClient.get(tableName, params)
if err != nil {
log.Errorf("Error while getting the incident. %s", err)
return nil, err
}
incidentsResponse := IncidentsResponse{}
err = json.Unmarshal(response, &incidentsResponse)
if err != nil {
log.Errorf("Error while unmarshalling the incident. %s", err)
return nil, err
}
return incidentsResponse.GetResults(), nil
}
// UpdateIncident will update an incident in ServiceNow from a given Incident, and return the updated incident
func (snClient *ServiceNowClient) UpdateIncident(tableName string, incidentParam Incident, sysID string) (Incident, error) {
log.Infof("Update %v field(s) of ServiceNow incident with id : %s", len(incidentParam), sysID)
postBody, err := json.Marshal(incidentParam)
if err != nil {
log.Errorf("Error while marshalling the incident. %s", err)
return nil, err
}
response, err := snClient.update(tableName, postBody, sysID)
if err != nil {
log.Errorf("Error while updating the incident. %s", err)
return nil, err
}
incidentResponse := IncidentResponse{}
err = json.Unmarshal(response, &incidentResponse)
if err != nil {
log.Errorf("Error while unmarshalling the incident. %s", err)
return nil, err
}
updatedIncident := incidentResponse.GetResult()
log.Infof("Incident %s updated", updatedIncident.GetNumber())
return updatedIncident, nil
}