blob: d671ab5278cc3627c57119f5263280c4a3799beb [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
373 Returns:
374 True if the remote host is up, False otherwise
375 """
376 try:
377 self.ssh_ping()
378 except error.AutoservError:
379 return False
380 else:
381 return True
382
383
384 def wait_up(self, timeout=None):
385 """
386 Wait until the remote host is up or the timeout expires.
387
388 In fact, it will wait until an ssh connection to the remote
389 host can be established, and getty is running.
390
391 Args:
392 timeout: time limit in seconds before returning even
393 if the host is not up.
394
395 Returns:
396 True if the host was found to be up, False otherwise
397 """
398 if timeout:
399 end_time = time.time() + timeout
400
401 while not timeout or time.time() < end_time:
402 if self.is_up():
403 try:
404 if self.are_wait_up_processes_up():
405 return True
406 except error.AutoservError:
407 pass
408 time.sleep(1)
409
410 return False
411
412
mbligh2ed998f2009-04-08 21:03:47 +0000413 def wait_down(self, timeout=None, warning_timer=None):
jadmanskica7da372008-10-21 16:26:52 +0000414 """
415 Wait until the remote host is down or the timeout expires.
416
417 In fact, it will wait until an ssh connection to the remote
418 host fails.
419
420 Args:
mbligh2ed998f2009-04-08 21:03:47 +0000421 timeout: time limit in seconds before returning even
422 if the host is still up.
423 warning_timer: time limit in seconds that will generate
424 a warning if the host is not down yet.
jadmanskica7da372008-10-21 16:26:52 +0000425
426 Returns:
427 True if the host was found to be down, False otherwise
428 """
mbligh2ed998f2009-04-08 21:03:47 +0000429 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000430 if timeout:
mbligh2ed998f2009-04-08 21:03:47 +0000431 end_time = current_time + timeout
jadmanskica7da372008-10-21 16:26:52 +0000432
mbligh2ed998f2009-04-08 21:03:47 +0000433 if warning_timer:
434 warn_time = current_time + warning_timer
435
436 while not timeout or current_time < end_time:
jadmanskica7da372008-10-21 16:26:52 +0000437 if not self.is_up():
438 return True
mbligh2ed998f2009-04-08 21:03:47 +0000439
440 if warning_timer and current_time > warn_time:
441 self.record("WARN", None, "shutdown",
442 "Shutdown took longer than %ds" % warning_timer)
443 # Print the warning only once.
444 warning_timer = None
mbligha4464402009-04-17 20:13:41 +0000445 # If a machine is stuck switching runlevels
446 # This may cause the machine to reboot.
447 self.run('kill -HUP 1', ignore_status=True)
mbligh2ed998f2009-04-08 21:03:47 +0000448
jadmanskica7da372008-10-21 16:26:52 +0000449 time.sleep(1)
mbligh2ed998f2009-04-08 21:03:47 +0000450 current_time = time.time()
jadmanskica7da372008-10-21 16:26:52 +0000451
452 return False
jadmanskif6562912008-10-21 17:59:01 +0000453
mbligha0a27592009-01-24 01:41:36 +0000454
jadmanskif6562912008-10-21 17:59:01 +0000455 # tunable constants for the verify & repair code
456 AUTOTEST_GB_DISKSPACE_REQUIRED = 20
mbligha0a27592009-01-24 01:41:36 +0000457
jadmanskif6562912008-10-21 17:59:01 +0000458
showardca572982009-09-18 21:20:01 +0000459 def verify_connectivity(self):
460 super(AbstractSSHHost, self).verify_connectivity()
jadmanskif6562912008-10-21 17:59:01 +0000461
showardb18134f2009-03-20 20:52:18 +0000462 logging.info('Pinging host ' + self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000463 self.ssh_ping()
mbligh2ba7ab02009-08-24 22:09:26 +0000464 logging.info("Host (ssh) %s is alive", self.hostname)
jadmanskif6562912008-10-21 17:59:01 +0000465
jadmanski80deb752009-01-21 17:14:16 +0000466 if self.is_shutting_down():
mblighc971c5f2009-06-08 16:48:54 +0000467 raise error.AutoservHostIsShuttingDownError("Host is shutting down")
jadmanski80deb752009-01-21 17:14:16 +0000468
mblighb49b5232009-02-12 21:54:49 +0000469
showardca572982009-09-18 21:20:01 +0000470 def verify_software(self):
471 super(AbstractSSHHost, self).verify_software()
jadmanskif6562912008-10-21 17:59:01 +0000472 try:
showardad812bf2009-10-20 23:49:56 +0000473 self.check_diskspace(autotest.Autotest.get_install_dir(self),
474 self.AUTOTEST_GB_DISKSPACE_REQUIRED)
jadmanskif6562912008-10-21 17:59:01 +0000475 except error.AutoservHostError:
476 raise # only want to raise if it's a space issue
showardad812bf2009-10-20 23:49:56 +0000477 except autotest.AutodirNotFoundError:
showardca572982009-09-18 21:20:01 +0000478 # autotest dir may not exist, etc. ignore
479 logging.debug('autodir space check exception, this is probably '
480 'safe to ignore\n' + traceback.format_exc())
mblighefccc1b2010-01-11 19:08:42 +0000481
482
483 def close(self):
484 super(AbstractSSHHost, self).close()
485 self._cleanup_master_ssh()
486
487
488 def _cleanup_master_ssh(self):
489 """
490 Release all resources (process, temporary directory) used by an active
491 master SSH connection.
492 """
493 # If a master SSH connection is running, kill it.
494 if self.master_ssh_job is not None:
495 utils.nuke_subprocess(self.master_ssh_job.sp)
496 self.master_ssh_job = None
497
498 # Remove the temporary directory for the master SSH socket.
499 if self.master_ssh_tempdir is not None:
500 self.master_ssh_tempdir.clean()
501 self.master_ssh_tempdir = None
502 self.master_ssh_option = ''
503
504
505 def start_master_ssh(self):
506 """
507 Called whenever a slave SSH connection needs to be initiated (e.g., by
508 run, rsync, scp). If master SSH support is enabled and a master SSH
509 connection is not active already, start a new one in the background.
510 Also, cleanup any zombie master SSH connections (e.g., dead due to
511 reboot).
512 """
513 if not enable_master_ssh:
514 return
515
516 # If a previously started master SSH connection is not running
517 # anymore, it needs to be cleaned up and then restarted.
518 if self.master_ssh_job is not None:
519 if self.master_ssh_job.sp.poll() is not None:
520 logging.info("Master ssh connection to %s is down.",
521 self.hostname)
522 self._cleanup_master_ssh()
523
524 # Start a new master SSH connection.
525 if self.master_ssh_job is None:
526 # Create a shared socket in a temp location.
527 self.master_ssh_tempdir = autotemp.tempdir(unique_id='ssh-master')
528 self.master_ssh_option = ("-o ControlPath=%s/socket" %
529 self.master_ssh_tempdir.name)
530
531 # Start the master SSH connection in the background.
532 master_cmd = self.ssh_command(options="-N -o ControlMaster=yes",
533 alive_interval=5)
534 logging.info("Starting master ssh connection '%s'" % master_cmd)
535 self.master_ssh_job = utils.BgJob(master_cmd)