v3bwfile.py 4.98 KB
Newer Older
juga's avatar
juga committed
1
2
3
4
# -*- coding: utf-8 -*-
"""Classes and functions that create the bandwidth measurements document
(v3bw) used by bandwidth authorities."""

5
import time
juga's avatar
juga committed
6
import logging
7
8
from sbws import __version__
from sbws.globals import SPEC_VERSION
juga's avatar
juga committed
9
10
11

log = logging.getLogger(__name__)

12
13
14
15
16
17
18
19
20
21
22
LINE_SEP = '\n'
K_SEP_V110 = '='
KV_SEP_V110 = '\n'
K_SEP_V200 = ' '
KV_SEP_V200 = ' '
ORDERED_KV = ['version', 'software', 'software_version']
ORDERED_K = ['timestamp', 'version', 'software', 'software_version']
ALLOWED_K = ORDERED_KV + ['earliest_bandwidth', 'generator_started']
TERMINATOR = '===='
LINE_TERMINATOR = TERMINATOR + LINE_SEP

juga's avatar
juga committed
23
24
25
26
27
28
29
30
31
32
33

class V3BwHeader(object):
    """
    Create a bandwidth measurements (V3bw) header
    following bandwidth measurements document spec version 1.1.0.

    :param int timestamp: timestamp in Unix Epoch seconds when the document
                          is created
    :param str version: the spec version
    :param str software: the name of the software that generates this
    :param str software_version: the version of the software
34
35
36
37
    :param dict kwargs: extra headers. Currently supported:
        - earliest_bandwidth: str, ISO timestamp when the first bandwidth was
          obtained
        - generator_started: str, ISO timestamp when the generator started
juga's avatar
juga committed
38
39
    """
    def __init__(self, timestamp=None, version=SPEC_VERSION, software='sbws',
juga's avatar
juga committed
40
                 software_version=__version__, **kwargs):
41
        self.timestamp = timestamp or int(time.time())
juga's avatar
juga committed
42
43
44
        self.version = version
        self.software = software
        self.software_version = software_version
45
46
        if kwargs.get('earliest_bandwidth'):
            self.earliest_bandwidth = kwargs['earliest_bandwidth']
47
        if kwargs.get('generator_started'):
48
            self.generator_started = kwargs['generator_started']
juga's avatar
juga committed
49

50
51
52
53
54
55
56
57
    @property
    def kv_ordered_ls(self):
        """Return list of headers KeyValue tuples for the KeyValues
        that have specific order.
        """
        kv_ls = [(k, str(getattr(self, k, ''))) for k in ORDERED_KV]
        log.debug('kv_ls %s', kv_ls)
        return kv_ls
juga's avatar
juga committed
58

59
60
61
62
63
64
65
66
67
68
69
70
71
    @property
    def k_extra_ls(self):
        """Return list of headers Keywords that do not have specific order."""
        k_extra = list(set(self.__dict__.keys()).difference(ORDERED_K)
                       .intersection(ALLOWED_K))
        log.debug('k_extra %s', k_extra)
        return k_extra

    @property
    def kv_extra_ls(self):
        """Return list of headers KeyValue tuples for the KeyValues
        that do not have specific order.
        """
juga's avatar
juga committed
72
        # sorting the list to generate determinist headers
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        kv_extra = sorted([(k, str(getattr(self, k)))
                          for k in self.k_extra_ls])
        log.debug('kv_extra %s', kv_extra)
        return kv_extra

    @property
    def kv_ls(self):
        return self.kv_ordered_ls + self.kv_extra_ls

    @property
    def kv_v110_ls(self):
        """Return header kv list of strings following spec v1.1.0."""
        kv = [str(self.timestamp)] + [K_SEP_V110.join([k, v])
                                      for k, v in self.kv_ls]
        log.debug('kv %s', kv)
        return kv

    def strv110(self):
        """Return header string following spec v1.1.0."""
        header_str = LINE_SEP.join(self.kv_v110_ls) + LINE_SEP + \
            LINE_TERMINATOR
        log.debug('header_str %s', header_str)
        return header_str

    @property
    def kv_v200_ls(self):
        """Return header kv following spec v2.0.0."""
        kv = [str(self.timestamp)] + [K_SEP_V200.join([k, v])
                                      for k, v in self.kv_ls]
        log.debug('kv %s', kv)
        return kv

    @property
    def strv200(self):
        """Return header string following spec v2.0.0."""
        header_str = LINE_SEP.join(self.kv_v200_ls) + LINE_SEP + \
            LINE_TERMINATOR
        log.debug('header_str %s', header_str)
        return header_str

    @classmethod
    def from_lines_v110(cls, lines):
        """
        :param list lines: list of lines to parse
        :returns: tuple of V3BwHeader object and non-header lines
        """
        assert isinstance(lines, list)
        try:
            index_terminator = lines.index(TERMINATOR)
        except ValueError as e:
            # is not a bw file or is v100
            log.warn('Terminator is not in lines')
            return None
        ts = int(lines[0])
        # not checking order
        kwargs = dict([l.split(K_SEP_V110)
                       for l in lines[:index_terminator]
                       if l.split(K_SEP_V110)[0] in ALLOWED_K])
        h = cls(ts, **kwargs)
        return h, lines[index_terminator + 1:]

    @classmethod
    def from_text_v110(self, text):
        """
        :param list lines: text to parse
        :returns: tuple of V3BwHeader object and non-header lines
        """
        assert isinstance(text, str)
        return self.from_lines_v110(text.split(LINE_SEP))

    def __str__(self):
        if self.version == '1.1.0':
            return self.strv110()
        return self.strv200