blob: e3bfe61ca26fa13f733cba16f9bea941d10ad79d [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
mblighc0649d62010-01-15 18:15:58 +00008enable_master_ssh = global_config.get_config_value('AUTOSERV',
9 'enable_master_ssh',
10 type=bool, default=False)
mblighefccc1b2010-01-11 19:08:42 +000011
12
13def make_ssh_command(user="root", port=22, opts='', connect_timeout=30,
14 alive_interval=300):
mbligh91afdc22010-01-26 21:59:01 +000015 base_command = ("/usr/bin/ssh -a -q -x %s -o StrictHostKeyChecking=no "
mblighc0649d62010-01-15 18:15:58 +000016 "-o UserKnownHostsFile=/dev/null -o BatchMode=yes "
mblighefccc1b2010-01-11 19:08:42 +000017 "-o ConnectTimeout=%d -o ServerAliveInterval=%d "
jadmanskica7da372008-10-21 16:26:52 +000018 "-l %s -p %d")
19 assert isinstance(connect_timeout, (int, long))
20 assert connect_timeout > 0 # can't disable the timeout
mblighefccc1b2010-01-11 19:08:42 +000021 return base_command % (opts, connect_timeout, alive_interval, user, port)
jadmanskica7da372008-10-21 16:26:52 +000022
23
mblighe8b93af2009-01-30 00:45:53 +000024# import site specific Host class
25SiteHost = utils.import_site_class(
26 __file__, "autotest_lib.server.hosts.site_host", "SiteHost",
27 remote.RemoteHost)
28
29
30class AbstractSSHHost(SiteHost):
mblighbc9402b2009-12-29 01:15:34 +000031 """
32 This class represents a generic implementation of most of the
jadmanskica7da372008-10-21 16:26:52 +000033 framework necessary for controlling a host via ssh. It implements
34 almost all of the abstract Host methods, except for the core
mblighbc9402b2009-12-29 01:15:34 +000035 Host.run method.
36 """
jadmanskica7da372008-10-21 16:26:52 +000037
jadmanskif6562912008-10-21 17:59:01 +000038 def _initialize(self, hostname, user="root", port=22, password="",
39 *args, **dargs):
40 super(AbstractSSHHost, self)._initialize(hostname=hostname,
41 *args, **dargs)
mbligh6369cf22008-10-24 17:21:57 +000042 self.ip = socket.getaddrinfo(self.hostname, None)[0][4][0]
jadmanskica7da372008-10-21 16:26:52 +000043 self.user = user
44 self.port = port
45 self.password = password
showard6eafb492010-01-15 20:29:06 +000046 self._use_rsync = None
jadmanskica7da372008-10-21 16:26:52 +000047
mblighefccc1b2010-01-11 19:08:42 +000048 """
49 Master SSH connection background job, socket temp directory and socket
50 control path option. If master-SSH is enabled, these fields will be
51 initialized by start_master_ssh when a new SSH connection is initiated.
52 """
53 self.master_ssh_job = None
54 self.master_ssh_tempdir = None
55 self.master_ssh_option = ''
56
showard6eafb492010-01-15 20:29:06 +000057
58 def use_rsync(self):
59 if self._use_rsync is not None:
60 return self._use_rsync
61
mblighc9892c02010-01-06 19:02:16 +000062 # Check if rsync is available on the remote host. If it's not,
63 # don't try to use it for any future file transfers.
showard6eafb492010-01-15 20:29:06 +000064 self._use_rsync = self._check_rsync()
65 if not self._use_rsync:
mblighc9892c02010-01-06 19:02:16 +000066 logging.warn("rsync not available on remote host %s -- disabled",
67 self.hostname)
68
69
70 def _check_rsync(self):
71 """
72 Check if rsync is available on the remote host.
73 """
74 try:
75 self.run("rsync --version", stdout_tee=None, stderr_tee=None)
76 except error.AutoservRunError:
77 return False
78 return True
79
jadmanskica7da372008-10-21 16:26:52 +000080
showard56176ec2009-10-28 19:52:30 +000081 def _encode_remote_paths(self, paths, escape=True):
mblighbc9402b2009-12-29 01:15:34 +000082 """
83 Given a list of file paths, encodes it as a single remote path, in
84 the style used by rsync and scp.
85 """
showard56176ec2009-10-28 19:52:30 +000086 if escape:
87 paths = [utils.scp_remote_escape(path) for path in paths]
88 return '%s@%s:"%s"' % (self.user, self.hostname, " ".join(paths))
jadmanskica7da372008-10-21 16:26:52 +000089
jadmanskica7da372008-10-21 16:26:52 +000090
mbligh45561782009-05-11 21:14:34 +000091 def _make_rsync_cmd(self, sources, dest, delete_dest, preserve_symlinks):
mblighbc9402b2009-12-29 01:15:34 +000092 """
93 Given a list of source paths and a destination path, produces the
jadmanskid7b79ed2009-01-07 17:19:48 +000094 appropriate rsync command for copying them. Remote paths must be
mblighbc9402b2009-12-29 01:15:34 +000095 pre-encoded.
96 """
mblighefccc1b2010-01-11 19:08:42 +000097 ssh_cmd = make_ssh_command(self.user, self.port,
98 self.master_ssh_option)
jadmanskid7b79ed2009-01-07 17:19:48 +000099 if delete_dest:
100 delete_flag = "--delete"
101 else:
102 delete_flag = ""
mbligh45561782009-05-11 21:14:34 +0000103 if preserve_symlinks:
104 symlink_flag = ""
105 else:
106 symlink_flag = "-L"
107 command = "rsync %s %s --timeout=1800 --rsh='%s' -az %s %s"
108 return command % (symlink_flag, delete_flag, ssh_cmd,
109 " ".join(sources), dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000110
111
112 def _make_scp_cmd(self, sources, dest):
mblighbc9402b2009-12-29 01:15:34 +0000113 """
114 Given a list of source paths and a destination path, produces the
jadmanskid7b79ed2009-01-07 17:19:48 +0000115 appropriate scp command for encoding it. Remote paths must be
mblighbc9402b2009-12-29 01:15:34 +0000116 pre-encoded.
117 """
mblighc0649d62010-01-15 18:15:58 +0000118 command = ("scp -rq %s -o StrictHostKeyChecking=no "
119 "-o UserKnownHostsFile=/dev/null -P %d %s '%s'")
mblighefccc1b2010-01-11 19:08:42 +0000120 return command % (self.master_ssh_option,
121 self.port, " ".join(sources), dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000122
123
124 def _make_rsync_compatible_globs(self, path, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000125 """
126 Given an rsync-style path, returns a list of globbed paths
jadmanskid7b79ed2009-01-07 17:19:48 +0000127 that will hopefully provide equivalent behaviour for scp. Does not
128 support the full range of rsync pattern matching behaviour, only that
129 exposed in the get/send_file interface (trailing slashes).
130
131 The is_local param is flag indicating if the paths should be
mblighbc9402b2009-12-29 01:15:34 +0000132 interpreted as local or remote paths.
133 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000134
135 # non-trailing slash paths should just work
136 if len(path) == 0 or path[-1] != "/":
137 return [path]
138
139 # make a function to test if a pattern matches any files
140 if is_local:
showard56176ec2009-10-28 19:52:30 +0000141 def glob_matches_files(path, pattern):
142 return len(glob.glob(path + pattern)) > 0
jadmanskid7b79ed2009-01-07 17:19:48 +0000143 else:
showard56176ec2009-10-28 19:52:30 +0000144 def glob_matches_files(path, pattern):
145 result = self.run("ls \"%s\"%s" % (utils.sh_escape(path),
146 pattern),
147 stdout_tee=None, ignore_status=True)
jadmanskid7b79ed2009-01-07 17:19:48 +0000148 return result.exit_status == 0
149
150 # take a set of globs that cover all files, and see which are needed
151 patterns = ["*", ".[!.]*"]
showard56176ec2009-10-28 19:52:30 +0000152 patterns = [p for p in patterns if glob_matches_files(path, p)]
jadmanskid7b79ed2009-01-07 17:19:48 +0000153
154 # convert them into a set of paths suitable for the commandline
jadmanskid7b79ed2009-01-07 17:19:48 +0000155 if is_local:
showard56176ec2009-10-28 19:52:30 +0000156 return ["\"%s\"%s" % (utils.sh_escape(path), pattern)
157 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000158 else:
showard56176ec2009-10-28 19:52:30 +0000159 return [utils.scp_remote_escape(path) + pattern
160 for pattern in patterns]
jadmanskid7b79ed2009-01-07 17:19:48 +0000161
162
163 def _make_rsync_compatible_source(self, source, is_local):
mblighbc9402b2009-12-29 01:15:34 +0000164 """
165 Applies the same logic as _make_rsync_compatible_globs, but
jadmanskid7b79ed2009-01-07 17:19:48 +0000166 applies it to an entire list of sources, producing a new list of
mblighbc9402b2009-12-29 01:15:34 +0000167 sources, properly quoted.
168 """
jadmanskid7b79ed2009-01-07 17:19:48 +0000169 return sum((self._make_rsync_compatible_globs(path, is_local)
170 for path in source), [])
jadmanskica7da372008-10-21 16:26:52 +0000171
172
mblighfeac0102009-04-28 18:31:12 +0000173 def _set_umask_perms(self, dest):
mblighbc9402b2009-12-29 01:15:34 +0000174 """
175 Given a destination file/dir (recursively) set the permissions on
176 all the files and directories to the max allowed by running umask.
177 """
mblighfeac0102009-04-28 18:31:12 +0000178
179 # now this looks strange but I haven't found a way in Python to _just_
180 # get the umask, apparently the only option is to try to set it
181 umask = os.umask(0)
182 os.umask(umask)
183
184 max_privs = 0777 & ~umask
185
186 def set_file_privs(filename):
187 file_stat = os.stat(filename)
188
189 file_privs = max_privs
190 # if the original file permissions do not have at least one
191 # executable bit then do not set it anywhere
192 if not file_stat.st_mode & 0111:
193 file_privs &= ~0111
194
195 os.chmod(filename, file_privs)
196
197 # try a bottom-up walk so changes on directory permissions won't cut
198 # our access to the files/directories inside it
199 for root, dirs, files in os.walk(dest, topdown=False):
200 # when setting the privileges we emulate the chmod "X" behaviour
201 # that sets to execute only if it is a directory or any of the
202 # owner/group/other already has execute right
203 for dirname in dirs:
204 os.chmod(os.path.join(root, dirname), max_privs)
205
206 for filename in files:
207 set_file_privs(os.path.join(root, filename))
208
209
210 # now set privs for the dest itself
211 if os.path.isdir(dest):
212 os.chmod(dest, max_privs)
213 else:
214 set_file_privs(dest)
215
216
mbligh45561782009-05-11 21:14:34 +0000217 def get_file(self, source, dest, delete_dest=False, preserve_perm=True,
218 preserve_symlinks=False):
jadmanskica7da372008-10-21 16:26:52 +0000219 """
220 Copy files from the remote host to a local path.
221
222 Directories will be copied recursively.
223 If a source component is a directory with a trailing slash,
224 the content of the directory will be copied, otherwise, the
225 directory itself and its content will be copied. This
226 behavior is similar to that of the program 'rsync'.
227
228 Args:
229 source: either
230 1) a single file or directory, as a string
231 2) a list of one or more (possibly mixed)
232 files or directories
233 dest: a file or a directory (if source contains a
234 directory or more than one element, you must
235 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000236 delete_dest: if this is true, the command will also clear
237 out any old files at dest that are not in the
238 source
mblighfeac0102009-04-28 18:31:12 +0000239 preserve_perm: tells get_file() to try to preserve the sources
240 permissions on files and dirs
mbligh45561782009-05-11 21:14:34 +0000241 preserve_symlinks: try to preserve symlinks instead of
242 transforming them into files/dirs on copy
jadmanskica7da372008-10-21 16:26:52 +0000243
244 Raises:
245 AutoservRunError: the scp command failed
246 """
mblighefccc1b2010-01-11 19:08:42 +0000247
248 # Start a master SSH connection if necessary.
249 self.start_master_ssh()
250
jadmanskica7da372008-10-21 16:26:52 +0000251 if isinstance(source, basestring):
252 source = [source]
jadmanskid7b79ed2009-01-07 17:19:48 +0000253 dest = os.path.abspath(dest)
jadmanskica7da372008-10-21 16:26:52 +0000254
mblighc9892c02010-01-06 19:02:16 +0000255 # If rsync is disabled or fails, try scp.
showard6eafb492010-01-15 20:29:06 +0000256 try_scp = True
257 if self.use_rsync():
mblighc9892c02010-01-06 19:02:16 +0000258 try:
259 remote_source = self._encode_remote_paths(source)
260 local_dest = utils.sh_escape(dest)
261 rsync = self._make_rsync_cmd([remote_source], local_dest,
262 delete_dest, preserve_symlinks)
263 utils.run(rsync)
showard6eafb492010-01-15 20:29:06 +0000264 try_scp = False
mblighc9892c02010-01-06 19:02:16 +0000265 except error.CmdError, e:
266 logging.warn("trying scp, rsync failed: %s" % e)
mblighc9892c02010-01-06 19:02:16 +0000267
268 if try_scp:
jadmanskid7b79ed2009-01-07 17:19:48 +0000269 # scp has no equivalent to --delete, just drop the entire dest dir
270 if delete_dest and os.path.isdir(dest):
271 shutil.rmtree(dest)
272 os.mkdir(dest)
jadmanskica7da372008-10-21 16:26:52 +0000273
jadmanskid7b79ed2009-01-07 17:19:48 +0000274 remote_source = self._make_rsync_compatible_source(source, False)
275 if remote_source:
showard56176ec2009-10-28 19:52:30 +0000276 # _make_rsync_compatible_source() already did the escaping
277 remote_source = self._encode_remote_paths(remote_source,
278 escape=False)
jadmanskid7b79ed2009-01-07 17:19:48 +0000279 local_dest = utils.sh_escape(dest)
jadmanski2583a432009-02-10 23:59:11 +0000280 scp = self._make_scp_cmd([remote_source], local_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000281 try:
282 utils.run(scp)
283 except error.CmdError, e:
284 raise error.AutoservRunError(e.args[0], e.args[1])
jadmanskica7da372008-10-21 16:26:52 +0000285
mblighfeac0102009-04-28 18:31:12 +0000286 if not preserve_perm:
287 # we have no way to tell scp to not try to preserve the
288 # permissions so set them after copy instead.
289 # for rsync we could use "--no-p --chmod=ugo=rwX" but those
290 # options are only in very recent rsync versions
291 self._set_umask_perms(dest)
292
jadmanskica7da372008-10-21 16:26:52 +0000293
mbligh45561782009-05-11 21:14:34 +0000294 def send_file(self, source, dest, delete_dest=False,
295 preserve_symlinks=False):
jadmanskica7da372008-10-21 16:26:52 +0000296 """
297 Copy files from a local path to the remote host.
298
299 Directories will be copied recursively.
300 If a source component is a directory with a trailing slash,
301 the content of the directory will be copied, otherwise, the
302 directory itself and its content will be copied. This
303 behavior is similar to that of the program 'rsync'.
304
305 Args:
306 source: either
307 1) a single file or directory, as a string
308 2) a list of one or more (possibly mixed)
309 files or directories
310 dest: a file or a directory (if source contains a
311 directory or more than one element, you must
312 supply a directory dest)
mbligh89e258d2008-10-24 13:58:08 +0000313 delete_dest: if this is true, the command will also clear
314 out any old files at dest that are not in the
315 source
mbligh45561782009-05-11 21:14:34 +0000316 preserve_symlinks: controls if symlinks on the source will be
317 copied as such on the destination or transformed into the
318 referenced file/directory
jadmanskica7da372008-10-21 16:26:52 +0000319
320 Raises:
321 AutoservRunError: the scp command failed
322 """
mblighefccc1b2010-01-11 19:08:42 +0000323
324 # Start a master SSH connection if necessary.
325 self.start_master_ssh()
326
jadmanskica7da372008-10-21 16:26:52 +0000327 if isinstance(source, basestring):
328 source = [source]
jadmanski2583a432009-02-10 23:59:11 +0000329 remote_dest = self._encode_remote_paths([dest])
jadmanskica7da372008-10-21 16:26:52 +0000330
mblighc9892c02010-01-06 19:02:16 +0000331 # If rsync is disabled or fails, try scp.
showard6eafb492010-01-15 20:29:06 +0000332 try_scp = True
333 if self.use_rsync():
mblighc9892c02010-01-06 19:02:16 +0000334 try:
335 local_sources = [utils.sh_escape(path) for path in source]
336 rsync = self._make_rsync_cmd(local_sources, remote_dest,
337 delete_dest, preserve_symlinks)
338 utils.run(rsync)
showard6eafb492010-01-15 20:29:06 +0000339 try_scp = False
mblighc9892c02010-01-06 19:02:16 +0000340 except error.CmdError, e:
341 logging.warn("trying scp, rsync failed: %s" % e)
mblighc9892c02010-01-06 19:02:16 +0000342
343 if try_scp:
jadmanskid7b79ed2009-01-07 17:19:48 +0000344 # scp has no equivalent to --delete, just drop the entire dest dir
345 if delete_dest:
showard27160152009-07-15 14:28:42 +0000346 is_dir = self.run("ls -d %s/" % dest,
jadmanskid7b79ed2009-01-07 17:19:48 +0000347 ignore_status=True).exit_status == 0
348 if is_dir:
349 cmd = "rm -rf %s && mkdir %s"
mbligh5a0ca532009-08-03 16:44:34 +0000350 cmd %= (dest, dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000351 self.run(cmd)
jadmanskica7da372008-10-21 16:26:52 +0000352
jadmanski2583a432009-02-10 23:59:11 +0000353 local_sources = self._make_rsync_compatible_source(source, True)
354 if local_sources:
355 scp = self._make_scp_cmd(local_sources, remote_dest)
jadmanskid7b79ed2009-01-07 17:19:48 +0000356 try:
357 utils.run(scp)
358 except error.CmdError, e:
359 raise error.AutoservRunError(e.args[0], e.args[1])
360
jadmanskica7da372008-10-21 16:26:52 +0000361
362 def ssh_ping(self, timeout=60):
363 try:
364 self.run("true", timeout=timeout, connect_timeout=timeout)
365 except error.AutoservSSHTimeout:
mblighd0e94982009-07-11 00:15:18 +0000366 msg = "Host (ssh) verify timed out (timeout = %d)" % timeout
jadmanskica7da372008-10-21 16:26:52 +0000367 raise error.AutoservSSHTimeout(msg)
mbligh9d738d62009-03-09 21:17:10 +0000368 except error.AutoservSshPermissionDeniedError:
369 #let AutoservSshPermissionDeniedError be visible to the callers
370 raise
jadmanskica7da372008-10-21 16:26:52 +0000371 except error.AutoservRunError, e:
mblighc971c5f2009-06-08 16:48:54 +0000372 # convert the generic AutoservRunError into something more
373 # specific for this context
374 raise error.AutoservSshPingHostError(e.description + '\n' +
375 repr(e.result_obj))
jadmanskica7da372008-10-21 16:26:52 +0000376
377
378 def is_up(self):
379 """
380 Check if the remote host is up.
381
jadmanskic0354912010-01-12 15:57:29 +0000382 @returns True if the remote host is up, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000383 """
384 try:
385 self.ssh_ping()
386 except error.AutoservError:
387 return False
388 else:
389 return True
390
391
392 def wait_up(self, timeout=None):
393 """
394 Wait until the remote host is up or the timeout expires.
395
396 In fact, it will wait until an ssh connection to the remote
397 host can be established, and getty is running.
398
jadmanskic0354912010-01-12 15:57:29 +0000399 @param timeout time limit in seconds before returning even
400 if the host is not up.
jadmanskica7da372008-10-21 16:26:52 +0000401
jadmanskic0354912010-01-12 15:57:29 +0000402 @returns True if the host was found to be up, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000403 """
404 if timeout:
405 end_time = time.time() + timeout
406
407 while not timeout or time.time() < end_time:
408 if self.is_up():
409 try:
410 if self.are_wait_up_processes_up():
411 return True
412 except error.AutoservError:
413 pass
414 time.sleep(1)
415
416 return False
417
418
jadmanskic0354912010-01-12 15:57:29 +0000419 def wait_down(self, timeout=None, warning_timer=None, old_boot_id=None):
jadmanskica7da372008-10-21 16:26:52 +0000420 """
421 Wait until the remote host is down or the timeout expires.
422
jadmanskic0354912010-01-12 15:57:29 +0000423 If old_boot_id is provided, this will wait until either the machine
424 is unpingable or self.get_boot_id() returns a value different from
425 old_boot_id. If the boot_id value has changed then the function
426 returns true under the assumption that the machine has shut down
427 and has now already come back up.
jadmanskica7da372008-10-21 16:26:52 +0000428
jadmanskic0354912010-01-12 15:57:29 +0000429 If old_boot_id is None then until the machine becomes unreachable the
430 method assumes the machine has not yet shut down.
jadmanskica7da372008-10-21 16:26:52 +0000431
jadmanskic0354912010-01-12 15:57:29 +0000432 @param timeout Time limit in seconds before returning even
433 if the host is still up.
434 @param warning_timer Time limit in seconds that will generate
435 a warning if the host is not down yet.
436 @param old_boot_id A string containing the result of self.get_boot_id()
437 prior to the host being told to shut down. Can be None if this is
438 not available.
439
440 @returns True if the host was found to be down, False otherwise
jadmanskica7da372008-10-21 16:26:52 +0000441 """
mbligh2ed998f2009-04-08 21:03:47 +0000442 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000443 if timeout:
mbligh2ed998f2009-04-08 21:03:47 +0000444 end_time = current_time + timeout
jadmanskica7da372008-10-21 16:26:52 +0000445
mbligh2ed998f2009-04-08 21:03:47 +0000446 if warning_timer:
447 warn_time = current_time + warning_timer
448
jadmanskic0354912010-01-12 15:57:29 +0000449 if old_boot_id is not None:
450 logging.debug('Host %s pre-shutdown boot_id is %s',
451 self.hostname, old_boot_id)
452
mbligh2ed998f2009-04-08 21:03:47 +0000453 while not timeout or current_time < end_time:
jadmanskic0354912010-01-12 15:57:29 +0000454 try:
455 new_boot_id = self.get_boot_id()
mblighdbc7e4a2010-01-15 20:34:20 +0000456 except error.AutoservError:
jadmanskic0354912010-01-12 15:57:29 +0000457 logging.debug('Host %s is now unreachable over ssh, is down',
458 self.hostname)
jadmanskica7da372008-10-21 16:26:52 +0000459 return True
jadmanskic0354912010-01-12 15:57:29 +0000460 else:
461 # if the machine is up but the boot_id value has changed from
462 # old boot id, then we can assume the machine has gone down
463 # and then already come back up
464 if old_boot_id is not None and old_boot_id != new_boot_id:
465 logging.debug('Host %s now has boot_id %s and so must '
466 'have rebooted', self.hostname, new_boot_id)
467 return True
mbligh2ed998f2009-04-08 21:03:47 +0000468
469 if warning_timer and current_time > warn_time:
470 self.record("WARN", None, "shutdown",
471 "Shutdown took longer than %ds" % warning_timer)
472 # Print the warning only once.
473 warning_timer = None
mbligha4464402009-04-17 20:13:41 +0000474 # If a machine is stuck switching runlevels
475 # This may cause the machine to reboot.
476 self.run('kill -HUP 1', ignore_status=True)
mbligh2ed998f2009-04-08 21:03:47 +0000477
jadmanskica7da372008-10-21 16:26:52 +0000478 time.sleep(1)
mbligh2ed998f2009-04-08 21:03:47 +0000479 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000480
481 return False
jadmanskif6562912008-10-21 17:59:01 +0000482
mbligha0a27592009-01-24 01:41:36 +0000483
jadmanskif6562912008-10-21 17:59:01 +0000484 # tunable constants for the verify & repair code
485 AUTOTEST_GB_DISKSPACE_REQUIRED = 20
mbligha0a27592009-01-24 01:41:36 +0000486
jadmanskif6562912008-10-21 17:59:01 +0000487
showardca572982009-09-18 21:20:01 +0000488 def verify_connectivity(self):
489 super(AbstractSSHHost, self).verify_connectivity()
jadmanskif6562912008-10-21 17:59:01 +0000490
showardb18134f2009-03-20 20:52:18 +0000491 logging.info('Pinging host ' + self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000492 self.ssh_ping()
mbligh2ba7ab02009-08-24 22:09:26 +0000493 logging.info("Host (ssh) %s is alive", self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000494
jadmanski80deb752009-01-21 17:14:16 +0000495 if self.is_shutting_down():
mblighc971c5f2009-06-08 16:48:54 +0000496 raise error.AutoservHostIsShuttingDownError("Host is shutting down")
jadmanski80deb752009-01-21 17:14:16 +0000497
mblighb49b5232009-02-12 21:54:49 +0000498
showardca572982009-09-18 21:20:01 +0000499 def verify_software(self):
500 super(AbstractSSHHost, self).verify_software()
jadmanskif6562912008-10-21 17:59:01 +0000501 try:
showardad812bf2009-10-20 23:49:56 +0000502 self.check_diskspace(autotest.Autotest.get_install_dir(self),
503 self.AUTOTEST_GB_DISKSPACE_REQUIRED)
jadmanskif6562912008-10-21 17:59:01 +0000504 except error.AutoservHostError:
505 raise # only want to raise if it's a space issue
showardad812bf2009-10-20 23:49:56 +0000506 except autotest.AutodirNotFoundError:
showardca572982009-09-18 21:20:01 +0000507 # autotest dir may not exist, etc. ignore
508 logging.debug('autodir space check exception, this is probably '
509 'safe to ignore\n' + traceback.format_exc())
mblighefccc1b2010-01-11 19:08:42 +0000510
511
512 def close(self):
513 super(AbstractSSHHost, self).close()
514 self._cleanup_master_ssh()
515
516
517 def _cleanup_master_ssh(self):
518 """
519 Release all resources (process, temporary directory) used by an active
520 master SSH connection.
521 """
522 # If a master SSH connection is running, kill it.
523 if self.master_ssh_job is not None:
524 utils.nuke_subprocess(self.master_ssh_job.sp)
525 self.master_ssh_job = None
526
527 # Remove the temporary directory for the master SSH socket.
528 if self.master_ssh_tempdir is not None:
529 self.master_ssh_tempdir.clean()
530 self.master_ssh_tempdir = None
531 self.master_ssh_option = ''
532
533
534 def start_master_ssh(self):
535 """
536 Called whenever a slave SSH connection needs to be initiated (e.g., by
537 run, rsync, scp). If master SSH support is enabled and a master SSH
538 connection is not active already, start a new one in the background.
539 Also, cleanup any zombie master SSH connections (e.g., dead due to
540 reboot).
541 """
542 if not enable_master_ssh:
543 return
544
545 # If a previously started master SSH connection is not running
546 # anymore, it needs to be cleaned up and then restarted.
547 if self.master_ssh_job is not None:
548 if self.master_ssh_job.sp.poll() is not None:
549 logging.info("Master ssh connection to %s is down.",
550 self.hostname)
551 self._cleanup_master_ssh()
552
553 # Start a new master SSH connection.
554 if self.master_ssh_job is None:
555 # Create a shared socket in a temp location.
556 self.master_ssh_tempdir = autotemp.tempdir(unique_id='ssh-master')
557 self.master_ssh_option = ("-o ControlPath=%s/socket" %
558 self.master_ssh_tempdir.name)
559
560 # Start the master SSH connection in the background.
mbligh5644c122010-01-29 17:43:26 +0000561 master_cmd = self.ssh_command(options="-N -o ControlMaster=yes")
mblighefccc1b2010-01-11 19:08:42 +0000562 logging.info("Starting master ssh connection '%s'" % master_cmd)
563 self.master_ssh_job = utils.BgJob(master_cmd)