v3bwfile.py 34.6 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."""

juga's avatar
juga committed
5
import copy
juga's avatar
juga committed
6
import logging
juga's avatar
juga committed
7
import os
juga's avatar
juga committed
8
from statistics import median, mean
9
from stem.descriptor import parse_file
juga's avatar
juga committed
10

11
from sbws import __version__
12
from sbws.globals import (SPEC_VERSION, BW_LINE_SIZE, SBWS_SCALE_CONSTANT,
13
14
                          TORFLOW_SCALING, SBWS_SCALING, TORFLOW_BW_MARGIN,
                          TORFLOW_OBS_LAST, TORFLOW_OBS_MEAN,
15
                          TORFLOW_ROUND_DIG, MIN_REPORT)
juga's avatar
juga committed
16
from sbws.lib.resultdump import ResultSuccess, _ResultType
17
from sbws.util.filelock import DirectoryLock
juga's avatar
juga committed
18
19
from sbws.util.timestamp import (now_isodt_str, unixts_to_isodt_str,
                                 now_unixts)
20
from sbws.util.state import State
juga's avatar
juga committed
21
22
23

log = logging.getLogger(__name__)

24
LINE_SEP = '\n'
25
26
27
28
29
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']
30
31
32
33
STATS_KEYVALUES = ['num_measured_relays', 'num_target_relays',
                   'num_net_relays', 'perc_measured_relays',
                   'perc_measured_targed']
KEYVALUES_INT = STATS_KEYVALUES
34
# List of all unordered KeyValues currently being used to generate the file
35
36
UNORDERED_KEYVALUES = EXTRA_ARG_KEYVALUES + STATS_KEYVALUES + \
                      ['latest_bandwidth']
37
38
# List of all the KeyValues currently being used to generate the file
ALL_KEYVALUES = ['version'] + UNORDERED_KEYVALUES
39
TERMINATOR = '===='
juga's avatar
juga committed
40
41
# Num header lines in v1.1.0 using all the KeyValues
NUM_LINES_HEADER_V110 = len(ALL_KEYVALUES) + 2
42
43
LINE_TERMINATOR = TERMINATOR + LINE_SEP

juga's avatar
juga committed
44
45
# KeyValue separator in Bandwidth Lines
BW_KEYVALUE_SEP_V110 = ' '
46
47
48
49
50
# not inclding in the files the extra bws for now
BW_KEYVALUES_BASIC = ['node_id', 'bw']
BW_KEYVALUES_FILE = BW_KEYVALUES_BASIC + \
                    ['master_key_ed25519', 'nick', 'rtt', 'time',
                     'success', 'error_stream', 'error_circ', 'error_misc']
51
52
BW_KEYVALUES_EXTRA_BWS = ['bw_bs_median', 'bw_bs_mean', 'desc_avg_bw_bs',
                          'desc_obs_bw_bs_last', 'desc_obs_bw_bs_mean']
53
BW_KEYVALUES_EXTRA = BW_KEYVALUES_FILE + BW_KEYVALUES_EXTRA_BWS
54
BW_KEYVALUES_INT = ['bw', 'rtt', 'success', 'error_stream',
55
56
                    'error_circ', 'error_misc'] + BW_KEYVALUES_EXTRA_BWS
BW_KEYVALUES = BW_KEYVALUES_BASIC + BW_KEYVALUES_EXTRA
juga's avatar
juga committed
57
58


59
60
61
62
63
64
def kb_round_x_sig_dig(bw_bs, digits=TORFLOW_ROUND_DIG):
    """Convert bw to KB and round to x most significat digits."""
    bw_kb = bw_bs / 1000
    return max(int(round(bw_kb, -digits)), 1)


juga's avatar
juga committed
65
66
67
68
69
70
71
72
73
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('-', '_')


74
class V3BWHeader(object):
juga's avatar
juga committed
75
76
77
78
    """
    Create a bandwidth measurements (V3bw) header
    following bandwidth measurements document spec version 1.1.0.

79
    :param str timestamp: timestamp in Unix Epoch seconds of the most recent
80
        generator result.
juga's avatar
juga committed
81
82
83
    :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
84
    :param dict kwargs: extra headers. Currently supported:
juga's avatar
juga committed
85

86
87
88
89
        - 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
