Skip to content

Commit b684402

Browse files
authored
Rebase and add 3.x Tests to PR-395 (#411)
* Python 2.6, 2.7, 3.4, 3.5, 3.6, 3.7 compatibility * Added Python 3.x versions to Travis
1 parent 2b68c4b commit b684402

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+494
-382
lines changed

.travis.yml

+3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
language: python
22
python:
33
- "2.7"
4+
- "3.4"
5+
- "3.5"
6+
- "3.6"
47
install:
58
- pip install pylint pylint_runner ordereddict mysqlclient requests feedparser prometheus_client
69
script:

collectors/0/couchbase.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def find_conf_file(pid):
8787
"""Returns config file for couchbase-server."""
8888
try:
8989
fd = open('/proc/%s/cmdline' % pid)
90-
except IOError, e:
90+
except IOError as e:
9191
utils.err("Couchbase (pid %s) went away ? %s" % (pid, e))
9292
return
9393
try:
@@ -100,7 +100,7 @@ def find_bindir_path(config_file):
100100
"""Returns the bin directory path"""
101101
try:
102102
fd = open(config_file)
103-
except IOError, e:
103+
except IOError as e:
104104
utils.err("Error for Config file (%s): %s" % (config_file, e))
105105
return None
106106
try:
@@ -142,7 +142,7 @@ def collect_stats(bin_dir, bucket):
142142
metric = stat.split(":")[0].lstrip(" ")
143143
value = stat.split(":")[1].lstrip(" \t")
144144
if metric in KEYS:
145-
print ("couchbase.%s %i %s bucket=%s" % (metric, ts, value, bucket))
145+
print("couchbase.%s %i %s bucket=%s" % (metric, ts, value, bucket))
146146

147147
def main():
148148
utils.drop_privileges()

collectors/0/dfstat.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def main():
5151
"""dfstats main loop"""
5252
try:
5353
f_mounts = open("/proc/mounts", "r")
54-
except IOError, e:
54+
except IOError as e:
5555
utils.err("error: can't open /proc/mounts: %s" % e)
5656
return 13 # Ask tcollector to not respawn us
5757

@@ -72,7 +72,7 @@ def main():
7272
# fs_passno # Order in which filesystem checks are done at reboot time
7373
try:
7474
fs_spec, fs_file, fs_vfstype, fs_mntops, fs_freq, fs_passno = line.split(None)
75-
except ValueError, e:
75+
except ValueError as e:
7676
utils.err("error: can't parse line at /proc/mounts: %s" % e)
7777
continue
7878

@@ -105,7 +105,7 @@ def main():
105105
fs_spec, fs_file, fs_vfstype = device
106106
try:
107107
r = os.statvfs(fs_file)
108-
except OSError, e:
108+
except OSError as e:
109109
utils.err("can't get info for mount point: %s: %s" % (fs_file, e))
110110
continue
111111

collectors/0/docker.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# More informations on https://docs.docker.com/articles/runmetrics/
33
"""Imports Docker stats from /sys/fs/cgroup."""
44

5+
from __future__ import print_function
6+
57
import os
68
import re
79
import socket
@@ -60,7 +62,7 @@ def getnameandimage(containerid):
6062
try:
6163
r = sock.connect_ex(DOCKER_SOCK)
6264
if (r != 0):
63-
print >>sys.stderr, "Can not connect to %s" % (DOCKER_SOCK)
65+
print("Can not connect to %s" % (DOCKER_SOCK), file=sys.stderr)
6466
else:
6567
message = 'GET /containers/' + containerid + '/json HTTP/1.1\r\nHost: http\n\n'
6668
sock.sendall(message)
@@ -79,16 +81,16 @@ def getnameandimage(containerid):
7981
try:
8082
containernames[containerid] = data["Name"].lstrip('/')
8183
except:
82-
print >>sys.stderr, containerid+" has no Name field"
84+
print(containerid+" has no Name field", file=sys.stderr)
8385
try:
8486
containerimages[containerid] = data["Config"]["Image"].replace(':', '_')
8587
except:
86-
print >>sys.stderr, containerid+" has no Image field"
88+
print(containerid+" has no Image field", file=sys.stderr)
8789
except:
88-
print >>sys.stderr, "Can not load json"
90+
print("Can not load json", file=sys.stderr)
8991

90-
except socket.timeout, e:
91-
print >>sys.stderr, "Socket: %s" % (e,)
92+
except socket.timeout as e:
93+
print("Socket: %s" % (e,), file=sys.stderr)
9294

9395
def senddata(datatosend, containerid):
9496
if datatosend:
@@ -97,7 +99,7 @@ def senddata(datatosend, containerid):
9799
datatosend += " containername="+containernames[containerid]
98100
if (containerid in containerimages):
99101
datatosend += " containerimage="+containerimages[containerid]
100-
print "docker.%s" % datatosend
102+
print("docker.%s" % datatosend)
101103
sys.stdout.flush()
102104

103105
def readdockerstats(path, containerid):
@@ -112,8 +114,8 @@ def readdockerstats(path, containerid):
112114
and ((file_stat in proc_names.keys()) or (file_stat in proc_names_to_agg.keys()))):
113115
try:
114116
f_stat = open(path+"/"+file_stat)
115-
except IOError, e:
116-
print >>sys.stderr, "Failed to open input file: %s" % (e,)
117+
except IOError as e:
118+
print("Failed to open input file: %s" % (e,), file=sys.stderr)
117119
return 1
118120
ts = int(time.time())
119121

