• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
14r"""Acloud metrics functions."""
15
16import logging
17import os
18import subprocess
19
20from acloud.internal import constants
21# pylint: disable=import-error
22
23_METRICS_URL = 'http://asuite-218222.appspot.com/acloud/metrics'
24_VALID_DOMAINS = ["google.com", "android.com"]
25_COMMAND_GIT_CONFIG = ["git", "config", "--get", "user.email"]
26
27logger = logging.getLogger(__name__)
28
29# pylint: disable=broad-except
30def LogUsage(argv):
31    """Log acloud start event.
32
33    Log acloud start event and the usage, following are the data we log:
34    - tool_name: All asuite tools are storing event in the same database. This
35      property is provided to distinguish different tools.
36    - command_line: Log all command arguments.
37    - test_references: Should be a list, we record the acloud sub-command.
38      e.g. create/delete/reconnect/..etc. We could use this property as filter
39      criteria to speed up query time.
40    - cwd: User's current working directory.
41    - os: The platform that users are working at.
42
43    Args:
44        argv: A list of system arguments.
45    """
46    # TODO(b131867764): We could remove this metics tool after we apply clearcut.
47    try:
48        from asuite import asuite_metrics
49        asuite_metrics.log_event(_METRICS_URL, dummy_key_fallback=False,
50                                 ldap=_GetLdap())
51    except ImportError:
52        logger.debug("No metrics recorder available, not sending metrics.")
53
54    #Log start event via clearcut tool.
55    try:
56        from asuite import atest_utils
57        from asuite.metrics import metrics_utils
58        atest_utils.print_data_collection_notice()
59        metrics_utils.send_start_event(tool_name=constants.TOOL_NAME,
60                                       command_line=' '.join(argv),
61                                       test_references=[argv[0]])
62    except Exception as e:
63        logger.debug("Failed to send start event:%s", str(e))
64
65
66#TODO(b131867764): We could remove this metics tool after we apply clearcut.
67def _GetLdap():
68    """Return string email username for valid domains only, None otherwise."""
69    try:
70        acloud_project = os.path.join(
71            os.environ[constants.ENV_ANDROID_BUILD_TOP], "tools", "acloud")
72        email = subprocess.check_output(_COMMAND_GIT_CONFIG,
73                                        cwd=acloud_project).strip()
74        ldap, domain = email.split("@", 2)
75        if domain in _VALID_DOMAINS:
76            return ldap
77    # pylint: disable=broad-except
78    except Exception as e:
79        logger.debug("error retrieving email: %s", e)
80    return None
81
82# pylint: disable=broad-except
83def LogExitEvent(exit_code, stacktrace="", logs=""):
84    """Log acloud exit event.
85
86    A start event should followed by an exit event to calculate the consuming
87    time. This function will be run at the end of acloud main process or
88    at the init of the error object.
89
90    Args:
91        exit_code: Integer, the exit code of acloud main process.
92        stacktrace: A string of stacktrace.
93        logs: A string of logs.
94    """
95    try:
96        from asuite.metrics import metrics_utils
97        metrics_utils.send_exit_event(exit_code, stacktrace=stacktrace,
98                                      logs=logs)
99    except Exception as e:
100        logger.debug("Failed to send exit event:%s", str(e))
101