90
    """
91
    def __init__(self, timestamp, **kwargs):
juga's avatar
juga committed
92
93
94
95
        assert isinstance(timestamp, str)
        for v in kwargs.values():
            assert isinstance(v, str)
        self.timestamp = timestamp
96
97
98
99
        # 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__)
100
        self.file_created = kwargs.get('file_created', now_isodt_str())
juga's avatar
juga committed
101
        # latest_bandwidth should not be in kwargs, since it MUST be the
102
        # same as timestamp
juga's avatar
juga committed
103
        self.latest_bandwidth = unixts_to_isodt_str(timestamp)
104
105
        [setattr(self, k, v) for k, v in kwargs.items()
         if k in EXTRA_ARG_KEYVALUES]
juga's avatar
juga committed
106

107
108
109
110
111
    def __str__(self):
        if self.version == '1.1.0':
            return self.strv110
        return self.strv200

juga's avatar
juga committed
112
    @classmethod
juga's avatar
juga committed
113
    def from_results(cls, results, state_fpath=''):
juga's avatar
juga committed
114
115
116
        kwargs = dict()
        latest_bandwidth = cls.latest_bandwidth_from_results(results)
        earliest_bandwidth = cls.earliest_bandwidth_from_results(results)
juga's avatar
juga committed
117
        generator_started = cls.generator_started_from_file(state_fpath)
juga's avatar
juga committed
118
119
120
121
122
123
124
125
        timestamp = str(latest_bandwidth)
        kwargs['latest_bandwidth'] = unixts_to_isodt_str(latest_bandwidth)
        kwargs['earliest_bandwidth'] = unixts_to_isodt_str(earliest_bandwidth)
        if generator_started is not None:
            kwargs['generator_started'] = generator_started
        h = cls(timestamp, **kwargs)
        return h

126
127
128
129
    @classmethod
    def from_lines_v110(cls, lines):
        """
        :param list lines: list of lines to parse
130
        :returns: tuple of V3BWHeader object and non-header lines
131
132
133
134
        """
        assert isinstance(lines, list)
        try:
            index_terminator = lines.index(TERMINATOR)
Matt Traudt's avatar
Matt Traudt committed
135
        except ValueError:
136
137
138
            # is not a bw file or is v100
            log.warn('Terminator is not in lines')
            return None
139
        ts = lines[0]
140
        kwargs = dict([l.split(KEYVALUE_SEP_V110)
141
                       for l in lines[:index_terminator]
142
                       if l.split(KEYVALUE_SEP_V110)[0] in ALL_KEYVALUES])
143
        h = cls(ts, **kwargs)
juga's avatar
juga committed
144
        # last line is new line
145
        return h, lines[index_terminator + 1:-1]
146
147
148
149

    @classmethod
    def from_text_v110(self, text):
        """
150
        :param str text: text to parse
151
        :returns: tuple of V3BWHeader object and non-header lines
152
153
154
        """
        assert isinstance(text, str)
        return self.from_lines_v110(text.split(LINE_SEP))
juga's avatar
juga committed
155

juga's avatar
juga committed
156
157
158
159
160
161
162
163
164
165
166
    @classmethod
    def from_lines_v100(cls, lines):
        """
        :param list lines: list of lines to parse
        :returns: tuple of V3BWHeader object and non-header lines
        """
        assert isinstance(lines, list)
        h = cls(lines[0])
        # last line is new line
        return h, lines[1:-1]

juga's avatar
juga committed
167
    @staticmethod
juga's avatar
juga committed
168
    def generator_started_from_file(state_fpath):
169
170
171
172
        '''
        ISO formatted timestamp for the time when the scanner process most
        recently started.
        '''
juga's avatar
juga committed
173
        state = State(state_fpath)
174
175
176
177
        if 'scanner_started' in state:
            return state['scanner_started']
        else:
            return None
juga's avatar
juga committed
178
179

    @staticmethod
juga's avatar
juga committed
180
    def latest_bandwidth_from_results(results):
juga's avatar
juga committed
181
        return round(max([r.time for fp in results for r in results[fp]]))
juga's avatar
juga committed
182
183
184

    @staticmethod
    def earliest_bandwidth_from_results(results):
juga's avatar
juga committed
185
        return round(min([r.time for fp in results for r in results[fp]]))
juga's avatar
juga committed
186

juga's avatar
juga committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
    @property
    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

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

    @property
    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

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

    @property
    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

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

    @property
    def num_lines(self):
        return len(self.__str__().split(LINE_SEP))
juga's avatar
juga committed
231
232


juga's avatar
juga committed
233
class V3BWLine(object):
juga's avatar
juga committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    """
    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
