blob: b39b329d14153de34234298aa05fe82075b86b66 [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
Cheng Yueh59a29662020-12-02 12:20:18 +080044from cros.factory.utils import sys_interface
Yilin Yang64dd8592020-11-10 16:16:23 +080045from cros.factory.utils import sys_utils
46from cros.factory.utils.type_utils import Enum
Yilin Yang42ba5c62020-05-05 10:32:34 +080047
Yilin Yangf54fb912020-01-08 11:42:38 +080048
Fei Shaobb0a3e62020-06-20 15:41:25 +080049_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', '4499'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080050
Fei Shaobb0a3e62020-06-20 15:41:25 +080051_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', '4455'))
52_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', '4456'))
53_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', '9000'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080054
55_BUFSIZE = 8192
56_RETRY_INTERVAL = 2
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080057_SEPARATOR = b'\r\n'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080058_PING_TIMEOUT = 3
59_PING_INTERVAL = 5
60_REQUEST_TIMEOUT_SECS = 60
61_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080062_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080063
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080064_CONTROL_START = 128
65_CONTROL_END = 129
66
Wei-Ning Huanga301f572015-06-03 17:34:21 +080067_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080068_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080069
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080070# Stream control
71_STDIN_CLOSED = '##STDIN_CLOSED##'
72
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080073SUCCESS = 'success'
74FAILED = 'failed'
75DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080076
Joel Kitching22b89042015-08-06 18:23:29 +080077
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080078class PingTimeoutError(Exception):
79 pass
80
81
82class RequestError(Exception):
83 pass
84
85
Fei Shaobd07c9a2020-06-15 19:04:50 +080086class BufferedSocket:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080087 """A buffered socket that supports unrecv.
88
89 Allow putting back data back to the socket for the next recv() call.
90 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080091 def __init__(self, sock):
92 self.sock = sock
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080093 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080094
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080095 def fileno(self):
96 return self.sock.fileno()
97
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080098 def Recv(self, bufsize, flags=0):
99 if self._buf:
100 if len(self._buf) >= bufsize:
101 ret = self._buf[:bufsize]
102 self._buf = self._buf[bufsize:]
103 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800104 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800105 self._buf = b''
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800106 return ret + self.sock.recv(bufsize - len(ret), flags)
107 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800108
109 def UnRecv(self, buf):
110 self._buf = buf + self._buf
111
112 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800113 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800114
115 def RecvBuf(self):
116 """Only recive from buffer."""
117 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800118 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800119 return ret
120
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800121 def Close(self):
122 self.sock.close()
123
124
Fei Shaobd07c9a2020-06-15 19:04:50 +0800125class TLSSettings:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800126 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800127 """Constructor.
128
129 Args:
130 tls_cert_file: TLS certificate in PEM format.
131 enable_tls_without_verify: enable TLS but don't verify certificate.
132 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800133 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800134 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800135 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800136 self._tls_context = None
137
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800138 def _UpdateContext(self):
139 if not self._enabled:
140 self._tls_context = None
141 return
142
143 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
144 self._tls_context.verify_mode = ssl.CERT_REQUIRED
145
146 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800147 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800148 self._tls_context.check_hostname = True
149 try:
150 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800151 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800152 except IOError as e:
153 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
154 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800155 else:
156 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
157 logging.info('TLSSettings: using built-in ca-certificates')
158 else:
159 self._tls_context.verify_mode = ssl.CERT_NONE
160 logging.info('TLSSettings: skipping TLS verification!!!')
161
162 def SetEnabled(self, enabled):
163 logging.info('TLSSettings: enabled: %s', enabled)
164
165 if self._enabled != enabled:
166 self._enabled = enabled
167 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800168
169 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800170 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800171
172 def Context(self):
173 return self._tls_context
174
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800175
Fei Shaobd07c9a2020-06-15 19:04:50 +0800176class Ghost:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800177 """Ghost implements the client protocol of Overlord.
178
179 Ghost provide terminal/shell/logcat functionality and manages the client
180 side connectivity.
181 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800182 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800183
184 MODE_NAME = {
185 NONE: 'NONE',
186 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800187 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800188 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800189 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800190 FILE: 'File',
191 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800192 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800193
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800194 RANDOM_MID = '##random_mid##'
195
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800196 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
197 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Peter Shih220a96d2016-12-22 17:02:16 +0800198 command=None, file_op=None, port=None, tls_mode=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800199 """Constructor.
200
201 Args:
202 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800203 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800204 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800205 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
206 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800207 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800208 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800209 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800210 terminal_sid: the terminal session ID associate with this client. This is
211 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800212 tty_device: the terminal device to open, if tty_device is None, as pseudo
213 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800214 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800215 file_op: a tuple (action, filepath, perm). action is either 'download' or
216 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800217 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800218 tls_mode: can be [True, False, None]. if not None, skip detection of
219 TLS and assume whether server use TLS or not.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800220 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800221 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
222 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800223 if mode == Ghost.SHELL:
224 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800225 if mode == Ghost.FILE:
226 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800227
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800228 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800229 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800230 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800231 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800232 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800233 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800234 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800235 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800236 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800237 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800238 self._ttyname_to_sid = {}
239 self._terminal_sid_to_pid = {}
240 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800241 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800242 self._register_status = DISCONNECTED
243 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800244 self._tls_mode = tls_mode
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800245
246 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800247 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800248 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800249
250 # Protocol specific
251 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800252 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800253 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800254 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800255 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800256 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800257
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800258 def SetIgnoreChild(self, status):
259 # Only ignore child for Agent since only it could spawn child Ghost.
260 if self._mode == Ghost.AGENT:
261 signal.signal(signal.SIGCHLD,
262 signal.SIG_IGN if status else signal.SIG_DFL)
263
264 def GetFileSha1(self, filename):
Yilin Yang0412c272019-12-05 16:57:40 +0800265 with open(filename, 'rb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800266 return hashlib.sha1(f.read()).hexdigest()
267
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800268 def TLSEnabled(self, host, port):
269 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800270 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
271 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800272 # Allow any certificate since we only want to check if server talks TLS.
273 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
274 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800275
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800276 sock = context.wrap_socket(sock, server_hostname=host)
277 sock.settimeout(_CONNECT_TIMEOUT)
278 sock.connect((host, port))
279 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800280 except ssl.SSLError:
281 return False
Stimim Chen3899a912020-07-17 10:52:03 +0800282 except socket.timeout:
283 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800284 except socket.error: # Connect refused or timeout
285 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800286 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800287 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800288
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800289 def Upgrade(self):
290 logging.info('Upgrade: initiating upgrade sequence...')
291
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800292 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800293 https_enabled = self.TLSEnabled(self._connected_addr[0],
294 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800295 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800296 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
297 'abort')
298 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800299
300 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800301 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
302 'without TLS enabled! Possible mis-configuration or '
303 'DNS/IP spoofing detected, abort')
304 return
305
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800306 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800307 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800308 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800309 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800310
311 # Download sha1sum for ghost.py for verification
312 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800313 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800314 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
315 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800316 if f.getcode() != 200:
317 raise RuntimeError('HTTP status %d' % f.getcode())
318 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800319 except (ssl.SSLError, ssl.CertificateError) as e:
320 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
321 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800322 except Exception:
323 logging.error('Upgrade: failed to download sha1sum file, abort')
324 return
325
326 if self.GetFileSha1(scriptpath) == sha1sum:
327 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
328 return
329
330 # Download upgrade version of ghost.py
331 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800332 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800333 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
334 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800335 if f.getcode() != 200:
336 raise RuntimeError('HTTP status %d' % f.getcode())
337 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800338 except (ssl.SSLError, ssl.CertificateError) as e:
339 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
340 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800341 except Exception:
342 logging.error('Upgrade: failed to download upgrade, abort')
343 return
344
345 # Compare SHA1 sum
346 if hashlib.sha1(data).hexdigest() != sha1sum:
347 logging.error('Upgrade: sha1sum mismatch, abort')
348 return
349
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800350 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800351 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800352 f.write(data)
353 except Exception:
354 logging.error('Upgrade: failed to write upgrade onto disk, abort')
355 return
356
357 logging.info('Upgrade: restarting ghost...')
358 self.CloseSockets()
359 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800360 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800361
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800362 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800363 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800364 if self._prop_file:
365 with open(self._prop_file, 'r') as f:
366 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800367 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800368 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800369
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800370 def CloseSockets(self):
371 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800372 if self._platform == 'Linux':
373 for fd in os.listdir('/proc/self/fd/'):
374 try:
375 real_fd = os.readlink('/proc/self/fd/%s' % fd)
376 if real_fd.startswith('socket'):
377 os.close(int(fd))
378 except Exception:
379 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800380
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800381 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800382 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800383 """Spawn a child ghost with specific mode.
384
385 Returns:
386 The spawned child process pid.
387 """
Joel Kitching22b89042015-08-06 18:23:29 +0800388 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800389 self.SetIgnoreChild(False)
390
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800391 pid = os.fork()
392 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800393 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800394 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
395 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800396 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800397 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800398 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800399 sys.exit(0)
400 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800401 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800402 return pid
403
404 def Timestamp(self):
405 return int(time.time())
406
407 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800408 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800409 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800410 ret = re.search('gateway: (.*)', output)
411 if ret:
412 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800413 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800414 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800415 with open('/proc/net/route', 'r') as f:
416 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800417
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800418 ips = []
419 for line in lines:
420 parts = line.split('\t')
421 if parts[2] == '00000000':
422 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800423
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800424 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800425 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800426 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800427 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800428 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800429
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800430 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800431
432 logging.warning('GetGateWayIP: unsupported platform')
433 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800434
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800435 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800436 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800437 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800438
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800439 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800440 match = re.match(r'^https?://(.*):.*$', url)
441 if match:
442 return [match.group(1)]
443 except Exception:
444 pass
445 return []
446
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800447 def GetMachineID(self):
448 """Generates machine-dependent ID string for a machine.
449 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800450 Linux:
451 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800452 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
453 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800454 We follow the listed order to generate machine ID, and fallback to the
455 next alternative if the previous doesn't work.
456
457 Darwin:
458 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800459 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800460 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800461 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800462 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800463 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800464
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800465 # Darwin
466 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800467 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
468 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800469 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
470 if ret:
471 return ret.group(1)
472
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800473 # Try factory device id
474 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800475 from cros.factory.test import session
476 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800477 except Exception:
478 pass
479
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800480 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800481 try:
482 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
483 return f.read().strip()
484 except Exception:
485 pass
486
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800487 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800488 try:
489 macs = []
490 ifaces = sorted(os.listdir('/sys/class/net'))
491 for iface in ifaces:
492 if iface == 'lo':
493 continue
494
495 with open('/sys/class/net/%s/address' % iface, 'r') as f:
496 macs.append(f.read().strip())
497
498 return ';'.join(macs)
499 except Exception:
500 pass
501
Peter Shihcb0e5512017-06-14 16:59:46 +0800502 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800503
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800504 def GetProcessWorkingDirectory(self, pid):
505 if self._platform == 'Linux':
506 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800507 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800508 PROC_PIDVNODEPATHINFO = 9
509 proc_vnodepathinfo_size = 2352
510 vid_path_offset = 152
511
512 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
513 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
514 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
515 ctypes.byref(buf), proc_vnodepathinfo_size)
516 buf = buf.raw[vid_path_offset:]
517 n = buf.index('\0')
518 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800519 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800520
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800521 def Reset(self):
522 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800523 if self._sock is not None:
524 self._sock.Close()
525 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800526 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800527 self._last_ping = 0
528 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800529 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800530 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800531
532 def SendMessage(self, msg):
533 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800534 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800535
536 def SendRequest(self, name, args, handler=None,
537 timeout=_REQUEST_TIMEOUT_SECS):
538 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800539 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800540
541 rid = str(uuid.uuid4())
542 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800543 if timeout >= 0:
544 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800545 self.SendMessage(msg)
546
547 def SendResponse(self, omsg, status, params=None):
548 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
549 self.SendMessage(msg)
550
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800551 def HandleTTYControl(self, fd, control_str):
552 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800553 command = msg['command']
554 params = msg['params']
555 if command == 'resize':
556 # some error happened on websocket
557 if len(params) != 2:
558 return
559 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
560 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
561 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800562 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800563
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800564 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800565 """Spawn a TTY server and forward I/O to the TCP socket."""
566 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800567
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800568 try:
569 if self._tty_device is None:
570 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800571
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800572 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800573 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800574 try:
575 server = GhostRPCServer()
576 server.RegisterTTY(self._session_id, ttyname)
577 server.RegisterSession(self._session_id, os.getpid())
578 except Exception:
579 # If ghost is launched without RPC server, the call will fail but we
580 # can ignore it.
581 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800582
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800583 # The directory that contains the current running ghost script
584 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800585
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800586 env = os.environ.copy()
587 env['USER'] = os.getenv('USER', 'root')
588 env['HOME'] = os.getenv('HOME', '/root')
589 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
590 os.chdir(env['HOME'])
591 os.execve(_SHELL, [_SHELL], env)
592 else:
593 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800594 tty.setraw(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800595 # 0: iflag
596 # 1: oflag
597 # 2: cflag
598 # 3: lflag
599 # 4: ispeed
600 # 5: ospeed
601 # 6: cc
Wei-Ning Huang39169902015-09-19 06:00:23 +0800602 attr = termios.tcgetattr(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800603 attr[0] &= (termios.IXON | termios.IXOFF)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800604 attr[2] |= termios.CLOCAL
605 attr[2] &= ~termios.CRTSCTS
606 attr[4] = termios.B115200
607 attr[5] = termios.B115200
608 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800609
Stimim Chen3899a912020-07-17 10:52:03 +0800610 nonlocals = {
611 'control_state': None,
612 'control_str': b''
613 }
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800614
615 def _ProcessBuffer(buf):
Stimim Chen3899a912020-07-17 10:52:03 +0800616 write_buffer = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800617 while buf:
618 if nonlocals['control_state']:
Stimim Chen3899a912020-07-17 10:52:03 +0800619 if _CONTROL_END in buf:
620 index = buf.index(_CONTROL_END)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800621 nonlocals['control_str'] += buf[:index]
622 self.HandleTTYControl(fd, nonlocals['control_str'])
623 nonlocals['control_state'] = None
Stimim Chen3899a912020-07-17 10:52:03 +0800624 nonlocals['control_str'] = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800625 buf = buf[index+1:]
626 else:
627 nonlocals['control_str'] += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800628 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800629 else:
Stimim Chen3899a912020-07-17 10:52:03 +0800630 if _CONTROL_START in buf:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800631 nonlocals['control_state'] = _CONTROL_START
Stimim Chen3899a912020-07-17 10:52:03 +0800632 index = buf.index(_CONTROL_START)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800633 write_buffer += buf[:index]
634 buf = buf[index+1:]
635 else:
636 write_buffer += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800637 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800638
639 if write_buffer:
640 os.write(fd, write_buffer)
641
642 _ProcessBuffer(self._sock.RecvBuf())
643
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800644 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800645 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800646
647 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800648 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800649
650 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800651 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800652 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800653 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800654 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800655 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800656 logging.error('SpawnTTYServer: %s', e, exc_info=True)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800657 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800658 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800659
660 logging.info('SpawnTTYServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800661 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800662
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800663 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800664 """Spawn a shell server and forward input/output from/to the TCP socket."""
665 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800666
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800667 # Add ghost executable to PATH
668 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
669 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800670 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800671
672 # Execute shell command from HOME directory
673 os.chdir(os.getenv('HOME', '/tmp'))
674
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800675 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800676 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800677 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800678
679 def make_non_block(fd):
680 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
681 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
682
683 make_non_block(p.stdout)
684 make_non_block(p.stderr)
685
686 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800687 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800688
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800689 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800690 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800691 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800692 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800693 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800694
695 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800696 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800697
698 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800699 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800700 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800701 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800702
703 try:
704 idx = ret.index(_STDIN_CLOSED * 2)
705 p.stdin.write(ret[:idx])
706 p.stdin.close()
707 except ValueError:
708 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800709 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800710 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800711 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800712 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800713 logging.error('SpawnShellServer: %s', e, exc_info=True)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800714 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800715 # Check if the process is terminated. If not, Send SIGTERM to process,
716 # then wait for 1 second. Send another SIGKILL to make sure the process is
717 # terminated.
718 p.poll()
719 if p.returncode is None:
720 try:
721 p.terminate()
722 time.sleep(1)
723 p.kill()
724 except Exception:
725 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800726
727 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800728 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800729
730 logging.info('SpawnShellServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800731 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800732
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800733 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800734 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800735 try:
736 size = os.stat(self._file_op[1]).st_size
737 except OSError as e:
738 logging.error('InitiateFileOperation: download: %s', e)
739 sys.exit(1)
740
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800741 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800742 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800743 'filename': os.path.basename(self._file_op[1]),
744 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800745 elif self._file_op[0] == 'upload':
746 self.SendRequest('clear_to_upload', {}, timeout=-1)
747 self.StartUploadServer()
748 else:
749 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800750
751 def StartDownloadServer(self):
752 logging.info('StartDownloadServer: started')
753
754 try:
755 with open(self._file_op[1], 'rb') as f:
756 while True:
757 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800758 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800759 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800760 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800761 except Exception as e:
762 logging.error('StartDownloadServer: %s', e)
763 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800764 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800765
766 logging.info('StartDownloadServer: terminated')
767 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800768
Wei-Ning Huange2981862015-08-03 15:03:08 +0800769 def StartUploadServer(self):
770 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800771 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800772 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800773 dirname = os.path.dirname(filepath)
774 if not os.path.exists(dirname):
775 try:
776 os.makedirs(dirname)
777 except Exception:
778 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800779
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800780 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800781 if self._file_op[2]:
782 os.fchmod(f.fileno(), self._file_op[2])
783
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800784 f.write(self._sock.RecvBuf())
785
Wei-Ning Huange2981862015-08-03 15:03:08 +0800786 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800787 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800788 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800789 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800790 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800791 break
792 f.write(buf)
793 except socket.error as e:
794 logging.error('StartUploadServer: socket error: %s', e)
795 except Exception as e:
796 logging.error('StartUploadServer: %s', e)
797 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800798 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800799
800 logging.info('StartUploadServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800801 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huange2981862015-08-03 15:03:08 +0800802
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800803 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800804 """Spawn a port forwarding server and forward I/O to the TCP socket."""
805 logging.info('SpawnPortForwardServer: started')
806
807 src_sock = None
808 try:
809 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800810 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800811 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800812
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800813 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800814
815 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800816 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800817
818 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800819 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800820 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800821 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800822 src_sock.send(data)
823
824 if src_sock in rd:
825 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800826 if not data:
Yilin Yang969b8012020-12-16 14:38:00 +0800827 continue
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800828 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800829 except Exception as e:
830 logging.error('SpawnPortForwardServer: %s', e)
831 finally:
832 if src_sock:
833 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800834 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800835
836 logging.info('SpawnPortForwardServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800837 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800838
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800839 def Ping(self):
840 def timeout_handler(x):
841 if x is None:
842 raise PingTimeoutError
843
844 self._last_ping = self.Timestamp()
845 self.SendRequest('ping', {}, timeout_handler, 5)
846
Wei-Ning Huangae923642015-09-24 14:08:09 +0800847 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800848 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800849 filepath = params['filename']
850 if not os.path.isabs(filepath):
851 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
852
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800853 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800854 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800855 pass
856 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800857 self.SendResponse(msg, str(e))
858 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800859
860 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800861 file_op=('download', filepath))
862 self.SendResponse(msg, SUCCESS)
863
864 def HandleFileUploadRequest(self, msg):
865 params = msg['params']
866
867 # Resolve upload filepath
868 filename = params['filename']
869 dest_path = filename
870
871 # If dest is specified, use it first
872 dest_path = params.get('dest', '')
873 if dest_path:
874 if not os.path.isabs(dest_path):
875 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
876
877 if os.path.isdir(dest_path):
878 dest_path = os.path.join(dest_path, filename)
879 else:
880 target_dir = os.getenv('HOME', '/tmp')
881
882 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800883 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800884 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
885 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800886 try:
887 target_dir = self.GetProcessWorkingDirectory(pid)
888 except Exception as e:
889 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800890
891 dest_path = os.path.join(target_dir, filename)
892
893 try:
894 os.makedirs(os.path.dirname(dest_path))
895 except Exception:
896 pass
897
898 try:
899 with open(dest_path, 'w') as _:
900 pass
901 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800902 self.SendResponse(msg, str(e))
903 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800904
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800905 # If not check_only, spawn FILE mode ghost agent to handle upload
906 if not params.get('check_only', False):
907 self.SpawnGhost(self.FILE, params['sid'],
908 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800909 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800910
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800911 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800912 command = msg['name']
913 params = msg['params']
914
915 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800916 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800917 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800918 self.SpawnGhost(self.TERMINAL, params['sid'],
919 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800920 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800921 elif command == 'shell':
922 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800923 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800924 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800925 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800926 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800927 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800928 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800929 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800930 elif command == 'forward':
931 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
932 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800933
934 def HandleResponse(self, response):
935 rid = str(response['rid'])
936 if rid in self._requests:
937 handler = self._requests[rid][2]
938 del self._requests[rid]
939 if callable(handler):
940 handler(response)
941 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800942 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800943
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800944 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800945 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800946 try:
947 index = buf.index(_SEPARATOR)
948 except ValueError:
949 self._sock.UnRecv(buf)
950 return
951
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800952 msgs_json = [buf[:index]]
953 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800954 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800955 msgs_json = buf.split(_SEPARATOR)
956 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800957
958 for msg_json in msgs_json:
959 try:
960 msg = json.loads(msg_json)
961 except ValueError:
962 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800963 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800964 continue
965
966 if 'name' in msg:
967 self.HandleRequest(msg)
968 elif 'response' in msg:
969 self.HandleResponse(msg)
970 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800971 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800972
973 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800974 """Scans for pending requests which have timed out.
975
976 If any timed-out requests are discovered, their handler is called with the
977 special response value of None.
978 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800979 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800980 request_time, timeout, handler = self._requests[rid]
981 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800982 if callable(handler):
983 handler(None)
984 else:
985 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800986 del self._requests[rid]
987
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800988 def InitiateDownload(self):
989 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800990 sid = self._ttyname_to_sid[ttyname]
991 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800992 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800993
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800994 def Listen(self):
995 try:
996 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800997 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800998 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800999
1000 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001001 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001002
1003 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +08001004 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001005 break
1006
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001007 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001008
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001009 if (self._mode == self.AGENT and
1010 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001011 self.Ping()
1012 self.ScanForTimeoutRequests()
1013
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001014 if not self._download_queue.empty():
1015 self.InitiateDownload()
1016
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001017 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001018 break
1019 except socket.error:
1020 raise RuntimeError('Connection dropped')
1021 except PingTimeoutError:
1022 raise RuntimeError('Connection timeout')
1023 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001024 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001025
1026 self._queue.put('resume')
1027
1028 if self._mode != Ghost.AGENT:
1029 sys.exit(1)
1030
1031 def Register(self):
1032 non_local = {}
1033 for addr in self._overlord_addrs:
1034 non_local['addr'] = addr
1035 def registered(response):
1036 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001037 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001038 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001039
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001040 self._register_status = response['response']
1041 if response['response'] != SUCCESS:
1042 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001043 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001044
1045 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1046 self._connected_addr = non_local['addr']
1047 self.Upgrade() # Check for upgrade
1048 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001049
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001050 try:
1051 logging.info('Trying %s:%d ...', *addr)
1052 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001053
Peter Shih220a96d2016-12-22 17:02:16 +08001054 # Check if server has TLS enabled. Only check if self._tls_mode is
1055 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001056 # Only control channel needs to determine if TLS is enabled. Other mode
1057 # should use the TLSSettings passed in when it was spawned.
1058 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001059 self._tls_settings.SetEnabled(
1060 self.TLSEnabled(*addr) if self._tls_mode is None
1061 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001062
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001063 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1064 sock.settimeout(_CONNECT_TIMEOUT)
1065
1066 try:
1067 if self._tls_settings.Enabled():
1068 tls_context = self._tls_settings.Context()
1069 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1070
1071 sock.connect(addr)
1072 except (ssl.SSLError, ssl.CertificateError) as e:
1073 logging.error('%s: %s', e.__class__.__name__, e)
1074 continue
1075 except IOError as e:
1076 if e.errno == 2: # No such file or directory
1077 logging.error('%s: %s', e.__class__.__name__, e)
1078 continue
1079 raise
1080
1081 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001082
1083 logging.info('Connection established, registering...')
1084 handler = {
1085 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001086 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001087 Ghost.SHELL: self.SpawnShellServer,
1088 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001089 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001090 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001091
1092 # Machine ID may change if MAC address is used (USB-ethernet dongle
1093 # plugged/unplugged)
1094 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001095 self.SendRequest('register',
1096 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001097 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001098 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001099 except socket.error:
1100 pass
1101 else:
Yilin Yangcb5e8922020-12-16 10:30:44 +08001102 # We only send dut data when it's agent mode.
1103 if self._mode == Ghost.AGENT:
1104 self.SendData()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001105 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001106 self.Listen()
1107
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001108 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001109
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001110 def Reconnect(self):
1111 logging.info('Received reconnect request from RPC server, reconnecting...')
1112 self._reset.set()
1113
Yilin Yang64dd8592020-11-10 16:16:23 +08001114 def CollectPytestAndStatus(self):
1115 STATUS = Enum(['failed', 'running', 'idle'])
1116 goofy = state.GetInstance()
1117 tests = goofy.GetTests()
1118
1119 # Ignore parents
1120 tests = [x for x in tests if not x.get('parent')]
1121
1122 scheduled_tests = (
1123 goofy.GetTestRunStatus(None).get('scheduled_tests') or [])
1124 scheduled_tests = {t['path']
1125 for t in scheduled_tests}
1126 tests = [x for x in tests if x['path'] in scheduled_tests]
1127 data = {
1128 'pytest': '',
1129 'status': STATUS.idle
1130 }
1131
1132 def parse_pytest_name(test):
1133 # test['path'] format: 'test_list_name:pytest_name'
1134 return test['path'][test['path'].index(':') + 1:]
1135
1136 for test in filter(lambda t: t['status'] == TestState.ACTIVE, tests):
1137 data['pytest'] = parse_pytest_name(test)
1138 data['status'] = STATUS.running
1139 return data
1140
1141 for test in filter(lambda t: t['status'] == TestState.FAILED, tests):
1142 data['pytest'] = parse_pytest_name(test)
1143 data['status'] = STATUS.failed
1144 return data
1145
1146 if tests:
1147 data['pytest'] = parse_pytest_name(tests[0])
1148
1149 return data
1150
1151 def CollectModelName(self):
1152 return {
1153 'model': cros_config_module.CrosConfig().GetModelName()
1154 }
1155
1156 def CollectIP(self):
1157 ip_addrs = []
1158 for interface in net_utils.GetNetworkInterfaces():
1159 ip = net_utils.GetEthernetIp(interface)[0]
1160 if ip:
1161 ip_addrs.append(ip)
1162
1163 return {
1164 'ip': ip_addrs
1165 }
1166
1167 def CollectData(self):
1168 """Collect dut data.
1169
1170 Data includes:
1171 1. status: Current test status
1172 2. pytest: Current pytest
1173 3. model: Model name
1174 4. ip: IP
1175 """
1176 data = {}
1177 data.update(self.CollectPytestAndStatus())
1178 data.update(self.CollectModelName())
1179 data.update(self.CollectIP())
1180
1181 return data
1182
1183 def SendData(self):
1184 if not sys_utils.InCrOSDevice():
1185 return
1186
1187 data = self.CollectData()
1188 logging.info('data = %s', data)
1189
1190 self.SendRequest('update_dut_data', data)
1191
Yilin Yang90c60c42020-11-11 14:45:08 +08001192 def TrackConnection(self, enabled, timeout_secs):
1193 logging.info('TrackConnection, enabled = %s, timeout_secs = %d', enabled,
1194 timeout_secs)
1195
1196 self.SendRequest('track_connection', {
1197 'enabled': enabled,
1198 'timeout_secs': timeout_secs
1199 })
1200
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001201 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001202 status = self._register_status
1203 if self._register_status == SUCCESS:
1204 ip, port = self._sock.sock.getpeername()
1205 status += ' %s:%d' % (ip, port)
1206 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001207
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001208 def AddToDownloadQueue(self, ttyname, filename):
1209 self._download_queue.put((ttyname, filename))
1210
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001211 def RegisterTTY(self, session_id, ttyname):
1212 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001213
1214 def RegisterSession(self, session_id, process_id):
1215 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001216
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001217 def StartLanDiscovery(self):
1218 """Start to listen to LAN discovery packet at
1219 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001220
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001221 def thread_func():
1222 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1223 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1224 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001225 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001226 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1227 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001228 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001229 return
1230
1231 logging.info('LAN Discovery: started')
1232 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001233 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001234
1235 if s in rd:
1236 data, source_addr = s.recvfrom(_BUFSIZE)
1237 parts = data.split()
1238 if parts[0] == 'OVERLORD':
1239 ip, port = parts[1].split(':')
1240 if not ip:
1241 ip = source_addr[0]
1242 self._queue.put((ip, int(port)), True)
1243
1244 try:
1245 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001246 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001247 pass
1248 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001249 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001250 self._queue.put(obj)
1251 elif obj == 'pause':
1252 logging.info('LAN Discovery: paused')
1253 while obj != 'resume':
1254 obj = self._queue.get(True)
1255 logging.info('LAN Discovery: resumed')
1256
1257 t = threading.Thread(target=thread_func)
1258 t.daemon = True
1259 t.start()
1260
1261 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001262 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001263 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1264 logRequests=False)
Yilin Yang64dd8592020-11-10 16:16:23 +08001265 rpc_server.register_function(self.SendData, 'SendData')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001266 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001267 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001268 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001269 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Yilin Yang90c60c42020-11-11 14:45:08 +08001270 rpc_server.register_function(self.TrackConnection, 'TrackConnection')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001271 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001272 t = threading.Thread(target=rpc_server.serve_forever)
1273 t.daemon = True
1274 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001275
Yilin Yang1512d972020-11-19 13:34:42 +08001276 def ApplyTestListParams(self):
1277 mgr = manager.Manager()
Cheng Yueh59a29662020-12-02 12:20:18 +08001278 device = sys_interface.SystemInterface()
1279 constants = mgr.GetTestListByID(mgr.GetActiveTestListId(device)).constants
Yilin Yang1512d972020-11-19 13:34:42 +08001280
1281 if 'overlord' not in constants:
1282 return
1283
1284 if 'overlord_urls' in constants['overlord']:
1285 for addr in [(x, _OVERLORD_PORT) for x in
1286 constants['overlord']['overlord_urls']]:
1287 if addr not in self._overlord_addrs:
1288 self._overlord_addrs.append(addr)
1289
1290 # This is sugar for ODM to turn off the verification quickly if they forgot.
1291 # So we don't support to turn on again.
1292 # If we want to turn on, we need to restart the ghost daemon.
1293 if 'tls_no_verify' in constants['overlord']:
1294 if constants['overlord']['tls_no_verify']:
1295 self._tls_settings = TLSSettings(None, False)
1296
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001297 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001298 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001299 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1300 if addr not in self._overlord_addrs:
1301 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001302
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001303 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001304 logging.info('%s started', self.MODE_NAME[self._mode])
1305 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001306 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001307
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001308 # We don't care about child process's return code, not wait is needed. This
1309 # is used to prevent zombie process from lingering in the system.
1310 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001311
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001312 if lan_disc:
1313 self.StartLanDiscovery()
1314
1315 if rpc_server:
1316 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001317
1318 try:
1319 while True:
1320 try:
1321 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001322 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001323 pass
1324 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001325 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001326 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1327 self._overlord_addrs.append(addr)
1328
Yilin Yang1512d972020-11-19 13:34:42 +08001329 if self._mode == Ghost.AGENT:
1330 self.ApplyTestListParams()
1331
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001332 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001333 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001334 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001335 # Don't show stack trace for RuntimeError, which we use in this file for
1336 # plausible and expected errors (such as can't connect to server).
1337 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001338 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001339 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001340 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001341 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001342 traceback.print_tb(exc_traceback)
1343 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001344 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001345 time.sleep(_RETRY_INTERVAL)
1346
1347 self.Reset()
1348 except KeyboardInterrupt:
1349 logging.error('Received keyboard interrupt, quit')
1350 sys.exit(0)
1351
1352
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001353def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001354 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001355 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1356
1357
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001358def ForkToBackground():
1359 """Fork process to run in background."""
1360 pid = os.fork()
1361 if pid != 0:
1362 logging.info('Ghost(%d) running in background.', pid)
1363 sys.exit(0)
1364
1365
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001366def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001367 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001368 filepath = os.path.abspath(filename)
1369 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001370 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001371 sys.exit(1)
1372
1373 # Check if we actually have permission to read the file
1374 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001375 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001376 sys.exit(1)
1377
1378 server = GhostRPCServer()
1379 server.AddToDownloadQueue(os.ttyname(0), filepath)
1380 sys.exit(0)
1381
1382
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001383def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001384 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001385 logger = logging.getLogger()
1386 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001387 handler = logging.StreamHandler()
1388 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1389 handler.setFormatter(formatter)
1390 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001391
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001392 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001393 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1394 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001395 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1396 default=None, help='use MID as machine ID')
1397 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1398 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001399 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1400 default=True, help='disable LAN discovery')
1401 parser.add_argument('--no-rpc-server', dest='rpc_server',
1402 action='store_false', default=True,
1403 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001404 parser.add_argument('--tls', dest='tls_mode', default='detect',
1405 choices=('y', 'n', 'detect'),
1406 help="specify 'y' or 'n' to force enable/disable TLS")
Yilin Yang64dd8592020-11-10 16:16:23 +08001407 parser.add_argument(
1408 '--tls-cert-file', metavar='TLS_CERT_FILE', dest='tls_cert_file',
1409 type=str, default=None,
1410 help='file containing the server TLS certificate in PEM '
1411 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001412 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1413 action='store_true', default=False,
1414 help='do not verify certificate if TLS is enabled')
Yilin Yang64dd8592020-11-10 16:16:23 +08001415 parser.add_argument(
1416 '--prop-file', metavar='PROP_FILE', dest='prop_file', type=str,
1417 default=None, help='file containing the JSON representation of client '
1418 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001419 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1420 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001421 parser.add_argument('--reset', dest='reset', default=False,
1422 action='store_true',
1423 help='reset ghost and reload all configs')
Yilin Yang64dd8592020-11-10 16:16:23 +08001424 parser.add_argument('--send-data', dest='send_data', default=False,
1425 action='store_true',
1426 help='send client data to overlord server')
Peter Shih5cafebb2017-06-30 16:36:22 +08001427 parser.add_argument('--status', dest='status', default=False,
1428 action='store_true',
1429 help='show status of the client')
Yilin Yang90c60c42020-11-11 14:45:08 +08001430 parser.add_argument('--track-connection', dest='track_connection',
1431 default=None, choices=('y', 'n'),
1432 help="specify 'y' or 'n' to track connection or not")
1433 parser.add_argument('--timeout-seconds', dest='timeout_secs', type=int,
1434 default=900,
1435 help='timeout seconds when track the connection')
Yilin Yang64dd8592020-11-10 16:16:23 +08001436 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str, nargs='*',
1437 help='overlord server address')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001438 args = parser.parse_args()
1439
Peter Shih5cafebb2017-06-30 16:36:22 +08001440 if args.status:
1441 print(GhostRPCServer().GetStatus())
1442 sys.exit()
1443
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001444 if args.fork:
1445 ForkToBackground()
1446
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001447 if args.reset:
1448 GhostRPCServer().Reconnect()
1449 sys.exit()
1450
Yilin Yang64dd8592020-11-10 16:16:23 +08001451 if args.send_data:
1452 GhostRPCServer().SendData()
1453 sys.exit()
1454
Yilin Yang90c60c42020-11-11 14:45:08 +08001455 if args.track_connection:
1456 GhostRPCServer().TrackConnection(args.track_connection == 'y',
1457 args.timeout_secs)
1458 sys.exit()
1459
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001460 if args.download:
1461 DownloadFile(args.download)
1462
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001463 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001464 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001465
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001466 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1467
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001468 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001469 tls_mode = args.tls_mode
1470 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001471 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001472 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001473 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001474
1475
1476if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001477 try:
1478 main()
1479 except Exception as e:
1480 logging.error(e)