blob: 67e0b094a0957caf5b363894e3444bab3df379b3 [file] [log] [blame]
Oleg Loskutoff75cc9b22019-10-16 17:28:12 -07001# Copyright (c) 2008 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
Dan Shid9be07a2017-08-18 09:51:45 -07005import os, time, socket, shutil, glob, logging, tempfile, re
xixuan6cf6d2f2016-01-29 15:29:00 -08006import shlex
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +08007import subprocess
8
Dan Shi4f8c0242017-07-07 15:34:49 -07009from autotest_lib.client.bin.result_tools import runner as result_tools_runner
Hidehiko Abe28422ed2017-06-21 10:50:44 +090010from autotest_lib.client.common_lib import error
Otabek Kasimovf5e0f102020-06-30 19:41:02 -070011from autotest_lib.client.common_lib import utils
Dan Shi9f92aa62017-07-27 17:07:05 -070012from autotest_lib.client.common_lib.cros.network import ping_runner
Hidehiko Abe28422ed2017-06-21 10:50:44 +090013from autotest_lib.client.common_lib.global_config import global_config
jadmanski31c49b72008-10-27 20:44:48 +000014from autotest_lib.server import utils, autotest
Prathmesh Prabhu8b5065d2017-01-10 17:13:01 -080015from autotest_lib.server.hosts import host_info
mblighe8b93af2009-01-30 00:45:53 +000016from autotest_lib.server.hosts import remote
Roshan Pius58e5dd32015-10-16 15:16:42 -070017from autotest_lib.server.hosts import rpc_server_tracker
Hidehiko Abe28422ed2017-06-21 10:50:44 +090018from autotest_lib.server.hosts import ssh_multiplex
jadmanskica7da372008-10-21 16:26:52 +000019
Otabek Kasimovf5e0f102020-06-30 19:41:02 -070020try:
21 from chromite.lib import metrics
22except ImportError:
23 metrics = utils.metrics_mock
24
Gwendal Grignou36b61702016-02-10 11:57:53 -080025# pylint: disable=C0111
jadmanskica7da372008-10-21 16:26:52 +000026
mblighb86bfa12010-02-12 20:22:21 +000027get_value = global_config.get_config_value
28enable_master_ssh = get_value('AUTOSERV', 'enable_master_ssh', type=bool,
29 default=False)
mblighefccc1b2010-01-11 19:08:42 +000030
Dan Shi9f92aa62017-07-27 17:07:05 -070031# Number of seconds to use the cached up status.
32_DEFAULT_UP_STATUS_EXPIRATION_SECONDS = 300
Dean Liaoe3e75f62017-11-14 10:36:43 +080033_DEFAULT_SSH_PORT = 22
mblighefccc1b2010-01-11 19:08:42 +000034
Lutz Justen043e9c12017-10-27 12:40:47 +020035# Number of seconds to wait for the host to shut down in wait_down().
36_DEFAULT_WAIT_DOWN_TIME_SECONDS = 120
37
Philip Chen7ce1e392018-12-09 23:53:32 -080038# Number of seconds to wait for the host to boot up in wait_up().
39_DEFAULT_WAIT_UP_TIME_SECONDS = 120
40
41# Timeout in seconds for a single call of get_boot_id() in wait_down()
42# and a single ssh ping in wait_up().
Lutz Justen043e9c12017-10-27 12:40:47 +020043_DEFAULT_MAX_PING_TIMEOUT = 10
44
Fang Deng96667ca2013-08-01 17:46:18 -070045class AbstractSSHHost(remote.RemoteHost):
mblighbc9402b2009-12-29 01:15:34 +000046 """
47 This class represents a generic implementation of most of the
jadmanskica7da372008-10-21 16:26:52 +000048 framework necessary for controlling a host via ssh. It implements
49 almost all of the abstract Host methods, except for the core
mblighbc9402b2009-12-29 01:15:34 +000050 Host.run method.
51 """
Simran Basi5ace6f22016-01-06 17:30:44 -080052 VERSION_PREFIX = ''
Prathmesh Prabhuf0507422018-08-28 15:51:45 -070053 # Timeout for master ssh connection setup, in seconds.
54 DEFAULT_START_MASTER_SSH_TIMEOUT_S = 5
jadmanskica7da372008-10-21 16:26:52 +000055
Dean Liaoe3e75f62017-11-14 10:36:43 +080056 def _initialize(self, hostname, user="root", port=_DEFAULT_SSH_PORT,
57 password="", is_client_install_supported=True,
58 afe_host=None, host_info_store=None, connection_pool=None,
Hidehiko Abe06893302017-06-24 07:32:38 +090059 *args, **dargs):
jadmanskif6562912008-10-21 17:59:01 +000060 super(AbstractSSHHost, self)._initialize(hostname=hostname,
61 *args, **dargs)
Kevin Cheng05ae2a42016-06-06 10:12:48 -070062 """
63 @param hostname: The hostname of the host.
64 @param user: The username to use when ssh'ing into the host.
65 @param password: The password to use when ssh'ing into the host.
66 @param port: The port to use for ssh.
67 @param is_client_install_supported: Boolean to indicate if we can
68 install autotest on the host.
69 @param afe_host: The host object attained from the AFE (get_hosts).
Prathmesh Prabhu8b5065d2017-01-10 17:13:01 -080070 @param host_info_store: Optional host_info.CachingHostInfoStore object
71 to obtain / update host information.
Hidehiko Abe06893302017-06-24 07:32:38 +090072 @param connection_pool: ssh_multiplex.ConnectionPool instance to share
73 the master ssh connection across control scripts.
Kevin Cheng05ae2a42016-06-06 10:12:48 -070074 """
Otabek Kasimovf5e0f102020-06-30 19:41:02 -070075 self._track_class_usage()
Dan Shic07b8932014-12-11 15:22:30 -080076 # IP address is retrieved only on demand. Otherwise the host
77 # initialization will fail for host is not online.
78 self._ip = None
jadmanskica7da372008-10-21 16:26:52 +000079 self.user = user
80 self.port = port
81 self.password = password
Roshan Piusa58163a2015-10-14 13:36:29 -070082 self._is_client_install_supported = is_client_install_supported
showard6eafb492010-01-15 20:29:06 +000083 self._use_rsync = None
Fang Deng3af66202013-08-16 15:19:25 -070084 self.known_hosts_file = tempfile.mkstemp()[1]
Roshan Pius58e5dd32015-10-16 15:16:42 -070085 self._rpc_server_tracker = rpc_server_tracker.RpcServerTracker(self);
jadmanskica7da372008-10-21 16:26:52 +000086
mblighefccc1b2010-01-11 19:08:42 +000087 """
88 Master SSH connection background job, socket temp directory and socket
89 control path option. If master-SSH is enabled, these fields will be
90 initialized by start_master_ssh when a new SSH connection is initiated.
91 """
Hidehiko Abe06893302017-06-24 07:32:38 +090092 self._connection_pool = connection_pool
93 if connection_pool:
94 self._master_ssh = connection_pool.get(hostname, user, port)
95 else:
96 self._master_ssh = ssh_multiplex.MasterSsh(hostname, user, port)
Simran Basi3b858a22015-03-17 16:23:24 -070097
Kevin Cheng05ae2a42016-06-06 10:12:48 -070098 self._afe_host = afe_host or utils.EmptyAFEHost()
Prathmesh Prabhu8b5065d2017-01-10 17:13:01 -080099 self.host_info_store = (host_info_store or
100 host_info.InMemoryHostInfoStore())
showard6eafb492010-01-15 20:29:06 +0000101
Dan Shi9f92aa62017-07-27 17:07:05 -0700102 # The cached status of whether the DUT responded to ping.
103 self._cached_up_status = None
104 # The timestamp when the value of _cached_up_status is set.
105 self._cached_up_status_updated = None
106
107
Dan Shic07b8932014-12-11 15:22:30 -0800108 @property
109 def ip(self):
110 """@return IP address of the host.
111 """
112 if not self._ip:
113 self._ip = socket.getaddrinfo(self.hostname, None)[0][4][0]
114 return self._ip
115
116
Roshan Piusa58163a2015-10-14 13:36:29 -0700117 @property
118 def is_client_install_supported(self):
119 """"
120 Returns True if the host supports autotest client installs, False
121 otherwise.
122 """
123 return self._is_client_install_supported
124
125
Roshan Pius58e5dd32015-10-16 15:16:42 -0700126 @property
127 def rpc_server_tracker(self):
128 """"
129 @return The RPC server tracker associated with this host.
130 """
131 return self._rpc_server_tracker
132
133
Dean Liaoe3e75f62017-11-14 10:36:43 +0800134 @property
135 def is_default_port(self):
136 """Returns True if its port is default SSH port."""
137 return self.port == _DEFAULT_SSH_PORT
138
139 @property
140 def host_port(self):
141 """Returns hostname if port is default. Otherwise, hostname:port.
142 """
143 if self.is_default_port:
144 return self.hostname
145 else:
146 return '%s:%d' % (self.hostname, self.port)
147
148
149 # Though it doesn't use self here, it is not declared as staticmethod
150 # because its subclass may use self to access member variables.
151 def make_ssh_command(self, user="root", port=_DEFAULT_SSH_PORT, opts='',
152 hosts_file='/dev/null', connect_timeout=30,
153 alive_interval=300, alive_count_max=3,
154 connection_attempts=1):
155 ssh_options = " ".join([
156 opts,
157 self.make_ssh_options(
158 hosts_file=hosts_file, connect_timeout=connect_timeout,
159 alive_interval=alive_interval, alive_count_max=alive_count_max,
160 connection_attempts=connection_attempts)])
161 return "/usr/bin/ssh -a -x %s -l %s -p %d" % (ssh_options, user, port)
162
163
164 @staticmethod
165 def make_ssh_options(hosts_file='/dev/null', connect_timeout=30,
166 alive_interval=300, alive_count_max=3,
167 connection_attempts=1):
168 """Composes SSH -o options."""
Fang Deng96667ca2013-08-01 17:46:18 -0700169 assert isinstance(connect_timeout, (int, long))
170 assert connect_timeout > 0 # can't disable the timeout
Dean Liaoe3e75f62017-11-14 10:36:43 +0800171
172 options = [("StrictHostKeyChecking", "no"),
173 ("UserKnownHostsFile", hosts_file),
174 ("BatchMode", "yes"),
175 ("ConnectTimeout", str(connect_timeout)),
176 ("ServerAliveInterval", str(alive_interval)),
177 ("ServerAliveCountMax", str(alive_count_max)),
178 ("ConnectionAttempts", str(connection_attempts))]
179 return " ".join("-o %s=%s" % kv for kv in options)
Fang Deng96667ca2013-08-01 17:46:18 -0700180
181
showard6eafb492010-01-15 20:29:06 +0000182 def use_rsync(self):
183 if self._use_rsync is not None:
184 return self._use_rsync
185
mblighc9892c02010-01-06 19:02:16 +0000186 # Check if rsync is available on the remote host. If it's not,
187 # don't try to use it for any future file transfers.
Gwendal Grignou03286f02017-03-24 10:50:59 -0700188 self._use_rsync = self.check_rsync()
showard6eafb492010-01-15 20:29:06 +0000189 if not self._use_rsync:
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -0700190 logging.warning("rsync not available on remote host %s -- disabled",
Dean Liaoe3e75f62017-11-14 10:36:43 +0800191 self.host_port)
Eric Lie0493a42010-11-15 13:05:43 -0800192 return self._use_rsync
mblighc9892c02010-01-06 19:02:16 +0000193
194
Gwendal Grignou03286f02017-03-24 10:50:59 -0700195 def check_rsync(self):
mblighc9892c02010-01-06 19:02:16 +0000196 """
197 Check if rsync is available on the remote host.
198 """
199 try:
Allen Liad719c12017-06-27 23:48:04 +0000200 self.run("rsync --version", stdout_tee=None, stderr_tee=None)
mblighc9892c02010-01-06 19:02:16 +0000201 except error.AutoservRunError:
202 return False
203 return True
204
jadmanskica7da372008-10-21 16:26:52 +0000205
Gwendal Grignou36b61702016-02-10 11:57:53 -0800206 def _encode_remote_paths(self, paths, escape=True, use_scp=False):
mblighbc9402b2009-12-29 01:15:34 +0000207 """
208 Given a list of file paths, encodes it as a single remote path, in
209 the style used by rsync and scp.
Gwendal Grignou36b61702016-02-10 11:57:53 -0800210 escape: add \\ to protect special characters.
211 use_scp: encode for scp if true, rsync if false.
mblighbc9402b2009-12-29 01:15:34 +0000212 """
showard56176ec2009-10-28 19:52:30 +0000213 if escape:
214 paths = [utils.scp_remote_escape(path) for path in paths]
Marc Herbert21eb6492015-11-13 15:48:53 -0800215
216 remote = self.hostname
217
218 # rsync and scp require IPv6 brackets, even when there isn't any
219 # trailing port number (ssh doesn't support IPv6 brackets).
220 # In the Python >= 3.3 future, 'import ipaddress' will parse addresses.
221 if re.search(r':.*:', remote):
222 remote = '[%s]' % remote
223
Gwendal Grignou36b61702016-02-10 11:57:53 -0800224 if use_scp:
225 return '%s@%s:"%s"' % (self.user, remote, " ".join(paths))
226 else:
227 return '%s@%s:%s' % (
228 self.user, remote,
229 " :".join('"%s"' % p for p in paths))
jadmanskica7da372008-10-21 16:26:52 +0000230
Gwendal Grignou36b61702016-02-10 11:57:53 -0800231 def _encode_local_paths(self, paths, escape=True):
232 """
233 Given a list of file paths, encodes it as a single local path.
234 escape: add \\ to protect special characters.
235 """
236 if escape:
237 paths = [utils.sh_escape(path) for path in paths]
238
239 return " ".join('"%s"' % p for p in paths)
jadmanskica7da372008-10-21 16:26:52 +0000240
Dean Liaoe3e75f62017-11-14 10:36:43 +0800241
242 def rsync_options(self, delete_dest=False, preserve_symlinks=False,
243 safe_symlinks=False, excludes=None):
244 """Obtains rsync options for the remote."""
Fang Deng96667ca2013-08-01 17:46:18 -0700245 ssh_cmd = self.make_ssh_command(user=self.user, port=self.port,
Hidehiko Abe28422ed2017-06-21 10:50:44 +0900246 opts=self._master_ssh.ssh_option,
Fang Deng96667ca2013-08-01 17:46:18 -0700247 hosts_file=self.known_hosts_file)
jadmanskid7b79ed2009-01-07 17:19:48 +0000248 if delete_dest:
249 delete_flag = "--delete"
250 else:
251 delete_flag = ""
Luigi Semenzato9b083072016-12-19 16:50:40 -0800252 if safe_symlinks:
253 symlink_flag = "-l --safe-links"
254 elif preserve_symlinks:
255 symlink_flag = "-l"
mbligh45561782009-05-11 21:14:34 +0000256 else:
257 symlink_flag = "-L"
Dan Shi92c34c92017-07-14 15:28:56 -0700258 exclude_args = ''
259 if excludes:
260 exclude_args = ' '.join(
261 ["--exclude '%s'" % exclude for exclude in excludes])
Dean Liaoe3e75f62017-11-14 10:36:43 +0800262 return "%s %s --timeout=1800 --rsh='%s' -az --no-o --no-g %s" % (
263 symlink_flag, delete_flag, ssh_cmd, exclude_args)
264
265
266 def _make_rsync_cmd(self, sources, dest, delete_dest,
267 preserve_symlinks, safe_symlinks, excludes=None):
268 """
269 Given a string of source paths and a destination path, produces the
270 appropriate rsync command for copying them. Remote paths must be
271 pre-encoded.
272 """
273 rsync_options = self.rsync_options(
274 delete_dest=delete_dest, preserve_symlinks=preserve_symlinks,
275 safe_symlinks=safe_symlinks, excludes=excludes)
276 return 'rsync %s %s "%s"' % (rsync_options, sources, dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000277
278
Eric Li861b2d52011-02-04 14:50:35 -0800279 def _make_ssh_cmd(self, cmd):
280 """
281 Create a base ssh command string for the host which can be used
282 to run commands directly on the machine
283 """
Fang Deng96667ca2013-08-01 17:46:18 -0700284 base_cmd = self.make_ssh_command(user=self.user, port=self.port,
Hidehiko Abe28422ed2017-06-21 10:50:44 +0900285 opts=self._master_ssh.ssh_option,
Fang Deng96667ca2013-08-01 17:46:18 -0700286 hosts_file=self.known_hosts_file)
Eric Li861b2d52011-02-04 14:50:35 -0800287
288 return '%s %s "%s"' % (base_cmd, self.hostname, utils.sh_escape(cmd))
289
jadmanskid7b79ed2009-01-07 17:19:48 +0000290 def _make_scp_cmd(self, sources, dest):
mblighbc9402b2009-12-29 01:15:34 +0000291 """
Gwendal Grignou36b61702016-02-10 11:57:53 -0800292 Given a string of source paths and a destination path, produces the
jadmanskid7b79ed2009-01-07 17:19:48 +0000293 appropriate scp command for encoding it. Remote paths must be
mblighbc9402b2009-12-29 01:15:34 +0000294 pre-encoded.
295 """
mblighc0649d62010-01-15 18:15:58 +0000296 command = ("scp -rq %s -o StrictHostKeyChecking=no "
lmraf676f32010-02-04 03:36:26 +0000297 "-o UserKnownHostsFile=%s -P %d %s '%s'")
Hidehiko Abe28422ed2017-06-21 10:50:44 +0900298 return command % (self._master_ssh.ssh_option, self.known_hosts_file,
Gwendal Grignou36b61702016-02-10 11:57:53 -0800299 self.port, sources, dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000300
301
302 def _make_rsync_compatible_globs(self, path, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000303 """
304 Given an rsync-style path, returns a list of globbed paths
jadmanskid7b79ed2009-01-07 17:19:48 +0000305 that will hopefully provide equivalent behaviour for scp. Does not
306 support the full range of rsync pattern matching behaviour, only that
307 exposed in the get/send_file interface (trailing slashes).
308
309 The is_local param is flag indicating if the paths should be
mblighbc9402b2009-12-29 01:15:34 +0000310 interpreted as local or remote paths.
311 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000312
313 # non-trailing slash paths should just work
314 if len(path) == 0 or path[-1] != "/":
315 return [path]
316
317 # make a function to test if a pattern matches any files
318 if is_local:
showard56176ec2009-10-28 19:52:30 +0000319 def glob_matches_files(path, pattern):
320 return len(glob.glob(path + pattern)) > 0
jadmanskid7b79ed2009-01-07 17:19:48 +0000321 else:
showard56176ec2009-10-28 19:52:30 +0000322 def glob_matches_files(path, pattern):
323 result = self.run("ls \"%s\"%s" % (utils.sh_escape(path),
324 pattern),
325 stdout_tee=None, ignore_status=True)
jadmanskid7b79ed2009-01-07 17:19:48 +0000326 return result.exit_status == 0
327
328 # take a set of globs that cover all files, and see which are needed
329 patterns = ["*", ".[!.]*"]
showard56176ec2009-10-28 19:52:30 +0000330 patterns = [p for p in patterns if glob_matches_files(path, p)]
jadmanskid7b79ed2009-01-07 17:19:48 +0000331
332 # convert them into a set of paths suitable for the commandline
jadmanskid7b79ed2009-01-07 17:19:48 +0000333 if is_local:
showard56176ec2009-10-28 19:52:30 +0000334 return ["\"%s\"%s" % (utils.sh_escape(path), pattern)
335 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000336 else:
showard56176ec2009-10-28 19:52:30 +0000337 return [utils.scp_remote_escape(path) + pattern
338 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000339
340
341 def _make_rsync_compatible_source(self, source, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000342 """
343 Applies the same logic as _make_rsync_compatible_globs, but
jadmanskid7b79ed2009-01-07 17:19:48 +0000344 applies it to an entire list of sources, producing a new list of
mblighbc9402b2009-12-29 01:15:34 +0000345 sources, properly quoted.
346 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000347 return sum((self._make_rsync_compatible_globs(path, is_local)
348 for path in source), [])
jadmanskica7da372008-10-21 16:26:52 +0000349
350
mblighfeac0102009-04-28 18:31:12 +0000351 def _set_umask_perms(self, dest):
mblighbc9402b2009-12-29 01:15:34 +0000352 """
353 Given a destination file/dir (recursively) set the permissions on
354 all the files and directories to the max allowed by running umask.
355 """
mblighfeac0102009-04-28 18:31:12 +0000356
357 # now this looks strange but I haven't found a way in Python to _just_
358 # get the umask, apparently the only option is to try to set it
359 umask = os.umask(0)
360 os.umask(umask)
361
362 max_privs = 0777 & ~umask
363
364 def set_file_privs(filename):
Chris Masone567d0d92011-12-19 09:38:30 -0800365 """Sets mode of |filename|. Assumes |filename| exists."""
366 file_stat = os.stat(filename)
mblighfeac0102009-04-28 18:31:12 +0000367
368 file_privs = max_privs
369 # if the original file permissions do not have at least one
370 # executable bit then do not set it anywhere
371 if not file_stat.st_mode & 0111:
372 file_privs &= ~0111
373
374 os.chmod(filename, file_privs)
375
376 # try a bottom-up walk so changes on directory permissions won't cut
377 # our access to the files/directories inside it
378 for root, dirs, files in os.walk(dest, topdown=False):
379 # when setting the privileges we emulate the chmod "X" behaviour
380 # that sets to execute only if it is a directory or any of the
381 # owner/group/other already has execute right
382 for dirname in dirs:
383 os.chmod(os.path.join(root, dirname), max_privs)
384
Chris Masone567d0d92011-12-19 09:38:30 -0800385 # Filter out broken symlinks as we go.
386 for filename in filter(os.path.exists, files):
mblighfeac0102009-04-28 18:31:12 +0000387 set_file_privs(os.path.join(root, filename))
388
389
390 # now set privs for the dest itself
391 if os.path.isdir(dest):
392 os.chmod(dest, max_privs)
393 else:
394 set_file_privs(dest)
395
396
mbligh45561782009-05-11 21:14:34 +0000397 def get_file(self, source, dest, delete_dest=False, preserve_perm=True,
Dana Goyette4d864e12019-09-19 11:05:44 -0700398 preserve_symlinks=False, retry=True, safe_symlinks=False,
399 try_rsync=True):
jadmanskica7da372008-10-21 16:26:52 +0000400 """
401 Copy files from the remote host to a local path.
402
403 Directories will be copied recursively.
404 If a source component is a directory with a trailing slash,
405 the content of the directory will be copied, otherwise, the
406 directory itself and its content will be copied. This
407 behavior is similar to that of the program 'rsync'.
408
409 Args:
410 source: either
411 1) a single file or directory, as a string
412 2) a list of one or more (possibly mixed)
413 files or directories
414 dest: a file or a directory (if source contains a
415 directory or more than one element, you must
416 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000417 delete_dest: if this is true, the command will also clear
418 out any old files at dest that are not in the
419 source
mblighfeac0102009-04-28 18:31:12 +0000420 preserve_perm: tells get_file() to try to preserve the sources
421 permissions on files and dirs
mbligh45561782009-05-11 21:14:34 +0000422 preserve_symlinks: try to preserve symlinks instead of
423 transforming them into files/dirs on copy
Luigi Semenzato9b083072016-12-19 16:50:40 -0800424 safe_symlinks: same as preserve_symlinks, but discard links
425 that may point outside the copied tree
Dana Goyette4d864e12019-09-19 11:05:44 -0700426 try_rsync: set to False to skip directly to using scp
jadmanskica7da372008-10-21 16:26:52 +0000427 Raises:
428 AutoservRunError: the scp command failed
429 """
Simran Basi882f15b2013-10-29 14:59:34 -0700430 logging.debug('get_file. source: %s, dest: %s, delete_dest: %s,'
431 'preserve_perm: %s, preserve_symlinks:%s', source, dest,
432 delete_dest, preserve_perm, preserve_symlinks)
Dan Shi4f8c0242017-07-07 15:34:49 -0700433
mblighefccc1b2010-01-11 19:08:42 +0000434 # Start a master SSH connection if necessary.
435 self.start_master_ssh()
436
jadmanskica7da372008-10-21 16:26:52 +0000437 if isinstance(source, basestring):
438 source = [source]
jadmanskid7b79ed2009-01-07 17:19:48 +0000439 dest = os.path.abspath(dest)
jadmanskica7da372008-10-21 16:26:52 +0000440
mblighc9892c02010-01-06 19:02:16 +0000441 # If rsync is disabled or fails, try scp.
showard6eafb492010-01-15 20:29:06 +0000442 try_scp = True
Dana Goyette4d864e12019-09-19 11:05:44 -0700443 if try_rsync and self.use_rsync():
Simran Basi882f15b2013-10-29 14:59:34 -0700444 logging.debug('Using Rsync.')
mblighc9892c02010-01-06 19:02:16 +0000445 try:
446 remote_source = self._encode_remote_paths(source)
447 local_dest = utils.sh_escape(dest)
Gwendal Grignou36b61702016-02-10 11:57:53 -0800448 rsync = self._make_rsync_cmd(remote_source, local_dest,
Luigi Semenzato9b083072016-12-19 16:50:40 -0800449 delete_dest, preserve_symlinks,
450 safe_symlinks)
mblighc9892c02010-01-06 19:02:16 +0000451 utils.run(rsync)
showard6eafb492010-01-15 20:29:06 +0000452 try_scp = False
mblighc9892c02010-01-06 19:02:16 +0000453 except error.CmdError, e:
Luigi Semenzato7f9dff12016-11-21 14:01:20 -0800454 # retry on rsync exit values which may be caused by transient
455 # network problems:
456 #
457 # rc 10: Error in socket I/O
458 # rc 12: Error in rsync protocol data stream
459 # rc 23: Partial transfer due to error
460 # rc 255: Ssh error
461 #
462 # Note that rc 23 includes dangling symlinks. In this case
463 # retrying is useless, but not very damaging since rsync checks
464 # for those before starting the transfer (scp does not).
465 status = e.result_obj.exit_status
466 if status in [10, 12, 23, 255] and retry:
467 logging.warning('rsync status %d, retrying', status)
468 self.get_file(source, dest, delete_dest, preserve_perm,
469 preserve_symlinks, retry=False)
470 # The nested get_file() does all that's needed.
471 return
472 else:
473 logging.warning("trying scp, rsync failed: %s (%d)",
474 e, status)
mblighc9892c02010-01-06 19:02:16 +0000475
476 if try_scp:
Simran Basi882f15b2013-10-29 14:59:34 -0700477 logging.debug('Trying scp.')
jadmanskid7b79ed2009-01-07 17:19:48 +0000478 # scp has no equivalent to --delete, just drop the entire dest dir
479 if delete_dest and os.path.isdir(dest):
480 shutil.rmtree(dest)
481 os.mkdir(dest)
jadmanskica7da372008-10-21 16:26:52 +0000482
jadmanskid7b79ed2009-01-07 17:19:48 +0000483 remote_source = self._make_rsync_compatible_source(source, False)
484 if remote_source:
showard56176ec2009-10-28 19:52:30 +0000485 # _make_rsync_compatible_source() already did the escaping
Gwendal Grignou36b61702016-02-10 11:57:53 -0800486 remote_source = self._encode_remote_paths(
487 remote_source, escape=False, use_scp=True)
jadmanskid7b79ed2009-01-07 17:19:48 +0000488 local_dest = utils.sh_escape(dest)
Gwendal Grignou36b61702016-02-10 11:57:53 -0800489 scp = self._make_scp_cmd(remote_source, local_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000490 try:
491 utils.run(scp)
492 except error.CmdError, e:
Simran Basi882f15b2013-10-29 14:59:34 -0700493 logging.debug('scp failed: %s', e)
jadmanskid7b79ed2009-01-07 17:19:48 +0000494 raise error.AutoservRunError(e.args[0], e.args[1])
jadmanskica7da372008-10-21 16:26:52 +0000495
mblighfeac0102009-04-28 18:31:12 +0000496 if not preserve_perm:
497 # we have no way to tell scp to not try to preserve the
498 # permissions so set them after copy instead.
499 # for rsync we could use "--no-p --chmod=ugo=rwX" but those
500 # options are only in very recent rsync versions
501 self._set_umask_perms(dest)
502
jadmanskica7da372008-10-21 16:26:52 +0000503
mbligh45561782009-05-11 21:14:34 +0000504 def send_file(self, source, dest, delete_dest=False,
Dan Shi92c34c92017-07-14 15:28:56 -0700505 preserve_symlinks=False, excludes=None):
jadmanskica7da372008-10-21 16:26:52 +0000506 """
507 Copy files from a local path to the remote host.
508
509 Directories will be copied recursively.
510 If a source component is a directory with a trailing slash,
511 the content of the directory will be copied, otherwise, the
512 directory itself and its content will be copied. This
513 behavior is similar to that of the program 'rsync'.
514
515 Args:
516 source: either
517 1) a single file or directory, as a string
518 2) a list of one or more (possibly mixed)
519 files or directories
520 dest: a file or a directory (if source contains a
521 directory or more than one element, you must
522 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000523 delete_dest: if this is true, the command will also clear
524 out any old files at dest that are not in the
525 source
mbligh45561782009-05-11 21:14:34 +0000526 preserve_symlinks: controls if symlinks on the source will be
527 copied as such on the destination or transformed into the
528 referenced file/directory
Dan Shi92c34c92017-07-14 15:28:56 -0700529 excludes: A list of file pattern that matches files not to be
530 sent. `send_file` will fail if exclude is set, since
531 local copy does not support --exclude, e.g., when
532 using scp to copy file.
jadmanskica7da372008-10-21 16:26:52 +0000533
534 Raises:
535 AutoservRunError: the scp command failed
536 """
Simran Basi882f15b2013-10-29 14:59:34 -0700537 logging.debug('send_file. source: %s, dest: %s, delete_dest: %s,'
538 'preserve_symlinks:%s', source, dest,
539 delete_dest, preserve_symlinks)
mblighefccc1b2010-01-11 19:08:42 +0000540 # Start a master SSH connection if necessary.
541 self.start_master_ssh()
542
jadmanskica7da372008-10-21 16:26:52 +0000543 if isinstance(source, basestring):
544 source = [source]
545
Gwendal Grignou36b61702016-02-10 11:57:53 -0800546 local_sources = self._encode_local_paths(source)
mukesh agrawal0d3616c2015-07-17 15:47:36 -0700547 if not local_sources:
Gwendal Grignou36b61702016-02-10 11:57:53 -0800548 raise error.TestError('source |%s| yielded an empty string' % (
mukesh agrawal0d3616c2015-07-17 15:47:36 -0700549 source))
Gwendal Grignou36b61702016-02-10 11:57:53 -0800550 if local_sources.find('\x00') != -1:
mukesh agrawal0d3616c2015-07-17 15:47:36 -0700551 raise error.TestError('one or more sources include NUL char')
552
mblighc9892c02010-01-06 19:02:16 +0000553 # If rsync is disabled or fails, try scp.
showard6eafb492010-01-15 20:29:06 +0000554 try_scp = True
555 if self.use_rsync():
Simran Basi882f15b2013-10-29 14:59:34 -0700556 logging.debug('Using Rsync.')
Gwendal Grignou36b61702016-02-10 11:57:53 -0800557 remote_dest = self._encode_remote_paths([dest])
mblighc9892c02010-01-06 19:02:16 +0000558 try:
mblighc9892c02010-01-06 19:02:16 +0000559 rsync = self._make_rsync_cmd(local_sources, remote_dest,
Luigi Semenzato9b083072016-12-19 16:50:40 -0800560 delete_dest, preserve_symlinks,
Dan Shi92c34c92017-07-14 15:28:56 -0700561 False, excludes=excludes)
mblighc9892c02010-01-06 19:02:16 +0000562 utils.run(rsync)
showard6eafb492010-01-15 20:29:06 +0000563 try_scp = False
mblighc9892c02010-01-06 19:02:16 +0000564 except error.CmdError, e:
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -0700565 logging.warning("trying scp, rsync failed: %s", e)
mblighc9892c02010-01-06 19:02:16 +0000566
567 if try_scp:
Simran Basi882f15b2013-10-29 14:59:34 -0700568 logging.debug('Trying scp.')
Dan Shi92c34c92017-07-14 15:28:56 -0700569 if excludes:
570 raise error.AutotestHostRunError(
571 '--exclude is not supported in scp, try to use rsync. '
Brian Norrisd7650482018-02-21 18:38:18 -0800572 'excludes: %s' % ','.join(excludes), None)
jadmanskid7b79ed2009-01-07 17:19:48 +0000573 # scp has no equivalent to --delete, just drop the entire dest dir
574 if delete_dest:
showard27160152009-07-15 14:28:42 +0000575 is_dir = self.run("ls -d %s/" % dest,
jadmanskid7b79ed2009-01-07 17:19:48 +0000576 ignore_status=True).exit_status == 0
577 if is_dir:
578 cmd = "rm -rf %s && mkdir %s"
mbligh5a0ca532009-08-03 16:44:34 +0000579 cmd %= (dest, dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000580 self.run(cmd)
jadmanskica7da372008-10-21 16:26:52 +0000581
Gwendal Grignou36b61702016-02-10 11:57:53 -0800582 remote_dest = self._encode_remote_paths([dest], use_scp=True)
jadmanski2583a432009-02-10 23:59:11 +0000583 local_sources = self._make_rsync_compatible_source(source, True)
584 if local_sources:
Cheng-Yi Chiang9b2812d2016-02-29 17:01:44 +0800585 sources = self._encode_local_paths(local_sources, escape=False)
586 scp = self._make_scp_cmd(sources, remote_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000587 try:
588 utils.run(scp)
589 except error.CmdError, e:
Simran Basi882f15b2013-10-29 14:59:34 -0700590 logging.debug('scp failed: %s', e)
jadmanskid7b79ed2009-01-07 17:19:48 +0000591 raise error.AutoservRunError(e.args[0], e.args[1])
mukesh agrawal0d3616c2015-07-17 15:47:36 -0700592 else:
593 logging.debug('skipping scp for empty source list')
jadmanskid7b79ed2009-01-07 17:19:48 +0000594
Jes B. Klinke249e72e2020-04-30 13:31:32 -0700595 # Make sure newly written files make it to stable storage, in
596 # case the next step of testing involves a reboot through
597 # servo power manipulation.
598 self.run("sync")
599
jadmanskica7da372008-10-21 16:26:52 +0000600
Simran Basi1621c632015-10-14 12:22:23 -0700601 def verify_ssh_user_access(self):
602 """Verify ssh access to this host.
603
604 @returns False if ssh_ping fails due to Permissions error, True
605 otherwise.
606 """
607 try:
608 self.ssh_ping()
609 except (error.AutoservSshPermissionDeniedError,
610 error.AutoservSshPingHostError):
611 return False
612 return True
613
614
Luigi Semenzato135574c2016-08-31 17:25:08 -0700615 def ssh_ping(self, timeout=60, connect_timeout=None, base_cmd='true'):
beepsadd66d32013-03-04 17:21:51 -0800616 """
617 Pings remote host via ssh.
618
Philip Chen7ce1e392018-12-09 23:53:32 -0800619 @param timeout: Command execution timeout in seconds.
beepsadd66d32013-03-04 17:21:51 -0800620 Defaults to 60 seconds.
Philip Chen7ce1e392018-12-09 23:53:32 -0800621 @param connect_timeout: ssh connection timeout in seconds.
beeps46dadc92013-11-07 14:07:10 -0800622 @param base_cmd: The base command to run with the ssh ping.
623 Defaults to true.
beepsadd66d32013-03-04 17:21:51 -0800624 @raise AutoservSSHTimeout: If the ssh ping times out.
625 @raise AutoservSshPermissionDeniedError: If ssh ping fails due to
626 permissions.
627 @raise AutoservSshPingHostError: For other AutoservRunErrors.
628 """
Luigi Semenzato135574c2016-08-31 17:25:08 -0700629 ctimeout = min(timeout, connect_timeout or timeout)
jadmanskica7da372008-10-21 16:26:52 +0000630 try:
Allen Liad719c12017-06-27 23:48:04 +0000631 self.run(base_cmd, timeout=timeout, connect_timeout=ctimeout,
632 ssh_failure_retry_ok=True)
jadmanskica7da372008-10-21 16:26:52 +0000633 except error.AutoservSSHTimeout:
mblighd0e94982009-07-11 00:15:18 +0000634 msg = "Host (ssh) verify timed out (timeout = %d)" % timeout
jadmanskica7da372008-10-21 16:26:52 +0000635 raise error.AutoservSSHTimeout(msg)
mbligh9d738d62009-03-09 21:17:10 +0000636 except error.AutoservSshPermissionDeniedError:
Allen Liad719c12017-06-27 23:48:04 +0000637 #let AutoservSshPermissionDeniedError be visible to the callers
mbligh9d738d62009-03-09 21:17:10 +0000638 raise
jadmanskica7da372008-10-21 16:26:52 +0000639 except error.AutoservRunError, e:
mblighc971c5f2009-06-08 16:48:54 +0000640 # convert the generic AutoservRunError into something more
641 # specific for this context
642 raise error.AutoservSshPingHostError(e.description + '\n' +
643 repr(e.result_obj))
jadmanskica7da372008-10-21 16:26:52 +0000644
645
Luigi Semenzato135574c2016-08-31 17:25:08 -0700646 def is_up(self, timeout=60, connect_timeout=None, base_cmd='true'):
jadmanskica7da372008-10-21 16:26:52 +0000647 """
beeps46dadc92013-11-07 14:07:10 -0800648 Check if the remote host is up by ssh-ing and running a base command.
jadmanskica7da372008-10-21 16:26:52 +0000649
Philip Chen7ce1e392018-12-09 23:53:32 -0800650 @param timeout: command execution timeout in seconds.
651 @param connect_timeout: ssh connection timeout in seconds.
beeps46dadc92013-11-07 14:07:10 -0800652 @param base_cmd: a base command to run with ssh. The default is 'true'.
beepsadd66d32013-03-04 17:21:51 -0800653 @returns True if the remote host is up before the timeout expires,
654 False otherwise.
jadmanskica7da372008-10-21 16:26:52 +0000655 """
656 try:
Luigi Semenzato135574c2016-08-31 17:25:08 -0700657 self.ssh_ping(timeout=timeout,
658 connect_timeout=connect_timeout,
659 base_cmd=base_cmd)
jadmanskica7da372008-10-21 16:26:52 +0000660 except error.AutoservError:
661 return False
662 else:
663 return True
664
665
Dan Shi9f92aa62017-07-27 17:07:05 -0700666 def is_up_fast(self):
667 """Return True if the host can be pinged."""
668 ping_config = ping_runner.PingConfig(
Derek Beckettaf402f82020-08-12 12:48:25 -0700669 self.hostname, count=1, ignore_result=True, ignore_status=True)
Dan Shi9f92aa62017-07-27 17:07:05 -0700670 return ping_runner.PingRunner().ping(ping_config).received > 0
671
672
Philip Chen7ce1e392018-12-09 23:53:32 -0800673 def wait_up(self, timeout=_DEFAULT_WAIT_UP_TIME_SECONDS):
jadmanskica7da372008-10-21 16:26:52 +0000674 """
675 Wait until the remote host is up or the timeout expires.
676
677 In fact, it will wait until an ssh connection to the remote
678 host can be established, and getty is running.
679
jadmanskic0354912010-01-12 15:57:29 +0000680 @param timeout time limit in seconds before returning even
681 if the host is not up.
jadmanskica7da372008-10-21 16:26:52 +0000682
beepsadd66d32013-03-04 17:21:51 -0800683 @returns True if the host was found to be up before the timeout expires,
684 False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000685 """
Philip Chen7ce1e392018-12-09 23:53:32 -0800686 current_time = int(time.time())
687 end_time = current_time + timeout
jadmanskica7da372008-10-21 16:26:52 +0000688
Luigi Semenzato135574c2016-08-31 17:25:08 -0700689 autoserv_error_logged = False
Philip Chen7ce1e392018-12-09 23:53:32 -0800690 while current_time < end_time:
691 ping_timeout = min(_DEFAULT_MAX_PING_TIMEOUT,
692 end_time - current_time)
693 if self.is_up(timeout=ping_timeout, connect_timeout=ping_timeout):
jadmanskica7da372008-10-21 16:26:52 +0000694 try:
695 if self.are_wait_up_processes_up():
Dean Liaoe3e75f62017-11-14 10:36:43 +0800696 logging.debug('Host %s is now up', self.host_port)
jadmanskica7da372008-10-21 16:26:52 +0000697 return True
Luigi Semenzato135574c2016-08-31 17:25:08 -0700698 except error.AutoservError as e:
699 if not autoserv_error_logged:
700 logging.debug('Ignoring failure to reach %s: %s %s',
Dean Liaoe3e75f62017-11-14 10:36:43 +0800701 self.host_port, e,
Luigi Semenzato135574c2016-08-31 17:25:08 -0700702 '(and further similar failures)')
703 autoserv_error_logged = True
jadmanskica7da372008-10-21 16:26:52 +0000704 time.sleep(1)
beeps46dadc92013-11-07 14:07:10 -0800705 current_time = int(time.time())
jadmanskica7da372008-10-21 16:26:52 +0000706
jadmanski7ebac3d2010-06-17 16:06:31 +0000707 logging.debug('Host %s is still down after waiting %d seconds',
Dean Liaoe3e75f62017-11-14 10:36:43 +0800708 self.host_port, int(timeout + time.time() - end_time))
jadmanskica7da372008-10-21 16:26:52 +0000709 return False
710
711
Lutz Justen043e9c12017-10-27 12:40:47 +0200712 def wait_down(self, timeout=_DEFAULT_WAIT_DOWN_TIME_SECONDS,
713 warning_timer=None, old_boot_id=None,
714 max_ping_timeout=_DEFAULT_MAX_PING_TIMEOUT):
jadmanskica7da372008-10-21 16:26:52 +0000715 """
716 Wait until the remote host is down or the timeout expires.
717
Lutz Justen043e9c12017-10-27 12:40:47 +0200718 If old_boot_id is provided, waits until either the machine is
719 unpingable or self.get_boot_id() returns a value different from
jadmanskic0354912010-01-12 15:57:29 +0000720 old_boot_id. If the boot_id value has changed then the function
Lutz Justen043e9c12017-10-27 12:40:47 +0200721 returns True under the assumption that the machine has shut down
jadmanskic0354912010-01-12 15:57:29 +0000722 and has now already come back up.
jadmanskica7da372008-10-21 16:26:52 +0000723
jadmanskic0354912010-01-12 15:57:29 +0000724 If old_boot_id is None then until the machine becomes unreachable the
725 method assumes the machine has not yet shut down.
jadmanskica7da372008-10-21 16:26:52 +0000726
Lutz Justen043e9c12017-10-27 12:40:47 +0200727 @param timeout Time limit in seconds before returning even if the host
728 is still up.
729 @param warning_timer Time limit in seconds that will generate a warning
730 if the host is not down yet. Can be None for no warning.
jadmanskic0354912010-01-12 15:57:29 +0000731 @param old_boot_id A string containing the result of self.get_boot_id()
732 prior to the host being told to shut down. Can be None if this is
733 not available.
Lutz Justen043e9c12017-10-27 12:40:47 +0200734 @param max_ping_timeout Maximum timeout in seconds for each
735 self.get_boot_id() call. If this timeout is hit, it is assumed that
736 the host went down and became unreachable.
jadmanskic0354912010-01-12 15:57:29 +0000737
Lutz Justen043e9c12017-10-27 12:40:47 +0200738 @returns True if the host was found to be down (max_ping_timeout timeout
739 expired or boot_id changed if provided) and False if timeout
740 expired.
jadmanskica7da372008-10-21 16:26:52 +0000741 """
mblighe5e3cf22010-05-27 23:33:14 +0000742 #TODO: there is currently no way to distinguish between knowing
743 #TODO: boot_id was unsupported and not knowing the boot_id.
beeps46dadc92013-11-07 14:07:10 -0800744 current_time = int(time.time())
Lutz Justen043e9c12017-10-27 12:40:47 +0200745 end_time = current_time + timeout
jadmanskica7da372008-10-21 16:26:52 +0000746
mbligh2ed998f2009-04-08 21:03:47 +0000747 if warning_timer:
748 warn_time = current_time + warning_timer
749
jadmanskic0354912010-01-12 15:57:29 +0000750 if old_boot_id is not None:
751 logging.debug('Host %s pre-shutdown boot_id is %s',
Dean Liaoe3e75f62017-11-14 10:36:43 +0800752 self.host_port, old_boot_id)
jadmanskic0354912010-01-12 15:57:29 +0000753
beepsadd66d32013-03-04 17:21:51 -0800754 # Impose semi real-time deadline constraints, since some clients
755 # (eg: watchdog timer tests) expect strict checking of time elapsed.
756 # Each iteration of this loop is treated as though it atomically
757 # completes within current_time, this is needed because if we used
758 # inline time.time() calls instead then the following could happen:
759 #
Lutz Justen043e9c12017-10-27 12:40:47 +0200760 # while time.time() < end_time: [23 < 30]
beepsadd66d32013-03-04 17:21:51 -0800761 # some code. [takes 10 secs]
762 # try:
763 # new_boot_id = self.get_boot_id(timeout=end_time - time.time())
764 # [30 - 33]
765 # The last step will lead to a return True, when in fact the machine
766 # went down at 32 seconds (>30). Hence we need to pass get_boot_id
767 # the same time that allowed us into that iteration of the loop.
Lutz Justen043e9c12017-10-27 12:40:47 +0200768 while current_time < end_time:
769 ping_timeout = min(end_time - current_time, max_ping_timeout)
jadmanskic0354912010-01-12 15:57:29 +0000770 try:
Lutz Justen043e9c12017-10-27 12:40:47 +0200771 new_boot_id = self.get_boot_id(timeout=ping_timeout)
mblighdbc7e4a2010-01-15 20:34:20 +0000772 except error.AutoservError:
jadmanskic0354912010-01-12 15:57:29 +0000773 logging.debug('Host %s is now unreachable over ssh, is down',
Dean Liaoe3e75f62017-11-14 10:36:43 +0800774 self.host_port)
jadmanskica7da372008-10-21 16:26:52 +0000775 return True
jadmanskic0354912010-01-12 15:57:29 +0000776 else:
777 # if the machine is up but the boot_id value has changed from
778 # old boot id, then we can assume the machine has gone down
779 # and then already come back up
780 if old_boot_id is not None and old_boot_id != new_boot_id:
781 logging.debug('Host %s now has boot_id %s and so must '
Dean Liaoe3e75f62017-11-14 10:36:43 +0800782 'have rebooted', self.host_port, new_boot_id)
jadmanskic0354912010-01-12 15:57:29 +0000783 return True
mbligh2ed998f2009-04-08 21:03:47 +0000784
785 if warning_timer and current_time > warn_time:
Scott Zawalskic86fdeb2013-10-23 10:24:04 -0400786 self.record("INFO", None, "shutdown",
mbligh2ed998f2009-04-08 21:03:47 +0000787 "Shutdown took longer than %ds" % warning_timer)
788 # Print the warning only once.
789 warning_timer = None
mbligha4464402009-04-17 20:13:41 +0000790 # If a machine is stuck switching runlevels
791 # This may cause the machine to reboot.
792 self.run('kill -HUP 1', ignore_status=True)
mbligh2ed998f2009-04-08 21:03:47 +0000793
jadmanskica7da372008-10-21 16:26:52 +0000794 time.sleep(1)
beeps46dadc92013-11-07 14:07:10 -0800795 current_time = int(time.time())
jadmanskica7da372008-10-21 16:26:52 +0000796
797 return False
jadmanskif6562912008-10-21 17:59:01 +0000798
mbligha0a27592009-01-24 01:41:36 +0000799
jadmanskif6562912008-10-21 17:59:01 +0000800 # tunable constants for the verify & repair code
mblighb86bfa12010-02-12 20:22:21 +0000801 AUTOTEST_GB_DISKSPACE_REQUIRED = get_value("SERVER",
802 "gb_diskspace_required",
Fang Deng6b05f5b2013-03-20 13:42:11 -0700803 type=float,
804 default=20.0)
mbligha0a27592009-01-24 01:41:36 +0000805
jadmanskif6562912008-10-21 17:59:01 +0000806
showardca572982009-09-18 21:20:01 +0000807 def verify_connectivity(self):
808 super(AbstractSSHHost, self).verify_connectivity()
jadmanskif6562912008-10-21 17:59:01 +0000809
Dean Liaoe3e75f62017-11-14 10:36:43 +0800810 logging.info('Pinging host ' + self.host_port)
jadmanskif6562912008-10-21 17:59:01 +0000811 self.ssh_ping()
Dean Liaoe3e75f62017-11-14 10:36:43 +0800812 logging.info("Host (ssh) %s is alive", self.host_port)
jadmanskif6562912008-10-21 17:59:01 +0000813
jadmanski80deb752009-01-21 17:14:16 +0000814 if self.is_shutting_down():
mblighc971c5f2009-06-08 16:48:54 +0000815 raise error.AutoservHostIsShuttingDownError("Host is shutting down")
jadmanski80deb752009-01-21 17:14:16 +0000816
mblighb49b5232009-02-12 21:54:49 +0000817
showardca572982009-09-18 21:20:01 +0000818 def verify_software(self):
819 super(AbstractSSHHost, self).verify_software()
jadmanskif6562912008-10-21 17:59:01 +0000820 try:
showardad812bf2009-10-20 23:49:56 +0000821 self.check_diskspace(autotest.Autotest.get_install_dir(self),
822 self.AUTOTEST_GB_DISKSPACE_REQUIRED)
Keith Haddow07f1d3e2017-08-03 17:40:41 -0700823 except error.AutoservDiskFullHostError:
824 # only want to raise if it's a space issue
825 raise
826 except (error.AutoservHostError, autotest.AutodirNotFoundError):
Lutz Justen043e9c12017-10-27 12:40:47 +0200827 logging.exception('autodir space check exception, this is probably '
Keith Haddow07f1d3e2017-08-03 17:40:41 -0700828 'safe to ignore\n')
mblighefccc1b2010-01-11 19:08:42 +0000829
830
831 def close(self):
832 super(AbstractSSHHost, self).close()
Godofredo Contreras773179e2016-05-24 10:17:48 -0700833 self.rpc_server_tracker.disconnect_all()
Hidehiko Abe06893302017-06-24 07:32:38 +0900834 if not self._connection_pool:
835 self._master_ssh.close()
xixuand6011f12016-12-08 15:01:58 -0800836 if os.path.exists(self.known_hosts_file):
837 os.remove(self.known_hosts_file)
mblighefccc1b2010-01-11 19:08:42 +0000838
839
Luigi Semenzato3b95ede2016-12-09 11:51:01 -0800840 def restart_master_ssh(self):
841 """
842 Stop and restart the ssh master connection. This is meant as a last
843 resort when ssh commands fail and we don't understand why.
844 """
845 logging.debug('Restarting master ssh connection')
Hidehiko Abe28422ed2017-06-21 10:50:44 +0900846 self._master_ssh.close()
847 self._master_ssh.maybe_start(timeout=30)
Luigi Semenzato3b95ede2016-12-09 11:51:01 -0800848
849
mblighefccc1b2010-01-11 19:08:42 +0000850
Prathmesh Prabhuf0507422018-08-28 15:51:45 -0700851 def start_master_ssh(self, timeout=DEFAULT_START_MASTER_SSH_TIMEOUT_S):
mblighefccc1b2010-01-11 19:08:42 +0000852 """
853 Called whenever a slave SSH connection needs to be initiated (e.g., by
854 run, rsync, scp). If master SSH support is enabled and a master SSH
855 connection is not active already, start a new one in the background.
856 Also, cleanup any zombie master SSH connections (e.g., dead due to
857 reboot).
Aviv Keshet0749a822013-10-17 09:53:26 -0700858
859 timeout: timeout in seconds (default 5) to wait for master ssh
860 connection to be established. If timeout is reached, a
861 warning message is logged, but no other action is taken.
mblighefccc1b2010-01-11 19:08:42 +0000862 """
863 if not enable_master_ssh:
864 return
Hidehiko Abe28422ed2017-06-21 10:50:44 +0900865 self._master_ssh.maybe_start(timeout=timeout)
mbligh0a883702010-04-21 01:58:34 +0000866
867
868 def clear_known_hosts(self):
869 """Clears out the temporary ssh known_hosts file.
870
871 This is useful if the test SSHes to the machine, then reinstalls it,
872 then SSHes to it again. It can be called after the reinstall to
873 reduce the spam in the logs.
874 """
875 logging.info("Clearing known hosts for host '%s', file '%s'.",
Dean Liaoe3e75f62017-11-14 10:36:43 +0800876 self.host_port, self.known_hosts_file)
mbligh0a883702010-04-21 01:58:34 +0000877 # Clear out the file by opening it for writing and then closing.
Fang Deng3af66202013-08-16 15:19:25 -0700878 fh = open(self.known_hosts_file, "w")
mbligh0a883702010-04-21 01:58:34 +0000879 fh.close()
Prashanth B98509c72014-04-04 16:01:34 -0700880
881
882 def collect_logs(self, remote_src_dir, local_dest_dir, ignore_errors=True):
883 """Copy log directories from a host to a local directory.
884
885 @param remote_src_dir: A destination directory on the host.
886 @param local_dest_dir: A path to a local destination directory.
887 If it doesn't exist it will be created.
888 @param ignore_errors: If True, ignore exceptions.
889
890 @raises OSError: If there were problems creating the local_dest_dir and
891 ignore_errors is False.
892 @raises AutoservRunError, AutotestRunError: If something goes wrong
893 while copying the directories and ignore_errors is False.
894 """
Dan Shi9f92aa62017-07-27 17:07:05 -0700895 if not self.check_cached_up_status():
896 logging.warning('Host %s did not answer to ping, skip collecting '
Dean Liaoe3e75f62017-11-14 10:36:43 +0800897 'logs.', self.host_port)
Dan Shi9f92aa62017-07-27 17:07:05 -0700898 return
899
Prashanth B98509c72014-04-04 16:01:34 -0700900 locally_created_dest = False
901 if (not os.path.exists(local_dest_dir)
902 or not os.path.isdir(local_dest_dir)):
903 try:
904 os.makedirs(local_dest_dir)
905 locally_created_dest = True
906 except OSError as e:
907 logging.warning('Unable to collect logs from host '
Dean Liaoe3e75f62017-11-14 10:36:43 +0800908 '%s: %s', self.host_port, e)
Prashanth B98509c72014-04-04 16:01:34 -0700909 if not ignore_errors:
910 raise
911 return
Dan Shi4f8c0242017-07-07 15:34:49 -0700912
913 # Build test result directory summary
914 try:
915 result_tools_runner.run_on_client(self, remote_src_dir)
916 except (error.AutotestRunError, error.AutoservRunError,
917 error.AutoservSSHTimeout) as e:
918 logging.exception(
919 'Non-critical failure: Failed to collect and throttle '
Dean Liaoe3e75f62017-11-14 10:36:43 +0800920 'results at %s from host %s', remote_src_dir,
921 self.host_port)
Dan Shi4f8c0242017-07-07 15:34:49 -0700922
Prashanth B98509c72014-04-04 16:01:34 -0700923 try:
Luigi Semenzato9b083072016-12-19 16:50:40 -0800924 self.get_file(remote_src_dir, local_dest_dir, safe_symlinks=True)
Prashanth B98509c72014-04-04 16:01:34 -0700925 except (error.AutotestRunError, error.AutoservRunError,
926 error.AutoservSSHTimeout) as e:
927 logging.warning('Collection of %s to local dir %s from host %s '
928 'failed: %s', remote_src_dir, local_dest_dir,
Dean Liaoe3e75f62017-11-14 10:36:43 +0800929 self.host_port, e)
Prashanth B98509c72014-04-04 16:01:34 -0700930 if locally_created_dest:
931 shutil.rmtree(local_dest_dir, ignore_errors=ignore_errors)
932 if not ignore_errors:
933 raise
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800934
Dan Shi4f8c0242017-07-07 15:34:49 -0700935 # Clean up directory summary file on the client side.
936 try:
937 result_tools_runner.run_on_client(self, remote_src_dir,
938 cleanup_only=True)
939 except (error.AutotestRunError, error.AutoservRunError,
940 error.AutoservSSHTimeout) as e:
941 logging.exception(
942 'Non-critical failure: Failed to cleanup result summary '
Lutz Justen043e9c12017-10-27 12:40:47 +0200943 'files at %s in host %s', remote_src_dir, self.hostname)
Dan Shi4f8c0242017-07-07 15:34:49 -0700944
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800945
xixuan6cf6d2f2016-01-29 15:29:00 -0800946 def create_ssh_tunnel(self, port, local_port):
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800947 """Create an ssh tunnel from local_port to port.
948
xixuan6cf6d2f2016-01-29 15:29:00 -0800949 This is used to forward a port securely through a tunnel process from
950 the server to the DUT for RPC server connection.
951
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800952 @param port: remote port on the host.
953 @param local_port: local forwarding port.
954
955 @return: the tunnel process.
956 """
957 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
Prathmesh Prabhu817b3f12017-07-31 17:08:41 -0700958 ssh_cmd = self.make_ssh_command(opts=tunnel_options, port=self.port)
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800959 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
960 logging.debug('Full tunnel command: %s', tunnel_cmd)
xixuan6cf6d2f2016-01-29 15:29:00 -0800961 # Exec the ssh process directly here rather than using a shell.
962 # Using a shell leaves a dangling ssh process, because we deliver
963 # signals to the shell wrapping ssh, not the ssh process itself.
964 args = shlex.split(tunnel_cmd)
Kuang-che Wu0ea03232019-08-31 10:52:31 +0800965 with open('/dev/null', 'w') as devnull:
966 tunnel_proc = subprocess.Popen(args, stdout=devnull, stderr=devnull,
967 close_fds=True)
Cheng-Yi Chianga155e7e2015-08-20 20:42:04 +0800968 logging.debug('Started ssh tunnel, local = %d'
969 ' remote = %d, pid = %d',
970 local_port, port, tunnel_proc.pid)
971 return tunnel_proc
Gilad Arnolda76bef02015-09-29 13:55:15 -0700972
973
Oleg Loskutoff1199bbb2019-10-21 12:27:13 -0700974 def disconnect_ssh_tunnel(self, tunnel_proc):
Roshan Pius58e5dd32015-10-16 15:16:42 -0700975 """
976 Disconnects a previously forwarded port from the server to the DUT for
977 RPC server connection.
978
xixuan6cf6d2f2016-01-29 15:29:00 -0800979 @param tunnel_proc: a tunnel process returned from |create_ssh_tunnel|.
Roshan Pius58e5dd32015-10-16 15:16:42 -0700980 """
981 if tunnel_proc.poll() is None:
982 tunnel_proc.terminate()
983 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
984 else:
985 logging.debug('Tunnel pid %d terminated early, status %d',
986 tunnel_proc.pid, tunnel_proc.returncode)
987
988
Gilad Arnolda76bef02015-09-29 13:55:15 -0700989 def get_os_type(self):
990 """Returns the host OS descriptor (to be implemented in subclasses).
991
992 @return A string describing the OS type.
993 """
Gwendal Grignou36b61702016-02-10 11:57:53 -0800994 raise NotImplementedError
Dan Shi9f92aa62017-07-27 17:07:05 -0700995
996
997 def check_cached_up_status(
998 self, expiration_seconds=_DEFAULT_UP_STATUS_EXPIRATION_SECONDS):
999 """Check if the DUT responded to ping in the past `expiration_seconds`.
1000
1001 @param expiration_seconds: The number of seconds to keep the cached
1002 status of whether the DUT responded to ping.
1003 @return: True if the DUT has responded to ping during the past
1004 `expiration_seconds`.
1005 """
1006 # Refresh the up status if any of following conditions is true:
1007 # * cached status is never set
1008 # * cached status is False, so the method can check if the host is up
1009 # again.
1010 # * If the cached status is older than `expiration_seconds`
1011 expire_time = time.time() - expiration_seconds
1012 if (self._cached_up_status_updated is None or
1013 not self._cached_up_status or
1014 self._cached_up_status_updated < expire_time):
1015 self._cached_up_status = self.is_up_fast()
1016 self._cached_up_status_updated = time.time()
1017 return self._cached_up_status
Otabek Kasimovf5e0f102020-06-30 19:41:02 -07001018
1019
1020 def _track_class_usage(self):
1021 """Tracking which class was used.
1022
1023 The idea to identify unused classes to be able clean them up.
1024 We skip names with dynamic created classes where the name is
1025 hostname of the device.
1026 """
1027 class_name = None
1028 if 'chrome' not in self.__class__.__name__:
1029 class_name = self.__class__.__name__
1030 else:
1031 for base in self.__class__.__bases__:
1032 if 'chrome' not in base.__name__:
1033 class_name = base.__name__
1034 break
1035 if class_name:
1036 data = {'host_class': class_name}
1037 metrics.Counter(
1038 'chromeos/autotest/used_hosts').increment(fields=data)