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