250
251
252
    def __init__(self, node_id, bw, **kwargs):
        assert isinstance(node_id, str)
        assert isinstance(bw, int)
253
        assert node_id.startswith('$')
juga's avatar
juga committed
254
255
256
        self.node_id = node_id
        self.bw = bw
        [setattr(self, k, v) for k, v in kwargs.items()
257
         if k in BW_KEYVALUES_EXTRA]
juga's avatar
juga committed
258

juga's avatar
juga committed
259
    def __str__(self):
juga's avatar
juga committed
260
261
        return self.bw_strv110

juga's avatar
juga committed
262
    @classmethod
juga's avatar
juga committed
263
264
    def from_results(cls, results, secs_recent=None, secs_away=None,
                     min_num=0):
265
266
267
268
269
270
271
272
273
        """Convert sbws results to relays' Bandwidth Lines

        ``bs`` stands for Bytes/seconds
        ``bw_bs_mean`` means the bw is obtained from the mean of the all the
        downloads' bandwidth.
        Downloads' bandwidth are calculated as the amount of data received
        divided by the the time it took to received.
        bw = data (Bytes) / time (seconds)
        """
juga's avatar
juga committed
274
275
276
277
278
279
280
281
        success_results = [r for r in results if isinstance(r, ResultSuccess)]
        node_id = '$' + results[0].fingerprint
        kwargs = dict()
        kwargs['nick'] = results[0].nickname
        if getattr(results[0], 'master_key_ed25519'):
            kwargs['master_key_ed25519'] = results[0].master_key_ed25519
        kwargs['time'] = cls.last_time_from_results(results)
        kwargs.update(cls.result_types_from_results(results))
282
283
        # useful args for scaling
        if success_results:
284
            if not len(success_results) >= min_num:
juga's avatar
juga committed
285
                # log.debug('The number of results is les than %s', min_num)
286
287
                return None
            results_away = \
288
289
290
291
292
                cls.results_away_each_other(success_results, secs_away)
            if not results_away:
                log.debug("There are no results with relays' results away from"
                          " each other {}".format(secs_away))
                return None
293
294
            results_recent = cls.results_recent_than(results_away, secs_recent)
            if not results_recent:
juga's avatar
juga committed
295
296
                log.debug("There are no results that are more recent than {}"
                          " secs".format(secs_recent))
297
                return None
298
299
            # the most recent should be the last
            kwargs['desc_avg_bw_bs'] = \
300
301
302
303
                results_recent[-1].relay_average_bandwidth
            kwargs['rtt'] = cls.rtt_from_results(results_recent)
            bw = cls.bw_bs_median_from_results(results_recent)
            kwargs['bw_bs_mean'] = cls.bw_bs_mean_from_results(results_recent)
304
            kwargs['bw_bs_median'] = cls.bw_bs_median_from_results(
305
                results_recent)
306
            kwargs['desc_obs_bw_bs_last'] = \
307
                cls.desc_obs_bw_bs_last_from_results(results_recent)
308
            kwargs['desc_obs_bw_bs_mean'] = \
309
                cls.desc_obs_bw_bs_mean_from_results(results_recent)
310
311
312
            bwl = cls(node_id, bw, **kwargs)
            return bwl
        return None
juga's avatar
juga committed
313
314
315
316
317
318

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

juga's avatar
juga committed
319
320
321
322
323
324
    @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
325
326
327
        for k, v in kwargs.items():
            if k in BW_KEYVALUES_INT:
                kwargs[k] = int(v)
328
329
330
331
332
        node_id = kwargs['node_id']
        bw = kwargs['bw']
        del kwargs['node_id']
        del kwargs['bw']
        bw_line = cls(node_id, bw, **kwargs)
juga's avatar
juga committed
333
334
        return bw_line

juga's avatar
juga committed
335
336
    @staticmethod
    def results_away_each_other(results, secs_away=None):
juga's avatar
juga committed
337
338
        # log.debug("Checking whether results are away from each other in %s "
        #           "secs.", secs_away)
