blob: 5fba36385fd32253374d5124319c5e9ef397ef2e [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08002# Copyright 2015 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08006import argparse
Yilin Yangf9fe1932019-11-04 17:09:34 +08007import binascii
8import codecs
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08009import contextlib
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080010import ctypes
11import ctypes.util
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080012import fcntl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080013import hashlib
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080014import json
15import logging
16import os
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080017import platform
Yilin Yang8b7f5192020-01-08 11:43:00 +080018import queue
Wei-Ning Huang829e0c82015-05-26 14:37:23 +080019import re
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080020import select
Wei-Ning Huanga301f572015-06-03 17:34:21 +080021import signal
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080022import socket
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080023import ssl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080024import struct
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080025import subprocess
26import sys
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080027import termios
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080028import threading
29import time
Joel Kitching22b89042015-08-06 18:23:29 +080030import traceback
Wei-Ning Huang39169902015-09-19 06:00:23 +080031import tty
Yilin Yangf54fb912020-01-08 11:42:38 +080032import urllib.request
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080033import uuid
34
Wei-Ning Huang2132de32015-04-13 17:24:38 +080035import jsonrpclib
36from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
Wei-Ning Huang2132de32015-04-13 17:24:38 +080037
Yilin Yang64dd8592020-11-10 16:16:23 +080038from cros.factory.gooftool import cros_config as cros_config_module
39from cros.factory.test import state
40from cros.factory.test.state import TestState
Yilin Yang1512d972020-11-19 13:34:42 +080041from cros.factory.test.test_lists import manager
Yilin Yang64dd8592020-11-10 16:16:23 +080042from cros.factory.utils import net_utils
Yilin Yang42ba5c62020-05-05 10:32:34 +080043from cros.factory.utils import process_utils
Yilin Yang64dd8592020-11-10 16:16:23 +080044from cros.factory.utils import sys_utils
45from cros.factory.utils.type_utils import Enum
Yilin Yang42ba5c62020-05-05 10:32:34 +080046
Yilin Yangf54fb912020-01-08 11:42:38 +080047
Fei Shaobb0a3e62020-06-20 15:41:25 +080048_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', '4499'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080049
Fei Shaobb0a3e62020-06-20 15:41:25 +080050_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', '4455'))
51_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', '4456'))
52_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', '9000'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080053
54_BUFSIZE = 8192
55_RETRY_INTERVAL = 2
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080056_SEPARATOR = b'\r\n'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080057_PING_TIMEOUT = 3
58_PING_INTERVAL = 5
59_REQUEST_TIMEOUT_SECS = 60
60_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080061_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080062
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080063_CONTROL_START = 128
64_CONTROL_END = 129
65
Wei-Ning Huanga301f572015-06-03 17:34:21 +080066_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080067_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080068
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080069# Stream control
70_STDIN_CLOSED = '##STDIN_CLOSED##'
71
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080072SUCCESS = 'success'
73FAILED = 'failed'
74DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080075
Joel Kitching22b89042015-08-06 18:23:29 +080076
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080077class PingTimeoutError(Exception):
78 pass
79
80
81class RequestError(Exception):
82 pass
83
84
Fei Shaobd07c9a2020-06-15 19:04:50 +080085class BufferedSocket:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080086 """A buffered socket that supports unrecv.
87
88 Allow putting back data back to the socket for the next recv() call.
89 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080090 def __init__(self, sock):
91 self.sock = sock
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080092 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080093
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080094 def fileno(self):
95 return self.sock.fileno()
96
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080097 def Recv(self, bufsize, flags=0):
98 if self._buf:
99 if len(self._buf) >= bufsize:
100 ret = self._buf[:bufsize]
101 self._buf = self._buf[bufsize:]
102 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800103 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800104 self._buf = b''
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800105 return ret + self.sock.recv(bufsize - len(ret), flags)
106 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800107
108 def UnRecv(self, buf):
109 self._buf = buf + self._buf
110
111 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800112 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800113
114 def RecvBuf(self):
115 """Only recive from buffer."""
116 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800117 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800118 return ret
119
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800120 def Close(self):
121 self.sock.close()
122
123
Fei Shaobd07c9a2020-06-15 19:04:50 +0800124class TLSSettings:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800125 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800126 """Constructor.
127
128 Args:
129 tls_cert_file: TLS certificate in PEM format.
130 enable_tls_without_verify: enable TLS but don't verify certificate.
131 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800132 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800133 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800134 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800135 self._tls_context = None
136
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800137 def _UpdateContext(self):
138 if not self._enabled:
139 self._tls_context = None
140 return
141
142 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
143 self._tls_context.verify_mode = ssl.CERT_REQUIRED
144
145 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800146 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800147 self._tls_context.check_hostname = True
148 try:
149 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800150 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800151 except IOError as e:
152 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
153 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800154 else:
155 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
156 logging.info('TLSSettings: using built-in ca-certificates')
157 else:
158 self._tls_context.verify_mode = ssl.CERT_NONE
159 logging.info('TLSSettings: skipping TLS verification!!!')
160
161 def SetEnabled(self, enabled):
162 logging.info('TLSSettings: enabled: %s', enabled)
163
164 if self._enabled != enabled:
165 self._enabled = enabled
166 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800167
168 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800169 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800170
171 def Context(self):
172 return self._tls_context
173
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800174
Fei Shaobd07c9a2020-06-15 19:04:50 +0800175class Ghost:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800176 """Ghost implements the client protocol of Overlord.
177
178 Ghost provide terminal/shell/logcat functionality and manages the client
179 side connectivity.
180 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800181 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800182
183 MODE_NAME = {
184 NONE: 'NONE',
185 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800186 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800187 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800188 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800189 FILE: 'File',
190 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800191 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800192
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800193 RANDOM_MID = '##random_mid##'
194
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800195 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
196 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Peter Shih220a96d2016-12-22 17:02:16 +0800197 command=None, file_op=None, port=None, tls_mode=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800198 """Constructor.
199
200 Args:
201 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800202 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800203 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800204 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
205 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800206 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800207 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800208 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800209 terminal_sid: the terminal session ID associate with this client. This is
210 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800211 tty_device: the terminal device to open, if tty_device is None, as pseudo
212 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800213 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800214 file_op: a tuple (action, filepath, perm). action is either 'download' or
215 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800216 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800217 tls_mode: can be [True, False, None]. if not None, skip detection of
218 TLS and assume whether server use TLS or not.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800219 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800220 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
221 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800222 if mode == Ghost.SHELL:
223 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800224 if mode == Ghost.FILE:
225 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800226
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800227 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800228 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800229 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800230 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800231 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800232 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800233 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800234 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800235 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800236 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800237 self._ttyname_to_sid = {}
238 self._terminal_sid_to_pid = {}
239 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800240 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800241 self._register_status = DISCONNECTED
242 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800243 self._tls_mode = tls_mode
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800244
245 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800246 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800247 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800248
249 # Protocol specific
250 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800251 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800252 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800253 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800254 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800255 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800256
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800257 def SetIgnoreChild(self, status):
258 # Only ignore child for Agent since only it could spawn child Ghost.
259 if self._mode == Ghost.AGENT:
260 signal.signal(signal.SIGCHLD,
261 signal.SIG_IGN if status else signal.SIG_DFL)
262
263 def GetFileSha1(self, filename):
Yilin Yang0412c272019-12-05 16:57:40 +0800264 with open(filename, 'rb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800265 return hashlib.sha1(f.read()).hexdigest()
266
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800267 def TLSEnabled(self, host, port):
268 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800269 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
270 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800271 # Allow any certificate since we only want to check if server talks TLS.
272 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
273 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800274
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800275 sock = context.wrap_socket(sock, server_hostname=host)
276 sock.settimeout(_CONNECT_TIMEOUT)
277 sock.connect((host, port))
278 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800279 except ssl.SSLError:
280 return False
Stimim Chen3899a912020-07-17 10:52:03 +0800281 except socket.timeout:
282 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800283 except socket.error: # Connect refused or timeout
284 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800285 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800286 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800287
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800288 def Upgrade(self):
289 logging.info('Upgrade: initiating upgrade sequence...')
290
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800291 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800292 https_enabled = self.TLSEnabled(self._connected_addr[0],
293 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800294 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800295 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
296 'abort')
297 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800298
299 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800300 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
301 'without TLS enabled! Possible mis-configuration or '
302 'DNS/IP spoofing detected, abort')
303 return
304
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800305 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800306 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800307 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800308 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800309
310 # Download sha1sum for ghost.py for verification
311 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800312 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800313 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
314 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800315 if f.getcode() != 200:
316 raise RuntimeError('HTTP status %d' % f.getcode())
317 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800318 except (ssl.SSLError, ssl.CertificateError) as e:
319 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
320 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800321 except Exception:
322 logging.error('Upgrade: failed to download sha1sum file, abort')
323 return
324
325 if self.GetFileSha1(scriptpath) == sha1sum:
326 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
327 return
328
329 # Download upgrade version of ghost.py
330 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800331 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800332 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
333 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800334 if f.getcode() != 200:
335 raise RuntimeError('HTTP status %d' % f.getcode())
336 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800337 except (ssl.SSLError, ssl.CertificateError) as e:
338 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
339 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800340 except Exception:
341 logging.error('Upgrade: failed to download upgrade, abort')
342 return
343
344 # Compare SHA1 sum
345 if hashlib.sha1(data).hexdigest() != sha1sum:
346 logging.error('Upgrade: sha1sum mismatch, abort')
347 return
348
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800349 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800350 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800351 f.write(data)
352 except Exception:
353 logging.error('Upgrade: failed to write upgrade onto disk, abort')
354 return
355
356 logging.info('Upgrade: restarting ghost...')
357 self.CloseSockets()
358 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800359 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800360
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800361 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800362 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800363 if self._prop_file:
364 with open(self._prop_file, 'r') as f:
365 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800366 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800367 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800368
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800369 def CloseSockets(self):
370 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800371 if self._platform == 'Linux':
372 for fd in os.listdir('/proc/self/fd/'):
373 try:
374 real_fd = os.readlink('/proc/self/fd/%s' % fd)
375 if real_fd.startswith('socket'):
376 os.close(int(fd))
377 except Exception:
378 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800379
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800380 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800381 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800382 """Spawn a child ghost with specific mode.
383
384 Returns:
385 The spawned child process pid.
386 """
Joel Kitching22b89042015-08-06 18:23:29 +0800387 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800388 self.SetIgnoreChild(False)
389
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800390 pid = os.fork()
391 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800392 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800393 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
394 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800395 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800396 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800397 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800398 sys.exit(0)
399 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800400 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800401 return pid
402
403 def Timestamp(self):
404 return int(time.time())
405
406 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800407 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800408 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800409 ret = re.search('gateway: (.*)', output)
410 if ret:
411 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800412 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800413 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800414 with open('/proc/net/route', 'r') as f:
415 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800416
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800417 ips = []
418 for line in lines:
419 parts = line.split('\t')
420 if parts[2] == '00000000':
421 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800422
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800423 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800424 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800425 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800426 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800427 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800428
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800429 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800430
431 logging.warning('GetGateWayIP: unsupported platform')
432 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800433
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800434 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800435 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800436 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800437
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800438 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800439 match = re.match(r'^https?://(.*):.*$', url)
440 if match:
441 return [match.group(1)]
442 except Exception:
443 pass
444 return []
445
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800446 def GetMachineID(self):
447 """Generates machine-dependent ID string for a machine.
448 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800449 Linux:
450 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800451 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
452 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800453 We follow the listed order to generate machine ID, and fallback to the
454 next alternative if the previous doesn't work.
455
456 Darwin:
457 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800458 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800459 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800460 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800461 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800462 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800463
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800464 # Darwin
465 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800466 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
467 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800468 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
469 if ret:
470 return ret.group(1)
471
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800472 # Try factory device id
473 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800474 from cros.factory.test import session
475 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800476 except Exception:
477 pass
478
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800479 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800480 try:
481 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
482 return f.read().strip()
483 except Exception:
484 pass
485
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800486 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800487 try:
488 macs = []
489 ifaces = sorted(os.listdir('/sys/class/net'))
490 for iface in ifaces:
491 if iface == 'lo':
492 continue
493
494 with open('/sys/class/net/%s/address' % iface, 'r') as f:
495 macs.append(f.read().strip())
496
497 return ';'.join(macs)
498 except Exception:
499 pass
500
Peter Shihcb0e5512017-06-14 16:59:46 +0800501 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800502
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800503 def GetProcessWorkingDirectory(self, pid):
504 if self._platform == 'Linux':
505 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800506 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800507 PROC_PIDVNODEPATHINFO = 9
508 proc_vnodepathinfo_size = 2352
509 vid_path_offset = 152
510
511 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
512 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
513 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
514 ctypes.byref(buf), proc_vnodepathinfo_size)
515 buf = buf.raw[vid_path_offset:]
516 n = buf.index('\0')
517 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800518 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800519
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800520 def Reset(self):
521 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800522 if self._sock is not None:
523 self._sock.Close()
524 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800525 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800526 self._last_ping = 0
527 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800528 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800529 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800530
531 def SendMessage(self, msg):
532 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800533 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800534
535 def SendRequest(self, name, args, handler=None,
536 timeout=_REQUEST_TIMEOUT_SECS):
537 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800538 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800539
540 rid = str(uuid.uuid4())
541 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800542 if timeout >= 0:
543 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800544 self.SendMessage(msg)
545
546 def SendResponse(self, omsg, status, params=None):
547 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
548 self.SendMessage(msg)
549
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800550 def HandleTTYControl(self, fd, control_str):
551 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800552 command = msg['command']
553 params = msg['params']
554 if command == 'resize':
555 # some error happened on websocket
556 if len(params) != 2:
557 return
558 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
559 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
560 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800561 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800562
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800563 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800564 """Spawn a TTY server and forward I/O to the TCP socket."""
565 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800566
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800567 try:
568 if self._tty_device is None:
569 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800570
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800571 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800572 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800573 try:
574 server = GhostRPCServer()
575 server.RegisterTTY(self._session_id, ttyname)
576 server.RegisterSession(self._session_id, os.getpid())
577 except Exception:
578 # If ghost is launched without RPC server, the call will fail but we
579 # can ignore it.
580 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800581
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800582 # The directory that contains the current running ghost script
583 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800584
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800585 env = os.environ.copy()
586 env['USER'] = os.getenv('USER', 'root')
587 env['HOME'] = os.getenv('HOME', '/root')
588 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
589 os.chdir(env['HOME'])
590 os.execve(_SHELL, [_SHELL], env)
591 else:
592 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800593 tty.setraw(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800594 # 0: iflag
595 # 1: oflag
596 # 2: cflag
597 # 3: lflag
598 # 4: ispeed
599 # 5: ospeed
600 # 6: cc
Wei-Ning Huang39169902015-09-19 06:00:23 +0800601 attr = termios.tcgetattr(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800602 attr[0] &= (termios.IXON | termios.IXOFF)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800603 attr[2] |= termios.CLOCAL
604 attr[2] &= ~termios.CRTSCTS
605 attr[4] = termios.B115200
606 attr[5] = termios.B115200
607 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800608
Stimim Chen3899a912020-07-17 10:52:03 +0800609 nonlocals = {
610 'control_state': None,
611 'control_str': b''
612 }
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800613
614 def _ProcessBuffer(buf):
Stimim Chen3899a912020-07-17 10:52:03 +0800615 write_buffer = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800616 while buf:
617 if nonlocals['control_state']:
Stimim Chen3899a912020-07-17 10:52:03 +0800618 if _CONTROL_END in buf:
619 index = buf.index(_CONTROL_END)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800620 nonlocals['control_str'] += buf[:index]
621 self.HandleTTYControl(fd, nonlocals['control_str'])
622 nonlocals['control_state'] = None
Stimim Chen3899a912020-07-17 10:52:03 +0800623 nonlocals['control_str'] = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800624 buf = buf[index+1:]
625 else:
626 nonlocals['control_str'] += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800627 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800628 else:
Stimim Chen3899a912020-07-17 10:52:03 +0800629 if _CONTROL_START in buf:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800630 nonlocals['control_state'] = _CONTROL_START
Stimim Chen3899a912020-07-17 10:52:03 +0800631 index = buf.index(_CONTROL_START)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800632 write_buffer += buf[:index]
633 buf = buf[index+1:]
634 else:
635 write_buffer += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800636 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800637
638 if write_buffer:
639 os.write(fd, write_buffer)
640
641 _ProcessBuffer(self._sock.RecvBuf())
642
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800643 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800644 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800645
646 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800647 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800648
649 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800650 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800651 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800652 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800653 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800654 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800655 logging.error('SpawnTTYServer: %s', e, exc_info=True)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800656 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800657 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800658
659 logging.info('SpawnTTYServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800660 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800661
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800662 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800663 """Spawn a shell server and forward input/output from/to the TCP socket."""
664 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800665
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800666 # Add ghost executable to PATH
667 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
668 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800669 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800670
671 # Execute shell command from HOME directory
672 os.chdir(os.getenv('HOME', '/tmp'))
673
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800674 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800675 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800676 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800677
678 def make_non_block(fd):
679 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
680 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
681
682 make_non_block(p.stdout)
683 make_non_block(p.stderr)
684
685 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800686 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800687
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800688 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800689 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800690 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800691 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800692 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800693
694 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800695 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800696
697 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800698 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800699 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800700 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800701
702 try:
703 idx = ret.index(_STDIN_CLOSED * 2)
704 p.stdin.write(ret[:idx])
705 p.stdin.close()
706 except ValueError:
707 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800708 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800709 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800710 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800711 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800712 logging.error('SpawnShellServer: %s', e, exc_info=True)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800713 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800714 # Check if the process is terminated. If not, Send SIGTERM to process,
715 # then wait for 1 second. Send another SIGKILL to make sure the process is
716 # terminated.
717 p.poll()
718 if p.returncode is None:
719 try:
720 p.terminate()
721 time.sleep(1)
722 p.kill()
723 except Exception:
724 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800725
726 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800727 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800728
729 logging.info('SpawnShellServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800730 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800731
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800732 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800733 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800734 try:
735 size = os.stat(self._file_op[1]).st_size
736 except OSError as e:
737 logging.error('InitiateFileOperation: download: %s', e)
738 sys.exit(1)
739
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800740 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800741 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800742 'filename': os.path.basename(self._file_op[1]),
743 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800744 elif self._file_op[0] == 'upload':
745 self.SendRequest('clear_to_upload', {}, timeout=-1)
746 self.StartUploadServer()
747 else:
748 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800749
750 def StartDownloadServer(self):
751 logging.info('StartDownloadServer: started')
752
753 try:
754 with open(self._file_op[1], 'rb') as f:
755 while True:
756 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800757 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800758 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800759 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800760 except Exception as e:
761 logging.error('StartDownloadServer: %s', e)
762 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800763 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800764
765 logging.info('StartDownloadServer: terminated')
766 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800767
Wei-Ning Huange2981862015-08-03 15:03:08 +0800768 def StartUploadServer(self):
769 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800770 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800771 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800772 dirname = os.path.dirname(filepath)
773 if not os.path.exists(dirname):
774 try:
775 os.makedirs(dirname)
776 except Exception:
777 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800778
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800779 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800780 if self._file_op[2]:
781 os.fchmod(f.fileno(), self._file_op[2])
782
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800783 f.write(self._sock.RecvBuf())
784
Wei-Ning Huange2981862015-08-03 15:03:08 +0800785 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800786 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800787 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800788 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800789 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800790 break
791 f.write(buf)
792 except socket.error as e:
793 logging.error('StartUploadServer: socket error: %s', e)
794 except Exception as e:
795 logging.error('StartUploadServer: %s', e)
796 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800797 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800798
799 logging.info('StartUploadServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800800 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huange2981862015-08-03 15:03:08 +0800801
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800802 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800803 """Spawn a port forwarding server and forward I/O to the TCP socket."""
804 logging.info('SpawnPortForwardServer: started')
805
806 src_sock = None
807 try:
808 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800809 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800810 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800811
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800812 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800813
814 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800815 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800816
817 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800818 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800819 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800820 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800821 src_sock.send(data)
822
823 if src_sock in rd:
824 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800825 if not data:
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800826 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800827 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800828 except Exception as e:
829 logging.error('SpawnPortForwardServer: %s', e)
830 finally:
831 if src_sock:
832 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800833 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800834
835 logging.info('SpawnPortForwardServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800836 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800837
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800838 def Ping(self):
839 def timeout_handler(x):
840 if x is None:
841 raise PingTimeoutError
842
843 self._last_ping = self.Timestamp()
844 self.SendRequest('ping', {}, timeout_handler, 5)
845
Wei-Ning Huangae923642015-09-24 14:08:09 +0800846 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800847 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800848 filepath = params['filename']
849 if not os.path.isabs(filepath):
850 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
851
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800852 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800853 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800854 pass
855 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800856 self.SendResponse(msg, str(e))
857 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800858
859 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800860 file_op=('download', filepath))
861 self.SendResponse(msg, SUCCESS)
862
863 def HandleFileUploadRequest(self, msg):
864 params = msg['params']
865
866 # Resolve upload filepath
867 filename = params['filename']
868 dest_path = filename
869
870 # If dest is specified, use it first
871 dest_path = params.get('dest', '')
872 if dest_path:
873 if not os.path.isabs(dest_path):
874 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
875
876 if os.path.isdir(dest_path):
877 dest_path = os.path.join(dest_path, filename)
878 else:
879 target_dir = os.getenv('HOME', '/tmp')
880
881 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800882 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800883 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
884 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800885 try:
886 target_dir = self.GetProcessWorkingDirectory(pid)
887 except Exception as e:
888 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800889
890 dest_path = os.path.join(target_dir, filename)
891
892 try:
893 os.makedirs(os.path.dirname(dest_path))
894 except Exception:
895 pass
896
897 try:
898 with open(dest_path, 'w') as _:
899 pass
900 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800901 self.SendResponse(msg, str(e))
902 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800903
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800904 # If not check_only, spawn FILE mode ghost agent to handle upload
905 if not params.get('check_only', False):
906 self.SpawnGhost(self.FILE, params['sid'],
907 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800908 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800909
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800910 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800911 command = msg['name']
912 params = msg['params']
913
914 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800915 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800916 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800917 self.SpawnGhost(self.TERMINAL, params['sid'],
918 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800919 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800920 elif command == 'shell':
921 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800922 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800923 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800924 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800925 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800926 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800927 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800928 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800929 elif command == 'forward':
930 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
931 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800932
933 def HandleResponse(self, response):
934 rid = str(response['rid'])
935 if rid in self._requests:
936 handler = self._requests[rid][2]
937 del self._requests[rid]
938 if callable(handler):
939 handler(response)
940 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800941 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800942
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800943 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800944 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800945 try:
946 index = buf.index(_SEPARATOR)
947 except ValueError:
948 self._sock.UnRecv(buf)
949 return
950
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800951 msgs_json = [buf[:index]]
952 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800953 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800954 msgs_json = buf.split(_SEPARATOR)
955 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800956
957 for msg_json in msgs_json:
958 try:
959 msg = json.loads(msg_json)
960 except ValueError:
961 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800962 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800963 continue
964
965 if 'name' in msg:
966 self.HandleRequest(msg)
967 elif 'response' in msg:
968 self.HandleResponse(msg)
969 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800970 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800971
972 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800973 """Scans for pending requests which have timed out.
974
975 If any timed-out requests are discovered, their handler is called with the
976 special response value of None.
977 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800978 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800979 request_time, timeout, handler = self._requests[rid]
980 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800981 if callable(handler):
982 handler(None)
983 else:
984 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800985 del self._requests[rid]
986
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800987 def InitiateDownload(self):
988 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800989 sid = self._ttyname_to_sid[ttyname]
990 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800991 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800992
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800993 def Listen(self):
994 try:
995 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800996 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800997 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800998
999 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001000 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001001
1002 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +08001003 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001004 break
1005
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001006 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001007
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001008 if (self._mode == self.AGENT and
1009 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001010 self.Ping()
1011 self.ScanForTimeoutRequests()
1012
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001013 if not self._download_queue.empty():
1014 self.InitiateDownload()
1015
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001016 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001017 break
1018 except socket.error:
1019 raise RuntimeError('Connection dropped')
1020 except PingTimeoutError:
1021 raise RuntimeError('Connection timeout')
1022 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001023 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001024
1025 self._queue.put('resume')
1026
1027 if self._mode != Ghost.AGENT:
1028 sys.exit(1)
1029
1030 def Register(self):
1031 non_local = {}
1032 for addr in self._overlord_addrs:
1033 non_local['addr'] = addr
1034 def registered(response):
1035 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001036 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001037 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001038
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001039 self._register_status = response['response']
1040 if response['response'] != SUCCESS:
1041 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001042 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001043
1044 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1045 self._connected_addr = non_local['addr']
1046 self.Upgrade() # Check for upgrade
1047 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001048
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001049 try:
1050 logging.info('Trying %s:%d ...', *addr)
1051 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001052
Peter Shih220a96d2016-12-22 17:02:16 +08001053 # Check if server has TLS enabled. Only check if self._tls_mode is
1054 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001055 # Only control channel needs to determine if TLS is enabled. Other mode
1056 # should use the TLSSettings passed in when it was spawned.
1057 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001058 self._tls_settings.SetEnabled(
1059 self.TLSEnabled(*addr) if self._tls_mode is None
1060 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001061
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001062 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1063 sock.settimeout(_CONNECT_TIMEOUT)
1064
1065 try:
1066 if self._tls_settings.Enabled():
1067 tls_context = self._tls_settings.Context()
1068 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1069
1070 sock.connect(addr)
1071 except (ssl.SSLError, ssl.CertificateError) as e:
1072 logging.error('%s: %s', e.__class__.__name__, e)
1073 continue
1074 except IOError as e:
1075 if e.errno == 2: # No such file or directory
1076 logging.error('%s: %s', e.__class__.__name__, e)
1077 continue
1078 raise
1079
1080 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001081
1082 logging.info('Connection established, registering...')
1083 handler = {
1084 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001085 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001086 Ghost.SHELL: self.SpawnShellServer,
1087 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001088 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001089 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001090
1091 # Machine ID may change if MAC address is used (USB-ethernet dongle
1092 # plugged/unplugged)
1093 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001094 self.SendRequest('register',
1095 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001096 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001097 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001098 except socket.error:
1099 pass
1100 else:
Yilin Yangb69f5642020-11-10 16:24:03 +08001101 self.SendData()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001102 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001103 self.Listen()
1104
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001105 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001106
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001107 def Reconnect(self):
1108 logging.info('Received reconnect request from RPC server, reconnecting...')
1109 self._reset.set()
1110
Yilin Yang64dd8592020-11-10 16:16:23 +08001111 def CollectPytestAndStatus(self):
1112 STATUS = Enum(['failed', 'running', 'idle'])
1113 goofy = state.GetInstance()
1114 tests = goofy.GetTests()
1115
1116 # Ignore parents
1117 tests = [x for x in tests if not x.get('parent')]
1118
1119 scheduled_tests = (
1120 goofy.GetTestRunStatus(None).get('scheduled_tests') or [])
1121 scheduled_tests = {t['path']
1122 for t in scheduled_tests}
1123 tests = [x for x in tests if x['path'] in scheduled_tests]
1124 data = {
1125 'pytest': '',
1126 'status': STATUS.idle
1127 }
1128
1129 def parse_pytest_name(test):
1130 # test['path'] format: 'test_list_name:pytest_name'
1131 return test['path'][test['path'].index(':') + 1:]
1132
1133 for test in filter(lambda t: t['status'] == TestState.ACTIVE, tests):
1134 data['pytest'] = parse_pytest_name(test)
1135 data['status'] = STATUS.running
1136 return data
1137
1138 for test in filter(lambda t: t['status'] == TestState.FAILED, tests):
1139 data['pytest'] = parse_pytest_name(test)
1140 data['status'] = STATUS.failed
1141 return data
1142
1143 if tests:
1144 data['pytest'] = parse_pytest_name(tests[0])
1145
1146 return data
1147
1148 def CollectModelName(self):
1149 return {
1150 'model': cros_config_module.CrosConfig().GetModelName()
1151 }
1152
1153 def CollectIP(self):
1154 ip_addrs = []
1155 for interface in net_utils.GetNetworkInterfaces():
1156 ip = net_utils.GetEthernetIp(interface)[0]
1157 if ip:
1158 ip_addrs.append(ip)
1159
1160 return {
1161 'ip': ip_addrs
1162 }
1163
1164 def CollectData(self):
1165 """Collect dut data.
1166
1167 Data includes:
1168 1. status: Current test status
1169 2. pytest: Current pytest
1170 3. model: Model name
1171 4. ip: IP
1172 """
1173 data = {}
1174 data.update(self.CollectPytestAndStatus())
1175 data.update(self.CollectModelName())
1176 data.update(self.CollectIP())
1177
1178 return data
1179
1180 def SendData(self):
1181 if not sys_utils.InCrOSDevice():
1182 return
1183
1184 data = self.CollectData()
1185 logging.info('data = %s', data)
1186
1187 self.SendRequest('update_dut_data', data)
1188
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001189 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001190 status = self._register_status
1191 if self._register_status == SUCCESS:
1192 ip, port = self._sock.sock.getpeername()
1193 status += ' %s:%d' % (ip, port)
1194 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001195
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001196 def AddToDownloadQueue(self, ttyname, filename):
1197 self._download_queue.put((ttyname, filename))
1198
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001199 def RegisterTTY(self, session_id, ttyname):
1200 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001201
1202 def RegisterSession(self, session_id, process_id):
1203 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001204
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001205 def StartLanDiscovery(self):
1206 """Start to listen to LAN discovery packet at
1207 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001208
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001209 def thread_func():
1210 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1211 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1212 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001213 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001214 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1215 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001216 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001217 return
1218
1219 logging.info('LAN Discovery: started')
1220 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001221 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001222
1223 if s in rd:
1224 data, source_addr = s.recvfrom(_BUFSIZE)
1225 parts = data.split()
1226 if parts[0] == 'OVERLORD':
1227 ip, port = parts[1].split(':')
1228 if not ip:
1229 ip = source_addr[0]
1230 self._queue.put((ip, int(port)), True)
1231
1232 try:
1233 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001234 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001235 pass
1236 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001237 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001238 self._queue.put(obj)
1239 elif obj == 'pause':
1240 logging.info('LAN Discovery: paused')
1241 while obj != 'resume':
1242 obj = self._queue.get(True)
1243 logging.info('LAN Discovery: resumed')
1244
1245 t = threading.Thread(target=thread_func)
1246 t.daemon = True
1247 t.start()
1248
1249 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001250 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001251 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1252 logRequests=False)
Yilin Yang64dd8592020-11-10 16:16:23 +08001253 rpc_server.register_function(self.SendData, 'SendData')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001254 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001255 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001256 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001257 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001258 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001259 t = threading.Thread(target=rpc_server.serve_forever)
1260 t.daemon = True
1261 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001262
Yilin Yang1512d972020-11-19 13:34:42 +08001263 def ApplyTestListParams(self):
1264 mgr = manager.Manager()
1265 constants = mgr.GetTestListByID(mgr.GetActiveTestListId()).constants
1266
1267 if 'overlord' not in constants:
1268 return
1269
1270 if 'overlord_urls' in constants['overlord']:
1271 for addr in [(x, _OVERLORD_PORT) for x in
1272 constants['overlord']['overlord_urls']]:
1273 if addr not in self._overlord_addrs:
1274 self._overlord_addrs.append(addr)
1275
1276 # This is sugar for ODM to turn off the verification quickly if they forgot.
1277 # So we don't support to turn on again.
1278 # If we want to turn on, we need to restart the ghost daemon.
1279 if 'tls_no_verify' in constants['overlord']:
1280 if constants['overlord']['tls_no_verify']:
1281 self._tls_settings = TLSSettings(None, False)
1282
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001283 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001284 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001285 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1286 if addr not in self._overlord_addrs:
1287 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001288
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001289 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001290 logging.info('%s started', self.MODE_NAME[self._mode])
1291 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001292 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001293
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001294 # We don't care about child process's return code, not wait is needed. This
1295 # is used to prevent zombie process from lingering in the system.
1296 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001297
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001298 if lan_disc:
1299 self.StartLanDiscovery()
1300
1301 if rpc_server:
1302 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001303
1304 try:
1305 while True:
1306 try:
1307 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001308 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001309 pass
1310 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001311 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001312 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1313 self._overlord_addrs.append(addr)
1314
Yilin Yang1512d972020-11-19 13:34:42 +08001315 if self._mode == Ghost.AGENT:
1316 self.ApplyTestListParams()
1317
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001318 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001319 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001320 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001321 # Don't show stack trace for RuntimeError, which we use in this file for
1322 # plausible and expected errors (such as can't connect to server).
1323 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001324 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001325 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001326 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001327 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001328 traceback.print_tb(exc_traceback)
1329 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001330 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001331 time.sleep(_RETRY_INTERVAL)
1332
1333 self.Reset()
1334 except KeyboardInterrupt:
1335 logging.error('Received keyboard interrupt, quit')
1336 sys.exit(0)
1337
1338
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001339def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001340 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001341 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1342
1343
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001344def ForkToBackground():
1345 """Fork process to run in background."""
1346 pid = os.fork()
1347 if pid != 0:
1348 logging.info('Ghost(%d) running in background.', pid)
1349 sys.exit(0)
1350
1351
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001352def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001353 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001354 filepath = os.path.abspath(filename)
1355 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001356 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001357 sys.exit(1)
1358
1359 # Check if we actually have permission to read the file
1360 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001361 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001362 sys.exit(1)
1363
1364 server = GhostRPCServer()
1365 server.AddToDownloadQueue(os.ttyname(0), filepath)
1366 sys.exit(0)
1367
1368
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001369def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001370 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001371 logger = logging.getLogger()
1372 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001373 handler = logging.StreamHandler()
1374 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1375 handler.setFormatter(formatter)
1376 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001377
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001378 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001379 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1380 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001381 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1382 default=None, help='use MID as machine ID')
1383 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1384 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001385 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1386 default=True, help='disable LAN discovery')
1387 parser.add_argument('--no-rpc-server', dest='rpc_server',
1388 action='store_false', default=True,
1389 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001390 parser.add_argument('--tls', dest='tls_mode', default='detect',
1391 choices=('y', 'n', 'detect'),
1392 help="specify 'y' or 'n' to force enable/disable TLS")
Yilin Yang64dd8592020-11-10 16:16:23 +08001393 parser.add_argument(
1394 '--tls-cert-file', metavar='TLS_CERT_FILE', dest='tls_cert_file',
1395 type=str, default=None,
1396 help='file containing the server TLS certificate in PEM '
1397 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001398 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1399 action='store_true', default=False,
1400 help='do not verify certificate if TLS is enabled')
Yilin Yang64dd8592020-11-10 16:16:23 +08001401 parser.add_argument(
1402 '--prop-file', metavar='PROP_FILE', dest='prop_file', type=str,
1403 default=None, help='file containing the JSON representation of client '
1404 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001405 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1406 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001407 parser.add_argument('--reset', dest='reset', default=False,
1408 action='store_true',
1409 help='reset ghost and reload all configs')
Yilin Yang64dd8592020-11-10 16:16:23 +08001410 parser.add_argument('--send-data', dest='send_data', default=False,
1411 action='store_true',
1412 help='send client data to overlord server')
Peter Shih5cafebb2017-06-30 16:36:22 +08001413 parser.add_argument('--status', dest='status', default=False,
1414 action='store_true',
1415 help='show status of the client')
Yilin Yang64dd8592020-11-10 16:16:23 +08001416 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str, nargs='*',
1417 help='overlord server address')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001418 args = parser.parse_args()
1419
Peter Shih5cafebb2017-06-30 16:36:22 +08001420 if args.status:
1421 print(GhostRPCServer().GetStatus())
1422 sys.exit()
1423
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001424 if args.fork:
1425 ForkToBackground()
1426
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001427 if args.reset:
1428 GhostRPCServer().Reconnect()
1429 sys.exit()
1430
Yilin Yang64dd8592020-11-10 16:16:23 +08001431 if args.send_data:
1432 GhostRPCServer().SendData()
1433 sys.exit()
1434
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001435 if args.download:
1436 DownloadFile(args.download)
1437
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001438 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001439 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001440
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001441 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1442
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001443 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001444 tls_mode = args.tls_mode
1445 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001446 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001447 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001448 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001449
1450
1451if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001452 try:
1453 main()
1454 except Exception as e:
1455 logging.error(e)