1+ from __future__ import unicode_literals
2+
3+ import codecs
14import json
2- import urllib2
3- import urllib
45import time
56import collections
67
8+ try :
9+ # Python 3
10+ from urllib .request import Request , urlopen , build_opener , install_opener , HTTPErrorProcessor
11+ from urllib .error import HTTPError , URLError
12+ from urllib .parse import quote , urlencode
13+ except ImportError :
14+ # Fall back to Python 2's urllib2
15+ from urllib2 import Request , urlopen , URLError , HTTPError , HTTPErrorProcessor , build_opener , install_opener
16+ from urllib import quote , urlencode
17+
718"""
8- TODO: Remember to do imports for Python 3 also and check the compatibility..
919TODO: Search datapoints with tags.. tag datapoints.
1020TODO: Allow changing instance's tenant?
1121TODO: Authentication when it's done..
1222TODO: Remove HawkularMetricsConnectionError and use HawkularMetricsError only?
1323TODO: HWKMETRICS-110 (fetching a single definition)
24+ TODO: Tag queries, stats queries
1425"""
1526
1627class MetricType :
@@ -31,21 +42,21 @@ class Availability:
3142 Up = 'up'
3243 Unknown = 'unknown'
3344
34- class HawkularMetricsError (urllib2 . HTTPError ):
45+ class HawkularMetricsError (HTTPError ):
3546 pass
3647
37- class HawkularMetricsConnectionError (urllib2 . URLError ):
48+ class HawkularMetricsConnectionError (URLError ):
3849 pass
3950
40- class HTTPErrorProcessor ( urllib2 . HTTPErrorProcessor ):
51+ class HawkularHTTPErrorProcessor ( HTTPErrorProcessor ):
4152 """
4253 Hawkular-Metrics uses http codes 201, 204
4354 """
4455 def http_response (self , request , response ):
4556
4657 if response .code in [200 , 201 , 204 ]:
4758 return response
48- return urllib2 . HTTPErrorProcessor .http_response (self , request , response )
59+ return HTTPErrorProcessor .http_response (self , request , response )
4960
5061 https_response = http_response
5162
@@ -75,15 +86,15 @@ def __init__(self,
7586 self .port = port
7687 self .path = path
7788
78- opener = urllib2 . build_opener (HTTPErrorProcessor ())
79- urllib2 . install_opener (opener )
89+ opener = build_opener (HawkularHTTPErrorProcessor ())
90+ install_opener (opener )
8091
8192 """
8293 Internal methods
8394 """
8495 @staticmethod
8596 def _clean_metric_id (metric_id ):
86- return urllib . quote (metric_id , '' )
97+ return quote (metric_id , '' )
8798
8899 def _get_base_url (self ):
89100 return "http://{0}:{1}/{2}/" .format (self .host , str (self .port ), self .path )
@@ -110,21 +121,28 @@ def _http(self, url, method, data=None):
110121 res = None
111122
112123 try :
113- req = urllib2 . Request (url = url )
124+ req = Request (url = url )
114125 req .add_header ('Content-Type' , 'application/json' )
115126 req .add_header ('Hawkular-Tenant' , self .tenant_id )
116127
117128 if not isinstance (data , str ):
118129 data = json .dumps (data , indent = 2 )
119130
131+ # writer = codecs.getencoder('utf-8')
132+ reader = codecs .getreader ('utf-8' )
133+
120134 if data :
121- req .add_data (data )
135+ try :
136+ req .add_data (data )
137+ except AttributeError :
138+ req .data = data .encode ('utf-8' )
122139
123- req .get_method = lambda : method
124- res = urllib2 . urlopen (req )
140+ req .get_method = lambda : method
141+ res = urlopen (req )
125142 if method == 'GET' :
126143 if res .getcode () == 200 :
127- data = json .load (res )
144+ data = json .load (reader (res ))
145+
128146 elif res .getcode () == 204 :
129147 data = {}
130148
@@ -147,14 +165,14 @@ def _post(self, url, data):
147165 self ._http (url , 'POST' , data )
148166
149167 def _get (self , url , ** url_params ):
150- params = urllib . urlencode (url_params )
168+ params = urlencode (url_params )
151169 if len (params ) > 0 :
152170 url = '{0}?{1}' .format (url , params )
153171
154172 return self ._http (url , 'GET' )
155173
156174 def _handle_error (self , e ):
157- if isinstance (e , urllib2 . HTTPError ):
175+ if isinstance (e , HTTPError ):
158176 # Cast to HawkularMetricsError
159177 e .__class__ = HawkularMetricsError
160178 err_json = e .read ()
@@ -167,7 +185,7 @@ def _handle_error(self, e):
167185 e .msg = err_json
168186
169187 raise e
170- elif isinstance (e , urllib2 . URLError ):
188+ elif isinstance (e , URLError ):
171189 # Cast to HawkularMetricsConnectionError
172190 e .__class__ = HawkularMetricsConnectionError
173191 e .msg = "Error, could not send event(s) to the Hawkular Metrics: " + str (e .reason )
@@ -312,7 +330,7 @@ def delete_metric_tags(self, metric_type, metric_id, **deleted_tags):
312330 """
313331 Delete one or more tags from the metric definition. The tag values must match what's stored on the server.
314332 """
315- tags = ',' .join ("%s:%s" % (key ,val ) for (key ,val ) in deleted_tags .iteritems ())
333+ tags = ',' .join ("%s:%s" % (key ,val ) for (key ,val ) in deleted_tags .items ())
316334 tags_url = self ._get_metrics_tags_url (self ._get_metrics_single_url (metric_type , metric_id )) + '/{0}' .format (tags )
317335
318336 self ._delete (tags_url )
@@ -334,12 +352,6 @@ def create_tenant(self, tenant_id):
334352 """
335353 item = { 'id' : tenant_id }
336354
337- # if retention_time is not None:
338- # item['dataRetention'] = retention_time
339-
340- # if len(tags) > 0:
341- # item.extend(tags)
342-
343355 tenants_url = self ._get_tenants_url ()
344356 self ._post (tenants_url , json .dumps (item , indent = 2 ))
345357
0 commit comments