blob: b0929499e645ac68166f713c1b4c72ad3bf334b1 [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
14from chromite.utils import metrics
15
16
17def deserialize_metrics_log(output_events, prefix=None):
18 """Read the current metrics events, adding to output_events.
19
20 This layer facilitates converting between the internal
21 chromite.utils.metrics representation of metric events and the
22 infra/proto/src/chromiumos/metrics.proto output type.
23
24 Args:
25 output_events: A chromiumos.MetricEvent protobuf message.
26 prefix: A string to prepend to all metric event names.
27 """
28 timers = {}
29
30 def make_name(name):
31 """Prepend a closed-over prefix to the given name."""
32 if prefix:
33 return '%s.%s' % (prefix, name)
34 else:
35 return name
36
37 # Reduce over the input events to append output_events.
38 for input_event in metrics.read_metrics_events():
39 if input_event.op == metrics.OP_START_TIMER:
40 timers[input_event.key] = (input_event.name,
41 input_event.timestamp_epoch_millis)
42 elif input_event.op == metrics.OP_STOP_TIMER:
43 timer = timers.pop(input_event.key)
44 if timer:
45 assert input_event.name == timer[0]
46 output_event = output_events.add()
47 output_event.name = make_name(timer[0])
48 output_event.timestamp_milliseconds = input_event.timestamp_epoch_millis
49 output_event.duration_milliseconds = (
50 output_event.timestamp_milliseconds - timer[1])
51 elif input_event.op == metrics.OP_NAMED_EVENT:
52 output_event = output_events.add()
53 output_event.name = make_name(input_event.name)
54 output_event.timestamp_milliseconds = input_event.timestamp_epoch_millis
55 else:
56 raise ValueError('unexpected op "%s" found in metric event: %s' % (
57 input_event.op, input_event))
58
59 # This is a sanity-check for unclosed timers.
60 assert len(timers.values()) == 0