Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# coding: utf-8

import os
import re
Expand All @@ -22,7 +21,7 @@
master_doc = 'index'

project = 'Graphite-Render'
copyright = u'2014, Bruno Renié'
copyright = '2014, Bruno Renié'

version = '1.1.5'
release = '1.1.5'
Expand Down Expand Up @@ -66,7 +65,7 @@ def can_document_member(cls, member, membername, isattr, parent):
) and parent.name == 'graphite_render.functions'

def format_args(self):
args = super(RenderFunctionDocumenter, self).format_args()
args = super().format_args()
if args is not None:
return re.sub('requestContext, ', '', args)

Expand All @@ -81,7 +80,7 @@ def setup(app):
add_module_names = False


class Mock(object):
class Mock:
__all__ = []

def __init__(self, *args, **kwargs):
Expand Down
12 changes: 6 additions & 6 deletions graphite_render/_vendor/whisper.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
def _py_fallocate(fd, offset, len_):
res = _fallocate(fd.fileno(), offset, len_)
if res != 0:
raise IOError(res, 'fallocate')
raise OSError(res, 'fallocate')
fallocate = _py_fallocate
del libc
del libc_name
Expand Down Expand Up @@ -99,7 +99,7 @@ def _py_fallocate(fd, offset, len_):
4: 'max',
5: 'min'
})
aggregationMethodToType = dict([[v,k] for k,v in aggregationTypeToMethod.items()])
aggregationMethodToType = {v:k for k,v in aggregationTypeToMethod.items()}
aggregationMethods = aggregationTypeToMethod.values()

debug = startBlock = endBlock = lambda *a,**k: None
Expand Down Expand Up @@ -176,10 +176,10 @@ def __init__(self, error, path):
self.path = path

def __repr__(self):
return "<CorruptWhisperFile[%s] %s>" % (self.path, self.error)
return "<CorruptWhisperFile[{}] {}>".format(self.path, self.error)

def __str__(self):
return "%s (%s)" % (self.error, self.path)
return "{} ({})".format(self.error, self.path)

def enableDebug():
global open, debug, startBlock, endBlock
Expand Down Expand Up @@ -208,7 +208,7 @@ def startBlock(name):
__timingBlocks[name] = time.time()

def endBlock(name):
debug("%s took %.5f seconds" % (name,time.time() - __timingBlocks.pop(name)))
debug("{} took {:.5f} seconds".format(name,time.time() - __timingBlocks.pop(name)))


def __readHeader(fh):
Expand Down Expand Up @@ -765,7 +765,7 @@ def file_fetch(fh, fromTime, untilTime, now = None):
# If the range of data is from too far in the past or fully in the future, we
# return nothing
if (fromTime > untilTime):
raise InvalidTimeInterval("Invalid time interval: from time '%s' is after until time '%s'" % (fromTime, untilTime))
raise InvalidTimeInterval("Invalid time interval: from time '{}' is after until time '{}'".format(fromTime, untilTime))

oldestTime = now - header['maxRetention']
# Range is in the future
Expand Down
28 changes: 13 additions & 15 deletions graphite_render/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def jsonify(data, status=200, headers=None):
body = json.dumps(data, cls=JSONEncoder)
if jsonp:
headers['Content-Type'] = 'text/javascript'
body = '{0}({1})'.format(jsonp, body)
body = f'{jsonp}({body})'
else:
headers['Content-Type'] = 'application/json'
return body, status, headers
Expand Down Expand Up @@ -71,7 +71,7 @@ def dashboard_find():