collectors/0/docker_engine.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# see <http://www.gnu.org/licenses/>.
1414
"""Imports Docker stats from the docker-api"""
1515

16+
from __future__ import print_function
1617
import sys
1718

1819
from collectors.etc import docker_engine_conf
@@ -32,7 +33,7 @@ def main():
3233
cli = DockerMetrics(METRICS_PATH)
3334

3435
for m in cli.get_endpoint():
35-
print m.get_metric_lines()
36+
print(m.get_metric_lines())
3637

3738

3839
if __name__ == "__main__":

collectors/0/elasticsearch.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
# Tested with ES 0.16.5, 0.17.x, 0.90.1 .
1717

1818
import errno
19-
import httplib
2019
try:
2120
import json
2221
except ImportError:
@@ -30,6 +29,11 @@
3029
from collectors.lib import utils
3130
from collectors.etc import elasticsearch_conf
3231

32+
try:
33+
from http.client import HTTPConnection, OK
34+
except ImportError:
35+
from httplib import HTTPConnection, OK
36+
3337

3438
COLLECTION_INTERVAL = 15 # seconds
3539
DEFAULT_TIMEOUT = 10.0 # seconds
@@ -57,7 +61,7 @@ def request(server, uri, json_in = True):
5761
"""Does a GET request of the given uri on the given HTTPConnection."""
5862
server.request("GET", uri)
5963
resp = server.getresponse()
60-
if resp.status != httplib.OK:
64+
if resp.status != OK:
6165
raise ESError(resp)
6266
if json_in:
6367
return json.loads(resp.read())
@@ -99,10 +103,10 @@ def printmetric(metric, ts, value, tags):
99103
# Warning, this should be called inside a lock
100104
if tags:
101105
tags = " " + " ".join("%s=%s" % (name.replace(" ",""), value.replace(" ",""))
102-
for name, value in tags.iteritems())
106+
for name, value in tags.items())
103107
else:
104108
tags = ""
105-
print ("%s %d %s %s"
109+
print("%s %d %s %s"
106110
% (metric, ts, value, tags))
107111

108112
def _traverse(metric, stats, ts, tags):
@@ -148,7 +152,7 @@ def _collect_indices(server, metric, tags, lock):
148152
# now print value
149153
with lock:
150154
printmetric(metric + ".cluster.byindex." + headerlist[count], ts, value, newtags)
151-
except ValueError, ve:
155+
except ValueError:
152156
# add this as a tag
153157
newtags[headerlist[count]] = value
154158
count += 1
@@ -200,11 +204,11 @@ def main(argv):
200204
return 1
201205

202206
for conf in elasticsearch_conf.get_servers():
203-
server = httplib.HTTPConnection( *conf )
207+
server = HTTPConnection( *conf )
204208
try:
205209
server.connect()
206-
except socket.error, (erno, e):
207-
if erno == errno.ECONNREFUSED:
210+
except socket.error as exc:
211+
if exc.errno == errno.ECONNREFUSED:
208212
continue
209213
raise
210214
servers.append( server )
@@ -222,7 +226,7 @@ def main(argv):
222226
t.start()
223227
threads.append(t)
224228
for thread in threads:
225-
t.join()
229+
thread.join()
226230
time.sleep(COLLECTION_INTERVAL)
227231

228232
if __name__ == "__main__":

collectors/0/flume.py

+20-14
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@
2626
2727
Based on the elastichsearch collector
2828
29-
"""
29+
"""
30+
31+
from __future__ import print_function
3032

3133
import errno
32-
import httplib
3334
try:
3435
import json
3536
except ImportError:
@@ -45,6 +46,11 @@
4546
except ImportError:
4647
flume_conf = None
4748

49+
try:
50+
from http.client import HTTPConnection, OK
51+
except ImportError:
52+
from httplib import HTTPConnection, OK
53+
4854
COLLECTION_INTERVAL = 15 # seconds
4955
DEFAULT_TIMEOUT = 10.0 # seconds
5056
FLUME_HOST = "localhost"
@@ -54,7 +60,7 @@
5460
EXCLUDE = [ 'StartTime', 'StopTime', 'Type' ]
5561

5662
def err(msg):
57-
print >>sys.stderr, msg
63+
print(msg, file=sys.stderr)
5864

5965
class FlumeError(RuntimeError):
6066
"""Exception raised if we don't get a 200 OK from Flume webserver."""
@@ -66,7 +72,7 @@ def request(server, uri):
6672
"""Does a GET request of the given uri on the given HTTPConnection."""
6773
server.request("GET", uri)
6874
resp = server.getresponse()
69-
if resp.status != httplib.OK:
75+
if resp.status != OK:
7076
raise FlumeError(resp)
7177
return json.loads(resp.read())
7278

@@ -94,11 +100,11 @@ def main(argv):
94100

95101
utils.drop_privileges()
96102
socket.setdefaulttimeout(DEFAULT_TIMEOUT)
97-
server = httplib.HTTPConnection(FLUME_HOST, FLUME_PORT)
103+
server = HTTPConnection(FLUME_HOST, FLUME_PORT)
98104
try:
99105
server.connect()
100-
except socket.error, (erno, e):
101-
if erno == errno.ECONNREFUSED:
106+
except socket.error as exc:
107+
if exc.errno == errno.ECONNREFUSED:
102108
return 13 # No Flume server available, ask tcollector to not respawn us.
103109
raise
104110
if json is None:
@@ -108,22 +114,22 @@ def main(argv):
108114
def printmetric(metric, value, **tags):
109115
if tags:
110116
tags = " " + " ".join("%s=%s" % (name, value)
111-
for name, value in tags.iteritems())
117+
for name, value in tags.items())
112118
else:
113119
tags = ""
114-
print ("flume.%s %d %s %s" % (metric, ts, value, tags))
120+
print(("flume.%s %d %s %s" % (metric, ts, value, tags)))
115121

