blob: 524d08421b6079905d6567feef676a841da065c7 [file] [log] [blame]
showardca572982009-09-18 21:20:01 +00001import os, time, types, socket, shutil, glob, logging, traceback
mblighefccc1b2010-01-11 19:08:42 +00002from autotest_lib.client.common_lib import autotemp, error, logging_manager
jadmanski31c49b72008-10-27 20:44:48 +00003from autotest_lib.server import utils, autotest
mblighe8b93af2009-01-30 00:45:53 +00004from autotest_lib.server.hosts import remote
mblighefccc1b2010-01-11 19:08:42 +00005from autotest_lib.client.common_lib.global_config import global_config
jadmanskica7da372008-10-21 16:26:52 +00006
7
mblighefccc1b2010-01-11 19:08:42 +00008enable_master_ssh = global_config.get_config_value(
9 'AUTOSERV', 'enable_master_ssh', type=bool, default=False)
10
11
12def make_ssh_command(user="root", port=22, opts='', connect_timeout=30,
13 alive_interval=300):
jadmanskica7da372008-10-21 16:26:52 +000014 base_command = ("/usr/bin/ssh -a -x %s -o BatchMode=yes "
mblighefccc1b2010-01-11 19:08:42 +000015 "-o ConnectTimeout=%d -o ServerAliveInterval=%d "
jadmanskica7da372008-10-21 16:26:52 +000016 "-l %s -p %d")
17 assert isinstance(connect_timeout, (int, long))
18 assert connect_timeout > 0 # can't disable the timeout
mblighefccc1b2010-01-11 19:08:42 +000019 return base_command % (opts, connect_timeout, alive_interval, user, port)
jadmanskica7da372008-10-21 16:26:52 +000020
21
mblighe8b93af2009-01-30 00:45:53 +000022# import site specific Host class
23SiteHost = utils.import_site_class(
24 __file__, "autotest_lib.server.hosts.site_host", "SiteHost",
25 remote.RemoteHost)
26
27
28class AbstractSSHHost(SiteHost):
mblighbc9402b2009-12-29 01:15:34 +000029 """
30 This class represents a generic implementation of most of the
jadmanskica7da372008-10-21 16:26:52 +000031 framework necessary for controlling a host via ssh. It implements
32 almost all of the abstract Host methods, except for the core
mblighbc9402b2009-12-29 01:15:34 +000033 Host.run method.
34 """
jadmanskica7da372008-10-21 16:26:52 +000035
jadmanskif6562912008-10-21 17:59:01 +000036 def _initialize(self, hostname, user="root", port=22, password="",
37 *args, **dargs):
38 super(AbstractSSHHost, self)._initialize(hostname=hostname,
39 *args, **dargs)
mbligh6369cf22008-10-24 17:21:57 +000040 self.ip = socket.getaddrinfo(self.hostname, None)[0][4][0]
jadmanskica7da372008-10-21 16:26:52 +000041 self.user = user
42 self.port = port
43 self.password = password
44
mblighefccc1b2010-01-11 19:08:42 +000045 """
46 Master SSH connection background job, socket temp directory and socket
47 control path option. If master-SSH is enabled, these fields will be
48 initialized by start_master_ssh when a new SSH connection is initiated.
49 """
50 self.master_ssh_job = None
51 self.master_ssh_tempdir = None
52 self.master_ssh_option = ''
53
mblighc9892c02010-01-06 19:02:16 +000054 # Check if rsync is available on the remote host. If it's not,
55 # don't try to use it for any future file transfers.
56 self.use_rsync = self._check_rsync()
57 if not self.use_rsync:
58 logging.warn("rsync not available on remote host %s -- disabled",
59 self.hostname)
60
61
62 def _check_rsync(self):
63 """
64 Check if rsync is available on the remote host.
65 """
66 try:
67 self.run("rsync --version", stdout_tee=None, stderr_tee=None)
68 except error.AutoservRunError:
69 return False
70 return True
71
jadmanskica7da372008-10-21 16:26:52 +000072
showard56176ec2009-10-28 19:52:30 +000073 def _encode_remote_paths(self, paths, escape=True):
mblighbc9402b2009-12-29 01:15:34 +000074 """
75 Given a list of file paths, encodes it as a single remote path, in
76 the style used by rsync and scp.
77 """
showard56176ec2009-10-28 19:52:30 +000078 if escape:
79 paths = [utils.scp_remote_escape(path) for path in paths]
80 return '%s@%s:"%s"' % (self.user, self.hostname, " ".join(paths))
jadmanskica7da372008-10-21 16:26:52 +000081
jadmanskica7da372008-10-21 16:26:52 +000082
mbligh45561782009-05-11 21:14:34 +000083 def _make_rsync_cmd(self, sources, dest, delete_dest, preserve_symlinks):
mblighbc9402b2009-12-29 01:15:34 +000084 """
85 Given a list of source paths and a destination path, produces the
jadmanskid7b79ed2009-01-07 17:19:48 +000086 appropriate rsync command for copying them. Remote paths must be
mblighbc9402b2009-12-29 01:15:34 +000087 pre-encoded.
88 """
mblighefccc1b2010-01-11 19:08:42 +000089 ssh_cmd = make_ssh_command(self.user, self.port,
90 self.master_ssh_option)
jadmanskid7b79ed2009-01-07 17:19:48 +000091 if delete_dest:
92 delete_flag = "--delete"
93 else:
94 delete_flag = ""
mbligh45561782009-05-11 21:14:34 +000095 if preserve_symlinks:
96 symlink_flag = ""
97 else:
98 symlink_flag = "-L"
99 command = "rsync %s %s --timeout=1800 --rsh='%s' -az %s %s"
100 return command % (symlink_flag, delete_flag, ssh_cmd,
101 " ".join(sources), dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000102
103
104 def _make_scp_cmd(self, sources, dest):
mblighbc9402b2009-12-29 01:15:34 +0000105 """
106 Given a list of source paths and a destination path, produces the
jadmanskid7b79ed2009-01-07 17:19:48 +0000107 appropriate scp command for encoding it. Remote paths must be
mblighbc9402b2009-12-29 01:15:34 +0000108 pre-encoded.
109 """
mblighefccc1b2010-01-11 19:08:42 +0000110 command = "scp -rq %s -P %d %s '%s'"
111 return command % (self.master_ssh_option,
112 self.port, " ".join(sources), dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000113
114
115 def _make_rsync_compatible_globs(self, path, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000116 """
117 Given an rsync-style path, returns a list of globbed paths
jadmanskid7b79ed2009-01-07 17:19:48 +0000118 that will hopefully provide equivalent behaviour for scp. Does not
119 support the full range of rsync pattern matching behaviour, only that
120 exposed in the get/send_file interface (trailing slashes).
121
122 The is_local param is flag indicating if the paths should be
mblighbc9402b2009-12-29 01:15:34 +0000123 interpreted as local or remote paths.
124 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000125
126 # non-trailing slash paths should just work
127 if len(path) == 0 or path[-1] != "/":
128 return [path]
129
130 # make a function to test if a pattern matches any files
131 if is_local:
showard56176ec2009-10-28 19:52:30 +0000132 def glob_matches_files(path, pattern):
133 return len(glob.glob(path + pattern)) > 0
jadmanskid7b79ed2009-01-07 17:19:48 +0000134 else:
showard56176ec2009-10-28 19:52:30 +0000135 def glob_matches_files(path, pattern):
136 result = self.run("ls \"%s\"%s" % (utils.sh_escape(path),
137 pattern),
138 stdout_tee=None, ignore_status=True)
jadmanskid7b79ed2009-01-07 17:19:48 +0000139 return result.exit_status == 0
140
141 # take a set of globs that cover all files, and see which are needed
142 patterns = ["*", ".[!.]*"]
showard56176ec2009-10-28 19:52:30 +0000143 patterns = [p for p in patterns if glob_matches_files(path, p)]
jadmanskid7b79ed2009-01-07 17:19:48 +0000144
145 # convert them into a set of paths suitable for the commandline
jadmanskid7b79ed2009-01-07 17:19:48 +0000146 if is_local:
showard56176ec2009-10-28 19:52:30 +0000147 return ["\"%s\"%s" % (utils.sh_escape(path), pattern)
148 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000149 else:
showard56176ec2009-10-28 19:52:30 +0000150 return [utils.scp_remote_escape(path) + pattern
151 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000152
153
154 def _make_rsync_compatible_source(self, source, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000155 """
156 Applies the same logic as _make_rsync_compatible_globs, but
jadmanskid7b79ed2009-01-07 17:19:48 +0000157 applies it to an entire list of sources, producing a new list of
mblighbc9402b2009-12-29 01:15:34 +0000158 sources, properly quoted.
159 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000160 return sum((self._make_rsync_compatible_globs(path, is_local)
161 for path in source), [])
jadmanskica7da372008-10-21 16:26:52 +0000162
163
mblighfeac0102009-04-28 18:31:12 +0000164 def _set_umask_perms(self, dest):
mblighbc9402b2009-12-29 01:15:34 +0000165 """
166 Given a destination file/dir (recursively) set the permissions on
167 all the files and directories to the max allowed by running umask.
168 """
mblighfeac0102009-04-28 18:31:12 +0000169
170 # now this looks strange but I haven't found a way in Python to _just_
171 # get the umask, apparently the only option is to try to set it
172 umask = os.umask(0)
173 os.umask(umask)
174
175 max_privs = 0777 & ~umask
176
177 def set_file_privs(filename):
178 file_stat = os.stat(filename)
179
180 file_privs = max_privs
181 # if the original file permissions do not have at least one
182 # executable bit then do not set it anywhere
183 if not file_stat.st_mode & 0111:
184 file_privs &= ~0111
185
186 os.chmod(filename, file_privs)
187
188 # try a bottom-up walk so changes on directory permissions won't cut
189 # our access to the files/directories inside it
190 for root, dirs, files in os.walk(dest, topdown=False):
191 # when setting the privileges we emulate the chmod "X" behaviour
192 # that sets to execute only if it is a directory or any of the
193 # owner/group/other already has execute right
194 for dirname in dirs:
195 os.chmod(os.path.join(root, dirname), max_privs)
196
197 for filename in files:
198 set_file_privs(os.path.join(root, filename))
199
200
201 # now set privs for the dest itself
202 if os.path.isdir(dest):
203 os.chmod(dest, max_privs)
204 else:
205 set_file_privs(dest)
206
207
mbligh45561782009-05-11 21:14:34 +0000208 def get_file(self, source, dest, delete_dest=False, preserve_perm=True,
209 preserve_symlinks=False):
jadmanskica7da372008-10-21 16:26:52 +0000210 """
211 Copy files from the remote host to a local path.
212
213 Directories will be copied recursively.
214 If a source component is a directory with a trailing slash,
215 the content of the directory will be copied, otherwise, the
216 directory itself and its content will be copied. This
217 behavior is similar to that of the program 'rsync'.
218
219 Args:
220 source: either
221 1) a single file or directory, as a string
222 2) a list of one or more (possibly mixed)
223 files or directories
224 dest: a file or a directory (if source contains a
225 directory or more than one element, you must
226 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000227 delete_dest: if this is true, the command will also clear
228 out any old files at dest that are not in the
229 source
mblighfeac0102009-04-28 18:31:12 +0000230 preserve_perm: tells get_file() to try to preserve the sources
231 permissions on files and dirs
mbligh45561782009-05-11 21:14:34 +0000232 preserve_symlinks: try to preserve symlinks instead of
233 transforming them into files/dirs on copy
jadmanskica7da372008-10-21 16:26:52 +0000234
235 Raises:
236 AutoservRunError: the scp command failed
237 """
mblighefccc1b2010-01-11 19:08:42 +0000238
239 # Start a master SSH connection if necessary.
240 self.start_master_ssh()
241
jadmanskica7da372008-10-21 16:26:52 +0000242 if isinstance(source, basestring):
243 source = [source]
jadmanskid7b79ed2009-01-07 17:19:48 +0000244 dest = os.path.abspath(dest)
jadmanskica7da372008-10-21 16:26:52 +0000245
mblighc9892c02010-01-06 19:02:16 +0000246 # If rsync is disabled or fails, try scp.
247 try_scp = not self.use_rsync
248 if self.use_rsync:
249 try:
250 remote_source = self._encode_remote_paths(source)
251 local_dest = utils.sh_escape(dest)
252 rsync = self._make_rsync_cmd([remote_source], local_dest,
253 delete_dest, preserve_symlinks)
254 utils.run(rsync)
255 except error.CmdError, e:
256 logging.warn("trying scp, rsync failed: %s" % e)
257 try_scp = True
258
259 if try_scp:
jadmanskid7b79ed2009-01-07 17:19:48 +0000260 # scp has no equivalent to --delete, just drop the entire dest dir
261 if delete_dest and os.path.isdir(dest):
262 shutil.rmtree(dest)
263 os.mkdir(dest)
jadmanskica7da372008-10-21 16:26:52 +0000264
jadmanskid7b79ed2009-01-07 17:19:48 +0000265 remote_source = self._make_rsync_compatible_source(source, False)
266 if remote_source:
showard56176ec2009-10-28 19:52:30 +0000267 # _make_rsync_compatible_source() already did the escaping
268 remote_source = self._encode_remote_paths(remote_source,
269 escape=False)
jadmanskid7b79ed2009-01-07 17:19:48 +0000270 local_dest = utils.sh_escape(dest)
jadmanski2583a432009-02-10 23:59:11 +0000271 scp = self._make_scp_cmd([remote_source], local_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000272 try:
273 utils.run(scp)
274 except error.CmdError, e:
275 raise error.AutoservRunError(e.args[0], e.args[1])
jadmanskica7da372008-10-21 16:26:52 +0000276
mblighfeac0102009-04-28 18:31:12 +0000277 if not preserve_perm:
278 # we have no way to tell scp to not try to preserve the
279 # permissions so set them after copy instead.
280 # for rsync we could use "--no-p --chmod=ugo=rwX" but those
281 # options are only in very recent rsync versions
282 self._set_umask_perms(dest)
283
jadmanskica7da372008-10-21 16:26:52 +0000284
mbligh45561782009-05-11 21:14:34 +0000285 def send_file(self, source, dest, delete_dest=False,
286 preserve_symlinks=False):
jadmanskica7da372008-10-21 16:26:52 +0000287 """
288 Copy files from a local path to the remote host.
289
290 Directories will be copied recursively.
291 If a source component is a directory with a trailing slash,
292 the content of the directory will be copied, otherwise, the
293 directory itself and its content will be copied. This
294 behavior is similar to that of the program 'rsync'.
295
296 Args:
297 source: either
298 1) a single file or directory, as a string
299 2) a list of one or more (possibly mixed)
300 files or directories
301 dest: a file or a directory (if source contains a
302 directory or more than one element, you must
303 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000304 delete_dest: if this is true, the command will also clear
305 out any old files at dest that are not in the
306 source
mbligh45561782009-05-11 21:14:34 +0000307 preserve_symlinks: controls if symlinks on the source will be
308 copied as such on the destination or transformed into the
309 referenced file/directory
jadmanskica7da372008-10-21 16:26:52 +0000310
311 Raises:
312 AutoservRunError: the scp command failed
313 """
mblighefccc1b2010-01-11 19:08:42 +0000314
315 # Start a master SSH connection if necessary.
316 self.start_master_ssh()
317
jadmanskica7da372008-10-21 16:26:52 +0000318 if isinstance(source, basestring):
319 source = [source]
jadmanski2583a432009-02-10 23:59:11 +0000320 remote_dest = self._encode_remote_paths([dest])
jadmanskica7da372008-10-21 16:26:52 +0000321
mblighc9892c02010-01-06 19:02:16 +0000322 # If rsync is disabled or fails, try scp.
323 try_scp = not self.use_rsync
324 if self.use_rsync:
325 try:
326 local_sources = [utils.sh_escape(path) for path in source]
327 rsync = self._make_rsync_cmd(local_sources, remote_dest,
328 delete_dest, preserve_symlinks)
329 utils.run(rsync)
330 except error.CmdError, e:
331 logging.warn("trying scp, rsync failed: %s" % e)
332 try_scp = True
333
334 if try_scp:
jadmanskid7b79ed2009-01-07 17:19:48 +0000335 # scp has no equivalent to --delete, just drop the entire dest dir
336 if delete_dest:
showard27160152009-07-15 14:28:42 +0000337 is_dir = self.run("ls -d %s/" % dest,
jadmanskid7b79ed2009-01-07 17:19:48 +0000338 ignore_status=True).exit_status == 0
339 if is_dir:
340 cmd = "rm -rf %s && mkdir %s"
mbligh5a0ca532009-08-03 16:44:34 +0000341 cmd %= (dest, dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000342 self.run(cmd)
jadmanskica7da372008-10-21 16:26:52 +0000343
jadmanski2583a432009-02-10 23:59:11 +0000344 local_sources = self._make_rsync_compatible_source(source, True)
345 if local_sources:
346 scp = self._make_scp_cmd(local_sources, remote_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000347 try:
348 utils.run(scp)
349 except error.CmdError, e:
350 raise error.AutoservRunError(e.args[0], e.args[1])
351
jadmanskica7da372008-10-21 16:26:52 +0000352
353 def ssh_ping(self, timeout=60):
354 try:
355 self.run("true", timeout=timeout, connect_timeout=timeout)
356 except error.AutoservSSHTimeout:
mblighd0e94982009-07-11 00:15:18 +0000357 msg = "Host (ssh) verify timed out (timeout = %d)" % timeout
jadmanskica7da372008-10-21 16:26:52 +0000358 raise error.AutoservSSHTimeout(msg)
mbligh9d738d62009-03-09 21:17:10 +0000359 except error.AutoservSshPermissionDeniedError:
360 #let AutoservSshPermissionDeniedError be visible to the callers
361 raise
jadmanskica7da372008-10-21 16:26:52 +0000362 except error.AutoservRunError, e:
mblighc971c5f2009-06-08 16:48:54 +0000363 # convert the generic AutoservRunError into something more
364 # specific for this context
365 raise error.AutoservSshPingHostError(e.description + '\n' +
366 repr(e.result_obj))
jadmanskica7da372008-10-21 16:26:52 +0000367
368
369 def is_up(self):
370 """
371 Check if the remote host is up.
372
jadmanskic0354912010-01-12 15:57:29 +0000373 @returns True if the remote host is up, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000374 """
375 try:
376 self.ssh_ping()
377 except error.AutoservError:
378 return False
379 else:
380 return True
381
382
383 def wait_up(self, timeout=None):
384 """
385 Wait until the remote host is up or the timeout expires.
386
387 In fact, it will wait until an ssh connection to the remote
388 host can be established, and getty is running.
389
jadmanskic0354912010-01-12 15:57:29 +0000390 @param timeout time limit in seconds before returning even
391 if the host is not up.
jadmanskica7da372008-10-21 16:26:52 +0000392
jadmanskic0354912010-01-12 15:57:29 +0000393 @returns True if the host was found to be up, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000394 """
395 if timeout:
396 end_time = time.time() + timeout
397
398 while not timeout or time.time() < end_time:
399 if self.is_up():
400 try:
401 if self.are_wait_up_processes_up():
402 return True
403 except error.AutoservError:
404 pass
405 time.sleep(1)
406
407 return False
408
409
jadmanskic0354912010-01-12 15:57:29 +0000410 def wait_down(self, timeout=None, warning_timer=None, old_boot_id=None):
jadmanskica7da372008-10-21 16:26:52 +0000411 """
412 Wait until the remote host is down or the timeout expires.
413
jadmanskic0354912010-01-12 15:57:29 +0000414 If old_boot_id is provided, this will wait until either the machine
415 is unpingable or self.get_boot_id() returns a value different from
416 old_boot_id. If the boot_id value has changed then the function
417 returns true under the assumption that the machine has shut down
418 and has now already come back up.
jadmanskica7da372008-10-21 16:26:52 +0000419
jadmanskic0354912010-01-12 15:57:29 +0000420 If old_boot_id is None then until the machine becomes unreachable the
421 method assumes the machine has not yet shut down.
jadmanskica7da372008-10-21 16:26:52 +0000422
jadmanskic0354912010-01-12 15:57:29 +0000423 @param timeout Time limit in seconds before returning even
424 if the host is still up.
425 @param warning_timer Time limit in seconds that will generate
426 a warning if the host is not down yet.
427 @param old_boot_id A string containing the result of self.get_boot_id()
428 prior to the host being told to shut down. Can be None if this is
429 not available.
430
431 @returns True if the host was found to be down, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000432 """
mbligh2ed998f2009-04-08 21:03:47 +0000433 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000434 if timeout:
mbligh2ed998f2009-04-08 21:03:47 +0000435 end_time = current_time + timeout
jadmanskica7da372008-10-21 16:26:52 +0000436
mbligh2ed998f2009-04-08 21:03:47 +0000437 if warning_timer:
438 warn_time = current_time + warning_timer
439
jadmanskic0354912010-01-12 15:57:29 +0000440 if old_boot_id is not None:
441 logging.debug('Host %s pre-shutdown boot_id is %s',
442 self.hostname, old_boot_id)
443
mbligh2ed998f2009-04-08 21:03:47 +0000444 while not timeout or current_time < end_time:
jadmanskic0354912010-01-12 15:57:29 +0000445 try:
446 new_boot_id = self.get_boot_id()
447 except error.AutoservSSHTimeout:
448 logging.debug('Host %s is now unreachable over ssh, is down',
449 self.hostname)
jadmanskica7da372008-10-21 16:26:52 +0000450 return True
jadmanskic0354912010-01-12 15:57:29 +0000451 else:
452 # if the machine is up but the boot_id value has changed from
453 # old boot id, then we can assume the machine has gone down
454 # and then already come back up
455 if old_boot_id is not None and old_boot_id != new_boot_id:
456 logging.debug('Host %s now has boot_id %s and so must '
457 'have rebooted', self.hostname, new_boot_id)
458 return True
mbligh2ed998f2009-04-08 21:03:47 +0000459
460 if warning_timer and current_time > warn_time:
461 self.record("WARN", None, "shutdown",
462 "Shutdown took longer than %ds" % warning_timer)
463 # Print the warning only once.
464 warning_timer = None
mbligha4464402009-04-17 20:13:41 +0000465 # If a machine is stuck switching runlevels
466 # This may cause the machine to reboot.
467 self.run('kill -HUP 1', ignore_status=True)
mbligh2ed998f2009-04-08 21:03:47 +0000468
jadmanskica7da372008-10-21 16:26:52 +0000469 time.sleep(1)
mbligh2ed998f2009-04-08 21:03:47 +0000470 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000471
472 return False
jadmanskif6562912008-10-21 17:59:01 +0000473
mbligha0a27592009-01-24 01:41:36 +0000474
jadmanskif6562912008-10-21 17:59:01 +0000475 # tunable constants for the verify & repair code
476 AUTOTEST_GB_DISKSPACE_REQUIRED = 20
mbligha0a27592009-01-24 01:41:36 +0000477
jadmanskif6562912008-10-21 17:59:01 +0000478
showardca572982009-09-18 21:20:01 +0000479 def verify_connectivity(self):
480 super(AbstractSSHHost, self).verify_connectivity()
jadmanskif6562912008-10-21 17:59:01 +0000481
showardb18134f2009-03-20 20:52:18 +0000482 logging.info('Pinging host ' + self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000483 self.ssh_ping()
mbligh2ba7ab02009-08-24 22:09:26 +0000484 logging.info("Host (ssh) %s is alive", self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000485
jadmanski80deb752009-01-21 17:14:16 +0000486 if self.is_shutting_down():
mblighc971c5f2009-06-08 16:48:54 +0000487 raise error.AutoservHostIsShuttingDownError("Host is shutting down")
jadmanski80deb752009-01-21 17:14:16 +0000488
mblighb49b5232009-02-12 21:54:49 +0000489
showardca572982009-09-18 21:20:01 +0000490 def verify_software(self):
491 super(AbstractSSHHost, self).verify_software()
jadmanskif6562912008-10-21 17:59:01 +0000492 try:
showardad812bf2009-10-20 23:49:56 +0000493 self.check_diskspace(autotest.Autotest.get_install_dir(self),
494 self.AUTOTEST_GB_DISKSPACE_REQUIRED)
jadmanskif6562912008-10-21 17:59:01 +0000495 except error.AutoservHostError:
496 raise # only want to raise if it's a space issue
showardad812bf2009-10-20 23:49:56 +0000497 except autotest.AutodirNotFoundError:
showardca572982009-09-18 21:20:01 +0000498 # autotest dir may not exist, etc. ignore
499 logging.debug('autodir space check exception, this is probably '
500 'safe to ignore\n' + traceback.format_exc())
mblighefccc1b2010-01-11 19:08:42 +0000501
502
503 def close(self):
504 super(AbstractSSHHost, self).close()
505 self._cleanup_master_ssh()
506
507
508 def _cleanup_master_ssh(self):
509 """
510 Release all resources (process, temporary directory) used by an active
511 master SSH connection.
512 """
513 # If a master SSH connection is running, kill it.
514 if self.master_ssh_job is not None:
515 utils.nuke_subprocess(self.master_ssh_job.sp)
516 self.master_ssh_job = None
517
518 # Remove the temporary directory for the master SSH socket.
519 if self.master_ssh_tempdir is not None:
520 self.master_ssh_tempdir.clean()
521 self.master_ssh_tempdir = None
522 self.master_ssh_option = ''
523
524
525 def start_master_ssh(self):
526 """
527 Called whenever a slave SSH connection needs to be initiated (e.g., by
528 run, rsync, scp). If master SSH support is enabled and a master SSH
529 connection is not active already, start a new one in the background.
530 Also, cleanup any zombie master SSH connections (e.g., dead due to
531 reboot).
532 """
533 if not enable_master_ssh:
534 return
535
536 # If a previously started master SSH connection is not running
537 # anymore, it needs to be cleaned up and then restarted.
538 if self.master_ssh_job is not None:
539 if self.master_ssh_job.sp.poll() is not None:
540 logging.info("Master ssh connection to %s is down.",
541 self.hostname)
542 self._cleanup_master_ssh()
543
544 # Start a new master SSH connection.
545 if self.master_ssh_job is None:
546 # Create a shared socket in a temp location.
547 self.master_ssh_tempdir = autotemp.tempdir(unique_id='ssh-master')
548 self.master_ssh_option = ("-o ControlPath=%s/socket" %
549 self.master_ssh_tempdir.name)
550
551 # Start the master SSH connection in the background.
552 master_cmd = self.ssh_command(options="-N -o ControlMaster=yes",
553 alive_interval=5)
554 logging.info("Starting master ssh connection '%s'" % master_cmd)
555 self.master_ssh_job = utils.BgJob(master_cmd)