blob: c390494a363e8b71174af66b98ce84c173ad2177 [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
Yilin Yang89a136c2021-01-05 15:25:05 +0800246 # The information of track_connection is lost after ghost restart.
247 self._track_connection = None
248 self._track_connection_timeout_secs = 900
249
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800250 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800251 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800252 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800253
254 # Protocol specific
255 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800256 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800257 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800258 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800259 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800260 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800261
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800262 def SetIgnoreChild(self, status):
263 # Only ignore child for Agent since only it could spawn child Ghost.
264 if self._mode == Ghost.AGENT:
265 signal.signal(signal.SIGCHLD,
266 signal.SIG_IGN if status else signal.SIG_DFL)
267
268 def GetFileSha1(self, filename):
Yilin Yang0412c272019-12-05 16:57:40 +0800269 with open(filename, 'rb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800270 return hashlib.sha1(f.read()).hexdigest()
271
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800272 def TLSEnabled(self, host, port):
273 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800274 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
275 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800276 # Allow any certificate since we only want to check if server talks TLS.
277 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
278 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800279
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800280 sock = context.wrap_socket(sock, server_hostname=host)
281 sock.settimeout(_CONNECT_TIMEOUT)
282 sock.connect((host, port))
283 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800284 except ssl.SSLError:
285 return False
Stimim Chen3899a912020-07-17 10:52:03 +0800286 except socket.timeout:
287 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800288 except socket.error: # Connect refused or timeout
289 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800290 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800291 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800292
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800293 def Upgrade(self):
294 logging.info('Upgrade: initiating upgrade sequence...')
295
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800296 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800297 https_enabled = self.TLSEnabled(self._connected_addr[0],
298 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800299 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800300 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
301 'abort')
302 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800303
304 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800305 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
306 'without TLS enabled! Possible mis-configuration or '
307 'DNS/IP spoofing detected, abort')
308 return
309
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800310 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800311 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800312 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800313 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800314
315 # Download sha1sum for ghost.py for verification
316 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800317 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800318 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
319 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800320 if f.getcode() != 200:
321 raise RuntimeError('HTTP status %d' % f.getcode())
322 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800323 except (ssl.SSLError, ssl.CertificateError) as e:
324 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
325 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800326 except Exception:
327 logging.error('Upgrade: failed to download sha1sum file, abort')
328 return
329
330 if self.GetFileSha1(scriptpath) == sha1sum:
331 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
332 return
333
334 # Download upgrade version of ghost.py
335 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800336 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800337 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
338 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800339 if f.getcode() != 200:
340 raise RuntimeError('HTTP status %d' % f.getcode())
341 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800342 except (ssl.SSLError, ssl.CertificateError) as e:
343 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
344 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800345 except Exception:
346 logging.error('Upgrade: failed to download upgrade, abort')
347 return
348
349 # Compare SHA1 sum
350 if hashlib.sha1(data).hexdigest() != sha1sum:
351 logging.error('Upgrade: sha1sum mismatch, abort')
352 return
353
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800354 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800355 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800356 f.write(data)
357 except Exception:
358 logging.error('Upgrade: failed to write upgrade onto disk, abort')
359 return
360
361 logging.info('Upgrade: restarting ghost...')
362 self.CloseSockets()
363 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800364 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800365
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800366 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800367 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800368 if self._prop_file:
369 with open(self._prop_file, 'r') as f:
370 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800371 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800372 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800373
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800374 def CloseSockets(self):
375 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800376 if self._platform == 'Linux':
377 for fd in os.listdir('/proc/self/fd/'):
378 try:
379 real_fd = os.readlink('/proc/self/fd/%s' % fd)
380 if real_fd.startswith('socket'):
381 os.close(int(fd))
382 except Exception:
383 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800384
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800385 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800386 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800387 """Spawn a child ghost with specific mode.
388
389 Returns:
390 The spawned child process pid.
391 """
Joel Kitching22b89042015-08-06 18:23:29 +0800392 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800393 self.SetIgnoreChild(False)
394
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800395 pid = os.fork()
396 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800397 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800398 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
399 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800400 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800401 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800402 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800403 sys.exit(0)
404 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800405 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800406 return pid
407
408 def Timestamp(self):
409 return int(time.time())
410
411 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800412 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800413 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800414 ret = re.search('gateway: (.*)', output)
415 if ret:
416 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800417 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800418 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800419 with open('/proc/net/route', 'r') as f:
420 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800421
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800422 ips = []
423 for line in lines:
424 parts = line.split('\t')
425 if parts[2] == '00000000':
426 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800427
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800428 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800429 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800430 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800431 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800432 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800433
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800434 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800435
436 logging.warning('GetGateWayIP: unsupported platform')
437 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800438
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800439 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800440 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800441 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800442
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800443 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800444 match = re.match(r'^https?://(.*):.*$', url)
445 if match:
446 return [match.group(1)]
447 except Exception:
448 pass
449 return []
450
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800451 def GetMachineID(self):
452 """Generates machine-dependent ID string for a machine.
453 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800454 Linux:
455 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800456 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
457 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800458 We follow the listed order to generate machine ID, and fallback to the
459 next alternative if the previous doesn't work.
460
461 Darwin:
462 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800463 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800464 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800465 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800466 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800467 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800468
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800469 # Darwin
470 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800471 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
472 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800473 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
474 if ret:
475 return ret.group(1)
476
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800477 # Try factory device id
478 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800479 from cros.factory.test import session
480 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800481 except Exception:
482 pass
483
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800484 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800485 try:
486 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
487 return f.read().strip()
488 except Exception:
489 pass
490
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800491 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800492 try:
493 macs = []
494 ifaces = sorted(os.listdir('/sys/class/net'))
495 for iface in ifaces:
496 if iface == 'lo':
497 continue
498
499 with open('/sys/class/net/%s/address' % iface, 'r') as f:
500 macs.append(f.read().strip())
501
502 return ';'.join(macs)
503 except Exception:
504 pass
505
Peter Shihcb0e5512017-06-14 16:59:46 +0800506 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800507
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800508 def GetProcessWorkingDirectory(self, pid):
509 if self._platform == 'Linux':
510 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800511 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800512 PROC_PIDVNODEPATHINFO = 9
513 proc_vnodepathinfo_size = 2352
514 vid_path_offset = 152
515
516 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
517 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
518 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
519 ctypes.byref(buf), proc_vnodepathinfo_size)
520 buf = buf.raw[vid_path_offset:]
521 n = buf.index('\0')
522 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800523 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800524
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800525 def Reset(self):
526 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800527 if self._sock is not None:
528 self._sock.Close()
529 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800530 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800531 self._last_ping = 0
532 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800533 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800534 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800535
536 def SendMessage(self, msg):
537 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800538 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800539
540 def SendRequest(self, name, args, handler=None,
541 timeout=_REQUEST_TIMEOUT_SECS):
542 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800543 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800544
545 rid = str(uuid.uuid4())
546 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800547 if timeout >= 0:
548 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800549 self.SendMessage(msg)
550
551 def SendResponse(self, omsg, status, params=None):
552 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
553 self.SendMessage(msg)
554
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800555 def HandleTTYControl(self, fd, control_str):
556 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800557 command = msg['command']
558 params = msg['params']
559 if command == 'resize':
560 # some error happened on websocket
561 if len(params) != 2:
562 return
563 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
564 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
565 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800566 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800567
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800568 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800569 """Spawn a TTY server and forward I/O to the TCP socket."""
570 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800571
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800572 try:
573 if self._tty_device is None:
574 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800575
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800576 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800577 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800578 try:
579 server = GhostRPCServer()
580 server.RegisterTTY(self._session_id, ttyname)
581 server.RegisterSession(self._session_id, os.getpid())
582 except Exception:
583 # If ghost is launched without RPC server, the call will fail but we
584 # can ignore it.
585 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800586
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800587 # The directory that contains the current running ghost script
588 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800589
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800590 env = os.environ.copy()
591 env['USER'] = os.getenv('USER', 'root')
592 env['HOME'] = os.getenv('HOME', '/root')
593 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
594 os.chdir(env['HOME'])
595 os.execve(_SHELL, [_SHELL], env)
596 else:
597 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800598 tty.setraw(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800599 # 0: iflag
600 # 1: oflag
601 # 2: cflag
602 # 3: lflag
603 # 4: ispeed
604 # 5: ospeed
605 # 6: cc
Wei-Ning Huang39169902015-09-19 06:00:23 +0800606 attr = termios.tcgetattr(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800607 attr[0] &= (termios.IXON | termios.IXOFF)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800608 attr[2] |= termios.CLOCAL
609 attr[2] &= ~termios.CRTSCTS
610 attr[4] = termios.B115200
611 attr[5] = termios.B115200
612 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800613
Stimim Chen3899a912020-07-17 10:52:03 +0800614 nonlocals = {
615 'control_state': None,
616 'control_str': b''
617 }
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800618
619 def _ProcessBuffer(buf):
Stimim Chen3899a912020-07-17 10:52:03 +0800620 write_buffer = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800621 while buf:
622 if nonlocals['control_state']:
Stimim Chen3899a912020-07-17 10:52:03 +0800623 if _CONTROL_END in buf:
624 index = buf.index(_CONTROL_END)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800625 nonlocals['control_str'] += buf[:index]
626 self.HandleTTYControl(fd, nonlocals['control_str'])
627 nonlocals['control_state'] = None
Stimim Chen3899a912020-07-17 10:52:03 +0800628 nonlocals['control_str'] = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800629 buf = buf[index+1:]
630 else:
631 nonlocals['control_str'] += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800632 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800633 else:
Stimim Chen3899a912020-07-17 10:52:03 +0800634 if _CONTROL_START in buf:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800635 nonlocals['control_state'] = _CONTROL_START
Stimim Chen3899a912020-07-17 10:52:03 +0800636 index = buf.index(_CONTROL_START)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800637 write_buffer += buf[:index]
638 buf = buf[index+1:]
639 else:
640 write_buffer += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800641 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800642
643 if write_buffer:
644 os.write(fd, write_buffer)
645
646 _ProcessBuffer(self._sock.RecvBuf())
647
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800648 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800649 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800650
651 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800652 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800653
654 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800655 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800656 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800657 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800658 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800659 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800660 logging.error('SpawnTTYServer: %s', e, exc_info=True)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800661 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800662 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800663
664 logging.info('SpawnTTYServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800665 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800666
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800667 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800668 """Spawn a shell server and forward input/output from/to the TCP socket."""
669 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800670
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800671 # Add ghost executable to PATH
672 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
673 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800674 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800675
676 # Execute shell command from HOME directory
677 os.chdir(os.getenv('HOME', '/tmp'))
678
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800679 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800680 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800681 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800682
683 def make_non_block(fd):
684 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
685 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
686
687 make_non_block(p.stdout)
688 make_non_block(p.stderr)
689
690 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800691 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800692
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800693 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800694 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800695 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800696 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800697 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800698
699 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800700 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800701
702 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800703 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800704 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800705 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800706
707 try:
708 idx = ret.index(_STDIN_CLOSED * 2)
709 p.stdin.write(ret[:idx])
710 p.stdin.close()
711 except ValueError:
712 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800713 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800714 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800715 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800716 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800717 logging.error('SpawnShellServer: %s', e, exc_info=True)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800718 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800719 # Check if the process is terminated. If not, Send SIGTERM to process,
720 # then wait for 1 second. Send another SIGKILL to make sure the process is
721 # terminated.
722 p.poll()
723 if p.returncode is None:
724 try:
725 p.terminate()
726 time.sleep(1)
727 p.kill()
728 except Exception:
729 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800730
731 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800732 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800733
734 logging.info('SpawnShellServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800735 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800736
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800737 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800738 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800739 try:
740 size = os.stat(self._file_op[1]).st_size
741 except OSError as e:
742 logging.error('InitiateFileOperation: download: %s', e)
743 sys.exit(1)
744
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800745 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800746 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800747 'filename': os.path.basename(self._file_op[1]),
748 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800749 elif self._file_op[0] == 'upload':
750 self.SendRequest('clear_to_upload', {}, timeout=-1)
751 self.StartUploadServer()
752 else:
753 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800754
755 def StartDownloadServer(self):
756 logging.info('StartDownloadServer: started')
757
758 try:
759 with open(self._file_op[1], 'rb') as f:
760 while True:
761 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800762 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800763 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800764 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800765 except Exception as e:
766 logging.error('StartDownloadServer: %s', e)
767 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800768 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800769
770 logging.info('StartDownloadServer: terminated')
771 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800772
Wei-Ning Huange2981862015-08-03 15:03:08 +0800773 def StartUploadServer(self):
774 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800775 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800776 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800777 dirname = os.path.dirname(filepath)
778 if not os.path.exists(dirname):
779 try:
780 os.makedirs(dirname)
781 except Exception:
782 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800783
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800784 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800785 if self._file_op[2]:
786 os.fchmod(f.fileno(), self._file_op[2])
787
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800788 f.write(self._sock.RecvBuf())
789
Wei-Ning Huange2981862015-08-03 15:03:08 +0800790 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800791 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800792 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800793 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800794 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800795 break
796 f.write(buf)
797 except socket.error as e:
798 logging.error('StartUploadServer: socket error: %s', e)
799 except Exception as e:
800 logging.error('StartUploadServer: %s', e)
801 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800802 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800803
804 logging.info('StartUploadServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800805 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huange2981862015-08-03 15:03:08 +0800806
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800807 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800808 """Spawn a port forwarding server and forward I/O to the TCP socket."""
809 logging.info('SpawnPortForwardServer: started')
810
811 src_sock = None
812 try:
813 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800814 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800815 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800816
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800817 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800818
819 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800820 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800821
822 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800823 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800824 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800825 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800826 src_sock.send(data)
827
828 if src_sock in rd:
829 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800830 if not data:
Yilin Yang969b8012020-12-16 14:38:00 +0800831 continue
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800832 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800833 except Exception as e:
834 logging.error('SpawnPortForwardServer: %s', e)
835 finally:
836 if src_sock:
837 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800838 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800839
840 logging.info('SpawnPortForwardServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800841 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800842
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800843 def Ping(self):
844 def timeout_handler(x):
845 if x is None:
846 raise PingTimeoutError
847
848 self._last_ping = self.Timestamp()
849 self.SendRequest('ping', {}, timeout_handler, 5)
850
Wei-Ning Huangae923642015-09-24 14:08:09 +0800851 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800852 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800853 filepath = params['filename']
854 if not os.path.isabs(filepath):
855 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
856
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800857 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800858 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800859 pass
860 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800861 self.SendResponse(msg, str(e))
862 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800863
864 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800865 file_op=('download', filepath))
866 self.SendResponse(msg, SUCCESS)
867
868 def HandleFileUploadRequest(self, msg):
869 params = msg['params']
870
871 # Resolve upload filepath
872 filename = params['filename']
873 dest_path = filename
874
875 # If dest is specified, use it first
876 dest_path = params.get('dest', '')
877 if dest_path:
878 if not os.path.isabs(dest_path):
879 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
880
881 if os.path.isdir(dest_path):
882 dest_path = os.path.join(dest_path, filename)
883 else:
884 target_dir = os.getenv('HOME', '/tmp')
885
886 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800887 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800888 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
889 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800890 try:
891 target_dir = self.GetProcessWorkingDirectory(pid)
892 except Exception as e:
893 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800894
895 dest_path = os.path.join(target_dir, filename)
896
897 try:
898 os.makedirs(os.path.dirname(dest_path))
899 except Exception:
900 pass
901
902 try:
903 with open(dest_path, 'w') as _:
904 pass
905 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800906 self.SendResponse(msg, str(e))
907 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800908
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800909 # If not check_only, spawn FILE mode ghost agent to handle upload
910 if not params.get('check_only', False):
911 self.SpawnGhost(self.FILE, params['sid'],
912 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800913 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800914
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800915 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800916 command = msg['name']
917 params = msg['params']
918
919 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800920 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800921 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800922 self.SpawnGhost(self.TERMINAL, params['sid'],
923 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800924 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800925 elif command == 'shell':
926 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800927 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800928 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800929 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800930 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800931 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800932 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800933 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800934 elif command == 'forward':
935 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
936 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800937
938 def HandleResponse(self, response):
939 rid = str(response['rid'])
940 if rid in self._requests:
941 handler = self._requests[rid][2]
942 del self._requests[rid]
943 if callable(handler):
944 handler(response)
945 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800946 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800947
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800948 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800949 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800950 try:
951 index = buf.index(_SEPARATOR)
952 except ValueError:
953 self._sock.UnRecv(buf)
954 return
955
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800956 msgs_json = [buf[:index]]
957 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800958 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800959 msgs_json = buf.split(_SEPARATOR)
960 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800961
962 for msg_json in msgs_json:
963 try:
964 msg = json.loads(msg_json)
965 except ValueError:
966 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800967 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800968 continue
969
970 if 'name' in msg:
971 self.HandleRequest(msg)
972 elif 'response' in msg:
973 self.HandleResponse(msg)
974 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800975 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800976
977 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800978 """Scans for pending requests which have timed out.
979
980 If any timed-out requests are discovered, their handler is called with the
981 special response value of None.
982 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800983 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800984 request_time, timeout, handler = self._requests[rid]
985 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800986 if callable(handler):
987 handler(None)
988 else:
989 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800990 del self._requests[rid]
991
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800992 def InitiateDownload(self):
993 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800994 sid = self._ttyname_to_sid[ttyname]
995 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800996 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800997
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800998 def Listen(self):
999 try:
1000 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001001 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +08001002 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001003
1004 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001005 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001006
1007 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +08001008 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001009 break
1010
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001011 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001012
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001013 if (self._mode == self.AGENT and
1014 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001015 self.Ping()
1016 self.ScanForTimeoutRequests()
1017
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001018 if not self._download_queue.empty():
1019 self.InitiateDownload()
1020
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001021 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001022 break
1023 except socket.error:
1024 raise RuntimeError('Connection dropped')
1025 except PingTimeoutError:
1026 raise RuntimeError('Connection timeout')
1027 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001028 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001029
1030 self._queue.put('resume')
1031
1032 if self._mode != Ghost.AGENT:
1033 sys.exit(1)
1034
1035 def Register(self):
1036 non_local = {}
1037 for addr in self._overlord_addrs:
1038 non_local['addr'] = addr
1039 def registered(response):
1040 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001041 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001042 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001043
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001044 self._register_status = response['response']
1045 if response['response'] != SUCCESS:
1046 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001047 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001048
1049 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1050 self._connected_addr = non_local['addr']
1051 self.Upgrade() # Check for upgrade
1052 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001053
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001054 try:
1055 logging.info('Trying %s:%d ...', *addr)
1056 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001057
Peter Shih220a96d2016-12-22 17:02:16 +08001058 # Check if server has TLS enabled. Only check if self._tls_mode is
1059 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001060 # Only control channel needs to determine if TLS is enabled. Other mode
1061 # should use the TLSSettings passed in when it was spawned.
1062 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001063 self._tls_settings.SetEnabled(
1064 self.TLSEnabled(*addr) if self._tls_mode is None
1065 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001066
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001067 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1068 sock.settimeout(_CONNECT_TIMEOUT)
1069
1070 try:
1071 if self._tls_settings.Enabled():
1072 tls_context = self._tls_settings.Context()
1073 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1074
1075 sock.connect(addr)
1076 except (ssl.SSLError, ssl.CertificateError) as e:
1077 logging.error('%s: %s', e.__class__.__name__, e)
1078 continue
1079 except IOError as e:
1080 if e.errno == 2: # No such file or directory
1081 logging.error('%s: %s', e.__class__.__name__, e)
1082 continue
1083 raise
1084
1085 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001086
1087 logging.info('Connection established, registering...')
1088 handler = {
1089 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001090 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001091 Ghost.SHELL: self.SpawnShellServer,
1092 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001093 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001094 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001095
1096 # Machine ID may change if MAC address is used (USB-ethernet dongle
1097 # plugged/unplugged)
1098 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001099 self.SendRequest('register',
1100 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001101 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001102 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001103 except socket.error:
1104 pass
1105 else:
Yilin Yangcb5e8922020-12-16 10:30:44 +08001106 # We only send dut data when it's agent mode.
1107 if self._mode == Ghost.AGENT:
1108 self.SendData()
Yilin Yang89a136c2021-01-05 15:25:05 +08001109 if self._track_connection is not None:
1110 self.TrackConnection(self._track_connection,
1111 self._track_connection_timeout_secs)
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001112 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001113 self.Listen()
1114
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001115 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001116
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001117 def Reconnect(self):
1118 logging.info('Received reconnect request from RPC server, reconnecting...')
1119 self._reset.set()
1120
Yilin Yang64dd8592020-11-10 16:16:23 +08001121 def CollectPytestAndStatus(self):
1122 STATUS = Enum(['failed', 'running', 'idle'])
1123 goofy = state.GetInstance()
1124 tests = goofy.GetTests()
1125
1126 # Ignore parents
1127 tests = [x for x in tests if not x.get('parent')]
1128
1129 scheduled_tests = (
1130 goofy.GetTestRunStatus(None).get('scheduled_tests') or [])
1131 scheduled_tests = {t['path']
1132 for t in scheduled_tests}
1133 tests = [x for x in tests if x['path'] in scheduled_tests]
1134 data = {
1135 'pytest': '',
1136 'status': STATUS.idle
1137 }
1138
1139 def parse_pytest_name(test):
1140 # test['path'] format: 'test_list_name:pytest_name'
1141 return test['path'][test['path'].index(':') + 1:]
1142
1143 for test in filter(lambda t: t['status'] == TestState.ACTIVE, tests):
1144 data['pytest'] = parse_pytest_name(test)
1145 data['status'] = STATUS.running
1146 return data
1147
1148 for test in filter(lambda t: t['status'] == TestState.FAILED, tests):
1149 data['pytest'] = parse_pytest_name(test)
1150 data['status'] = STATUS.failed
1151 return data
1152
1153 if tests:
1154 data['pytest'] = parse_pytest_name(tests[0])
1155
1156 return data
1157
1158 def CollectModelName(self):
1159 return {
1160 'model': cros_config_module.CrosConfig().GetModelName()
1161 }
1162
1163 def CollectIP(self):
1164 ip_addrs = []
1165 for interface in net_utils.GetNetworkInterfaces():
1166 ip = net_utils.GetEthernetIp(interface)[0]
1167 if ip:
1168 ip_addrs.append(ip)
1169
1170 return {
1171 'ip': ip_addrs
1172 }
1173
1174 def CollectData(self):
1175 """Collect dut data.
1176
1177 Data includes:
1178 1. status: Current test status
1179 2. pytest: Current pytest
1180 3. model: Model name
1181 4. ip: IP
1182 """
1183 data = {}
1184 data.update(self.CollectPytestAndStatus())
1185 data.update(self.CollectModelName())
1186 data.update(self.CollectIP())
1187
1188 return data
1189
1190 def SendData(self):
1191 if not sys_utils.InCrOSDevice():
1192 return
1193
1194 data = self.CollectData()
1195 logging.info('data = %s', data)
1196
1197 self.SendRequest('update_dut_data', data)
1198
Yilin Yang90c60c42020-11-11 14:45:08 +08001199 def TrackConnection(self, enabled, timeout_secs):
1200 logging.info('TrackConnection, enabled = %s, timeout_secs = %d', enabled,
1201 timeout_secs)
1202
Yilin Yang89a136c2021-01-05 15:25:05 +08001203 self._track_connection = enabled
1204 self._track_connection_timeout_secs = timeout_secs
Yilin Yang90c60c42020-11-11 14:45:08 +08001205 self.SendRequest('track_connection', {
1206 'enabled': enabled,
1207 'timeout_secs': timeout_secs
1208 })
1209
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001210 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001211 status = self._register_status
1212 if self._register_status == SUCCESS:
1213 ip, port = self._sock.sock.getpeername()
1214 status += ' %s:%d' % (ip, port)
1215 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001216
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001217 def AddToDownloadQueue(self, ttyname, filename):
1218 self._download_queue.put((ttyname, filename))
1219
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001220 def RegisterTTY(self, session_id, ttyname):
1221 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001222
1223 def RegisterSession(self, session_id, process_id):
1224 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001225
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001226 def StartLanDiscovery(self):
1227 """Start to listen to LAN discovery packet at
1228 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001229
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001230 def thread_func():
1231 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1232 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1233 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001234 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001235 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1236 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001237 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001238 return
1239
1240 logging.info('LAN Discovery: started')
1241 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001242 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001243
1244 if s in rd:
1245 data, source_addr = s.recvfrom(_BUFSIZE)
1246 parts = data.split()
1247 if parts[0] == 'OVERLORD':
1248 ip, port = parts[1].split(':')
1249 if not ip:
1250 ip = source_addr[0]
1251 self._queue.put((ip, int(port)), True)
1252
1253 try:
1254 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001255 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001256 pass
1257 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001258 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001259 self._queue.put(obj)
1260 elif obj == 'pause':
1261 logging.info('LAN Discovery: paused')
1262 while obj != 'resume':
1263 obj = self._queue.get(True)
1264 logging.info('LAN Discovery: resumed')
1265
1266 t = threading.Thread(target=thread_func)
1267 t.daemon = True
1268 t.start()
1269
1270 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001271 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001272 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1273 logRequests=False)
Yilin Yang64dd8592020-11-10 16:16:23 +08001274 rpc_server.register_function(self.SendData, 'SendData')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001275 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001276 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001277 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001278 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Yilin Yang90c60c42020-11-11 14:45:08 +08001279 rpc_server.register_function(self.TrackConnection, 'TrackConnection')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001280 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001281 t = threading.Thread(target=rpc_server.serve_forever)
1282 t.daemon = True
1283 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001284
Yilin Yang1512d972020-11-19 13:34:42 +08001285 def ApplyTestListParams(self):
1286 mgr = manager.Manager()
Cheng Yueh59a29662020-12-02 12:20:18 +08001287 device = sys_interface.SystemInterface()
1288 constants = mgr.GetTestListByID(mgr.GetActiveTestListId(device)).constants
Yilin Yang1512d972020-11-19 13:34:42 +08001289
1290 if 'overlord' not in constants:
1291 return
1292
1293 if 'overlord_urls' in constants['overlord']:
1294 for addr in [(x, _OVERLORD_PORT) for x in
1295 constants['overlord']['overlord_urls']]:
1296 if addr not in self._overlord_addrs:
1297 self._overlord_addrs.append(addr)
1298
1299 # This is sugar for ODM to turn off the verification quickly if they forgot.
1300 # So we don't support to turn on again.
1301 # If we want to turn on, we need to restart the ghost daemon.
1302 if 'tls_no_verify' in constants['overlord']:
1303 if constants['overlord']['tls_no_verify']:
1304 self._tls_settings = TLSSettings(None, False)
1305
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001306 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001307 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001308 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1309 if addr not in self._overlord_addrs:
1310 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001311
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001312 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001313 logging.info('%s started', self.MODE_NAME[self._mode])
1314 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001315 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001316
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001317 # We don't care about child process's return code, not wait is needed. This
1318 # is used to prevent zombie process from lingering in the system.
1319 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001320
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001321 if lan_disc:
1322 self.StartLanDiscovery()
1323
1324 if rpc_server:
1325 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001326
1327 try:
1328 while True:
1329 try:
1330 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001331 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001332 pass
1333 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001334 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001335 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1336 self._overlord_addrs.append(addr)
1337
Yilin Yang1512d972020-11-19 13:34:42 +08001338 if self._mode == Ghost.AGENT:
1339 self.ApplyTestListParams()
1340
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001341 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001342 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001343 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001344 # Don't show stack trace for RuntimeError, which we use in this file for
1345 # plausible and expected errors (such as can't connect to server).
1346 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001347 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001348 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001349 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001350 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001351 traceback.print_tb(exc_traceback)
1352 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001353 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001354 time.sleep(_RETRY_INTERVAL)
1355
1356 self.Reset()
1357 except KeyboardInterrupt:
1358 logging.error('Received keyboard interrupt, quit')
1359 sys.exit(0)
1360
1361
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001362def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001363 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001364 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1365
1366
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001367def ForkToBackground():
1368 """Fork process to run in background."""
1369 pid = os.fork()
1370 if pid != 0:
1371 logging.info('Ghost(%d) running in background.', pid)
1372 sys.exit(0)
1373
1374
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001375def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001376 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001377 filepath = os.path.abspath(filename)
1378 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001379 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001380 sys.exit(1)
1381
1382 # Check if we actually have permission to read the file
1383 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001384 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001385 sys.exit(1)
1386
1387 server = GhostRPCServer()
1388 server.AddToDownloadQueue(os.ttyname(0), filepath)
1389 sys.exit(0)
1390
1391
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001392def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001393 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001394 logger = logging.getLogger()
1395 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001396 handler = logging.StreamHandler()
1397 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1398 handler.setFormatter(formatter)
1399 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001400
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001401 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001402 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1403 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001404 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1405 default=None, help='use MID as machine ID')
1406 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1407 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001408 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1409 default=True, help='disable LAN discovery')
1410 parser.add_argument('--no-rpc-server', dest='rpc_server',
1411 action='store_false', default=True,
1412 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001413 parser.add_argument('--tls', dest='tls_mode', default='detect',
1414 choices=('y', 'n', 'detect'),
1415 help="specify 'y' or 'n' to force enable/disable TLS")
Yilin Yang64dd8592020-11-10 16:16:23 +08001416 parser.add_argument(
1417 '--tls-cert-file', metavar='TLS_CERT_FILE', dest='tls_cert_file',
1418 type=str, default=None,
1419 help='file containing the server TLS certificate in PEM '
1420 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001421 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1422 action='store_true', default=False,
1423 help='do not verify certificate if TLS is enabled')
Yilin Yang64dd8592020-11-10 16:16:23 +08001424 parser.add_argument(
1425 '--prop-file', metavar='PROP_FILE', dest='prop_file', type=str,
1426 default=None, help='file containing the JSON representation of client '
1427 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001428 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1429 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001430 parser.add_argument('--reset', dest='reset', default=False,
1431 action='store_true',
1432 help='reset ghost and reload all configs')
Yilin Yang64dd8592020-11-10 16:16:23 +08001433 parser.add_argument('--send-data', dest='send_data', default=False,
1434 action='store_true',
1435 help='send client data to overlord server')
Peter Shih5cafebb2017-06-30 16:36:22 +08001436 parser.add_argument('--status', dest='status', default=False,
1437 action='store_true',
1438 help='show status of the client')
Yilin Yang90c60c42020-11-11 14:45:08 +08001439 parser.add_argument('--track-connection', dest='track_connection',
1440 default=None, choices=('y', 'n'),
1441 help="specify 'y' or 'n' to track connection or not")
1442 parser.add_argument('--timeout-seconds', dest='timeout_secs', type=int,
1443 default=900,
1444 help='timeout seconds when track the connection')
Yilin Yang64dd8592020-11-10 16:16:23 +08001445 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str, nargs='*',
1446 help='overlord server address')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001447 args = parser.parse_args()
1448
Peter Shih5cafebb2017-06-30 16:36:22 +08001449 if args.status:
1450 print(GhostRPCServer().GetStatus())
1451 sys.exit()
1452
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001453 if args.fork:
1454 ForkToBackground()
1455
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001456 if args.reset:
1457 GhostRPCServer().Reconnect()
1458 sys.exit()
1459
Yilin Yang64dd8592020-11-10 16:16:23 +08001460 if args.send_data:
1461 GhostRPCServer().SendData()
1462 sys.exit()
1463
Yilin Yang90c60c42020-11-11 14:45:08 +08001464 if args.track_connection:
1465 GhostRPCServer().TrackConnection(args.track_connection == 'y',
1466 args.timeout_secs)
1467 sys.exit()
1468
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001469 if args.download:
1470 DownloadFile(args.download)
1471
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001472 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001473 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001474
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001475 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1476
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001477 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001478 tls_mode = args.tls_mode
1479 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001480 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001481 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001482 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001483
1484
1485if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001486 try:
1487 main()
1488 except Exception as e:
1489 logging.error(e)