116122
while True:
117123
# Get the metrics
118124
ts = int(time.time()) # In case last call took a while.
119125
stats = flume_metrics(server)
120126

121127
for metric in stats:
122-
(component, name) = metric.split(".")
123-
tags = {component.lower(): name}
124-
for key,value in stats[metric].items():
125-
if key not in EXCLUDE:
126-
printmetric(key.lower(), value, **tags)
128+
(component, name) = metric.split(".")
129+
tags = {component.lower(): name}
130+
for key,value in stats[metric].items():
131+
if key not in EXCLUDE:
132+
printmetric(key.lower(), value, **tags)
127133

128134
time.sleep(COLLECTION_INTERVAL)
129135

collectors/0/g1gc.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def sec2milli(seconds):
161161

162162
def flush_collector(collector):
163163
for metric_name, value in collector['data'].items():
164-
print metric_name % (collector['timestamp'], value)
164+
print(metric_name % (collector['timestamp'], value))
165165

166166
collector['timestamp'] = None
167167
collector['data'] = {}
@@ -372,11 +372,11 @@ def process_gc_log(collector):
372372

373373
if not collector['timestamp'] is None:
374374
for gen, value in collector['gensize'].items():
375-
print "%s.gc.g1.gensize %s %s gen=%s" % (prefix, current_timestamp_in_sec, value, gen)
375+
print("%s.gc.g1.gensize %s %s gen=%s" % (prefix, current_timestamp_in_sec, value, gen))
376376

377377
# publish gc event count metrics
378378
for event, value in collector['count'].items():
379-
print "%s.gc.g1.event.count %s %s event=%s" % (prefix, current_timestamp_in_sec, value, event)
379+
print("%s.gc.g1.event.count %s %s event=%s" % (prefix, current_timestamp_in_sec, value, event))
380380

381381
except Exception:
382382
exc_type, exc_value, exc_traceback = sys.exc_info()

collectors/0/graphite_bridge.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,13 @@
1717

1818
import sys
1919
from collectors.lib import utils
20-
import SocketServer
2120
import threading
2221

22+
try:
23+
from socketserver import ThreadingTCPServer, BaseRequestHandler
24+
except ImportError:
25+
from SocketServer import ThreadingTCPServer, BaseRequestHandler
26+
2327
try:
2428
from collectors.etc import graphite_bridge_conf
2529
except ImportError:
@@ -29,12 +33,12 @@
2933
PORT = 2003
3034
SIZE = 8192
3135

32-
class GraphiteServer(SocketServer.ThreadingTCPServer):
36+
class GraphiteServer(ThreadingTCPServer):
3337
allow_reuse_address = True
3438

3539
print_lock = threading.Lock()
3640

37-
class GraphiteHandler(SocketServer.BaseRequestHandler):
41+
class GraphiteHandler(BaseRequestHandler):
3842

3943
def handle_line(self, line):
4044
line_parts = line.split()

0 commit comments

Comments
 (0)