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

import logging
juga's avatar
juga committed
6
import os
juga's avatar
juga committed
7
from statistics import median
juga's avatar
juga committed
8

9
from sbws import __version__
juga's avatar
juga committed
10
from sbws.globals import SPEC_VERSION, BW_LINE_SIZE
juga's avatar
juga committed
11
from sbws.lib.resultdump import ResultSuccess, _ResultType
12
from sbws.util.filelock import DirectoryLock
Matt Traudt's avatar
Matt Traudt committed
13
from sbws.util.timestamp import now_isodt_str, unixts_to_isodt_str
14
from sbws.util.state import State
juga's avatar
juga committed
15
16
17

log = logging.getLogger(__name__)

18
LINE_SEP = '\n'
19
20
21
22
23
24
KEYVALUE_SEP_V110 = '='
KEYVALUE_SEP_V200 = ' '
# List of the extra KeyValues accepted by the class
EXTRA_ARG_KEYVALUES = ['software', 'software_version', 'file_created',
                       'earliest_bandwidth', 'generator_started']
# List of all unordered KeyValues currently being used to generate the file
juga's avatar
juga committed
25
UNORDERED_KEYVALUES = EXTRA_ARG_KEYVALUES + ['latest_bandwidth']
26
27
# List of all the KeyValues currently being used to generate the file
ALL_KEYVALUES = ['version'] + UNORDERED_KEYVALUES
28
TERMINATOR = '===='
juga's avatar
juga committed
29
30
# Num header lines in v1.1.0 using all the KeyValues
NUM_LINES_HEADER_V110 = len(ALL_KEYVALUES) + 2
31
32
LINE_TERMINATOR = TERMINATOR + LINE_SEP

juga's avatar
juga committed
33
34
# KeyValue separator in Bandwidth Lines
BW_KEYVALUE_SEP_V110 = ' '
juga's avatar
juga committed
35
BW_EXTRA_ARG_KEYVALUES = ['master_key_ed25519', 'nick', 'rtt', 'time',
juga's avatar
juga committed
36
                          'success', 'error_stream', 'error_circ',
juga's avatar
juga committed
37
                          'error_misc']
38
BW_KEYVALUES_INT = ['bw', 'rtt', 'success', 'error_stream',
juga's avatar
juga committed
39
                    'error_circ', 'error_misc']
juga's avatar
juga committed
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
BW_KEYVALUES = ['node_id', 'bw'] + BW_EXTRA_ARG_KEYVALUES


def total_bw(bw_lines):
    return sum([l.bw for l in bw_lines])


def avg_bw(bw_lines):
    assert len(bw_lines) > 0
    return total_bw(bw_lines) / len(bw_lines)


def scale_lines(bw_lines, scale_constant):
    avg = avg_bw(bw_lines)
    for line in bw_lines:
        line.bw = round(line.bw / avg * scale_constant)
    warn_if_not_accurate_enough(bw_lines, scale_constant)
    return bw_lines


def warn_if_not_accurate_enough(bw_lines, scale_constant):
    margin = 0.001
    accuracy_ratio = avg_bw(bw_lines) / scale_constant
    log.info('The generated lines are within {:.5}% of what they should '
             'be'.format((1 - accuracy_ratio) * 100))
    if accuracy_ratio < 1 - margin or accuracy_ratio > 1 + margin:
        log.warning('There was %f%% error and only +/- %f%% is '
                    'allowed', (1 - accuracy_ratio) * 100, margin * 100)

juga's avatar
juga committed
69

juga's avatar
juga committed
70
71
72
73
74
75
76
77
78
def num_results_of_type(results, type_str):
    return len([r for r in results if r.type == type_str])


# Better way to use enums?
def result_type_to_key(type_str):
    return type_str.replace('-', '_')


79
class V3BWHeader(object):
juga's avatar
juga committed
80
81
82
83
    """
    Create a bandwidth measurements (V3bw) header
    following bandwidth measurements document spec version 1.1.0.

84
    :param str timestamp: timestamp in Unix Epoch seconds of the most recent
85
        generator result.
juga's avatar
juga committed
86
87
88
    :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
89
    :param dict kwargs: extra headers. Currently supported:
juga's avatar
juga committed
90

91
92
93
94
        - earliest_bandwidth: str, ISO 8601 timestamp in UTC time zone
          when the first bandwidth was obtained
        - generator_started: str, ISO 8601 timestamp in UTC time zone
          when the generator started
juga's avatar
juga committed
95
    """
96
    def __init__(self, timestamp, **kwargs):
