forked from signalfx/splunk-otel-collector-chart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
285 lines (232 loc) · 8.32 KB
/
common.py
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
"""
Copyright 2018-2019 Splunk, Inc..
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import json
import logging
import time
import requests
import os
import sys
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
TIMEROUT = 500
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s -' +
' %(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
def check_events_from_splunk(index="circleci_events",
start_time="-1h@h",
end_time="now",
url="",
user="",
query="",
password=""):
'''
send a search request to splunk and return the events from the result
'''
#logger.info("search query = " + str(query))
events = _collect_events(query, start_time, end_time, url, user, password)
return events
def check_metrics_from_splunk(index="circleci_metrics",
start_time="-1h@h",
end_time="now",
url="",
user="",
password="",
metric_name=""):
'''
send a search api request to splunk to check for values associated with a given metric and dimension
'''
logger.debug("Calling _collect_metrics ")
events = _collect_metrics(start_time, end_time, url, user, password, index, metric_name)
return events
def create_index_in_splunk(index="",
url="",
user="",
password=""):
'''
Send a request to a Splunk instance to create an index
@param: index (index to be deleted)
@param: url (splunkd rest api url)
@param: user (splunk username)
@param: password (splunk password)
returns True/False
'''
search_url = '{0}/services/data/indexes/{1}?output_mode=json'.format(url, index)
logger.debug('requesting: %s', search_url)
data = {
'name': index
}
create_job = _requests_retry_session().post(
search_url,
auth=(user, password),
verify=False, data=data)
if create_job.status_code == 201:
logger.info('The index: %s successfully created', index)
elif create_job.status_code == 409:
logger.info('The index: %s already exits', index)
else:
logger.info('The index: {0} not created, exit code is {1}'.format(index, create_job.status_code))
return False
return True
def delete_index_in_splunk(index="",
user="",
url="",
password=""):
'''
Send a request to a Splunk instance to delete an index
@param: index (index to be deleted)
@param: url (splunkd rest api url)
@param: user (splunk username)
@param: password (splunk password)
returns True/False
'''
search_url = '{0}/services/data/indexes/{1}?output_mode=json'.format(url, index)
logger.debug('requesting: %s', search_url)
data = {
'name': index
}
create_job = _requests_retry_session().delete(
search_url,
auth=(user, password),
verify=False, data=data)
if create_job.status_code == 200:
logger.info('The index: %s successfully deleted', index)
elif create_job.status_code == 409:
logger.info('The index: %s already disabled', index)
else:
return False
return True
def _collect_events(query, start_time, end_time, url="", user="", password=""):
'''
Collect events by running the given search query
@param: query (search query)
@param: start_time (search start time)
@param: end_time (search end time)
returns events
'''
search_url = '{0}/services/search/jobs?output_mode=json'.format(
url)
logger.debug('requesting: %s', search_url)
data = {
'search': query,
'earliest_time': start_time,
'latest_time': end_time,
}
create_job = _requests_retry_session().post(
search_url,
auth=(user, password),
verify=False, data=data)
_check_request_status(create_job)
json_res = create_job.json()
job_id = json_res['sid']
events = _wait_for_job_and__get_events(job_id, url, user, password)
return events
def _collect_metrics(start_time, end_time, url="", user="", password="", index="", metric_name=""):
'''
Verify metrics by running the given api query
@param: dimension (metric dimension)
@param: metric_name (metric name)
@param: start_time (search start time)
@param: end_time (search end time)
returns events
'''
api_url = url + '/services/catalog/metricstore/dimensions/host/values?filter=index%3d' + index + '&metric_name=' + metric_name + '&earliest=' + start_time + '&latest=' + end_time + '&output_mode=json'.format(
url)
logger.debug('requesting: %s', api_url)
create_job = _requests_retry_session().get(
api_url,
auth=(user, password),
verify=False
)
_check_request_status(create_job)
json_res = create_job.json()
events = json_res['entry']
#logger.info('events: %s', events)
return events
def _wait_for_job_and__get_events(job_id, url="", user="", password=""):
'''
Wait for the search job to finish and collect the result events
@param: job_id
returns events
'''
events = []
job_url = '{0}/services/search/jobs/{1}?output_mode=json'.format(
url, str(job_id))
logger.debug('requesting: %s', job_url)
for _ in range(TIMEROUT):
res = _requests_retry_session().get(
job_url,
auth=(user, password),
verify=False)
_check_request_status(res)
job_res = res.json()
dispatch_state = job_res['entry'][0]['content']['dispatchState']
if dispatch_state == 'DONE':
events = _get_events(job_id, url, user, password)
break
if dispatch_state == 'FAILED':
raise Exception('Search job: {0} failed'.format(job_url))
time.sleep(1)
return events
def _get_events(job_id, url="", user="", password=""):
'''
collect the result events from a search job
@param: job_id
returns events
'''
event_url = '{0}/services/search/jobs/{1}/events?output_mode=json'.format(
url, str(job_id))
logger.debug('requesting: %s', event_url)
event_job = _requests_retry_session().get(
event_url, auth=(user, password),
verify=False)
_check_request_status(event_job)
event_job_json = event_job.json()
events = event_job_json['results']
logger.debug("Events from get_events method returned %s events",
len(events))
return events
def _check_request_status(req_obj):
'''
check if a request is successful
@param: req_obj
returns True/False
'''
if not req_obj.ok:
raise Exception('status code: {0} \n details: {1}'.format(
str(req_obj.status_code), req_obj.text))
def _requests_retry_session(
retries=10,
backoff_factor=0.1,
status_forcelist=(500, 502, 504)):
'''
create a retry session for HTTP/HTTPS requests
@param: retries (num of retry time)
@param: backoff_factor
@param: status_forcelist (list of error status code to trigger retry)
@param: session
returns: session
'''
session = requests.Session()
retry = Retry(
total=int(retries),
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session