|
| 1 | +# Copyright 2018 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import base64 |
| 16 | +import contextlib |
| 17 | +import copy |
| 18 | +import functools |
| 19 | +import google.auth |
| 20 | +import google.auth.exceptions |
| 21 | +import logging |
| 22 | +import os |
| 23 | +import time |
| 24 | + |
| 25 | +from opencensus import tags |
| 26 | +from opencensus.stats import aggregation |
| 27 | +from opencensus.stats import measure |
| 28 | +from opencensus.stats import stats |
| 29 | +from opencensus.stats import view |
| 30 | +from opencensus.stats.exporters import stackdriver_exporter |
| 31 | +from opencensus.stats.exporters.base import StatsExporter |
| 32 | +from opencensus.tags import execution_context |
| 33 | +from opencensus.tags.propagation import binary_serializer |
| 34 | + |
| 35 | +_logger = logging.getLogger('fireci.stats') |
| 36 | +STATS = stats.Stats() |
| 37 | + |
| 38 | +_m_latency = measure.MeasureFloat("latency", "The latency in milliseconds", |
| 39 | + "ms") |
| 40 | +_m_success = measure.MeasureInt("success", "Indicated success or failure.", "1") |
| 41 | + |
| 42 | +_key_stage = tags.TagKey("stage") |
| 43 | + |
| 44 | +_TAGS = [ |
| 45 | + _key_stage, |
| 46 | + tags.TagKey("repo_owner"), |
| 47 | + tags.TagKey("repo_name"), |
| 48 | + tags.TagKey("pull_number"), |
| 49 | + tags.TagKey("job_name"), |
| 50 | +] |
| 51 | + |
| 52 | +_METRICS_ENABLED = False |
| 53 | + |
| 54 | + |
| 55 | +class StdoutExporter(StatsExporter): |
| 56 | + """Fallback exporter in case stackdriver cannot be configured.""" |
| 57 | + |
| 58 | + def on_register_view(self, view): |
| 59 | + pass |
| 60 | + |
| 61 | + def emit(self, view_datas): |
| 62 | + _logger.info("emit %s", self.repr_data(view_datas)) |
| 63 | + |
| 64 | + def export(self, view_data): |
| 65 | + _logger.info("export %s", self._repr_data(view_data)) |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def _repr_data(view_data): |
| 69 | + return [ |
| 70 | + "ViewData<view={}, start={}, end={}>".format(d.view, d.start_time, |
| 71 | + d.end_time) |
| 72 | + for d in view_data |
| 73 | + ] |
| 74 | + |
| 75 | + |
| 76 | +def _new_exporter(): |
| 77 | + """ |
| 78 | + Initializes a metrics exporter. |
| 79 | +
|
| 80 | + Tries to initialize a Stackdriver exporter, falls back to StdoutExporter. |
| 81 | + """ |
| 82 | + try: |
| 83 | + _, project_id = google.auth.default() |
| 84 | + return stackdriver_exporter.new_stats_exporter( |
| 85 | + stackdriver_exporter.Options(project_id=project_id, resource='global')) |
| 86 | + except google.auth.exceptions.DefaultCredentialsError: |
| 87 | + _logger.exception("Using stdout exporter") |
| 88 | + return StdoutExporter() |
| 89 | + |
| 90 | + |
| 91 | +def configure(): |
| 92 | + """Globally enables metrics collection.""" |
| 93 | + global _METRICS_ENABLED |
| 94 | + if _METRICS_ENABLED: |
| 95 | + return |
| 96 | + _METRICS_ENABLED = True |
| 97 | + |
| 98 | + STATS.view_manager.register_exporter(_new_exporter()) |
| 99 | + latency_view = view.View( |
| 100 | + "fireci/latency", "Latency of fireci execution stages", _TAGS, _m_latency, |
| 101 | + aggregation.LastValueAggregation()) |
| 102 | + success_view = view.View( |
| 103 | + "fireci/success", "Success indication of fireci execution stages", _TAGS, |
| 104 | + _m_success, aggregation.LastValueAggregation()) |
| 105 | + STATS.view_manager.register_view(latency_view) |
| 106 | + STATS.view_manager.register_view(success_view) |
| 107 | + |
| 108 | + context = tags.TagMap() |
| 109 | + for tag in _TAGS: |
| 110 | + if tag.upper() in os.environ: |
| 111 | + context.insert(tag, tags.TagValue(os.environ[tag.upper()])) |
| 112 | + |
| 113 | + execution_context.set_current_tag_map(context) |
| 114 | + |
| 115 | + |
| 116 | +@contextlib.contextmanager |
| 117 | +def _measure(name): |
| 118 | + tmap = copy.deepcopy(execution_context.get_current_tag_map()) |
| 119 | + tmap.insert(_key_stage, name) |
| 120 | + start = time.time() |
| 121 | + try: |
| 122 | + yield |
| 123 | + except: |
| 124 | + mmap = STATS.stats_recorder.new_measurement_map() |
| 125 | + mmap.measure_int_put(_m_success, 0) |
| 126 | + mmap.record(tmap) |
| 127 | + raise |
| 128 | + |
| 129 | + elapsed = (time.time() - start) * 1000 |
| 130 | + mmap = STATS.stats_recorder.new_measurement_map() |
| 131 | + mmap.measure_float_put(_m_latency, elapsed) |
| 132 | + mmap.measure_int_put(_m_success, 1) |
| 133 | + mmap.record(tmap) |
| 134 | + _logger.info("%s took %sms", name, elapsed) |
| 135 | + |
| 136 | + |
| 137 | +@contextlib.contextmanager |
| 138 | +def measure(name): |
| 139 | + """Context manager that measures the time it took for a block of code to execute.""" |
| 140 | + if not _METRICS_ENABLED: |
| 141 | + yield |
| 142 | + return |
| 143 | + with _measure(name): |
| 144 | + yield |
| 145 | + |
| 146 | + |
| 147 | +def measure_call(name): |
| 148 | + """Function decorator that measures the time it took to execute the target function.""" |
| 149 | + |
| 150 | + def decorator(f): |
| 151 | + |
| 152 | + def decorated(*args, **kwargs): |
| 153 | + with measure(name): |
| 154 | + f(*args, **kwargs) |
| 155 | + |
| 156 | + functools.update_wrapper(decorated, f) |
| 157 | + return decorated |
| 158 | + |
| 159 | + return decorator |
| 160 | + |
| 161 | + |
| 162 | +def propagate_context_into(data_dict): |
| 163 | + """Propagates Tag context into a dictionary.""" |
| 164 | + if not _METRICS_ENABLED: |
| 165 | + return |
| 166 | + value = binary_serializer.BinarySerializer().to_byte_array( |
| 167 | + execution_context.get_current_tag_map()) |
| 168 | + data_dict['OPENCENSUS_STATS_CONTEXT'] = base64.b64encode(value) |
0 commit comments