juga's avatar
juga committed
97
98
99
100
        assert isinstance(timestamp, str)
        for v in kwargs.values():
            assert isinstance(v, str)
        self.timestamp = timestamp
101
102
103
104
        # KeyValues with default value when not given by kwargs
        self.version = kwargs.get('version', SPEC_VERSION)
        self.software = kwargs.get('software', 'sbws')
        self.software_version = kwargs.get('software_version', __version__)
105
        self.file_created = kwargs.get('file_created', now_isodt_str())
juga's avatar
juga committed
106
        # latest_bandwidth should not be in kwargs, since it MUST be the
107
        # same as timestamp
juga's avatar
juga committed
108
        self.latest_bandwidth = unixts_to_isodt_str(timestamp)
109
110
        [setattr(self, k, v) for k, v in kwargs.items()
         if k in EXTRA_ARG_KEYVALUES]
juga's avatar
juga committed
111

112
    @property
113
114
115
116
117
118
    def keyvalue_unordered_tuple_ls(self):
        """Return list of KeyValue tuples that do not have specific order."""
        # sort the list to generate determinist headers
        keyvalue_tuple_ls = sorted([(k, v) for k, v in self.__dict__.items()
                                    if k in UNORDERED_KEYVALUES])
        return keyvalue_tuple_ls
119
120

    @property
121
122
123
    def keyvalue_tuple_ls(self):
        """Return list of all KeyValue tuples"""
        return [('version', self.version)] + self.keyvalue_unordered_tuple_ls
124
125

    @property
126
127
128
129
130
    def keyvalue_v110str_ls(self):
        """Return KeyValue list of strings following spec v1.1.0."""
        keyvalues = [self.timestamp] + [KEYVALUE_SEP_V110.join([k, v])
                                        for k, v in self.keyvalue_tuple_ls]
        return keyvalues
131
132
133
134

    @property
    def strv110(self):
        """Return header string following spec v1.1.0."""
135
        header_str = LINE_SEP.join(self.keyvalue_v110str_ls) + LINE_SEP + \
136
137
138
139
            LINE_TERMINATOR
        return header_str

    @property
140
141
142
143
144
    def keyvalue_v200_ls(self):
        """Return KeyValue list of strings following spec v2.0.0."""
        keyvalue = [self.timestamp] + [KEYVALUE_SEP_V200.join([k, v])
                                       for k, v in self.keyvalue_tuple_ls]
        return keyvalue
145
146
147
148

    @property
    def strv200(self):
        """Return header string following spec v2.0.0."""
149
        header_str = LINE_SEP.join(self.keyvalue_v200_ls) + LINE_SEP + \
150
151
152
            LINE_TERMINATOR
        return header_str

153
154
155
156
157
    def __str__(self):
        if self.version == '1.1.0':
            return self.strv110
        return self.strv200

158
159
160
161
    @classmethod
    def from_lines_v110(cls, lines):
        """
        :param list lines: list of lines to parse
162
        :returns: tuple of V3BWHeader object and non-header lines
163
164
165
166
        """
        assert isinstance(lines, list)
        try:
            index_terminator = lines.index(TERMINATOR)
Matt Traudt's avatar
Matt Traudt committed
167
        except ValueError:
168
169
170
            # is not a bw file or is v100
            log.warn('Terminator is not in lines')
            return None
171
        ts = lines[0]
172
        kwargs = dict([l.split(KEYVALUE_SEP_V110)
173
                       for l in lines[:index_terminator]
174
                       if l.split(KEYVALUE_SEP_V110)[0] in ALL_KEYVALUES])
175
176
177
178
179
180
        h = cls(ts, **kwargs)
        return h, lines[index_terminator + 1:]

    @classmethod
    def from_text_v110(self, text):
        """
181
        :param str text: text to parse
182
        :returns: tuple of V3BWHeader object and non-header lines
183
184
185
        """
        assert isinstance(text, str)
        return self.from_lines_v110(text.split(LINE_SEP))
juga's avatar
juga committed
186
187
188
189
190
191
192

    @property
    def num_lines(self):
        return len(self.__str__().split(LINE_SEP))

    @staticmethod
    def generator_started_from_file(conf):
193
194
195
196
197
        state = State(conf['paths']['state_fname'])
        if 'scanner_started' in state:
            return state['scanner_started']
        else:
            return None
juga's avatar
juga committed
198
199

    @staticmethod
juga's avatar
juga committed
200
    def latest_bandwidth_from_results(results):
juga's avatar
juga committed
201
        return round(max([r.time for fp in results for r in results[fp]]))
juga's avatar
juga committed
202
203
204

    @staticmethod
    def earliest_bandwidth_from_results(results):
