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
17
18from acloud.internal import constants
19_NO_METRICS = "--no-metrics"
20
21
22logger = logging.getLogger(__name__)
23
24
25# pylint: disable=broad-except, import-error
26def LogUsage(argv):
27    """Log acloud start event.
28
29    Log acloud start event and the usage, following are the data we log:
30    - tool_name: All asuite tools are storing event in the same database. This
31      property is provided to distinguish different tools.
32    - command_line: Log all command arguments.
33    - test_references: Should be a list, we record the acloud sub-command.
34      e.g. create/delete/reconnect/..etc. We could use this property as filter
35      criteria to speed up query time.
36    - cwd: User's current working directory.
37    - os: The platform that users are working at.
38
39    Args:
40        argv: A list of system arguments.
41
42    Returns:
43        True if start event is sent and need to pair with end event.
44    """
45    if _NO_METRICS in argv:
46        return False
47
48    try:
49        from asuite import atest_utils
50        from asuite.metrics import metrics_utils
51        atest_utils.print_data_collection_notice()
52        metrics_utils.send_start_event(tool_name=constants.TOOL_NAME,
53                                       command_line=' '.join(argv),
54                                       test_references=[argv[0]])
55        return True
56    except Exception as e:
57        logger.debug("Failed to send start event:%s", str(e))
58
59    return False
60
61
62# pylint: disable=broad-except
63def LogExitEvent(exit_code, stacktrace="", logs=""):
64    """Log acloud exit event.
65
66    A start event should followed by an exit event to calculate the consuming
67    time. This function will be run at the end of acloud main process or
68    at the init of the error object.
69
70    Args:
71        exit_code: Integer, the exit code of acloud main process.
72        stacktrace: A string of stacktrace.
73        logs: A string of logs.
74    """
75    try:
76        from asuite.metrics import metrics_utils
77        metrics_utils.send_exit_event(exit_code, stacktrace=stacktrace,
78                                      logs=logs)
79    except Exception as e:
80        logger.debug("Failed to send exit event:%s", str(e))
81