1#!/usr/bin/env python
2#
3#   Copyright 2017 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16import re
17
18# Handles edge case of acronyms then another word, eg. CPUMetric -> CPU_Metric
19# or lower camel case, cpuMetric -> cpu_Metric.
20first_cap_re = re.compile('(.)([A-Z][a-z]+)')
21# Handles CpuMetric -> Cpu_Metric
22all_cap_re = re.compile('([a-z0-9])([A-Z])')
23
24
25class Runner:
26    """Calls metrics and passes response to reporters.
27
28    Attributes:
29        metric_list: a list of metric objects
30        reporter_list: a list of reporter objects
31        object and value is dictionary returned by that response
32    """
33
34    def __init__(self, metric_list, reporter_list):
35        self.metric_list = metric_list
36        self.reporter_list = reporter_list
37
38    def run(self):
39        """Calls metrics and passes response to reporters."""
40        raise NotImplementedError()
41
42
43class InstantRunner(Runner):
44    def convert_to_snake(self, name):
45        """Converts a CamelCaseName to snake_case_name
46
47        Args:
48            name: The string you want to convert.
49        Returns:
50            snake_case_format of name.
51        """
52        temp_str = first_cap_re.sub(r'\1_\2', name)
53        return all_cap_re.sub(r'\1_\2', temp_str).lower()
54
55    def run(self):
56        """Calls all metrics, passes responses to reporters."""
57        responses = {}
58        for metric in self.metric_list:
59            # [:-7] removes the ending '_metric'.
60            key_name = self.convert_to_snake(metric.__class__.__name__)[:-7]
61            responses[key_name] = metric.gather_metric()
62        for reporter in self.reporter_list:
63            reporter.report(responses)
64