juga's avatar
juga committed
205
        return round(min([r.time for fp in results for r in results[fp]]))
juga's avatar
juga committed
206
207
208
209

    @classmethod
    def from_results(cls, conf, results):
        kwargs = dict()
juga's avatar
juga committed
210
        latest_bandwidth = cls.latest_bandwidth_from_results(results)
juga's avatar
juga committed
211
        earliest_bandwidth = cls.earliest_bandwidth_from_results(results)
juga's avatar
juga committed
212
        generator_started = cls.generator_started_from_file(conf)
juga's avatar
juga committed
213
214
        timestamp = str(latest_bandwidth)
        kwargs['latest_bandwidth'] = unixts_to_isodt_str(latest_bandwidth)
juga's avatar
juga committed
215
        kwargs['earliest_bandwidth'] = unixts_to_isodt_str(earliest_bandwidth)
216
217
        if generator_started is not None:
            kwargs['generator_started'] = generator_started
juga's avatar
juga committed
218
219
        h = cls(timestamp, **kwargs)
        return h
juga's avatar
juga committed
220
221


juga's avatar
juga committed
222
class V3BWLine(object):
juga's avatar
juga committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    """
    Create a Bandwidth List line following the spec version 1.1.0.

    :param str node_id:
    :param int bw:
    :param dict kwargs: extra headers. Currently supported:

        - nickname, str
        - master_key_ed25519, str
        - rtt, int
        - time, str
        - sucess, int
        - error_stream, int
        - error_circ, int
        - error_misc, int
    """
juga's avatar
juga committed
239
240
241
    def __init__(self, node_id, bw, **kwargs):
        assert isinstance(node_id, str)
        assert isinstance(bw, int)
242
        assert node_id.startswith('$')
juga's avatar
juga committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
        self.node_id = node_id
        self.bw = bw
        [setattr(self, k, v) for k, v in kwargs.items()
         if k in BW_EXTRA_ARG_KEYVALUES]

    @property
    def bw_keyvalue_tuple_ls(self):
        """Return list of KeyValue Bandwidth Line tuples."""
        # sort the list to generate determinist headers
        keyvalue_tuple_ls = sorted([(k, v) for k, v in self.__dict__.items()
                                    if k in BW_KEYVALUES])
        return keyvalue_tuple_ls

    @property
    def bw_keyvalue_v110str_ls(self):
        """Return list of KeyValue Bandwidth Line strings following
        spec v1.1.0.
        """
        bw_keyvalue_str = [KEYVALUE_SEP_V110 .join([k, str(v)])
                           for k, v in self.bw_keyvalue_tuple_ls]
        return bw_keyvalue_str

    @property
    def bw_strv110(self):
        """Return Bandwidth Line string following spec v1.1.0."""
        bw_line_str = BW_KEYVALUE_SEP_V110.join(
                        self.bw_keyvalue_v110str_ls) + LINE_SEP
juga's avatar
juga committed
270
271
272
273
274
        if len(bw_line_str) > BW_LINE_SIZE:
            # if this is the case, probably there are too many KeyValues,
            # or the limit needs to be changed in Tor
            log.warn("The bandwidth line %s is longer than %s",
                     len(bw_line_str), BW_LINE_SIZE)
juga's avatar
juga committed
275
        return bw_line_str
juga's avatar
juga committed
276
277

    def __str__(self):
juga's avatar
juga committed
278
279
280
281
282
283
284
285
        return self.bw_strv110

    @classmethod
    def from_bw_line_v110(cls, line):
        assert isinstance(line, str)
        kwargs = dict([kv.split(KEYVALUE_SEP_V110)
                       for kv in line.split(BW_KEYVALUE_SEP_V110)
                       if kv.split(KEYVALUE_SEP_V110)[0] in BW_KEYVALUES])
juga's avatar
juga committed
286
287
288
        for k, v in kwargs.items():
            if k in BW_KEYVALUES_INT:
                kwargs[k] = int(v)
juga's avatar
juga committed
289
290
291
292
293
294
295
        bw_line = cls(**kwargs)
        return bw_line

    @staticmethod
    def bw_from_results(results):
        median_bw = median([dl['amount'] / dl['duration']
                            for r in results for dl in r.downloads])
296
297
298
299
300
301
302
303
304
305
306
        # If a relay has MaxAdvertisedBandwidth set, they may be capable of
        # some large amount of bandwidth but prefer if they didn't receive it.
        # We also could have managed to measure them faster than their
        # {,Relay}BandwidthRate somehow.
        #
        # See https://github.com/pastly/simple-bw-scanner/issues/155 and
        # https://trac.torproject.org/projects/tor/ticket/8494
        #
        # Note how this isn't some measured-by-us average of bandwidth. It's
        # the first value on the 'bandwidth' line in the relay's server
        # descriptor.