juga's avatar
juga committed
339
340
341
342
343
344
345
346
        if secs_away is None or len(results) < 2:
            return results
        # the last one should be the most recent
        results_away = [results[-1]]
        # iterate over the rest of the results in reverse order
        for r in reversed(results[:-1]):
            if abs(results_away[0].time - r.time) > secs_away:
                results_away.insert(0, r)
347
348
349
350
        # if there is only 1 result, is the one inserted at the beginning,
        # so there are no results away from each other
        if len(results_away) < 2:
            return None
juga's avatar
juga committed
351
352
353
354
355
356
357
358
359
360
361
        return results_away

    @staticmethod
    def results_recent_than(results, secs_recent=None):
        if secs_recent is None:
            return results
        results_recent = filter(
                            lambda x: (now_unixts() - x.time) < secs_recent,
                            results)
        return list(results_recent)

362
363
364
365
366
367
368
369
370
371
    @staticmethod
    def bw_bs_median_from_results(results):
        return max(round(median([dl['amount'] / dl['duration']
                                 for r in results for dl in r.downloads])), 1)

    @staticmethod
    def bw_bs_mean_from_results(results):
        return max(round(mean([dl['amount'] / dl['duration']
                               for r in results for dl in r.downloads])), 1)

juga's avatar
juga committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    @staticmethod
    def last_time_from_results(results):
        return unixts_to_isodt_str(round(max([r.time for r in results])))

    @staticmethod
    def rtt_from_results(results):
        # 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

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    @staticmethod
    def desc_obs_bw_bs_mean_from_results(results):
        desc_obs_bws = []
        for r in results:
            if r.relay_observed_bandwidth is not None:
                desc_obs_bws.append(r.relay_observed_bandwidth)
        if desc_obs_bws:
            return max(round(mean(desc_obs_bws)), 1)
        return None

    @staticmethod
    def desc_obs_bw_bs_last_from_results(results):
        # the last is at the end of the list
        for r in reversed(results):
            if r.relay_observed_bandwidth is not None:
                return r.relay_observed_bandwidth
        return None

juga's avatar
juga committed
408
409
410
411
412
413
414
    @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
juga's avatar
juga committed
415

juga's avatar
juga committed
416
417
418
419
420
421
422
423
    @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
juga's avatar
juga committed
424

juga's avatar
juga committed
425
426
427
428
429
430
431
432
433
434
435
    @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
        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)
        return bw_line_str
juga's avatar
juga committed
436

juga's avatar
juga committed
437

438
class V3BWFile(object):
juga's avatar
juga committed
439
440
441
442
443
444
    """
    Create a Bandwidth List file following spec version 1.1.0

    :param V3BWHeader v3bwheader: header
    :param list v3bwlines: V3BWLines
    """
juga's avatar
juga committed
445
446
447
448
449
    def __init__(self, v3bwheader, v3bwlines):
        self.header = v3bwheader
        self.bw_lines = v3bwlines

    def __str__(self):
450
        return str(self.header) + ''.join([str(bw_line) or ''
juga's avatar
juga committed
451
452
                                           for bw_line in self.bw_lines])

juga's avatar
juga committed
453
    @classmethod
juga's avatar
juga committed
454
    def from_results(cls, results, state_fpath='',
455
456
                     scale_constant=SBWS_SCALE_CONSTANT,
                     scaling_method=None, torflow_obs=TORFLOW_OBS_LAST,
juga's avatar
juga committed
457
                     torflow_cap=TORFLOW_BW_MARGIN,
458
                     torflow_round_digs=TORFLOW_ROUND_DIG,
459
                     secs_recent=None, secs_away=None, min_num=0,
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
                     reverse=False):
        """Create V3BWFile class from sbws Results.

        :param dict results: see below
        :param str state_fpath: path to the state file
        :param int scaling_method:
            Scaling method to obtain the bandwidth
            Posiable values: {NONE, SBWS_SCALING, TORFLOW_SCALING} = {0, 1, 2}
        :param int scale_constant: sbws scaling constant
        :param int torflow_obs: method to choose descriptor observed bandwidth
        :param bool reverse: whether to sort the bw lines descending or not

        Results are in the form::

            {'relay_fp1': [Result1, Result2, ...],
             'relay_fp2': [Result1, Result2, ...]}

        """
        # TODO: change scaling_method to TORFLOW_SCALING before getting this
        # in production
        log.info('Processing results to generate a bandwidth list file.')
        header = V3BWHeader.from_results(results, state_fpath)
        bw_lines_raw = []
