• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# coding=utf-8
3
4#
5# Copyright (c) 2022 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18import getpass
19import os
20import platform
21import sys
22import tempfile
23from dataclasses import dataclass
24
25__all__ = ["Variables"]
26
27SRC_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
28MODULES_DIR = os.path.abspath(os.path.dirname(__file__))
29TOP_DIR = os.path.abspath(
30    os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
31sys.path.insert(0, SRC_DIR)
32sys.path.insert(1, MODULES_DIR)
33sys.path.insert(2, TOP_DIR)
34
35
36@dataclass
37class ReportVariables:
38    report_dir = ""
39    log_dir = ""
40    log_format = ""
41    log_level = ""
42    log_handler = ""
43    pub_key_file = None
44    pub_key_string = ""
45
46
47@dataclass
48class Variables:
49    modules_dir = ""
50    top_dir = ""
51    res_dir = ""
52    exec_dir = ""
53    temp_dir = ""
54    report_vars = ReportVariables()
55    task_name = ""
56    source_code_rootpath = ""
57
58
59def _init_global_config():
60    import logging
61
62    from _core.common import get_source_code_rootpath
63
64    Variables.modules_dir = MODULES_DIR
65    Variables.top_dir = TOP_DIR
66    Variables.res_dir = os.path.abspath(os.path.join(
67        MODULES_DIR, "_core", "resource"))
68
69    # create xdevice temp folder
70    Variables.temp_dir = os.path.join(_get_temp_dir(), "xdevice_data")
71    if not os.path.exists(Variables.temp_dir):
72        os.makedirs(Variables.temp_dir)
73
74    # set report variables
75    Variables.report_vars.log_dir = "log"
76    Variables.report_vars.report_dir = "reports"
77    Variables.report_vars.log_format = \
78        "[%(asctime)s] [%(thread)d] [%(name)s] [%(levelname)s] %(message)s"
79    Variables.report_vars.log_level = logging.INFO
80    Variables.report_vars.log_handler = "console, file"
81
82    # set execution directory
83    if not Variables.exec_dir:
84        current_exec_dir = os.path.abspath(os.getcwd())
85        try:
86            common_path = os.path.commonpath([Variables.top_dir,
87                                              current_exec_dir])
88            if os.path.normcase(common_path) == os.path.normcase(
89                    Variables.top_dir):
90                Variables.exec_dir = common_path
91            else:
92                Variables.exec_dir = current_exec_dir
93        except (ValueError, AttributeError) as _:
94            Variables.exec_dir = current_exec_dir
95    Variables.source_code_rootpath = get_source_code_rootpath(
96        Variables.top_dir)
97    _init_logger()
98
99
100def _get_temp_dir():
101    name = platform.system()
102    if name == "Linux":
103        return os.path.join(tempfile.gettempdir(), getpass.getuser())
104    else:
105        return tempfile.gettempdir()
106
107
108def _init_logger():
109    import time
110    from _core.constants import LogType
111    from _core.logger import Log
112    from _core.plugin import Plugin
113    from _core.plugin import get_plugin
114
115    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)
116    if tool_logger_plugin:
117        return
118
119    @Plugin(type=Plugin.LOG, id=LogType.tool, enabled=True)
120    class ToolLog(Log):
121        @classmethod
122        def get_plugin_type(cls):
123            return Plugin.LOG
124
125        @classmethod
126        def get_plugin_id(cls):
127            return LogType.tool
128
129    tool_log_file = None
130    if Variables.exec_dir and os.path.normcase(
131            Variables.exec_dir) == os.path.normcase(Variables.top_dir):
132        host_log_path = os.path.join(Variables.exec_dir,
133                                     Variables.report_vars.report_dir,
134                                     Variables.report_vars.log_dir)
135        os.makedirs(host_log_path, exist_ok=True)
136        time_str = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
137        tool_file_name = "platform_log_{}.log".format(time_str)
138        tool_log_file = os.path.join(host_log_path, tool_file_name)
139
140    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)[0] or ToolLog()
141    tool_logger_plugin.__initial__(Variables.report_vars.log_handler,
142                                   tool_log_file,
143                                   Variables.report_vars.log_level,
144                                   Variables.report_vars.log_format)
145
146
147def _iter_module_plugins(packages):
148    import importlib
149    import pkgutil
150    for package in packages:
151        pkg_path = getattr(package, "__path__", "")
152        pkg_name = getattr(package, "__name__", "")
153        if not pkg_name or not pkg_path:
154            continue
155
156        _iter_modules = pkgutil.iter_modules(pkg_path, "%s%s" % (
157            pkg_name, "."))
158        for _, name, _ in _iter_modules:
159            importlib.import_module(name)
160
161
162def _load_internal_plugins():
163    import _core.driver
164    import _core.testkit
165    import _core.environment
166    import _core.executor
167    _iter_module_plugins([_core.driver, _core.testkit, _core.environment,
168                          _core.executor])
169
170
171_init_global_config()
172_load_internal_plugins()
173
174del _init_global_config
175del _init_logger
176del _load_internal_plugins
177del _iter_module_plugins
178