@app.route('/dashboard/load/<name>', methods=methods)
def dashboard_load(name):
return jsonify({'error': "Dashboard '{0}' does not exist.".format(name)},
return jsonify({'error': f"Dashboard '{name}' does not exist."},
status=404)


Expand Down Expand Up @@ -115,7 +115,7 @@ def metrics_find():

format = RequestParams.get('format', 'treejson')
if format not in ['treejson', 'completer', 'nodelist', 'json']:
errors['format'] = 'unrecognized format: "{0}".'.format(format)
errors['format'] = f'unrecognized format: "{format}".'

if 'query' not in RequestParams:
errors['query'] = 'this parameter is required.'
Expand Down Expand Up @@ -208,7 +208,7 @@ def recurse(query, index):
if node.is_leaf:
index.add(node.path)
else:
recurse('{0}.*'.format(node.path), index)
recurse(f'{node.path}.*', index)


@app.route('/metrics/index.json', methods=methods)
Expand Down Expand Up @@ -264,9 +264,9 @@ def render():
request_options['graphType'] = graph_type
request_options['graphClass'] = graph_class
except KeyError:
graph_types_str = "', '".join(sorted(GraphTypes))
errors['graphType'] = (
"Invalid graphType '{0}', must be one of '{1}'.".format(
graph_type, "', '".join(sorted(GraphTypes))))
f"Invalid graphType '{graph_type}', must be one of '{graph_types_str}'.")
request_options['pieMode'] = RequestParams.get('pieMode', 'average')
targets = RequestParams.getlist('target')
if not len(targets):
Expand Down Expand Up @@ -315,7 +315,7 @@ def render():
try:
tzinfo = pytz.timezone(tz)
except pytz.UnknownTimeZoneError:
errors['tz'] = "Unknown timezone: '{0}'.".format(tz)
errors['tz'] = f"Unknown timezone: '{tz}'."
request_options['tzinfo'] = tzinfo

# Get the time interval for time-oriented graph types
Expand Down Expand Up @@ -359,7 +359,7 @@ def render():
headers = {
'Last-Modified': http_date(time.time()),
'Expires': http_date(time.time() + (cache_timeout or 60)),
'Cache-Control': 'max-age={0}'.format(cache_timeout or 60)
'Cache-Control': f'max-age={cache_timeout or 60}'
} if use_cache else {
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
Expand Down Expand Up @@ -393,7 +393,7 @@ def render():
try:
value = float(value)
except ValueError:
errors['target'] = "Invalid target: '{0}'.".format(target)
errors['target'] = f"Invalid target: '{target}'."
context['data'].append((name, value))
else:
series_list = evaluateTarget(context, target, data_store)
Expand Down Expand Up @@ -503,10 +503,9 @@ def render():
if request_options['format'] == 'raw':
response = StringIO()
for series in context['data']:
response.write(u"%s,%d,%d,%d|" % (
series.name, series.start, series.end, series.step))
response.write(u','.join(map(repr, series)))
response.write(u'\n')
response.write(f"{series.name},{series.start},{series.end},{series.step}|")
response.write(','.join(map(repr, series)))
response.write('\n')
response.seek(0)
headers['Content-Type'] = 'text/plain'
response = (response.read(), 200, headers)
Expand All @@ -528,8 +527,7 @@ def render():

if use_svg and 'jsonp' in request_options:
headers['Content-Type'] = 'text/javascript'
response = ('{0}({1})'.format(request_options['jsonp'],
json.dumps(image.decode('utf-8'))),
response = (f'{request_options["jsonp"]}({json.dumps(image.decode("utf-8"))})',
200, headers)
else:
if use_svg:
Expand Down
12 changes: 6 additions & 6 deletions graphite_render/carbonlink.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
logger = get_logger()

pickle_safe = {
'copy_reg': set(['_reconstructor']),
'__builtin__': set(['object', 'list']),
'collections': set(['deque']),
'copy_reg': {'_reconstructor'},
'__builtin__': {'object', 'list'},
'collections': {'deque'},
}
renames = {
'copy_reg': 'copyreg',
Expand Down Expand Up @@ -68,7 +68,7 @@ def loads(cls, s):
return obj.load()


class ConsistentHashRing(object):
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100, hash_type='carbon_ch'):
self.ring = []
self.ring_len = len(self.ring)
Expand All @@ -81,7 +81,7 @@ def __init__(self, nodes, replica_count=100, hash_type='carbon_ch'):

def compute_ring_position(self, key):
if self.hash_type == 'fnv1a_ch':
big_hash = '{0:x}'.format(int(fnv32a(str(key))))
big_hash = f'{int(fnv32a(str(key))):x}'
small_hash = int(big_hash[:4], 16) ^ int(big_hash[4:], 16)
else:
big_hash = md5(str(key).encode()).hexdigest()
Expand Down Expand Up @@ -131,7 +131,7 @@ def get_nodes(self, key):
return nodes


class CarbonLinkPool(object):
class CarbonLinkPool:
def __init__(self, hosts, timeout=1, retry_delay=15,
carbon_prefix='carbon', replication_factor=1,
hashing_keyfunc=lambda x: x, hashing_type='carbon_ch'):
Expand Down
12 changes: 6 additions & 6 deletions graphite_render/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ def _get_local_timezone_name():


# attributes of a classical log record
NON_EXTRA = set(['module', 'filename', 'levelno', 'exc_text', 'pathname',
NON_EXTRA = {'module', 'filename', 'levelno', 'exc_text', 'pathname',
'lineno', 'msg', 'funcName', 'relativeCreated',
'levelname', 'msecs', 'threadName', 'name', 'created',
'process', 'processName', 'thread'])
'process', 'processName', 'thread'}


class StructlogFormatter(logging.Formatter):
Expand All @@ -68,8 +68,8 @@ def __init__(self, *args, **kwargs):

def format(self, record):
if not record.name.startswith('graphite_render'):
kw = dict(((k, v) for k, v in record.__dict__.items()
if k not in NON_EXTRA))
kw = {k: v for k, v in record.__dict__.items()
if k not in NON_EXTRA}
kw['logger'] = record.name
return self._bound._process_event(
record.levelname.lower(), record.getMessage(), kw)[0]
Expand All @@ -95,7 +95,7 @@ def configure(app):
config = yaml.safe_load(f)
config['path'] = config_file
else:
warnings.warn("Unable to find configuration file at {0}, using "
warnings.warn("Unable to find configuration file at {}, using "
"default config.".format(config_file))
config = {}

Expand Down Expand Up @@ -128,7 +128,7 @@ def configure(app):
cache_conf = {'CACHE_DEFAULT_TIMEOUT': 60,
'CACHE_KEY_PREFIX': 'graphite-render:'}
for key, value in config['cache'].items():
cache_conf['CACHE_{0}'.format(key.upper())] = value
cache_conf[f'CACHE_{key.upper()}'] = value
app.cache = Cache(app, config=cache_conf)

loaded_config = {'functions': {}}
Expand Down
2 changes: 1 addition & 1 deletion graphite_render/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ def default(self, o):
pass
elif hasattr(o, '__iter__'):
return [i for i in o]
return super(JSONEncoder, self).default(o)
return super().default(o)
9 changes: 4 additions & 5 deletions graphite_render/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ def pathsFromTokens(requestContext, tokens, replacements=None):
replacements)
for kwarg in tokens.call.kwargs])