juga's avatar
juga committed
483
484
485
        for fp, values in results.items():
            line = V3BWLine.from_results(values, secs_recent, secs_away,
                                         min_num)
juga's avatar
juga committed
486
487
            if line is not None:
                bw_lines_raw.append(line)
488
489
490
491
        if not bw_lines_raw:
            return cls(header, [])
        if scaling_method == SBWS_SCALING:
            bw_lines = cls.bw_sbws_scale(bw_lines_raw, scale_constant)
juga's avatar
juga committed
492
            cls.warn_if_not_accurate_enough(bw_lines, scale_constant)
493
494
            # log.debug(bw_lines[-1])
        elif scaling_method == TORFLOW_SCALING:
juga's avatar
juga committed
495
            bw_lines = cls.bw_torflow_scale(bw_lines_raw, torflow_obs,
496
                                            torflow_cap, torflow_round_digs)
497
            # log.debug(bw_lines[-1])
juga's avatar
juga committed
498
        else:
499
500
            bw_lines = cls.bw_kb(bw_lines_raw)
            # log.debug(bw_lines[-1])
juga's avatar
juga committed
501
502
503
        f = cls(header, bw_lines)
        return f

504
505
506
507
508
509
510
511
512
513
    @classmethod
    def from_v110_fpath(cls, fpath):
        log.info('Parsing bandwidth file %s', fpath)
        with open(fpath) as fd:
            text = fd.read()
        all_lines = text.split(LINE_SEP)
        header, lines = V3BWHeader.from_lines_v110(all_lines)
        bw_lines = [V3BWLine.from_bw_line_v110(line) for line in lines]
        return cls(header, bw_lines)

514
515
516
517
518
519
520
521
522
523
524
    @classmethod
    def from_v100_fpath(cls, fpath):
        log.info('Parsing bandwidth file %s', fpath)
        with open(fpath) as fd:
            text = fd.read()
        all_lines = text.split(LINE_SEP)
        header, lines = V3BWHeader.from_lines_v100(all_lines)
        bw_lines = sorted([V3BWLine.from_bw_line_v110(l) for l in lines],
                          key=lambda l: l.bw)
        return cls(header, bw_lines)

juga's avatar
juga committed
525
526
527
528
529
530
531
    @staticmethod
    def bw_kb(bw_lines, reverse=False):
        bw_lines_scaled = copy.deepcopy(bw_lines)
        for l in bw_lines_scaled:
            l.bw = max(round(l.bw / 1000), 1)
        return sorted(bw_lines_scaled, key=lambda x: x.bw, reverse=reverse)

juga's avatar
juga committed
532
    @staticmethod
533
    def bw_sbws_scale(bw_lines, scale_constant=SBWS_SCALE_CONSTANT,
juga's avatar
juga committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
                      reverse=False):
        """Return a new V3BwLine list scaled using sbws method.

        :param list bw_lines:
            bw lines to scale, not self.bw_lines,
            since this method will be before self.bw_lines have been
            initialized.
        :param int scale_constant:
            the constant to multiply by the ratio and
            the bandwidth to obtain the new bandwidth
        :returns list: V3BwLine list
        """
        # 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.
        log.debug('Scaling bandwidth using sbws method.')
        m = median([l.bw for l in bw_lines])
        bw_lines_scaled = copy.deepcopy(bw_lines)
        for l in bw_lines_scaled:
            # min is to limit the bw to descriptor average-bandwidth
            # max to avoid bandwidth with 0 value
            l.bw = max(round(min(l.desc_avg_bw_bs,
564
                                 l.bw * scale_constant / m)
juga's avatar
juga committed
565
566
567
568
569
                             / 1000), 1)
        return sorted(bw_lines_scaled, key=lambda x: x.bw, reverse=reverse)

    @staticmethod
    def warn_if_not_accurate_enough(bw_lines,
570
                                    scale_constant=SBWS_SCALE_CONSTANT):
