blob: 767629c03d1bf98871e071f7f891461c4ab9651e [file] [log] [blame]
Fang Deng5d518f42013-08-02 14:04:32 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4#
5# Expects to be run in an environment with sudo and no interactive password
6# prompt, such as within the Chromium OS development chroot.
7
8
9"""This file provides core logic for servo verify/repair process."""
10
11
Fang Deng5d518f42013-08-02 14:04:32 -070012import logging
Raul E Rangel52ca2e82018-07-03 14:10:14 -060013import os
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -080014import re
15import tarfile
Garry Wangc1288cf2019-12-17 14:58:00 -080016import time
Gregory Nisbet265a52c2019-12-10 20:38:42 -080017import traceback
Dana Goyette4dc0adc2019-05-06 14:51:53 -070018import xmlrpclib
Fang Deng5d518f42013-08-02 14:04:32 -070019
20from autotest_lib.client.bin import utils
Garry Wang79e9af62019-06-12 15:19:19 -070021from autotest_lib.client.common_lib import error
beeps5e8c45a2013-12-17 22:05:11 -080022from autotest_lib.client.common_lib import global_config
Richard Barnette9a26ad62016-06-10 12:03:08 -070023from autotest_lib.client.common_lib import hosts
Fang Deng5d518f42013-08-02 14:04:32 -070024from autotest_lib.client.common_lib.cros import retry
Christopher Wileycef1f902014-06-19 11:11:23 -070025from autotest_lib.client.common_lib.cros.network import ping_runner
Richard Barnette9a26ad62016-06-10 12:03:08 -070026from autotest_lib.server.cros.servo import servo
Richard Barnetted31580e2018-05-14 19:58:00 +000027from autotest_lib.server.hosts import servo_repair
Garry Wangebc015b2019-06-06 17:45:06 -070028from autotest_lib.server.hosts import base_servohost
Dan Shi5e2efb72017-02-07 11:40:23 -080029
Fang Deng5d518f42013-08-02 14:04:32 -070030
Simran Basi0739d682015-02-25 16:22:56 -080031# Names of the host attributes in the database that represent the values for
32# the servo_host and servo_port for a servo connected to the DUT.
33SERVO_HOST_ATTR = 'servo_host'
34SERVO_PORT_ATTR = 'servo_port'
Richard Barnettee519dcd2016-08-15 17:37:17 -070035SERVO_BOARD_ATTR = 'servo_board'
Nick Sanders2f3c9852018-10-24 12:10:24 -070036# Model is inferred from host labels.
37SERVO_MODEL_ATTR = 'servo_model'
Kevin Cheng643ce8a2016-09-15 15:42:12 -070038SERVO_SERIAL_ATTR = 'servo_serial'
Prathmesh Prabhucba44292018-08-28 17:44:45 -070039SERVO_ATTR_KEYS = (
40 SERVO_BOARD_ATTR,
41 SERVO_HOST_ATTR,
42 SERVO_PORT_ATTR,
43 SERVO_SERIAL_ATTR,
44)
Simran Basi0739d682015-02-25 16:22:56 -080045
Garry Wangc1288cf2019-12-17 14:58:00 -080046# Timeout value for stop/start servod process.
47SERVOD_TEARDOWN_TIMEOUT = 3
48SERVOD_QUICK_STARTUP_TIMEOUT = 20
49SERVOD_STARTUP_TIMEOUT = 60
50
Garry Wangd7367482020-02-27 13:52:40 -080051# pools that support dual v4. (go/cros-fw-lab-strategy)
52POOLS_SUPPORT_DUAL_V4 = {'faft-cr50',
53 'faft-cr50-experimental',
54 'faft-cr50-tot',
55 'faft-cr50-debug',
56 'faft_cr50_debug'
57 'faft-pd-debug',
58 'faft_pd_debug'}
59
Dan Shi3b2adf62015-09-02 17:46:54 -070060_CONFIG = global_config.global_config
xixuan6cf6d2f2016-01-29 15:29:00 -080061ENABLE_SSH_TUNNEL_FOR_SERVO = _CONFIG.get_config_value(
62 'CROS', 'enable_ssh_tunnel_for_servo', type=bool, default=False)
Simran Basi0739d682015-02-25 16:22:56 -080063
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070064AUTOTEST_BASE = _CONFIG.get_config_value(
65 'SCHEDULER', 'drone_installation_directory',
66 default='/usr/local/autotest')
67
Otabek Kasimovcc9738e2020-02-14 16:17:15 -080068SERVO_STATE_LABEL_PREFIX = 'servo_state'
69SERVO_STATE_WORKING = 'WORKING'
70SERVO_STATE_BROKEN = 'BROKEN'
Otabek Kasimov7267a7a2020-03-04 11:18:45 -080071SERVO_STATE_NOT_CONNECTED = 'NOT_CONNECTED'
72SERVO_STATE_UNKNOWN = 'UNKNOWN'
Fang Deng5d518f42013-08-02 14:04:32 -070073
Garry Wangebc015b2019-06-06 17:45:06 -070074class ServoHost(base_servohost.BaseServoHost):
75 """Host class for a servo host(e.g. beaglebone, labstation)
Dana Goyette0b6e6402019-10-04 11:09:24 -070076 that with a servo instance for a specific port.
77
78 @type _servo: servo.Servo | None
79 """
Fang Deng5d518f42013-08-02 14:04:32 -070080
Raul E Rangel52ca2e82018-07-03 14:10:14 -060081 DEFAULT_PORT = int(os.getenv('SERVOD_PORT', '9999'))
Richard Barnette9a26ad62016-06-10 12:03:08 -070082
Dan Shie5b3c512014-08-21 12:12:09 -070083 # Timeout for initializing servo signals.
Wai-Hong Tam37b6ed32017-09-19 15:52:39 -070084 INITIALIZE_SERVO_TIMEOUT_SECS = 60
Richard Barnette9a26ad62016-06-10 12:03:08 -070085
xixuan6cf6d2f2016-01-29 15:29:00 -080086 # Ready test function
87 SERVO_READY_METHOD = 'get_version'
Fang Deng5d518f42013-08-02 14:04:32 -070088
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -080089 # Directory prefix on the servo host where the servod logs are stored.
90 SERVOD_LOG_PREFIX = '/var/log/servod'
91
92 # Exit code to use when symlinks for servod logs are not found.
93 NO_SYMLINKS_CODE = 9
94
95 # Directory in the job's results directory to dump the logs into.
96 LOG_DIR = 'servod'
97
98 # Prefix for joint loglevel files in the logs.
99 JOINT_LOG_PREFIX = 'log'
100
101 # Regex group to extract timestamp from logfile name.
102 TS_GROUP = 'ts'
103
104 # This regex is used to extract the timestamp from servod logs.
105 # files always start with log.
106 TS_RE = (r'log.'
107 # The timestamp is of format %Y-%m-%d--%H-%M-%S.MS
108 r'(?P<%s>\d{4}(\-\d{2}){2}\-(-\d{2}){3}.\d{3})'
109 # The loglevel is optional depending on labstation version.
110 r'(.(INFO|DEBUG|WARNING))?' % TS_GROUP)
111 TS_EXTRACTOR = re.compile(TS_RE)
112
113 # Regex group to extract MCU name from logline in servod logs.
114 MCU_GROUP = 'mcu'
115
116 # Regex group to extract logline from MCU logline in servod logs.
117 LINE_GROUP = 'line'
118
119 # This regex is used to extract the mcu and the line content from an
120 # MCU logline in servod logs. e.g. EC or servo_v4 console logs.
121 # Here is an example log-line:
122 #
123 # 2020-01-23 13:15:12,223 - servo_v4 - EC3PO.Console - DEBUG -
124 # console.py:219:LogConsoleOutput - /dev/pts/9 - cc polarity: cc1
125 #
126 # Here is conceptually how they are formatted:
127 #
128 # <time> - <MCU> - EC3PO.Console - <LVL> - <file:line:func> - <pts> -
129 # <output>
130 #
131 # The log format starts with a timestamp
132 MCU_RE = (r'[\d\-]+ [\d:,]+ '
133 # The mcu that is logging this is next.
134 r'- (?P<%s>\w+) - '
135 # Next, we have more log outputs before the actual line.
136 # Information about the file line, logging function etc.
137 # Anchor on EC3PO Console, LogConsoleOutput and dev/pts.
138 # NOTE: if the log format changes, this regex needs to be
139 # adjusted.
140 r'EC3PO\.Console[\s\-\w\d:.]+LogConsoleOutput - /dev/pts/\d+ - '
141 # Lastly, we get the MCU's console line.
142 r'(?P<%s>.+$)' % (MCU_GROUP, LINE_GROUP))
143 MCU_EXTRACTOR = re.compile(MCU_RE)
144
145 # Suffix to identify compressed logfiles.
146 COMPRESSION_SUFFIX = '.tbz2'
147
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800148 def _init_attributes(self):
149 self._servo_state = None
150 self.servo_port = None
151 self.servo_board = None
152 self.servo_model = None
153 self.servo_serial = None
154 self._servo = None
155 self._servod_server_proxy = None
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800156 # Flag to make sure that multiple calls to close do not result in the
157 # logic executing multiple times.
158 self._closed = False
Fang Deng5d518f42013-08-02 14:04:32 -0700159
Richard Barnette17bfc6c2016-08-04 18:41:43 -0700160 def _initialize(self, servo_host='localhost',
Richard Barnettee519dcd2016-08-15 17:37:17 -0700161 servo_port=DEFAULT_PORT, servo_board=None,
Nick Sanders2f3c9852018-10-24 12:10:24 -0700162 servo_model=None, servo_serial=None, is_in_lab=None,
163 *args, **dargs):
Fang Deng5d518f42013-08-02 14:04:32 -0700164 """Initialize a ServoHost instance.
165
166 A ServoHost instance represents a host that controls a servo.
167
168 @param servo_host: Name of the host where the servod process
169 is running.
Raul E Rangel52ca2e82018-07-03 14:10:14 -0600170 @param servo_port: Port the servod process is listening on. Defaults
171 to the SERVOD_PORT environment variable if set,
172 otherwise 9999.
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700173 @param servo_board: Board that the servo is connected to.
Nick Sanders2f3c9852018-10-24 12:10:24 -0700174 @param servo_model: Model that the servo is connected to.
Dan Shi4d478522014-02-14 13:46:32 -0800175 @param is_in_lab: True if the servo host is in Cros Lab. Default is set
176 to None, for which utils.host_is_in_lab_zone will be
177 called to check if the servo host is in Cros lab.
Fang Deng5d518f42013-08-02 14:04:32 -0700178
179 """
180 super(ServoHost, self)._initialize(hostname=servo_host,
Garry Wangebc015b2019-06-06 17:45:06 -0700181 is_in_lab=is_in_lab, *args, **dargs)
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800182 self._init_attributes()
Richard Barnette42f4db92018-08-23 15:05:15 -0700183 self.servo_port = int(servo_port)
Richard Barnettee519dcd2016-08-15 17:37:17 -0700184 self.servo_board = servo_board
Nick Sanders2f3c9852018-10-24 12:10:24 -0700185 self.servo_model = servo_model
Kevin Cheng643ce8a2016-09-15 15:42:12 -0700186 self.servo_serial = servo_serial
Wai-Hong Tam3a8a2552019-11-19 14:28:04 +0800187
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800188 # The location of the log files on the servo host for this instance.
189 self.remote_log_dir = '%s_%s' % (self.SERVOD_LOG_PREFIX,
190 self.servo_port)
Garry Wang79e9af62019-06-12 15:19:19 -0700191 # Path of the servo host lock file.
192 self._lock_file = (self.TEMP_FILE_DIR + str(self.servo_port)
193 + self.LOCK_FILE_POSTFIX)
194 # File path to declare a reboot request.
195 self._reboot_file = (self.TEMP_FILE_DIR + str(self.servo_port)
196 + self.REBOOT_FILE_POSTFIX)
197
198 # Lock the servo host if it's an in-lab labstation to prevent other
199 # task to reboot it until current task completes. We also wait and
200 # make sure the labstation is up here, in the case of the labstation is
201 # in the middle of reboot.
Garry Wang7c00b0f2019-06-25 17:28:17 -0700202 self._is_locked = False
Garry Wang42b4d862019-06-25 15:50:49 -0700203 if (self.wait_up(self.REBOOT_TIMEOUT) and self.is_in_lab()
204 and self.is_labstation()):
Garry Wang79e9af62019-06-12 15:19:19 -0700205 self._lock()
Garry Wangebc015b2019-06-06 17:45:06 -0700206
Richard Barnette9a26ad62016-06-10 12:03:08 -0700207 self._repair_strategy = (
208 servo_repair.create_servo_repair_strategy())
Richard Barnettee519dcd2016-08-15 17:37:17 -0700209
Richard Barnette9a26ad62016-06-10 12:03:08 -0700210 def connect_servo(self):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700211 """Establish a connection to the servod server on this host.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700212
213 Initializes `self._servo` and then verifies that all network
214 connections are working. This will create an ssh tunnel if
215 it's required.
216
217 As a side effect of testing the connection, all signals on the
218 target servo are reset to default values, and the USB stick is
219 set to the neutral (off) position.
220 """
Kevin Cheng643ce8a2016-09-15 15:42:12 -0700221 servo_obj = servo.Servo(servo_host=self, servo_serial=self.servo_serial)
Kuang-che Wu05763f52019-08-30 16:48:21 +0800222 self._servo = servo_obj
Richard Barnette9a26ad62016-06-10 12:03:08 -0700223 timeout, _ = retry.timeout(
224 servo_obj.initialize_dut,
225 timeout_sec=self.INITIALIZE_SERVO_TIMEOUT_SECS)
226 if timeout:
227 raise hosts.AutoservVerifyError(
228 'Servo initialize timed out.')
Richard Barnette9a26ad62016-06-10 12:03:08 -0700229
230
231 def disconnect_servo(self):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700232 """Disconnect our servo if it exists.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700233
234 If we've previously successfully connected to our servo,
235 disconnect any established ssh tunnel, and set `self._servo`
236 back to `None`.
237 """
238 if self._servo:
239 # N.B. This call is safe even without a tunnel:
240 # rpc_server_tracker.disconnect() silently ignores
241 # unknown ports.
242 self.rpc_server_tracker.disconnect(self.servo_port)
243 self._servo = None
Fang Deng5d518f42013-08-02 14:04:32 -0700244
Garry Wangc1288cf2019-12-17 14:58:00 -0800245
Wai-Hong Tam3a8a2552019-11-19 14:28:04 +0800246 def _create_servod_server_proxy(self):
247 """Create a proxy that can be used to communicate with servod server.
Fang Deng5d518f42013-08-02 14:04:32 -0700248
249 @returns: An xmlrpclib.ServerProxy that is connected to the servod
250 server on the host.
Fang Deng5d518f42013-08-02 14:04:32 -0700251 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700252 if ENABLE_SSH_TUNNEL_FOR_SERVO and not self.is_localhost():
253 return self.rpc_server_tracker.xmlrpc_connect(
254 None, self.servo_port,
255 ready_test_name=self.SERVO_READY_METHOD,
Allen Li2b1a8992018-11-27 14:17:18 -0800256 timeout_seconds=60,
Allen Li556f4532018-12-03 18:11:23 -0800257 request_timeout_seconds=3600)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700258 else:
259 remote = 'http://%s:%s' % (self.hostname, self.servo_port)
260 return xmlrpclib.ServerProxy(remote)
Fang Deng5d518f42013-08-02 14:04:32 -0700261
262
Wai-Hong Tam3a8a2552019-11-19 14:28:04 +0800263 def get_servod_server_proxy(self):
264 """Return a cached proxy if exists; otherwise, create a new one.
265
266 @returns: An xmlrpclib.ServerProxy that is connected to the servod
267 server on the host.
268 """
269 # Single-threaded execution, no race
270 if self._servod_server_proxy is None:
271 self._servod_server_proxy = self._create_servod_server_proxy()
272 return self._servod_server_proxy
273
274
Richard Barnette1edbb162016-11-01 11:47:50 -0700275 def verify(self, silent=False):
276 """Update the servo host and verify it's in a good state.
277
278 @param silent If true, suppress logging in `status.log`.
279 """
Richard Barnetteabbdc252018-07-26 16:57:42 -0700280 message = 'Beginning verify for servo host %s port %s serial %s'
281 message %= (self.hostname, self.servo_port, self.servo_serial)
282 self.record('INFO', None, None, message)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700283 try:
Richard Barnette1edbb162016-11-01 11:47:50 -0700284 self._repair_strategy.verify(self, silent)
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800285 self._servo_state = SERVO_STATE_WORKING
286 self.record('INFO', None, None, 'ServoHost verify set servo_state as WORKING')
Richard Barnette9a26ad62016-06-10 12:03:08 -0700287 except:
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800288 self._servo_state = SERVO_STATE_BROKEN
289 self.record('INFO', None, None, 'ServoHost verify set servo_state as BROKEN')
Richard Barnette9a26ad62016-06-10 12:03:08 -0700290 self.disconnect_servo()
Garry Wangc1288cf2019-12-17 14:58:00 -0800291 self.stop_servod()
Richard Barnette9a26ad62016-06-10 12:03:08 -0700292 raise
Fang Deng5d518f42013-08-02 14:04:32 -0700293
294
Richard Barnette1edbb162016-11-01 11:47:50 -0700295 def repair(self, silent=False):
296 """Attempt to repair servo host.
297
298 @param silent If true, suppress logging in `status.log`.
299 """
Richard Barnetteabbdc252018-07-26 16:57:42 -0700300 message = 'Beginning repair for servo host %s port %s serial %s'
301 message %= (self.hostname, self.servo_port, self.servo_serial)
302 self.record('INFO', None, None, message)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700303 try:
Richard Barnette1edbb162016-11-01 11:47:50 -0700304 self._repair_strategy.repair(self, silent)
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800305 self._servo_state = SERVO_STATE_WORKING
306 self.record('INFO', None, None, 'ServoHost repair set servo_state as WORKING')
Garry Wang464ff1e2019-07-18 17:20:34 -0700307 # If target is a labstation then try to withdraw any existing
308 # reboot request created by this servo because it passed repair.
309 if self.is_labstation():
310 self.withdraw_reboot_request()
Richard Barnette9a26ad62016-06-10 12:03:08 -0700311 except:
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800312 self._servo_state = SERVO_STATE_BROKEN
313 self.record('INFO', None, None, 'ServoHost repair set servo_state as BROKEN')
Richard Barnette9a26ad62016-06-10 12:03:08 -0700314 self.disconnect_servo()
Garry Wangc1288cf2019-12-17 14:58:00 -0800315 self.stop_servod()
Richard Barnette9a26ad62016-06-10 12:03:08 -0700316 raise
Fang Deng5d518f42013-08-02 14:04:32 -0700317
318
Dan Shi4d478522014-02-14 13:46:32 -0800319 def get_servo(self):
320 """Get the cached servo.Servo object.
Fang Deng5d518f42013-08-02 14:04:32 -0700321
Dan Shi4d478522014-02-14 13:46:32 -0800322 @return: a servo.Servo object.
Dana Goyette353d1d92019-06-27 10:43:59 -0700323 @rtype: autotest_lib.server.cros.servo.servo.Servo
Fang Deng5d518f42013-08-02 14:04:32 -0700324 """
Dan Shi4d478522014-02-14 13:46:32 -0800325 return self._servo
326
327
Garry Wang79e9af62019-06-12 15:19:19 -0700328 def request_reboot(self):
329 """Request servohost to be rebooted when it's safe to by touch a file.
330 """
331 logging.debug('Request to reboot servohost %s has been created by '
Garry Wang464ff1e2019-07-18 17:20:34 -0700332 'servo with port # %s', self.hostname, self.servo_port)
Garry Wang79e9af62019-06-12 15:19:19 -0700333 self.run('touch %s' % self._reboot_file, ignore_status=True)
334
335
Garry Wang464ff1e2019-07-18 17:20:34 -0700336 def withdraw_reboot_request(self):
337 """Withdraw a servohost reboot request if exists by remove the flag
338 file.
339 """
340 logging.debug('Withdrawing request to reboot servohost %s that created'
341 ' by servo with port # %s if exists.',
342 self.hostname, self.servo_port)
343 self.run('rm -f %s' % self._reboot_file, ignore_status=True)
344
345
Garry Wangc1288cf2019-12-17 14:58:00 -0800346 def start_servod(self, quick_startup=False):
347 """Start the servod process on servohost.
348 """
Garry Wang2ac15ee2019-12-30 19:03:02 -0800349 # Skip if running on the localhost.(crbug.com/1038168)
350 if self.is_localhost():
351 logging.debug("Servohost is a localhost, skipping start servod.")
352 return
353
354 cmd = 'start servod'
Garry Wangc1288cf2019-12-17 14:58:00 -0800355 if self.servo_board:
Garry Wang2ac15ee2019-12-30 19:03:02 -0800356 cmd += ' BOARD=%s' % self.servo_board
Garry Wangc1288cf2019-12-17 14:58:00 -0800357 if self.servo_model:
358 cmd += ' MODEL=%s' % self.servo_model
Garry Wangc1288cf2019-12-17 14:58:00 -0800359 else:
Garry Wang2ac15ee2019-12-30 19:03:02 -0800360 logging.warning('Board for DUT is unknown; starting servod'
361 ' assuming a pre-configured board.')
362
363 cmd += ' PORT=%d' % self.servo_port
364 if self.servo_serial:
365 cmd += ' SERIAL=%s' % self.servo_serial
Garry Wangd7367482020-02-27 13:52:40 -0800366
367 # Start servod with dual_v4 if the DUT/servo from designated pools.
368 dut_host_info = self.get_dut_host_info()
369 if dut_host_info:
370 if bool(dut_host_info.pools & POOLS_SUPPORT_DUAL_V4):
371 logging.debug('The DUT is detected in following designated'
372 ' pools %s,starting servod with DUAL_V4 option.',
373 POOLS_SUPPORT_DUAL_V4)
374 cmd += ' DUAL_V4=1'
375
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800376 # Remove the symbolic links from the logs. This helps ensure that
377 # a failed servod instantiation does not cause us to grab old logs
378 # by mistake.
379 self.remove_latest_log_symlinks()
Garry Wangcdd27b22020-01-13 14:59:11 -0800380 self.run(cmd, timeout=60)
Garry Wangc1288cf2019-12-17 14:58:00 -0800381
382 # There's a lag between when `start servod` completes and when
383 # the _ServodConnectionVerifier trigger can actually succeed.
384 # The call to time.sleep() below gives time to make sure that
385 # the trigger won't fail after we return.
386
387 # Normally servod on servo_v3 and labstation take ~10 seconds to ready,
388 # But in the rare case all servo on a labstation are in heavy use they
389 # may take ~30 seconds. So the timeout value will double these value,
390 # and we'll try quick start up when first time initialize servohost,
391 # and use standard start up timeout in repair.
392 if quick_startup:
393 timeout = SERVOD_QUICK_STARTUP_TIMEOUT
394 else:
395 timeout = SERVOD_STARTUP_TIMEOUT
396 logging.debug('Wait %s seconds for servod process fully up.', timeout)
397 time.sleep(timeout)
398
399
400 def stop_servod(self):
401 """Stop the servod process on servohost.
402 """
Garry Wang2ac15ee2019-12-30 19:03:02 -0800403 # Skip if running on the localhost.(crbug.com/1038168)
404 if self.is_localhost():
405 logging.debug("Servohost is a localhost, skipping stop servod.")
406 return
407
Garry Wangc1288cf2019-12-17 14:58:00 -0800408 logging.debug('Stopping servod on port %s', self.servo_port)
Garry Wangcdd27b22020-01-13 14:59:11 -0800409 self.run('stop servod PORT=%d' % self.servo_port,
410 timeout=60, ignore_status=True)
Garry Wangc1288cf2019-12-17 14:58:00 -0800411 logging.debug('Wait %s seconds for servod process fully teardown.',
412 SERVOD_TEARDOWN_TIMEOUT)
413 time.sleep(SERVOD_TEARDOWN_TIMEOUT)
414
415
416 def restart_servod(self, quick_startup=False):
417 """Restart the servod process on servohost.
418 """
419 self.stop_servod()
420 self.start_servod(quick_startup)
421
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800422 def _extract_compressed_logs(self, logdir, relevant_files):
423 """Decompress servod logs in |logdir|.
424
425 @param logdir: directory containing compressed servod logs.
426 @param relevant_files: list of files in |logdir| to consider.
427
428 @returns: tuple, (tarfiles, files) where
429 tarfiles: list of the compressed filenames that have been
430 extracted and deleted
431 files: list of the uncompressed files that were generated
432 """
433 # For all tar-files, first extract them to the directory, and
434 # then let the common flow handle them.
435 tarfiles = [cf for cf in relevant_files if
436 cf.endswith(self.COMPRESSION_SUFFIX)]
437 files = []
438 for f in tarfiles:
439 norm_name = os.path.basename(f)[:-len(self.COMPRESSION_SUFFIX)]
440 with tarfile.open(f) as tf:
441 # Each tarfile has only one member, as
442 # that's the compressed log.
443 member = tf.members[0]
444 # Manipulate so that it only extracts the basename, and not
445 # the directories etc.
446 member.name = norm_name
447 files.append(os.path.join(logdir, member.name))
448 tf.extract(member, logdir)
449 # File has been extracted: remove the compressed file.
450 os.remove(f)
451 return tarfiles, files
452
453 def _extract_mcu_logs(self, log_subdir):
454 """Extract MCU (EC, Cr50, etc) console output from servod debug logs.
455
456 Using the MCU_EXTRACTOR regex (above) extract and split out MCU console
457 lines from the logs to generate invidiual console logs e.g. after
458 this method, you can find an ec.txt and servo_v4.txt in |log_dir| if
459 those MCUs had any console input/output.
460
461 @param log_subdir: directory with log.DEBUG.txt main servod debug logs.
462 """
463 # Extract the MCU for each one. The MCU logs are only in the .DEBUG
464 # files
465 mcu_lines_file = os.path.join(log_subdir, 'log.DEBUG.txt')
466 if not os.path.exists(mcu_lines_file):
467 logging.info('No DEBUG logs found to extract MCU logs from.')
468 return
469 mcu_files = {}
470 mcu_file_template = '%s.txt'
471 with open(mcu_lines_file, 'r') as f:
472 for line in f:
473 match = self.MCU_EXTRACTOR.match(line)
474 if match:
475 mcu = match.group(self.MCU_GROUP).lower()
476 line = match.group(self.LINE_GROUP)
477 if mcu not in mcu_files:
478 mcu_file = os.path.join(log_subdir,
479 mcu_file_template % mcu)
480 mcu_files[mcu] = open(mcu_file, 'a')
481 fd = mcu_files[mcu]
482 fd.write(line + '\n')
483 for f in mcu_files:
484 mcu_files[f].close()
485
486
487 def remove_latest_log_symlinks(self):
488 """Remove the conveninence symlinks 'latest' servod logs."""
489 symlink_wildcard = '%s/latest*' % self.remote_log_dir
490 cmd = 'rm ' + symlink_wildcard
491 self.run(cmd, stderr_tee=None, ignore_status=True)
492
493 def grab_logs(self, outdir):
494 """Retrieve logs from servo_host to |outdir|/servod_{port}.{ts}/.
495
496 This method first collects all logs on the servo_host side pertaining
497 to this servod instance (port, instatiation). It glues them together
498 into combined log.[level].txt files and extracts all available MCU
499 console I/O from the logs into individual files e.g. servo_v4.txt
500
501 All the output can be found in a directory inside |outdir| that
502 this generates based on |LOG_DIR|, the servod port, and the instance
503 timestamp on the servo_host side.
504
505 @param outdir: directory to create a subdirectory into to place the
506 servod logs into.
507 """
508 # First, extract the timestamp. This cmd gives the real filename of
509 # the latest aka current log file.
510 cmd = ('if [ -f %(dir)s/latest.DEBUG ];'
511 'then realpath %(dir)s/latest.DEBUG;'
512 'elif [ -f %(dir)s/latest ];'
513 'then realpath %(dir)s/latest;'
514 'else exit %(code)d;'
515 'fi' % {'dir': self.remote_log_dir,
516 'code': self.NO_SYMLINKS_CODE})
517 res = self.run(cmd, stderr_tee=None, ignore_status=True)
518 if res.exit_status != 0:
519 if res.exit_status == self.NO_SYMLINKS_CODE:
520 logging.warning('servod log latest symlinks not found. '
521 'This is likely due to an error starting up '
522 'servod. Ignoring..')
523 else:
524 logging.warning('Failed to find servod logs on servo host.')
525 logging.warning(res.stderr.strip())
526 return
527 fname = os.path.basename(res.stdout.strip())
528 # From the fname, ought to extract the timestamp using the TS_EXTRACTOR
Ruben Rodriguez Buchillone9aa2b02020-03-04 12:14:28 -0800529 ts_match = self.TS_EXTRACTOR.match(fname)
530 if not ts_match:
531 logging.warning('Failed to extract timestamp from servod log file '
532 '%r. Skipping. The servo host is using outdated '
533 'servod logging and needs to be updated.', fname)
534 return
535 instance_ts = ts_match.group(self.TS_GROUP)
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800536 # Create the local results log dir.
537 log_dir = os.path.join(outdir, '%s_%s.%s' % (self.LOG_DIR,
538 str(self.servo_port),
539 instance_ts))
540 logging.info('Saving servod logs to %s.', log_dir)
541 os.mkdir(log_dir)
542 # Now, get all files with that timestamp.
543 cmd = 'find %s -maxdepth 1 -name "log.%s*"' % (self.remote_log_dir,
544 instance_ts)
545 res = self.run(cmd, stderr_tee=None, ignore_status=True)
546 files = res.stdout.strip().split()
547 try:
548 self.get_file(files, log_dir, try_rsync=False)
549
550 except error.AutoservRunError as e:
551 result = e.result_obj
552 if result.exit_status != 0:
553 stderr = result.stderr.strip()
554 logging.warning("Couldn't retrieve servod logs. Ignoring: %s",
555 stderr or '\n%s' % result)
556 return
557 local_files = [os.path.join(log_dir, f) for f in os.listdir(log_dir)]
558 # TODO(crrev.com/c/1793030): remove no-level case once CL is pushed
559 for level_name in ('DEBUG', 'INFO', 'WARNING', ''):
560 # Create the joint files for each loglevel. i.e log.DEBUG
561 joint_file = self.JOINT_LOG_PREFIX
562 if level_name:
563 joint_file = '%s.%s' % (self.JOINT_LOG_PREFIX, level_name)
564 # This helps with some online tools to avoid complaints about an
565 # unknown filetype.
566 joint_file = joint_file + '.txt'
567 joint_path = os.path.join(log_dir, joint_file)
568 files = [f for f in local_files if level_name in f]
569 if not files:
570 # TODO(crrev.com/c/1793030): remove no-level case once CL
571 # is pushed
572 continue
573 # Extract compressed logs if any.
574 compressed, extracted = self._extract_compressed_logs(log_dir,
575 files)
576 files = list(set(files) - set(compressed))
577 files.extend(extracted)
578 # Need to sort. As they all share the same timestamp, and
579 # loglevel, the index itself is sufficient. The highest index
580 # is the oldest file, therefore we need a descending sort.
581 def sortkey(f, level=level_name):
582 """Custom sortkey to sort based on rotation number int."""
583 if f.endswith(level_name): return 0
584 return int(f.split('.')[-1])
585
586 files.sort(reverse=True, key=sortkey)
587 # Just rename the first file rather than building from scratch.
588 os.rename(files[0], joint_path)
589 with open(joint_path, 'a') as joint_f:
590 for logfile in files[1:]:
591 # Transfer the file to the joint file line by line.
592 with open(logfile, 'r') as log_f:
593 for line in log_f:
594 joint_f.write(line)
595 # File has been written over. Delete safely.
596 os.remove(logfile)
597 # Need to remove all files form |local_files| so we don't
598 # analyze them again.
599 local_files = list(set(local_files) - set(files) - set(compressed))
600 # Lastly, extract MCU logs from the joint logs.
601 self._extract_mcu_logs(log_dir)
602
Garry Wangc1288cf2019-12-17 14:58:00 -0800603
Garry Wang79e9af62019-06-12 15:19:19 -0700604 def _lock(self):
605 """lock servohost by touching a file.
606 """
607 logging.debug('Locking servohost %s by touching %s file',
608 self.hostname, self._lock_file)
609 self.run('touch %s' % self._lock_file, ignore_status=True)
Garry Wang7c00b0f2019-06-25 17:28:17 -0700610 self._is_locked = True
Garry Wang79e9af62019-06-12 15:19:19 -0700611
612
613 def _unlock(self):
614 """Unlock servohost by removing the lock file.
615 """
616 logging.debug('Unlocking servohost by removing %s file',
617 self._lock_file)
618 self.run('rm %s' % self._lock_file, ignore_status=True)
Garry Wang7c00b0f2019-06-25 17:28:17 -0700619 self._is_locked = False
Garry Wang79e9af62019-06-12 15:19:19 -0700620
621
Congbin Guoa1f9cba2018-07-03 11:36:59 -0700622 def close(self):
Congbin Guofc3b8962019-03-22 17:38:46 -0700623 """Close the associated servo and the host object."""
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800624 if self._closed:
625 logging.debug('ServoHost is already closed.')
626 return
Congbin Guoa1f9cba2018-07-03 11:36:59 -0700627 if self._servo:
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800628 outdir = None if not self.job else self.job.resultdir
Congbin Guo2e5e2a22018-07-27 10:32:48 -0700629 # In some cases when we run as lab-tools, the job object is None.
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800630 self._servo.close(outdir)
631
632 if self.job and not self.is_localhost():
633 # Grab all logs from this servod instance before stopping servod.
634 # TODO(crbug.com/1011516): once enabled, remove the check against
635 # localhost and instead check against log-rotiation enablement.
636 try:
637 self.grab_logs(self.job.resultdir)
638 except error.AutoservRunError as e:
639 logging.info('Failed to grab servo logs due to: %s. '
640 'This error is forgiven.', str(e))
Congbin Guoa1f9cba2018-07-03 11:36:59 -0700641
Garry Wang7c00b0f2019-06-25 17:28:17 -0700642 if self._is_locked:
643 # Remove the lock if the servohost has been locked.
Garry Wang79e9af62019-06-12 15:19:19 -0700644 try:
645 self._unlock()
646 except error.AutoservSSHTimeout:
647 logging.error('Unlock servohost failed due to ssh timeout.'
648 ' It may caused by servohost went down during'
649 ' the task.')
Garry Wangc1288cf2019-12-17 14:58:00 -0800650 # We want always stop servod after task to minimum the impact of bad
651 # servod process interfere other servods.(see crbug.com/1028665)
Garry Wang4c624bc2020-01-27 16:34:43 -0800652 try:
653 self.stop_servod()
654 except error.AutoservRunError as e:
655 logging.info("Failed to stop servod due to:\n%s\n"
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800656 "This error is forgiven.", str(e))
Garry Wangc1288cf2019-12-17 14:58:00 -0800657
Congbin Guoa1f9cba2018-07-03 11:36:59 -0700658 super(ServoHost, self).close()
Ruben Rodriguez Buchillon93084d02020-01-21 15:17:36 -0800659 # Mark closed.
660 self._closed = True
Congbin Guoa1f9cba2018-07-03 11:36:59 -0700661
662
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800663 def get_servo_state(self):
Shelley Chen905f1272020-03-06 20:52:07 +0000664 return SERVO_STATE_BROKEN if self._servo_state is None else self._servo_state
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800665
666
Richard Barnetteea3e4602016-06-10 12:36:41 -0700667def make_servo_hostname(dut_hostname):
668 """Given a DUT's hostname, return the hostname of its servo.
669
670 @param dut_hostname: hostname of a DUT.
671
672 @return hostname of the DUT's servo.
673
674 """
675 host_parts = dut_hostname.split('.')
676 host_parts[0] = host_parts[0] + '-servo'
677 return '.'.join(host_parts)
678
679
680def servo_host_is_up(servo_hostname):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700681 """Given a servo host name, return if it's up or not.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700682
683 @param servo_hostname: hostname of the servo host.
684
685 @return True if it's up, False otherwise
686 """
687 # Technically, this duplicates the SSH ping done early in the servo
688 # proxy initialization code. However, this ping ends in a couple
689 # seconds when if fails, rather than the 60 seconds it takes to decide
690 # that an SSH ping has timed out. Specifically, that timeout happens
691 # when our servo DNS name resolves, but there is no host at that IP.
692 logging.info('Pinging servo host at %s', servo_hostname)
693 ping_config = ping_runner.PingConfig(
694 servo_hostname, count=3,
695 ignore_result=True, ignore_status=True)
696 return ping_runner.PingRunner().ping(ping_config).received > 0
697
698
Richard Barnettee519dcd2016-08-15 17:37:17 -0700699def _map_afe_board_to_servo_board(afe_board):
700 """Map a board we get from the AFE to a servo appropriate value.
701
702 Many boards are identical to other boards for servo's purposes.
703 This function makes that mapping.
704
705 @param afe_board string board name received from AFE.
706 @return board we expect servo to have.
707
708 """
709 KNOWN_SUFFIXES = ['-freon', '_freon', '_moblab', '-cheets']
710 BOARD_MAP = {'gizmo': 'panther'}
711 mapped_board = afe_board
712 if afe_board in BOARD_MAP:
713 mapped_board = BOARD_MAP[afe_board]
714 else:
715 for suffix in KNOWN_SUFFIXES:
716 if afe_board.endswith(suffix):
717 mapped_board = afe_board[0:-len(suffix)]
718 break
719 if mapped_board != afe_board:
720 logging.info('Mapping AFE board=%s to %s', afe_board, mapped_board)
721 return mapped_board
722
723
Prathmesh Prabhub4810232018-09-07 13:24:08 -0700724def get_servo_args_for_host(dut_host):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700725 """Return servo data associated with a given DUT.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700726
Richard Barnetteea3e4602016-06-10 12:36:41 -0700727 @param dut_host Instance of `Host` on which to find the servo
728 attributes.
Prathmesh Prabhuf605dd32018-08-28 17:09:04 -0700729 @return `servo_args` dict with host and an optional port.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700730 """
Prathmesh Prabhucba44292018-08-28 17:44:45 -0700731 info = dut_host.host_info_store.get()
732 servo_args = {k: v for k, v in info.attributes.iteritems()
733 if k in SERVO_ATTR_KEYS}
Richard Barnetteea3e4602016-06-10 12:36:41 -0700734
Prathmesh Prabhucba44292018-08-28 17:44:45 -0700735 if SERVO_PORT_ATTR in servo_args:
736 try:
737 servo_args[SERVO_PORT_ATTR] = int(servo_args[SERVO_PORT_ATTR])
738 except ValueError:
739 logging.error('servo port is not an int: %s',
740 servo_args[SERVO_PORT_ATTR])
741 # Reset servo_args because we don't want to use an invalid port.
742 servo_args.pop(SERVO_HOST_ATTR, None)
743
744 if info.board:
745 servo_args[SERVO_BOARD_ATTR] = _map_afe_board_to_servo_board(info.board)
Nick Sanders2f3c9852018-10-24 12:10:24 -0700746 if info.model:
747 servo_args[SERVO_MODEL_ATTR] = info.model
Prathmesh Prabhu6f5f6362018-09-05 17:20:31 -0700748 return servo_args if SERVO_HOST_ATTR in servo_args else None
Richard Barnetteea3e4602016-06-10 12:36:41 -0700749
750
Prathmesh Prabhuefb1b482018-08-28 17:15:05 -0700751def _tweak_args_for_ssp_moblab(servo_args):
752 if servo_args[SERVO_HOST_ATTR] in ['localhost', '127.0.0.1']:
753 servo_args[SERVO_HOST_ATTR] = _CONFIG.get_config_value(
754 'SSP', 'host_container_ip', type=str, default=None)
755
756
Dan Shi023aae32016-05-25 11:13:01 -0700757def create_servo_host(dut, servo_args, try_lab_servo=False,
Gregory Nisbetde13e2a2019-12-09 22:44:00 -0800758 try_servo_repair=False, dut_host_info=None):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700759 """Create a ServoHost object for a given DUT, if appropriate.
Dan Shi4d478522014-02-14 13:46:32 -0800760
Richard Barnette9a26ad62016-06-10 12:03:08 -0700761 This function attempts to create and verify or repair a `ServoHost`
762 object for a servo connected to the given `dut`, subject to various
763 constraints imposed by the parameters:
764 * When the `servo_args` parameter is not `None`, a servo
765 host must be created, and must be checked with `repair()`.
766 * Otherwise, if a servo exists in the lab and `try_lab_servo` is
767 true:
768 * If `try_servo_repair` is true, then create a servo host and
769 check it with `repair()`.
770 * Otherwise, if the servo responds to `ping` then create a
771 servo host and check it with `verify()`.
Fang Denge545abb2014-12-30 18:43:47 -0800772
Richard Barnette9a26ad62016-06-10 12:03:08 -0700773 In cases where `servo_args` was not `None`, repair failure
774 exceptions are passed back to the caller; otherwise, exceptions
Richard Barnette07c2e1d2016-10-26 14:24:28 -0700775 are logged and then discarded. Note that this only happens in cases
776 where we're called from a test (not special task) control file that
777 has an explicit dependency on servo. In that case, we require that
778 repair not write to `status.log`, so as to avoid polluting test
779 results.
780
781 TODO(jrbarnette): The special handling for servo in test control
782 files is a thorn in my flesh; I dearly hope to see it cut out before
783 my retirement.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700784
785 Parameters for a servo host consist of a host name, port number, and
786 DUT board, and are determined from one of these sources, in order of
787 priority:
Richard Barnetteea3e4602016-06-10 12:36:41 -0700788 * Servo attributes from the `dut` parameter take precedence over
789 all other sources of information.
790 * If a DNS entry for the servo based on the DUT hostname exists in
791 the CrOS lab network, that hostname is used with the default
Richard Barnette9a26ad62016-06-10 12:03:08 -0700792 port and the DUT's board.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700793 * If no other options are found, the parameters will be taken
Richard Barnette9a26ad62016-06-10 12:03:08 -0700794 from the `servo_args` dict passed in from the caller.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700795
796 @param dut An instance of `Host` from which to take
797 servo parameters (if available).
798 @param servo_args A dictionary with servo parameters to use if
799 they can't be found from `dut`. If this
800 argument is supplied, unrepaired exceptions
801 from `verify()` will be passed back to the
802 caller.
803 @param try_lab_servo If not true, servo host creation will be
804 skipped unless otherwise required by the
805 caller.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700806 @param try_servo_repair If true, check a servo host with
807 `repair()` instead of `verify()`.
Dan Shi4d478522014-02-14 13:46:32 -0800808
809 @returns: A ServoHost object or None. See comments above.
810
811 """
Richard Barnette07c2e1d2016-10-26 14:24:28 -0700812 servo_dependency = servo_args is not None
Richard Barnette07c2e1d2016-10-26 14:24:28 -0700813 if dut is not None and (try_lab_servo or servo_dependency):
Prathmesh Prabhub4810232018-09-07 13:24:08 -0700814 servo_args_override = get_servo_args_for_host(dut)
Richard Barnetteea3e4602016-06-10 12:36:41 -0700815 if servo_args_override is not None:
Prathmesh Prabhuefb1b482018-08-28 17:15:05 -0700816 if utils.in_moblab_ssp():
817 _tweak_args_for_ssp_moblab(servo_args_override)
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700818 logging.debug(
819 'Overriding provided servo_args (%s) with arguments'
820 ' determined from the host (%s)',
821 servo_args,
822 servo_args_override,
823 )
Richard Barnetteea3e4602016-06-10 12:36:41 -0700824 servo_args = servo_args_override
Prathmesh Prabhucba44292018-08-28 17:44:45 -0700825
Richard Barnetteea3e4602016-06-10 12:36:41 -0700826 if servo_args is None:
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700827 logging.debug('No servo_args provided, and failed to find overrides.')
Shelley Chen905f1272020-03-06 20:52:07 +0000828 return None
829 if SERVO_HOST_ATTR not in servo_args:
830 logging.debug('%s attribute missing from servo_args: %s',
831 SERVO_HOST_ATTR, servo_args)
832 return None
Richard Barnette07c2e1d2016-10-26 14:24:28 -0700833 if (not servo_dependency and not try_servo_repair and
Shelley Chen905f1272020-03-06 20:52:07 +0000834 not servo_host_is_up(servo_args[SERVO_HOST_ATTR])):
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700835 logging.debug('ServoHost is not up.')
Shelley Chen905f1272020-03-06 20:52:07 +0000836 return None
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700837
Garry Wangebc015b2019-06-06 17:45:06 -0700838 newhost = ServoHost(**servo_args)
Garry Wangcdd27b22020-01-13 14:59:11 -0800839 try:
840 newhost.restart_servod(quick_startup=True)
841 except error.AutoservSSHTimeout:
842 logging.warning("Restart servod failed due ssh connection "
843 "to servohost timed out. This error is forgiven"
844 " here, we will retry in servo repair process.")
845 except error.AutoservRunError as e:
846 logging.warning("Restart servod failed due to:\n%s\n"
847 "This error is forgiven here, we will retry"
848 " in servo repair process.", str(e))
Garry Wangebc015b2019-06-06 17:45:06 -0700849
Gregory Nisbetde13e2a2019-12-09 22:44:00 -0800850 # TODO(gregorynisbet): Clean all of this up.
851 logging.debug('create_servo_host: attempt to set info store on '
852 'servo host')
853 try:
854 if dut_host_info is None:
855 logging.debug('create_servo_host: dut_host_info is '
856 'None, skipping')
857 else:
858 newhost.set_dut_host_info(dut_host_info)
859 logging.debug('create_servo_host: successfully set info '
860 'store')
861 except Exception:
862 logging.error("create_servo_host: (%s)", traceback.format_exc())
863
Richard Barnette9a26ad62016-06-10 12:03:08 -0700864 # Note that the logic of repair() includes everything done
865 # by verify(). It's sufficient to call one or the other;
866 # we don't need both.
Richard Barnette07c2e1d2016-10-26 14:24:28 -0700867 if servo_dependency:
868 newhost.repair(silent=True)
Shelley Chen905f1272020-03-06 20:52:07 +0000869 return newhost
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700870
871 if try_servo_repair:
872 try:
873 newhost.repair()
874 except Exception:
875 logging.exception('servo repair failed for %s', newhost.hostname)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700876 else:
877 try:
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700878 newhost.verify()
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700879 except Exception:
Prathmesh Prabhu88bf6052018-08-28 16:21:26 -0700880 logging.exception('servo verify failed for %s', newhost.hostname)
Shelley Chen905f1272020-03-06 20:52:07 +0000881 return newhost
Otabek Kasimov7267a7a2020-03-04 11:18:45 -0800882
883
884def _is_servo_host_information_exist(hostname, port_int):
885 if hostname is None or len(hostname.strip()) == 0:
886 return False
887 if port_int is None or not type(port_int) is int:
888 return False
889 return True
890
891
892def is_servo_host_information_valid(hostname, port_int):
893 if not _is_servo_host_information_exist(hostname, port_int):
894 return False
895 # checking range and correct of the port
896 if port_int < 1 or port_int > 65000:
897 return False
898 # we expecting host contain only latters, digits and '-' or '_'
899 if not re.match('[a-zA-Z0-9-_]*$', hostname) or len(hostname) < 5:
900 return False
901 return True