• 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    data_path = os.path.join(_get_temp_dir(), "xdevice_data")
73    os.makedirs(data_path, exist_ok=True)
74    Variables.temp_dir = data_path
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    from _core.constants import LogType
112    from _core.logger import Log
113    from _core.plugin import Plugin
114    from _core.plugin import get_plugin
115
116    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)
117    if tool_logger_plugin:
118        return
119
120    @Plugin(type=Plugin.LOG, id=LogType.tool, enabled=True)
121    class ToolLog(Log):
122        @classmethod
123        def get_plugin_type(cls):
124            return Plugin.LOG
125
126        @classmethod
127        def get_plugin_id(cls):
128            return LogType.tool
129
130    tool_log_file = None
131    if Variables.exec_dir and os.path.normcase(
132            Variables.exec_dir) == os.path.normcase(Variables.top_dir):
133        host_log_path = os.path.join(Variables.exec_dir,
134                                     Variables.report_vars.report_dir,
135                                     Variables.report_vars.log_dir)
136        os.makedirs(host_log_path, exist_ok=True)
137        tool_log_file = os.path.join(host_log_path, "platform_log.log")
138
139    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)[0] or ToolLog()
140    tool_logger_plugin.__initial__(Variables.report_vars.log_handler,
141                                   tool_log_file,
142                                   Variables.report_vars.log_level,
143                                   Variables.report_vars.log_format)
144
145
146def _iter_module_plugins(packages):
147    import importlib
148    import pkgutil
149    for package in packages:
150        pkg_path = getattr(package, "__path__", "")
151        pkg_name = getattr(package, "__name__", "")
152        if not pkg_name or not pkg_path:
153            continue
154
155        _iter_modules = pkgutil.iter_modules(pkg_path, "%s%s" % (
156            pkg_name, "."))
157        for _, name, _ in _iter_modules:
158            importlib.import_module(name)
159
160
161def _load_internal_plugins():
162    import _core.driver
163    import _core.testkit
164    import _core.environment
165    import _core.executor
166    _iter_module_plugins([_core.driver, _core.testkit, _core.environment,
167                          _core.executor])
168
169
170_init_global_config()
171_load_internal_plugins()
172
173del _init_global_config
174del _init_logger
175del _load_internal_plugins
176del _iter_module_plugins
177