• 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#
18
19import os
20import sys
21from dataclasses import dataclass
22
23__all__ = ["Variables"]
24
25SRC_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
26MODULES_DIR = os.path.abspath(os.path.dirname(__file__))
27TOP_DIR = os.path.abspath(
28    os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
29sys.path.insert(0, SRC_DIR)
30sys.path.insert(1, MODULES_DIR)
31sys.path.insert(2, TOP_DIR)
32
33
34@dataclass
35class ReportVariables:
36    report_dir = ""
37    log_dir = ""
38    log_format = ""
39    log_level = ""
40    log_handler = ""
41    pub_key_file = None
42    pub_key_string = ""
43
44
45@dataclass
46class Variables:
47    modules_dir = ""
48    top_dir = ""
49    res_dir = ""
50    exec_dir = ""
51    report_vars = ReportVariables()
52    task_name = ""
53    source_code_rootpath = ""
54
55
56def _init_global_config():
57    import logging
58
59    from _core.common import get_source_code_rootpath
60
61    Variables.modules_dir = MODULES_DIR
62    Variables.top_dir = TOP_DIR
63    Variables.res_dir = os.path.abspath(os.path.join(
64        MODULES_DIR, "_core", "resource"))
65
66    # set report variables
67    Variables.report_vars.log_dir = "log"
68    Variables.report_vars.report_dir = "reports"
69    Variables.report_vars.log_format = \
70        "[%(asctime)s] [%(thread)d] [%(name)s] [%(levelname)s] %(message)s"
71    Variables.report_vars.log_level = logging.INFO
72    Variables.report_vars.log_handler = "console, file"
73
74    # set execution directory
75    if not Variables.exec_dir:
76        current_exec_dir = os.path.abspath(os.getcwd())
77        try:
78            common_path = os.path.commonpath([Variables.top_dir,
79                                              current_exec_dir])
80            if os.path.normcase(common_path) == os.path.normcase(
81                    Variables.top_dir):
82                Variables.exec_dir = common_path
83            else:
84                Variables.exec_dir = current_exec_dir
85        except (ValueError, AttributeError) as _:
86            Variables.exec_dir = current_exec_dir
87    Variables.source_code_rootpath = get_source_code_rootpath(
88        Variables.top_dir)
89    _init_logger()
90
91
92def _init_logger():
93    import time
94    from _core.constants import LogType
95    from _core.logger import Log
96    from _core.plugin import Plugin
97    from _core.plugin import get_plugin
98
99    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)
100    if tool_logger_plugin:
101        return
102
103    @Plugin(type=Plugin.LOG, id=LogType.tool, enabled=True)
104    class ToolLog(Log):
105        @classmethod
106        def get_plugin_type(cls):
107            return Plugin.LOG
108
109        @classmethod
110        def get_plugin_id(cls):
111            return LogType.tool
112
113    tool_log_file = None
114    if Variables.exec_dir and os.path.normcase(
115            Variables.exec_dir) == os.path.normcase(Variables.top_dir):
116        host_log_path = os.path.join(Variables.exec_dir,
117                                     Variables.report_vars.report_dir,
118                                     Variables.report_vars.log_dir)
119        os.makedirs(host_log_path, exist_ok=True)
120        time_str = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
121        tool_file_name = "platform_log_{}.log".format(time_str)
122        tool_log_file = os.path.join(host_log_path, tool_file_name)
123
124    tool_logger_plugin = get_plugin(Plugin.LOG, LogType.tool)[0] or ToolLog()
125    tool_logger_plugin.__initial__(Variables.report_vars.log_handler,
126                                   tool_log_file,
127                                   Variables.report_vars.log_level,
128                                   Variables.report_vars.log_format)
129
130
131def _iter_module_plugins(packages):
132    import importlib
133    import pkgutil
134    for package in packages:
135        pkg_path = getattr(package, "__path__", "")
136        pkg_name = getattr(package, "__name__", "")
137        if not pkg_name or not pkg_path:
138            continue
139
140        _iter_modules = pkgutil.iter_modules(pkg_path, "%s%s" % (
141            pkg_name, "."))
142        for _, name, _ in _iter_modules:
143            importlib.import_module(name)
144
145
146def _load_internal_plugins():
147    import _core.driver
148    import _core.testkit
149    import _core.environment
150    import _core.executor
151    _iter_module_plugins([_core.driver, _core.testkit, _core.environment,
152                          _core.executor])
153
154
155_init_global_config()
156_load_internal_plugins()
157
158del _init_global_config
159del _init_logger
160del _load_internal_plugins
161del _iter_module_plugins
162