1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2022 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import threading
17import socket
18import json
19import time
20import subprocess
21import os
22import shutil
23
24
25class TestServer(threading.Thread):
26
27    IP = '127.0.0.1'
28
29    PORT = 23495
30
31    config_file_name = "config.json"
32
33    # Run base_ Dir directory
34    TestModeBase = 1
35
36    # Run run_dir directory
37    TestModeRun = 2
38
39    # Send config information
40    S_C_MAIN_ID_SEND_CONFIG_INFO = 1
41
42    # Request to start test
43    C_S_MAIN_ID_REQUEST_TEST_INFO = 2
44
45    # Distribute test data
46    S_C_MAIN_ID_SEND_TEST_INFO = 3
47
48    # Test a set of data
49    C_S_MAIN_ID_TEST_FINISH_INFO = 4
50
51    # All tests completed
52    S_C_MAIN_ID_All_TESTS_COMPLETE = 5
53
54
55    def __init__(self):
56        threading.Thread.__init__(self)
57        print("tcp_server_init__")
58        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59        self.tcp_server_socket.bind((self.IP, self.PORT))
60        self.tcp_server_socket.listen(128)
61
62        self.config = self.read_data_from_json(self.config_file_name)
63        self.test_group_index = 0
64
65
66    def send_message(self, conn, info):
67        clientdata = json.dumps(info).encode("utf-8")
68        print('send msg:  ', clientdata)
69        conn.send(clientdata)
70
71
72    def init_data(self):
73        self.test_case_index = 0
74        self.test_case = self.config['testGroup'][self.test_group_index]['test_case']
75        self.test_case_dir = self.config['testGroup'][self.test_group_index]['test_case_dir']
76
77        if len(self.config['testGroup'][self.test_group_index]['test_case']) <= 0:
78            self.test_case = self.traverasl_files(self.config['testGroup'][self.test_group_index]['test_case_dir'])
79            print(self.test_case)
80
81
82    def tcp_connect(self, conn, addr):
83        print(' Connected by: ', addr)
84        time.sleep(3)
85
86        self.init_data()
87        self.start_test(conn)
88        while True:
89            data = conn.recv(1024)
90            data = (int)(data.decode("utf-8"))
91            print("recv msg: ", data)
92            if data == self.C_S_MAIN_ID_REQUEST_TEST_INFO:
93                print("begin test: ", data)
94                self.test_case_index = 0
95                self.send_test_info(conn)
96            elif data == self.C_S_MAIN_ID_TEST_FINISH_INFO:
97                self.test_case_index += 1
98                self.send_test_info(conn)
99
100
101    def send_all_test_finish(self, conn):
102        send_config =  {'main_id':self.S_C_MAIN_ID_All_TESTS_COMPLETE}
103        self.send_message(conn, send_config)
104
105        self.test_group_index += 1
106        if self.test_group_index >= len(self.config['testGroup']):
107            self.test_group_index = 0
108            return
109
110        print("send_all_test_finish------test_group_index=", self.test_group_index,\
111                "------len=", len(self.config['testGroup']))
112        self.start_client_process()
113
114
115    def send_test_info(self, conn):
116        if len(self.test_case):
117            if self.test_case_index < len(self.test_case):
118                json_data = self.read_data_from_json(self.test_case_dir + '/' + self.test_case[self.test_case_index])
119                json_data['main_id'] = self.S_C_MAIN_ID_SEND_TEST_INFO
120                print(json_data)
121                self.send_message(conn, json_data)
122            else:
123                self.send_all_test_finish(conn)
124
125
126    def start_test(self, conn):
127        send_config = self.config['testGroup'][self.test_group_index]
128        test_mode = send_config['test_mode']
129        base_dir = send_config['base_dir']
130        run_dir = send_config['run_dir']
131        log_dir = send_config['log_dir']
132
133        if test_mode == self.TestModeBase:
134            self.clear_directory(base_dir)
135        elif test_mode == self.TestModeRun:
136            self.clear_directory(run_dir)
137
138        send_config =  {'main_id': self.S_C_MAIN_ID_SEND_CONFIG_INFO,\
139            'test_mode': test_mode,\
140            'base_dir': base_dir,\
141            'run_dir': run_dir,\
142            'log_dir': log_dir}
143
144        self.send_message(conn, send_config)
145
146
147    def read_data_from_json(self, filename):
148        with open(filename, 'r') as json_file:
149            json_data = json.load(json_file)
150
151        return json_data
152
153
154    def start_client_process(self):
155        print(time.time(), '----time is up')
156        process_dir = self.config['testGroup'][self.test_group_index]['process_dir']
157        process_name = self.config['testGroup'][self.test_group_index]['process_name']
158
159        process = process_dir + process_name + ' -f'
160        subprocess.Popen(process, cwd=process_dir)
161        result = subprocess.getstatusoutput(process_dir)
162        print(result)
163
164
165    def traverasl_files(self, path):
166        self.filelist = []
167        obj = os.scandir(path)
168        for entry in obj:
169            if entry.is_file():
170                self.filelist.append(entry.name)
171
172        return self.filelist
173
174
175    def clear_directory(self, filepath):
176        if not os.path.exists(filepath):
177            os.mkdir(filepath)
178        else:
179            shutil.rmtree(filepath)
180            os.mkdir(filepath)
181
182
183    def run(self):
184        print("TcpServer_run__")
185        while True:
186            conn, addr = self.tcp_server_socket.accept()
187            print("TcpServer_run__, conn, addr", conn, addr)
188            thread_recv = threading.Thread(target=self.tcp_connect, args=(conn, addr))
189            thread_recv.start()
190
191        self.tcp_server_socket.close()