• 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(os.path.dirname(__file__))))
28MODULES_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
29TOP_DIR = os.path.abspath(
30    os.path.dirname(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    task_id = ""
57    source_code_rootpath = ""
58    config = None
59
60
61def _init_global_config():
62    import logging
63
64    from _core.common import get_source_code_rootpath
65
66    Variables.modules_dir = MODULES_DIR
67    Variables.top_dir = TOP_DIR
68    Variables.res_dir = os.path.abspath(os.path.join(
69        MODULES_DIR, "_core", "resource"))
70
71    # create xdevice temp folder  /temp
72    Variables.temp_dir = os.path.join(_get_temp_dir(), "xdevice_data")
73    if not os.path.exists(Variables.temp_dir):
74        os.makedirs(Variables.temp_dir)
75
76    # set report variables
77    Variables.report_vars.log_dir = "log"
78    Variables.report_vars.report_dir = "reports"
79    Variables.report_vars.log_format = \
80        "[%(asctime)s] [%(thread)d] [%(name)s] [%(levelname)s] %(message)s"
81    Variables.report_vars.log_level = logging.INFO
82    Variables.report_vars.log_handler = "console, file"
83
84    # set execution directory
85    if not Variables.exec_dir:
86        current_exec_dir = os.path.abspath(os.getcwd())
87        try:
88            common_path = os.path.commonpath([Variables.top_dir,
89                                              current_exec_dir])
90            if os.path.normcase(common_path) == os.path.normcase(
91                    Variables.top_dir):
92                Variables.exec_dir = common_path
93            else:
94                Variables.exec_dir = current_exec_dir
95        except (ValueError, AttributeError) as _:
96            Variables.exec_dir = current_exec_dir
97    Variables.source_code_rootpath = get_source_code_rootpath(
98        Variables.top_dir)
99    _init_logger()
100
101
102def _get_temp_dir():
103    name = platform.system()
104    if name == "Linux":
105        return os.path.join(tempfile.gettempdir(), getpass.getuser())
106    else:
107        return tempfile.gettempdir()
108
109
110def _init_logger():
111    import time
112    from _core.constants import LogType
113    from _core.logger import Log
114    from _core.plugin import Plugin
115    from _core.plugin import get_plugin
116
117    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)
118    if tool_logger_plugin:
119        return
120
121    @Plugin(type=Plugin.LOG, id=LogType.tool, enabled=True)
122    class ToolLog(Log):
123        @classmethod
124        def get_plugin_type(cls):
125            return Plugin.LOG
126
127        @classmethod
128        def get_plugin_id(cls):
129            return LogType.tool
130
131    tool_log_file = None
132    if Variables.exec_dir and os.path.normcase(
133            Variables.exec_dir) == os.path.normcase(Variables.top_dir):
134        host_log_path = os.path.join(Variables.exec_dir,
135                                     Variables.report_vars.report_dir,
136                                     Variables.report_vars.log_dir)
137        os.makedirs(host_log_path, exist_ok=True)
138        time_str = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
139        tool_file_name = "platform_log_{}.log".format(time_str)
140        tool_log_file = os.path.join(host_log_path, tool_file_name)
141
142    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)[0] or ToolLog()
143    tool_logger_plugin.__initial__(Variables.report_vars.log_handler,
144                                   tool_log_file,
145                                   Variables.report_vars.log_level,
146                                   Variables.report_vars.log_format)
147
148
149def _iter_module_plugins(packages):
150    import importlib
151    import pkgutil
152    for package in packages:
153        pkg_path = getattr(package, "__path__", "")
154        pkg_name = getattr(package, "__name__", "")
155        if not pkg_name or not pkg_path:
156            continue
157
158        _iter_modules = pkgutil.iter_modules(pkg_path, "%s%s" % (
159            pkg_name, "."))
160        for _, name, _ in _iter_modules:
161            importlib.import_module(name)
162
163
164def _load_internal_plugins():
165    import _core.driver
166    import _core.testkit
167    import _core.environment
168    import _core.executor
169    _iter_module_plugins([_core.driver, _core.testkit, _core.environment,
170                          _core.executor])
171
172
173_init_global_config()
174_load_internal_plugins()
175
176del _init_global_config
177del _init_logger
178del _load_internal_plugins
179del _iter_module_plugins
180