File: utils.py

package info (click to toggle)
python-opentracing 2.4.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 816 kB
  • sloc: python: 3,489; makefile: 98
file content (87 lines) | stat: -rw-r--r-- 2,143 bytes parent folder | download | duplicates (2)
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
from __future__ import print_function

import logging
import threading
import time


class RefCount(object):
    """Thread-safe counter"""
    def __init__(self, count=1):
        self._lock = threading.Lock()
        self._count = count

    def incr(self):
        with self._lock:
            self._count += 1
            return self._count

    def decr(self):
        with self._lock:
            self._count -= 1
            return self._count


def await_until(func, timeout=5.0):
    """Polls for func() to return True"""
    end_time = time.time() + timeout
    while time.time() < end_time and not func():
        time.sleep(0.01)


def stop_loop_when(loop, cond_func, timeout=5.0):
    """
    Registers a periodic callback that stops the loop when cond_func() == True.
    Compatible with both Tornado and asyncio.
    """
    if cond_func() or timeout <= 0.0:
        loop.stop()
        return

    timeout -= 0.1
    loop.call_later(0.1, stop_loop_when, loop, cond_func, timeout)


def get_logger(name):
    """Returns a logger with log level set to INFO"""
    logging.basicConfig(level=logging.INFO)
    return logging.getLogger(name)


def get_one_by_tag(spans, key, value):
    """Return a single Span with a tag value/key from a list,
    errors if more than one is found."""

    found = []
    for span in spans:
        if span.tags.get(key) == value:
            found.append(span)

    if len(found) > 1:
        raise RuntimeError('Too many values')

    return found[0] if len(found) > 0 else None


def get_one_by_operation_name(spans, name):
    """Return a single Span with a name from a list,
    errors if more than one is found."""
    found = []
    for span in spans:
        if span.operation_name == name:
            found.append(span)

    if len(found) > 1:
        raise RuntimeError('Too many values')

    return found[0] if len(found) > 0 else None


def get_tags_count(span, prefix):
    """Returns the tag count with the given prefix from a Span"""
    test_keys = set()
    for key in span.tags.keys():
        if key.startswith(prefix):
            test_keys.add(key)

    return len(test_keys)