blob: 739c7468abfbbdb6f7592fad5e94aaeca2f74951 [file] [log] [blame]
Will Bradley7e5b8c12019-07-30 12:44:15 -06001# -*- coding: utf-8 -*-
2# Copyright 2019 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Metrics for general consumption.
7
8See infra/proto/metrics.proto for a description of the type of record that this
9module will be creating.
10"""
11
12from __future__ import print_function
13
Mike Frysinger9f9fe912019-09-09 16:19:55 -040014from chromite.lib import cros_logging as logging
Will Bradley7e5b8c12019-07-30 12:44:15 -060015from chromite.utils import metrics
16
17
18def deserialize_metrics_log(output_events, prefix=None):
19 """Read the current metrics events, adding to output_events.
20
21 This layer facilitates converting between the internal
22 chromite.utils.metrics representation of metric events and the
23 infra/proto/src/chromiumos/metrics.proto output type.
24
25 Args:
26 output_events: A chromiumos.MetricEvent protobuf message.
27 prefix: A string to prepend to all metric event names.
28 """
29 timers = {}
30
31 def make_name(name):
32 """Prepend a closed-over prefix to the given name."""
33 if prefix:
34 return '%s.%s' % (prefix, name)
35 else:
36 return name
37
38 # Reduce over the input events to append output_events.
39 for input_event in metrics.read_metrics_events():
40 if input_event.op == metrics.OP_START_TIMER:
41 timers[input_event.key] = (input_event.name,
42 input_event.timestamp_epoch_millis)
43 elif input_event.op == metrics.OP_STOP_TIMER:
Mike Frysinger9f9fe912019-09-09 16:19:55 -040044 # TODO(wbbradley): Drop the None fallback https://crbug.com/1001909.
45 timer = timers.pop(input_event.key, None)
46 if timer is None:
47 logging.error('%s: stop timer recorded, but missing start timer!?',
48 input_event.key)
Will Bradley7e5b8c12019-07-30 12:44:15 -060049 if timer:
50 assert input_event.name == timer[0]
51 output_event = output_events.add()
52 output_event.name = make_name(timer[0])
53 output_event.timestamp_milliseconds = input_event.timestamp_epoch_millis
54 output_event.duration_milliseconds = (
55 output_event.timestamp_milliseconds - timer[1])
56 elif input_event.op == metrics.OP_NAMED_EVENT:
57 output_event = output_events.add()
58 output_event.name = make_name(input_event.name)
59 output_event.timestamp_milliseconds = input_event.timestamp_epoch_millis
60 else:
61 raise ValueError('unexpected op "%s" found in metric event: %s' % (
62 input_event.op, input_event))
63
64 # This is a sanity-check for unclosed timers.
65 assert len(timers.values()) == 0