-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.py
More file actions
234 lines (185 loc) · 7.46 KB
/
client.py
File metadata and controls
234 lines (185 loc) · 7.46 KB
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
import logging
import json
import time
from netuitive import __version__
try:
import urllib.request as urllib2
except ImportError: # pragma: no cover
import urllib2
try:
from urllib.parse import urlparse
except ImportError: # pragma: no cover
from urlparse import urlparse
class Client(object):
"""
Netuitive Rest Api Client for agent data ingest.
Posts Element data to Netuitive Cloud
:param url: Base data source URL
:type url: string
:param api_key: API Key for data source
:type api_key: string
"""
def __init__(self, url='https://api.app.netuitive.com/ingest',
api_key='apikey',
agent='Netuitive-Python/' + __version__,
connection_timeout=5):
if url.endswith('/'):
url = url[:-1]
self.url = url
self.api_key = api_key
self.dataurl = self.url + '/' + self.api_key
self.timeurl = '{uri.scheme}://{uri.netloc}/time'.format(
uri=urlparse(url))
self.eventurl = self.dataurl.replace('/ingest/', '/ingest/events/', 1)
self.checkurl = self.dataurl.replace('/ingest/', '/check/', 1) \
.replace('/infrastructure', '', 1)
self.agent = agent
self.disabled = False
self.kill_codes = [410, 418]
self.post_error_count = 0
self.max_post_errors = 10
self.connection_timeout = connection_timeout
self.max_check_retry_count = 3
def post(self, element):
"""
:param element: Element to post to Netuitive
:type element: object
"""
try:
if self.disabled is True:
element.clear_samples()
logging.error('Posting has been disabled. '
'See previous errors for details.')
return(False)
if element.id is None:
raise Exception('element id is not set')
element.merge_metrics()
payload = json.dumps(
[element], default=lambda o: o.__dict__, sort_keys=True)
logging.debug(payload)
headers = {'Content-Type': 'application/json',
'User-Agent': self.agent}
request = urllib2.Request(
self.dataurl, data=payload, headers=headers)
resp = urllib2.urlopen(request, timeout=self.connection_timeout)
logging.debug("Response code: %d", resp.getcode())
resp.close()
self.post_error_count = 0
return(True)
except urllib2.HTTPError as e:
logging.debug("Response code: %d", e.code)
if e.code in self.kill_codes:
self.disabled = True
logging.exception('Posting has been disabled.'
'See previous errors for details.')
else:
self.post_error_count += 1
if self.post_error_count > self.max_post_errors:
element.clear_samples()
logging.exception(
'error posting payload to api ingest endpoint (%s): %s',
self.dataurl, e)
except Exception as e:
self.post_error_count += 1
if self.post_error_count > self.max_post_errors:
element.clear_samples() # pragma: no cover
logging.exception(
'error posting payload to api ingest endpoint (%s): %s',
self.dataurl, e)
def post_event(self, event):
"""
:param event: Event to post to Netuitive
:type event: object
"""
if self.disabled is True:
logging.error('Posting has been disabled. '
'See previous errors for details.')
return(False)
payload = json.dumps(
[event], default=lambda o: o.__dict__, sort_keys=True)
logging.debug(payload)
try:
headers = {'Content-Type': 'application/json',
'User-Agent': self.agent}
request = urllib2.Request(
self.eventurl, data=payload, headers=headers)
resp = urllib2.urlopen(request, timeout=self.connection_timeout)
logging.debug("Response code: %d", resp.getcode())
resp.close()
return(True)
except urllib2.HTTPError as e:
logging.debug("Response code: %d", e.code)
if e.code in self.kill_codes:
self.disabled = True
logging.exception('Posting has been disabled.'
'See previous errors for details.')
else:
logging.exception(
'error posting payload to api ingest endpoint (%s): %s',
self.eventurl, e)
except Exception as e:
logging.exception(
'error posting payload to api ingest endpoint (%s): %s',
self.eventurl, e)
def post_check(self, check):
"""
:param check: Check to post to Metricly
:type check: object
"""
if self.disabled is True:
logging.error('Posting has been disabled. '
'See previous errors for details.')
return(False)
url = self.checkurl + '/' \
+ check.name + '/' \
+ check.elementId + '/' \
+ str(check.ttl)
headers = {'User-Agent': self.agent}
try:
request = urllib2.Request(
url, data='', headers=headers)
resp = self._repeat_request(request, self.connection_timeout)
logging.debug("Response code: %d", resp.getcode())
resp.close()
return(True)
except urllib2.HTTPError as e:
logging.debug("Response code: %d", e.code)
if e.code in self.kill_codes:
self.disabled = True
logging.exception('Posting has been disabled.'
'See previous errors for details.')
else:
logging.exception(
'HTTPError posting payload to api ingest endpoint'
+ ' (%s): %s',
url, e)
def check_time_offset(self, epoch=None):
req = urllib2.Request(self.timeurl,
headers={'User-Agent': self.agent})
req.get_method = lambda: 'HEAD'
resp = urllib2.urlopen(req, timeout=self.connection_timeout)
rdate = resp.info()['Date']
if epoch is None:
ltime = int(time.mktime(time.gmtime()))
else:
ltime = epoch
rtime = int(time.mktime(
time.strptime(rdate, "%a, %d %b %Y %H:%M:%S %Z")))
ret = ltime - rtime
return(ret)
def time_insync(self):
if self.check_time_offset() in range(-300, 300):
return(True)
else:
return(False)
def _repeat_request(self, request, timeout):
for i in range(self.max_check_retry_count + 1):
try:
return urllib2.urlopen(request, timeout=timeout)
except urllib2.HTTPError as e:
if 500 <= e.code < 600 and i < self.max_check_retry_count:
logging.debug("Response code: %d, retry count: %d from %d",
e.code, i + 1, self.max_check_retry_count)
time.sleep(0.25 * (i + 1))
else:
raise