juga's avatar
juga committed
307
308
309
310
311
312
313
        bw = median_bw
        relay_average_bw = [r.relay_average_bandwidth for r in results
                            if r.relay_average_bandwidth is not None]
        if relay_average_bw:
            median_relay_average_bw = median(relay_average_bw)
            if median_bw > median_relay_average_bw:
                bw = median_relay_average_bw
juga's avatar
juga committed
314
        # convert to KB and ensure it's at least 1
315
        bw_kb = max(round(bw / 1024), 1)
juga's avatar
juga committed
316
317
318
319
320
321
322
        return bw_kb

    @staticmethod
    def last_time_from_results(results):
        return unixts_to_isodt_str(round(max([r.time for r in results])))

    @staticmethod
juga's avatar
juga committed
323
    def rtt_from_results(results):
juga's avatar
juga committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        # convert from miliseconds to seconds
        rtts = [(round(rtt * 1000)) for r in results for rtt in r.rtts]
        rtt = round(median(rtts))
        return rtt

    @staticmethod
    def result_types_from_results(results):
        rt_dict = dict([(result_type_to_key(rt.value),
                         num_results_of_type(results, rt.value))
                        for rt in _ResultType])
        return rt_dict

    @classmethod
    def from_results(cls, results):
        success_results = [r for r in results if isinstance(r, ResultSuccess)]
Matt Traudt's avatar
Matt Traudt committed
339
        # log.debug('len(success_results) %s', len(success_results))
340
        node_id = '$' + results[0].fingerprint
juga's avatar
juga committed
341
342
343
        bw = cls.bw_from_results(success_results)
        kwargs = dict()
        kwargs['nick'] = results[0].nickname
juga's avatar
juga committed
344
345
        if getattr(results[0], 'master_key_ed25519'):
            kwargs['master_key_ed25519'] = results[0].master_key_ed25519
juga's avatar
juga committed
346
347
        kwargs['rtt'] = cls.rtt_from_results(success_results)
        kwargs['time'] = cls.last_time_from_results(results)
juga's avatar
juga committed
348
349
350
351
352
353
354
355
356
        kwargs.update(cls.result_types_from_results(results))
        bwl = cls(node_id, bw, **kwargs)
        return bwl

    @classmethod
    def from_data(cls, data, fingerprint):
        assert fingerprint in data
        return cls.from_results(data[fingerprint])

juga's avatar
juga committed
357

358
class V3BWFile(object):
juga's avatar
juga committed
359
360
361
362
363
364
    """
    Create a Bandwidth List file following spec version 1.1.0

    :param V3BWHeader v3bwheader: header
    :param list v3bwlines: V3BWLines
    """
juga's avatar
juga committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    def __init__(self, v3bwheader, v3bwlines):
        self.header = v3bwheader
        self.bw_lines = v3bwlines

    def __str__(self):
        return str(self.header) + ''.join([str(bw_line)
                                           for bw_line in self.bw_lines])

    @property
    def total_bw(self):
        return total_bw(self.bw_lines)

    @property
    def num_lines(self):
        return len(self.bw_lines)

    @property
    def avg_bw(self):
        return self.total_bw / self.num_lines

    @classmethod
    def from_arg_results(cls, args, conf, results):
        bw_lines = [V3BWLine.from_results(results[fp]) for fp in results]
        bw_lines = sorted(bw_lines, key=lambda d: d.bw, reverse=True)
        if args.scale:
            bw_lines = scale_lines(bw_lines, args.scale_constant)
391
        header = V3BWHeader.from_results(conf, results)
juga's avatar
juga committed
392
393
        f = cls(header, bw_lines)
        return f
juga's avatar
juga committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413

    def write(self, output):
        if output == '/dev/stdout':
            log.info("Writing to stdout is not supported.")
            return
        log.info('Writing v3bw file to %s', output)
        out_dir = os.path.dirname(output)
        out_link = os.path.join(out_dir, 'latest.v3bw')
        if os.path.exists(out_link):
            log.debug('Deleting existing symlink before creating a new one.')
            os.remove(out_link)
        with DirectoryLock(out_dir):
            with open(output, 'wt') as fd:
                fd.write(str(self.header))
                for line in self.bw_lines:
                    fd.write(str(line))
            output_basename = os.path.basename(output)
            log.debug('Creating symlink from {} to {}.'
                      .format(output_basename, out_link))
            os.symlink(output_basename, out_link)