for path in itertools.chain(*iters):
yield path
yield from itertools.chain(*iters)


def evaluateTarget(requestContext, target, data_store=None):
Expand Down Expand Up @@ -128,10 +127,10 @@ def evaluateTokens(requestContext, tokens, data_store=None, replacements=None):
args = [evaluateTokens(requestContext, arg, data_store, replacements)
for arg in tokens.call.args]
requestContext['args'] = tokens.call.args
kwargs = dict([(kwarg.argname,
kwargs = {kwarg.argname:
evaluateTokens(requestContext, kwarg.args[0],
data_store, replacements))
for kwarg in tokens.call.kwargs])
data_store, replacements)
for kwarg in tokens.call.kwargs}
ret = func(requestContext, *args, **kwargs)
return ret

Expand Down
7 changes: 3 additions & 4 deletions graphite_render/finders/whisper.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
logger = get_logger()


class WhisperFinder(object):
class WhisperFinder:
def __init__(self, config):
self.directories = config['whisper']['directories']
self.carbonlink = None
Expand Down Expand Up @@ -97,8 +97,7 @@ def _find_paths(self, current_dir, patterns):
if patterns: # we've still got more directories to traverse
for subdir in matching_subdirs:
absolute_path = os.path.join(current_dir, subdir)
for match in self._find_paths(absolute_path, patterns):
yield match
yield from self._find_paths(absolute_path, patterns)

else: # we've got the last pattern
if not has_wildcard:
Expand All @@ -111,7 +110,7 @@ def _find_paths(self, current_dir, patterns):
yield os.path.join(current_dir, _basename)


class WhisperReader(object):
class WhisperReader:

__slots__ = ('fs_path', 'real_metric_path', 'carbonlink')

Expand Down
Loading