77import logging
88import os
99
10+ import multiprocessing as mp
11+
1012from metric .base import MetricBase
1113from utils import fileopt
1214from utils import util
@@ -19,6 +21,9 @@ def __init__(self, args, basedir=None, subdir=None):
1921
2022 self .host = args .host if args .host else 'localhost'
2123 self .port = args .port if args .port else 9090
24+ self .proc_num = args .proc_num if args .proc_num else int (
25+ mp .cpu_count () / 2 + 1 )
26+
2227 self .api_uri = '/api/v1'
2328 self .url_base = 'http://%s:%s%s' % (self .host , self .port , self .api_uri )
2429
@@ -33,20 +38,33 @@ def get_label_names(self):
3338 logging .debug ("Found %s available metric keys..." % len (result ))
3439 return result
3540
41+ def query_worker (self , metric ):
42+ url = '%s/query_range?query=%s&start=%s&end=%s&step=%s' % (
43+ self .url_base , metric , self .start_time , self .end_time , self .resolution )
44+ response = util .read_url (url )[0 ]
45+ if 'success' not in response [:20 ].decode ('utf-8' ):
46+ logging .error ("Error querying for key '%s'." % metric )
47+ logging .debug ("Output is:\n %s" % response )
48+ return
49+ metric_filename = '%s_%s_to_%s_%ss.json' % (
50+ metric , self .start_time , self .end_time , self .resolution )
51+ fileopt .write_file (os .path .join (
52+ self .outdir , metric_filename ), response )
53+ logging .debug ("Saved data for key '%s'." % metric )
54+
3655 def run_collecting (self ):
3756 if self .resolution < 15.0 :
3857 logging .warning (
3958 "Sampling resolution < 15s don't increase accuracy but data size." )
40- for metric in self .get_label_names ():
41- url = '%s/query_range?query=%s&start=%s&end=%s&step=%s' % (
42- self .url_base , metric , self .start_time , self .end_time , self .resolution )
43- matrix = json .loads (util .read_url (url )[0 ])
44- if not matrix ['status' ] == 'success' :
45- logging .info ("Error querying for key '%s'." % metric )
46- logging .debug ("Output is:\n %s" % matrix )
47- continue
48- metric_filename = '%s_%s_to_%s_%ss.json' % (
49- metric , self .start_time , self .end_time , self .resolution )
50- fileopt .write_file (os .path .join (
51- self .outdir , metric_filename ), json .dumps (matrix ['data' ]['result' ]))
52- logging .debug ("Saved data for key '%s'." % metric )
59+ pool = mp .Pool (self .proc_num )
60+ metric_names = self .get_label_names ()
61+ pool .map_async (unwrap_self_f , zip (
62+ [self ] * len (metric_names ), metric_names ))
63+ pool .close ()
64+ pool .join ()
65+
66+
67+ # a trick to use multiprocessing.Pool inside a class
68+ # see http://www.rueckstiess.net/research/snippets/show/ca1d7d90 for details
69+ def unwrap_self_f (arg , ** kwarg ):
70+ return PromMetrics .query_worker (* arg , ** kwarg )
0 commit comments