blob: 531887c52f15e2cbabc72336edb3749ccd70c26d [file] [log] [blame]
ZhiQiang Fan39f97222013-09-20 04:49:44 +08001# Copyright 2012 OpenStack Foundation
Jay Pipes051075a2012-04-28 17:39:37 -04002# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
Jay Pipes051075a2012-04-28 17:39:37 -040016
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070017import cStringIO
Matthew Treinisha83a16e2012-12-07 13:44:02 -050018import select
llg821243b20502014-02-22 10:32:49 +080019import six
Matthew Treinisha83a16e2012-12-07 13:44:02 -050020import socket
21import time
22import warnings
23
Daryl Walleck6b9b2882012-04-08 21:43:39 -050024from tempest import exceptions
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010025from tempest.openstack.common import log as logging
Daryl Walleck1465d612011-11-02 02:22:15 -050026
Jay Pipes051075a2012-04-28 17:39:37 -040027
Daryl Walleck1465d612011-11-02 02:22:15 -050028with warnings.catch_warnings():
29 warnings.simplefilter("ignore")
30 import paramiko
31
32
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010033LOG = logging.getLogger(__name__)
34
35
Daryl Walleck1465d612011-11-02 02:22:15 -050036class Client(object):
37
Attila Fazekasa23f5002012-10-23 19:32:45 +020038 def __init__(self, host, username, password=None, timeout=300, pkey=None,
Jay Pipes051075a2012-04-28 17:39:37 -040039 channel_timeout=10, look_for_keys=False, key_filename=None):
Daryl Walleck1465d612011-11-02 02:22:15 -050040 self.host = host
41 self.username = username
42 self.password = password
llg821243b20502014-02-22 10:32:49 +080043 if isinstance(pkey, six.string_types):
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070044 pkey = paramiko.RSAKey.from_private_key(
45 cStringIO.StringIO(str(pkey)))
Attila Fazekasa23f5002012-10-23 19:32:45 +020046 self.pkey = pkey
Jay Pipes051075a2012-04-28 17:39:37 -040047 self.look_for_keys = look_for_keys
48 self.key_filename = key_filename
Daryl Walleck1465d612011-11-02 02:22:15 -050049 self.timeout = int(timeout)
Jaroslav Hennerab327842012-09-11 15:44:29 +020050 self.channel_timeout = float(channel_timeout)
51 self.buf_size = 1024
Daryl Walleck1465d612011-11-02 02:22:15 -050052
Gary Kottonc3128c02014-01-12 06:59:45 -080053 def _get_ssh_connection(self, sleep=1.5, backoff=1):
Sean Daguef237ccb2013-01-04 15:19:14 -050054 """Returns an ssh connection to the specified host."""
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010055 bsleep = sleep
Daryl Walleck1465d612011-11-02 02:22:15 -050056 ssh = paramiko.SSHClient()
57 ssh.set_missing_host_key_policy(
58 paramiko.AutoAddPolicy())
59 _start_time = time.time()
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010060 if self.pkey is not None:
61 LOG.info("Creating ssh connection to '%s' as '%s'"
62 " with public key authentication",
63 self.host, self.username)
64 else:
65 LOG.info("Creating ssh connection to '%s' as '%s'"
66 " with password %s",
67 self.host, self.username, str(self.password))
68 attempts = 0
69 while True:
Daryl Walleck1465d612011-11-02 02:22:15 -050070 try:
71 ssh.connect(self.host, username=self.username,
Jay Pipes051075a2012-04-28 17:39:37 -040072 password=self.password,
73 look_for_keys=self.look_for_keys,
74 key_filename=self.key_filename,
Soren Hansenb20cf3a2013-11-27 14:39:28 +010075 timeout=self.channel_timeout, pkey=self.pkey)
Marc Solanasb15d8b62014-02-07 00:04:15 -080076 LOG.info("ssh connection to %s@%s successfuly created",
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010077 self.username, self.host)
78 return ssh
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010079 except (socket.error,
Gary Kottonc3128c02014-01-12 06:59:45 -080080 paramiko.SSHException) as e:
81 if self._is_timed_out(_start_time):
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010082 LOG.exception("Failed to establish authenticated ssh"
83 " connection to %s@%s after %d attempts",
84 self.username, self.host, attempts)
85 raise exceptions.SSHTimeout(host=self.host,
86 user=self.username,
87 password=self.password)
Gary Kottonc3128c02014-01-12 06:59:45 -080088 bsleep += backoff
89 attempts += 1
90 LOG.warning("Failed to establish authenticated ssh"
91 " connection to %s@%s (%s). Number attempts: %s."
92 " Retry after %d seconds.",
93 self.username, self.host, e, attempts, bsleep)
94 time.sleep(bsleep)
Daryl Walleck1465d612011-11-02 02:22:15 -050095
Mate Lakatc3f8cd62013-08-23 12:00:42 +010096 def _is_timed_out(self, start_time):
97 return (time.time() - self.timeout) > start_time
Daryl Walleck1465d612011-11-02 02:22:15 -050098
Daryl Walleck1465d612011-11-02 02:22:15 -050099 def exec_command(self, cmd):
Jaroslav Hennerab327842012-09-11 15:44:29 +0200100 """
101 Execute the specified command on the server.
Daryl Walleck1465d612011-11-02 02:22:15 -0500102
Jaroslav Hennerab327842012-09-11 15:44:29 +0200103 Note that this method is reading whole command outputs to memory, thus
104 shouldn't be used for large outputs.
Daryl Walleck1465d612011-11-02 02:22:15 -0500105
Jaroslav Hennerab327842012-09-11 15:44:29 +0200106 :returns: data read from standard output of the command.
107 :raises: SSHExecCommandFailed if command returns nonzero
108 status. The exception contains command status stderr content.
Daryl Walleck1465d612011-11-02 02:22:15 -0500109 """
110 ssh = self._get_ssh_connection()
Jaroslav Hennerab327842012-09-11 15:44:29 +0200111 transport = ssh.get_transport()
112 channel = transport.open_session()
Attila Fazekase14e5a42013-03-06 07:52:51 +0100113 channel.fileno() # Register event pipe
Jaroslav Hennerab327842012-09-11 15:44:29 +0200114 channel.exec_command(cmd)
115 channel.shutdown_write()
116 out_data = []
117 err_data = []
Matthew Treinishdcaa2b42013-08-12 19:16:16 +0000118 poll = select.poll()
119 poll.register(channel, select.POLLIN)
Mate Lakat99f16632013-08-23 08:50:32 +0100120 start_time = time.time()
121
Jaroslav Hennerab327842012-09-11 15:44:29 +0200122 while True:
Matthew Treinishdcaa2b42013-08-12 19:16:16 +0000123 ready = poll.poll(self.channel_timeout)
Jaroslav Hennerab327842012-09-11 15:44:29 +0200124 if not any(ready):
Mate Lakatc3f8cd62013-08-23 12:00:42 +0100125 if not self._is_timed_out(start_time):
Mate Lakat99f16632013-08-23 08:50:32 +0100126 continue
Jaroslav Hennerab327842012-09-11 15:44:29 +0200127 raise exceptions.TimeoutException(
Sean Dague14c68182013-04-14 15:34:30 -0400128 "Command: '{0}' executed on host '{1}'.".format(
129 cmd, self.host))
Jay Pipes8fe53922014-01-14 20:08:16 -0500130 if not ready[0]: # If there is nothing to read.
Jaroslav Hennerab327842012-09-11 15:44:29 +0200131 continue
132 out_chunk = err_chunk = None
133 if channel.recv_ready():
134 out_chunk = channel.recv(self.buf_size)
135 out_data += out_chunk,
136 if channel.recv_stderr_ready():
137 err_chunk = channel.recv_stderr(self.buf_size)
138 err_data += err_chunk,
139 if channel.closed and not err_chunk and not out_chunk:
140 break
141 exit_status = channel.recv_exit_status()
142 if 0 != exit_status:
143 raise exceptions.SSHExecCommandFailed(
Sean Dague14c68182013-04-14 15:34:30 -0400144 command=cmd, exit_status=exit_status,
145 strerror=''.join(err_data))
Jaroslav Hennerab327842012-09-11 15:44:29 +0200146 return ''.join(out_data)
Daryl Walleck1465d612011-11-02 02:22:15 -0500147
148 def test_connection_auth(self):
Attila Fazekasad7ef7d2013-11-20 10:12:53 +0100149 """Raises an exception when we can not connect to server via ssh."""
150 connection = self._get_ssh_connection()
151 connection.close()