1# Copyright 2018, The Android Open Source Project 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"""Asuite simple Metrics Functions""" 16 17import json 18import logging 19import os 20import uuid 21 22try: 23 from urllib.request import Request 24 from urllib.request import urlopen 25except ImportError: 26 # for compatibility of asuite_metrics_lib_tests and asuite_cc_lib_tests. 27 from urllib2 import Request 28 from urllib2 import urlopen 29 30 31_JSON_HEADERS = {'Content-Type': 'application/json'} 32_METRICS_RESPONSE = 'done' 33_METRICS_TIMEOUT = 2 #seconds 34_ANDROID_BUILD_TOP = 'ANDROID_BUILD_TOP' 35 36UNUSED_UUID = '00000000-0000-4000-8000-000000000000' 37 38 39#pylint: disable=broad-except 40def log_event(metrics_url, unused_key_fallback=True, **kwargs): 41 """Base log event function for asuite backend. 42 43 Args: 44 metrics_url: String, URL to report metrics to. 45 unused_key_fallback: Boolean, If True and unable to get grouping key, 46 use a unused key otherwise return out. Sometimes we 47 don't want to return metrics for users we are 48 unable to identify. Default True. 49 kwargs: Dict, additional fields we want to return metrics for. 50 """ 51 try: 52 try: 53 key = str(_get_grouping_key()) 54 except Exception: 55 if not unused_key_fallback: 56 return 57 key = UNUSED_UUID 58 data = {'grouping_key': key, 59 'run_id': str(uuid.uuid4())} 60 if kwargs: 61 data.update(kwargs) 62 data = json.dumps(data) 63 request = Request(metrics_url, data=data, 64 headers=_JSON_HEADERS) 65 response = urlopen(request, timeout=_METRICS_TIMEOUT) 66 content = response.read() 67 if content != _METRICS_RESPONSE: 68 raise Exception('Unexpected metrics response: %s' % content) 69 except Exception as e: 70 logging.debug('Exception sending metrics: %s', e) 71 72 73def _get_grouping_key(): 74 """Get grouping key. Returns UUID.uuid5.""" 75 meta_file = os.path.join(os.path.expanduser('~'), 76 '.config', 'asuite', '.metadata') 77 # (b/278503654) Treat non-human invocation as the same user when the email 78 # is null. 79 # Prevent circular import. 80 #pylint: disable=import-outside-toplevel 81 from atest.metrics import metrics_base 82 key = uuid.uuid5(uuid.NAMESPACE_DNS, metrics_base.get_user_email()) 83 dir_path = os.path.dirname(meta_file) 84 if os.path.isfile(dir_path): 85 os.remove(dir_path) 86 try: 87 os.makedirs(dir_path) 88 except OSError as e: 89 if not os.path.isdir(dir_path): 90 raise e 91 with open(meta_file, 'w+') as f: 92 f.write(str(key)) 93 return key 94