/
utils.py
403 lines (344 loc) · 13 KB
/
utils.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import os
import pytz
import queue
import logging
import xmljson
import requests
import threading
import traceback
from math import floor, ceil
try:
from urllib.parse import urlencode
from urllib.parse import urlsplit
except ImportError:
# Python 2 compatibility
from urllib import urlencode
from urlparse import urlsplit
from bs4 import BeautifulSoup as bs
from datetime import datetime, timedelta
from defusedxml import lxml as dlxml
from django.conf import settings
from django.db.models.fields.related import RelatedField
from geonode.settings import DATETIME_INPUT_FORMATS
GS_FORMAT = '%Y-%m-%dT%H:%M:%S' # 2010-06-20T2:00:00
log = logging.getLogger(__name__)
class MonitoringHandler(logging.Handler):
def __init__(self, service, *args, **kwargs):
super(MonitoringHandler, self).__init__(*args, **kwargs)
self.service = service
def emit(self, record):
from geonode.monitoring.models import RequestEvent, ExceptionEvent
exc_info = record.exc_info
req = record.request
resp = record.response
if not req._monitoring.get('processed'):
try:
re = RequestEvent.from_geonode(self.service, req, resp)
req._monitoring['processed'] = re
except BaseException:
req._monitoring['processed'] = None
re = req._monitoring.get('processed')
if re and exc_info:
tb = traceback.format_exception(*exc_info)
ExceptionEvent.add_error(self.service, exc_info[1], tb, request=re)
class RequestToMonitoringThread(threading.Thread):
q = queue.Queue()
def __init__(self, service, *args, **kwargs):
super(RequestToMonitoringThread, self).__init__(*args, **kwargs)
self.service = service
def add(self, req, resp):
item = (req, resp,)
RequestToMonitoringThread.q.put(item)
def run(self):
from geonode.monitoring.models import RequestEvent
q = RequestToMonitoringThread.q
while True:
if not q.empty():
item = q.get()
req, resp = item
RequestEvent.from_geonode(self.service, req, resp)
class GeoServerMonitorClient(object):
REPORT_FORMATS = ('html', 'xml', 'json',)
def __init__(self, base_url):
self.base_url = base_url
def get_href(self, link, format=None):
href = urlsplit(link['href'])
base_url = urlsplit(self.base_url)
if href and href.netloc != base_url.netloc:
href = href._replace(netloc=base_url.netloc)
href = href._replace(scheme=base_url.scheme)
if format is None:
return href.geturl()
if format in self.REPORT_FORMATS:
href, ext = os.path.splitext(href.geturl())
return '{}.{}'.format(href, format)
return format
def get_requests(self, format=None, since=None, until=None):
"""
Returns list of requests from monitoring
"""
from requests.auth import HTTPBasicAuth
rest_url = '{}rest/monitor/requests.html'.format(self.base_url)
qargs = {}
if since:
# since = since.astimezone(utc)
qargs['from'] = since.strftime(GS_FORMAT)
if until:
# until = until.astimezone(utc)
qargs['to'] = until.strftime(GS_FORMAT)
if qargs:
rest_url = '{}?{}'.format(rest_url, urlencode(qargs))
log.debug('checking', rest_url)
username = settings.OGC_SERVER['default']['USER']
password = settings.OGC_SERVER['default']['PASSWORD']
resp = requests.get(
rest_url,
auth=HTTPBasicAuth(username, password),
timeout=30,
verify=False)
doc = bs(resp.content, features="lxml")
links = doc.find_all('a')
for l in links:
href = self.get_href(l, format)
data = self.get_request(href, format=format)
if data:
yield data
else:
log.warning("Skipping payload for {}".format(href))
def get_request(self, href, format=format):
from requests.auth import HTTPBasicAuth
username = settings.OGC_SERVER['default']['USER']
password = settings.OGC_SERVER['default']['PASSWORD']
log.debug(" href: %s " % href)
r = requests.get(
href,
auth=HTTPBasicAuth(username, password),
timeout=30,
verify=False)
if r.status_code != 200:
log.warning('Invalid response for %s: %s', href, r)
return
data = None
try:
data = r.json()
except (ValueError, TypeError,):
# traceback.print_exc()
try:
data = dlxml.fromstring(r.content)
except Exception as err:
log.debug("Cannot parse xml contents for %s: %s", href, err, exc_info=err)
data = bs(r.content)
if len(data) and format != 'json':
return self.to_json(data, format)
return data
def _from_xml(self, val):
try:
return xmljson.yahoo.data(val)
except BaseException:
# raise ValueError("Cannot convert from val %s" % val)
pass
def _from_html(self, val):
raise ValueError("Cannot convert from html")
def to_json(self, data, from_format):
h = getattr(self, '_from_{}'.format(from_format), None)
if not h or not len(data):
raise ValueError(
"Cannot convert from {} - no handler".format(from_format))
return h(data)
def align_period_end(end, interval):
utc = pytz.utc
day_end = datetime(*end.date().timetuple()[:6]).replace(tzinfo=utc)
# timedelta
diff = (end - day_end)
# seconds
diff_s = diff.total_seconds()
int_s = interval.total_seconds()
# rounding to last lower full period
interval_num = ceil(diff_s / float(int_s))
return day_end + \
timedelta(seconds=(interval_num * interval.total_seconds()))
def align_period_start(start, interval):
utc = pytz.utc
day_start = datetime(*start.date().timetuple()[:6]).replace(tzinfo=utc)
# timedelta
diff = (start.replace(tzinfo=utc) - day_start)
# seconds
diff_s = diff.total_seconds()
int_s = interval.total_seconds()
# rounding to last lower full period
interval_num = floor(diff_s / float(int_s))
return day_start + \
timedelta(seconds=(interval_num * interval.total_seconds()))
def generate_periods(since, interval, end=None, align=True):
"""
Generator of periods: tuple of [start, end).
since parameter will be aligned to closest interval before since.
"""
utc = pytz.utc
end = end or datetime.utcnow().replace(tzinfo=utc)
if align:
since_aligned = align_period_start(since, interval)
else:
since_aligned = since
if end < since:
raise ValueError("End cannot be earlienr than beginning")
full_interval = (end - since).total_seconds()
_periods = divmod(full_interval, interval.total_seconds())
periods_count = _periods[0]
if _periods[1]:
periods_count += 1
end = since_aligned + \
timedelta(seconds=(periods_count * interval.total_seconds()))
while since_aligned < end:
yield (since_aligned, since_aligned + interval,)
since_aligned = since_aligned + interval
class TypeChecks(object):
AUDIT_TYPE_JSON = 'json'
AUDIT_TYPE_XML = 'xml'
AUDIT_FORMATS = (AUDIT_TYPE_JSON, AUDIT_TYPE_XML,)
@classmethod
def audit_format(cls, val):
if val not in cls.AUDIT_FORMATS:
raise ValueError("Invalid value for audit format: {}".format(val))
return val
@staticmethod
def host_type(val):
from geonode.monitoring.models import Host
try:
return Host.objects.get(name=val)
except Host.DoesNotExist:
raise ValueError("Host {} does not exist".format(val))
@staticmethod
def resource_type(val):
from geonode.monitoring.models import MonitoredResource
try:
val = int(val)
return MonitoredResource.objects.get(id=val)
except (ValueError, TypeError,):
try:
rtype, rname = val.split('=')
except (ValueError, IndexError,):
raise ValueError(
"{} is not valid resource description".format(val))
return MonitoredResource.objects.get(type=rtype, name=rname)
@staticmethod
def resource_type_type(val):
from geonode.monitoring.models import MonitoredResource
if val in MonitoredResource._TYPES:
return val
raise ValueError("Invalid monitored resource type: {}".format(val))
@staticmethod
def metric_name_type(val):
from geonode.monitoring.models import Metric
try:
return Metric.objects.get(name=val)
except Metric.DoesNotExist:
raise ValueError("Metric {} doesn't exist".format(val))
@staticmethod
def service_type(val):
from geonode.monitoring.models import Service
try:
return Service.objects.get(name=val)
except Service.DoesNotExist:
raise ValueError("Service {} does not exist".format(val))
@staticmethod
def service_type_type(val):
from geonode.monitoring.models import ServiceType
try:
return ServiceType.objects.get(name=val)
except ServiceType.DoesNotExist:
raise ValueError("Service Type {} does not exist".format(val))
@staticmethod
def label_type(val):
from geonode.monitoring.models import MetricLabel
try:
return MetricLabel.objects.get(id=val)
except (ValueError, TypeError, MetricLabel.DoesNotExist,):
try:
return MetricLabel.objects.get(name=val)
except MetricLabel.DoesNotExist:
pass
raise ValueError("Invalid label value: {}".format(val))
@staticmethod
def user_type(val):
from geonode.monitoring.models import MetricLabel
try:
if MetricLabel.objects.filter(user=val).count():
return val
except MetricLabel.DoesNotExist:
raise ValueError("Invalid user value: {}".format(val))
@staticmethod
def event_type_type(val):
from geonode.monitoring.models import EventType
try:
return EventType.objects.get(name=val)
except EventType.DoesNotExist:
raise ValueError("Event Type {} doesn't exist".format(val))
@staticmethod
def ows_service_type(val):
if str(val).lower() in ("true", "1"):
return True
elif str(val).lower() in ("false", "0"):
return False
else:
raise ValueError("Invalid ows_service value {}".format(val))
def dump(obj, additional_fields=tuple()):
if hasattr(obj, '_meta'):
fields = obj._meta.fields
else:
fields = []
out = {}
for field in fields:
fname = field.name
val = getattr(obj, fname)
if isinstance(field, RelatedField):
if val is not None:
v = val
val = {'class': '{}.{}'.format(val.__class__.__module__, val.__class__.__name__),
'id': val.pk}
if hasattr(v, 'name'):
val['name'] = v.name
if isinstance(val, timedelta):
val = {'class': 'datetime.timedelta',
'seconds': val.total_seconds()}
out[fname] = val
for fname in additional_fields:
val = getattr(obj, fname, None)
if isinstance(val, timedelta):
val = {'class': 'datetime.timedelta',
'seconds': val.total_seconds()}
out[fname] = val
return out
def extend_datetime_input_formats(formats):
"""
Add new DateTime input formats
:param formats: input formats yoy want to add (tuple or list)
:return: extended input formats
"""
input_formats = DATETIME_INPUT_FORMATS
if isinstance(input_formats, tuple):
input_formats += tuple(formats)
elif isinstance(input_formats, list):
input_formats.extend(formats)
else:
raise ValueError("Input parameter must be tuple or list.")
return input_formats