juga's avatar
juga committed
571
572
573
574
575
576
577
578
        margin = 0.001
        accuracy_ratio = median([l.bw for l in 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)

579
    @staticmethod
580
    def bw_torflow_scale(bw_lines, desc_obs_bws=TORFLOW_OBS_MEAN,
581
582
                         cap=TORFLOW_BW_MARGIN,
                         num_round_dig=TORFLOW_ROUND_DIG, reverse=False):
juga's avatar
juga committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
        """
        Obtain final bandwidth measurements applying Torflow's scaling
        method.

        From Torflow's README.spec.txt (section 2.2)::

            In this way, the resulting network status consensus bandwidth values  # NOQA
            are effectively re-weighted proportional to how much faster the node  # NOQA
            was as compared to the rest of the network.

        The variables and steps used in Torflow:

        **strm_bw**::

            The strm_bw field is the average (mean) of all the streams for the relay  # NOQA
            identified by the fingerprint field.
            strm_bw = sum(bw stream x)/|n stream|

        **filt_bw**::

            The filt_bw field is computed similarly, but only the streams equal to  # NOQA
            or greater than the strm_bw are counted in order to filter very slow  # NOQA
            streams due to slow node pairings.

        **filt_sbw and strm_sbw**::

            for rs in RouterStats.query.filter(stats_clause).\
                  options(eagerload_all('router.streams.circuit.routers')).all():  # NOQA
              tot_sbw = 0
              sbw_cnt = 0
              for s in rs.router.streams:
                if isinstance(s, ClosedStream):
                  skip = False
                  #for br in badrouters:
                  #  if br != rs:
                  #    if br.router in s.circuit.routers:
                  #      skip = True
                  if not skip:
                    # Throw out outliers < mean
                    # (too much variance for stddev to filter much)
                    if rs.strm_closed == 1 or s.bandwidth() >= rs.sbw:
                      tot_sbw += s.bandwidth()
                      sbw_cnt += 1

            if sbw_cnt: rs.filt_sbw = tot_sbw/sbw_cnt
            else: rs.filt_sbw = None

        **filt_avg, and strm_avg**::

            Once we have determined the most recent measurements for each node, we  # NOQA
            compute an average of the filt_bw fields over all nodes we have measured.  # NOQA

        ::

            filt_avg = sum(map(lambda n: n.filt_bw, nodes.itervalues()))/float(len(nodes))  # NOQA
            strm_avg = sum(map(lambda n: n.strm_bw, nodes.itervalues()))/float(len(nodes))  # NOQA

        **true_filt_avg and true_strm_avg**::

            for cl in ["Guard+Exit", "Guard", "Exit", "Middle"]:
                true_filt_avg[cl] = filt_avg
                true_strm_avg[cl] = strm_avg

        In the non-pid case, all types of nodes get the same avg

        **n.fbw_ratio and n.fsw_ratio**::

            for n in nodes.itervalues():
                n.fbw_ratio = n.filt_bw/true_filt_avg[n.node_class()]
                n.sbw_ratio = n.strm_bw/true_strm_avg[n.node_class()]

        **n.ratio**::

            These averages are used to produce ratios for each node by dividing the  # NOQA
            measured value for that node by the network average.

        ::

            # Choose the larger between sbw and fbw
              if n.sbw_ratio > n.fbw_ratio:
                n.ratio = n.sbw_ratio
              else:
                n.ratio = n.fbw_ratio

        **desc_bw**:

        It is the ``observed bandwidth`` in the descriptor, NOT the ``average
        bandwidth``::

            return Router(ns.idhex, ns.nickname, bw_observed, dead, exitpolicy,
            ns.flags, ip, version, os, uptime, published, contact, rate_limited,  # NOQA
            ns.orhash, ns.bandwidth, extra_info_digest, ns.unmeasured)
            self.desc_bw = max(bw,1) # Avoid div by 0

        **new_bw**::

            These ratios are then multiplied by the most recent observed descriptor  # NOQA
            bandwidth we have available for each node, to produce a new value for  # NOQA
            the network status consensus process.

        ::

            n.new_bw = n.desc_bw*n.ratio

        The descriptor observed bandwidth is multiplied by the ratio.

        **Limit the bandwidth to a maximum**::

            NODE_CAP = 0.05

        ::

            if n.new_bw > tot_net_bw*NODE_CAP:
              plog("INFO", "Clipping extremely fast "+n.node_class()+" node "+n.idhex+"="+n.nick+  # NOQA
                   " at "+str(100*NODE_CAP)+"% of network capacity ("+
                   str(n.new_bw)+"->"+str(int(tot_net_bw*NODE_CAP))+") "+
                   " pid_error="+str(n.pid_error)+
                   " pid_error_sum="+str(n.pid_error_sum))
              n.new_bw = int(tot_net_bw*NODE_CAP)

        However, tot_net_bw does not seems to be updated when not using pid.
        This clipping would make faster relays to all have the same value.

        All of that can be expressed as:

        .. math::
709

juga's avatar
juga committed
710
711
712
713
714
715
            bwn_i &=
                max\\left(
                    \\frac{bw_i}{\\mu},
                    \\frac{bwf_i}{\\mu_{bwf}}
                    \\right)
                \\times bwobs_i
juga's avatar
juga committed
716
717
718

        .. math::

juga's avatar
juga committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
             bwn_i &=
                max\\left(
                    \\frac{bw_i}{\\mu},
                    min \\left(
                        bw_i,
                        bw_i \\times \\mu
                        \\right)
                            \\times
                            \\frac{bw_i}{\\sum_{i=1}^{n}
                            min \\left(bw_i,
                                bw_i \\times \\mu
                            \\right)}
                    \\right)
                \\times bwobs_i \\
733

juga's avatar
juga committed
734
735
736
737
             &=
                max\\left(
                    \\frac{bw_i}{\\frac{\\sum_{i=1}^{n}bw_i}{n}},
                    min \\left(
juga's avatar
juga committed
738
                        bw_i,
juga's avatar
juga committed
739
740
741
742
743
744
745
746
747
                        bw_i \\times \\frac{\\sum_{i=1}^{n}bw_i}{n}
                        \\right)
                            \\times
                            \\frac{bw_i}{\\sum_{i=1}^{n}
                            min \\left(bw_i,
                                bw_i \\times \\frac{\\sum_{i=1}^{n}bw_i}{n}
                            \\right)}
                    \\right)
                \\times bwobs_i
juga's avatar
juga committed
748
749
750
751
752
753
754
755
756
757

        """
        log.info("Calculating relays' bandwidth using Torflow method.")
        bw_lines_tf = copy.deepcopy(bw_lines)
        # mean (Torflow's strm_avg)
        mu = mean([l.bw_bs_mean for l in bw_lines])
        # filtered mean (Torflow's filt_avg)
        muf = mean([min(l.bw_bs_mean, mu) for l in bw_lines])
        # bw sum (Torflow's tot_net_bw or tot_sbw)
        sum_bw = sum([l.bw_bs_mean for l in bw_lines])
juga's avatar
juga committed
758
759
        # Torflow's clipping
        hlimit = sum_bw * TORFLOW_BW_MARGIN
juga's avatar
juga committed
760
761
762
        log.debug('sum %s', sum_bw)
        log.debug('mu %s', mu)
        log.debug('muf %s', muf)
juga's avatar
juga committed
763
        log.debug('hlimit %s', hlimit)
juga's avatar
juga committed
764
765
766
767
768
769
        for l in bw_lines_tf:
            if desc_obs_bws == TORFLOW_OBS_LAST:
                desc_obs_bw = l.desc_obs_bw_bs_last
            elif desc_obs_bws == TORFLOW_OBS_MEAN:
                desc_obs_bw = l.desc_obs_bw_bs_mean
            # just applying the formula above:
770
771
            bw_new = kb_round_x_sig_dig(
                max(
juga's avatar
juga committed
772
773
                    l.bw_bs_mean / mu,  # ratio
                    min(l.bw_bs_mean, mu) / muf  # ratio filtered
774
775
                    ) * desc_obs_bw, \
                digits=num_round_dig)  # convert to KB
juga's avatar
juga committed
776
777
778
779
780
            # Cap maximum bw
            if cap is not None:
                bw_new = min(hlimit, bw_new)
            # remove decimals and avoid 0
            l.bw = max(round(bw_new), 1)
juga's avatar
juga committed
781
        return sorted(bw_lines_tf, key=lambda x: x.bw, reverse=reverse)
782

783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
    @staticmethod
    def measured_progress_stats(bw_lines, consensus_path):
        """ Statistics about measurements progress,
        to be included in the header.

        :param list bw_lines: the bw_lines after scaling and applying filters.
        :param str consensus_path: the path to the cached consensus file.
        :returns dict, bool: Statistics about the progress made with
            measurements and whether the percentage of measured relays has been
            reached.

        """
        # cached-consensus should be updated every time that scanner get the
        # network status or descriptors?
        # It will not be updated to the last consensus, but the list of
        # measured relays is not either.
        assert isinstance(consensus_path, str)
        assert isinstance(bw_lines, list)
        statsd = {}
        statsd['num_measured_relays'] = len(bw_lines)
        statsd['num_net_relays'] = len(list(parse_file(consensus_path)))
        statsd['num_target_relays'] = round(statsd['num_net_relays']
                                            * MIN_REPORT / 100)
        statsd['perc_measured_relays'] = round(len(bw_lines) * 100
                                               / statsd['num_target_relays'])
        statsd['perc_measured_targed'] = MIN_REPORT
        if statsd['num_measured_relays'] < statsd['num_target_relays']:
            log.warning('The percentage of the measured relays is less than'
                        ' the %s%% of the relays in the network (%s).',
                        MIN_REPORT, statsd['num_net_relays'])
            return statsd, False
        return statsd, True

    @property
    def is_min_perc(self):
        if getattr(self.header, 'num_measured_relays', 0) \
                < getattr(self.header, 'num_target_relays', 0):
            return False
        return True

juga's avatar
juga committed
823
    @property
juga's avatar
juga committed
824
825
    def sum_bw(self):
        return sum([l.bw for l in self.bw_lines])
juga's avatar
juga committed
826
827

    @property
juga's avatar
juga committed
828
    def num(self):
juga's avatar
juga committed
829
830
831
        return len(self.bw_lines)

    @property
juga's avatar
juga committed
832
833
834
835
836
837
    def mean_bw(self):
        return mean([l.bw for l in self.bw_lines])

    @property
    def median_bw(self):
        return median([l.bw for l in self.bw_lines])
juga's avatar
juga committed
838

juga's avatar
juga committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
    @property
    def max_bw(self):
        return max([l.bw for l in self.bw_lines])

    @property
    def min_bw(self):
        return min([l.bw for l in self.bw_lines])

    @property
    def info_stats(self):
        if not self.bw_lines:
            return
        [log.info(': '.join([attr, str(getattr(self, attr))])) for attr in
         ['sum_bw', 'mean_bw', 'median_bw', 'num',
          'max_bw', 'min_bw']]

juga's avatar
juga committed
855
856
857
858
859
860
861
862
863
864
    def bw_line_for_node_id(self, node_id):
        """Returns the bandwidth line for a given node fingerprint.

        Used to combine data when plotting.
        """
        bwl = [l for l in self.bw_lines if l.node_id == node_id]
        if bwl:
            return bwl[0]
        return None

juga's avatar
juga committed
865
866
867
868
869
870
871
872
873
    def to_plt(self, attrs=['bw'], sorted_by=None):
        """Return bandwidth data in a format useful for matplotlib.

        Used from external tool to plot.
        """
        x = [i for i in range(0, self.num)]
        ys = [[getattr(l, k) for l in self.bw_lines] for k in attrs]
        return x, ys, attrs

juga's avatar
juga committed
874
875
876
877
878
879
880
881
882
883
884
    def rm_link(self, output):
        """"""
        out_dir = os.path.dirname(output)
        out_link = os.path.join(out_dir, 'latest.v3bw')
        log.info('Removing %s link.', output)
        with DirectoryLock(out_dir):
            try:
                os.unlink(out_link)
            except FileNotFoundError:
                pass

juga's avatar
juga committed
885
886
887
888
889
    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)
890
891
        # To avoid inconsistent reads, the bandwidth data is written to an
        # archive path, then atomically symlinked to 'latest.v3bw'
juga's avatar
juga committed
892
893
        out_dir = os.path.dirname(output)
        out_link = os.path.join(out_dir, 'latest.v3bw')
894
        out_link_tmp = out_link + '.tmp'
juga's avatar
juga committed
895
896
897
898
899
900
        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)
901
902
903
904
905
906
907
908
909
910
            # To atomically symlink a file, we need to create a temporary link,
            # then rename it to the final link name. (POSIX guarantees that
            # rename is atomic.)
            log.debug('Creating symlink {} -> {}.'
                      .format(out_link_tmp, output_basename))
            os.symlink(output_basename, out_link_tmp)
            log.debug('Renaming symlink {} -> {} to {} -> {}.'
                      .format(out_link_tmp, output_basename,
                              out_link, output_basename))
            os.rename(out_link_tmp, out_link)