blob: 9c143777df0c75f1b07fe1c65c32ed2b0b4974a2 [file] [log] [blame]
Jay Pipes051075a2012-04-28 17:39:37 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
ZhiQiang Fan39f97222013-09-20 04:49:44 +08003# Copyright 2012 OpenStack Foundation
Jay Pipes051075a2012-04-28 17:39:37 -04004# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17
Jay Pipes051075a2012-04-28 17:39:37 -040018
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070019import cStringIO
Matthew Treinisha83a16e2012-12-07 13:44:02 -050020import select
21import socket
22import time
23import warnings
24
Daryl Walleck6b9b2882012-04-08 21:43:39 -050025from tempest import exceptions
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010026from tempest.openstack.common import log as logging
Daryl Walleck1465d612011-11-02 02:22:15 -050027
Jay Pipes051075a2012-04-28 17:39:37 -040028
Daryl Walleck1465d612011-11-02 02:22:15 -050029with warnings.catch_warnings():
30 warnings.simplefilter("ignore")
31 import paramiko
32
33
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010034LOG = logging.getLogger(__name__)
35
36
Daryl Walleck1465d612011-11-02 02:22:15 -050037class Client(object):
38
Attila Fazekasa23f5002012-10-23 19:32:45 +020039 def __init__(self, host, username, password=None, timeout=300, pkey=None,
Jay Pipes051075a2012-04-28 17:39:37 -040040 channel_timeout=10, look_for_keys=False, key_filename=None):
Daryl Walleck1465d612011-11-02 02:22:15 -050041 self.host = host
42 self.username = username
43 self.password = password
Attila Fazekasa23f5002012-10-23 19:32:45 +020044 if isinstance(pkey, basestring):
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070045 pkey = paramiko.RSAKey.from_private_key(
46 cStringIO.StringIO(str(pkey)))
Attila Fazekasa23f5002012-10-23 19:32:45 +020047 self.pkey = pkey
Jay Pipes051075a2012-04-28 17:39:37 -040048 self.look_for_keys = look_for_keys
49 self.key_filename = key_filename
Daryl Walleck1465d612011-11-02 02:22:15 -050050 self.timeout = int(timeout)
Jaroslav Hennerab327842012-09-11 15:44:29 +020051 self.channel_timeout = float(channel_timeout)
52 self.buf_size = 1024
Daryl Walleck1465d612011-11-02 02:22:15 -050053
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010054 def _get_ssh_connection(self, sleep=1.5, backoff=1.01):
Sean Daguef237ccb2013-01-04 15:19:14 -050055 """Returns an ssh connection to the specified host."""
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010056 bsleep = sleep
Daryl Walleck1465d612011-11-02 02:22:15 -050057 ssh = paramiko.SSHClient()
58 ssh.set_missing_host_key_policy(
59 paramiko.AutoAddPolicy())
60 _start_time = time.time()
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010061 if self.pkey is not None:
62 LOG.info("Creating ssh connection to '%s' as '%s'"
63 " with public key authentication",
64 self.host, self.username)
65 else:
66 LOG.info("Creating ssh connection to '%s' as '%s'"
67 " with password %s",
68 self.host, self.username, str(self.password))
69 attempts = 0
70 while True:
Daryl Walleck1465d612011-11-02 02:22:15 -050071 try:
72 ssh.connect(self.host, username=self.username,
Jay Pipes051075a2012-04-28 17:39:37 -040073 password=self.password,
74 look_for_keys=self.look_for_keys,
75 key_filename=self.key_filename,
Soren Hansenb20cf3a2013-11-27 14:39:28 +010076 timeout=self.channel_timeout, pkey=self.pkey)
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010077 LOG.info("ssh connection to %s@%s sucessfuly created",
78 self.username, self.host)
79 return ssh
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010080 except (socket.error,
Joe Gordon31a91a62013-11-22 14:44:13 -080081 paramiko.SSHException):
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010082 attempts += 1
Andrea Frittoli334f1fd2013-05-15 06:57:43 +010083 time.sleep(bsleep)
84 bsleep *= backoff
Attila Fazekasad7ef7d2013-11-20 10:12:53 +010085 if not self._is_timed_out(_start_time):
86 continue
87 else:
88 LOG.exception("Failed to establish authenticated ssh"
89 " connection to %s@%s after %d attempts",
90 self.username, self.host, attempts)
91 raise exceptions.SSHTimeout(host=self.host,
92 user=self.username,
93 password=self.password)
Daryl Walleck1465d612011-11-02 02:22:15 -050094
Mate Lakatc3f8cd62013-08-23 12:00:42 +010095 def _is_timed_out(self, start_time):
96 return (time.time() - self.timeout) > start_time
Daryl Walleck1465d612011-11-02 02:22:15 -050097
Daryl Walleck1465d612011-11-02 02:22:15 -050098 def exec_command(self, cmd):
Jaroslav Hennerab327842012-09-11 15:44:29 +020099 """
100 Execute the specified command on the server.
Daryl Walleck1465d612011-11-02 02:22:15 -0500101
Jaroslav Hennerab327842012-09-11 15:44:29 +0200102 Note that this method is reading whole command outputs to memory, thus
103 shouldn't be used for large outputs.
Daryl Walleck1465d612011-11-02 02:22:15 -0500104
Jaroslav Hennerab327842012-09-11 15:44:29 +0200105 :returns: data read from standard output of the command.
106 :raises: SSHExecCommandFailed if command returns nonzero
107 status. The exception contains command status stderr content.
Daryl Walleck1465d612011-11-02 02:22:15 -0500108 """
109 ssh = self._get_ssh_connection()
Jaroslav Hennerab327842012-09-11 15:44:29 +0200110 transport = ssh.get_transport()
111 channel = transport.open_session()
Attila Fazekase14e5a42013-03-06 07:52:51 +0100112 channel.fileno() # Register event pipe
Jaroslav Hennerab327842012-09-11 15:44:29 +0200113 channel.exec_command(cmd)
114 channel.shutdown_write()
115 out_data = []
116 err_data = []
Matthew Treinishdcaa2b42013-08-12 19:16:16 +0000117 poll = select.poll()
118 poll.register(channel, select.POLLIN)
Mate Lakat99f16632013-08-23 08:50:32 +0100119 start_time = time.time()
120
Jaroslav Hennerab327842012-09-11 15:44:29 +0200121 while True:
Matthew Treinishdcaa2b42013-08-12 19:16:16 +0000122 ready = poll.poll(self.channel_timeout)
Jaroslav Hennerab327842012-09-11 15:44:29 +0200123 if not any(ready):
Mate Lakatc3f8cd62013-08-23 12:00:42 +0100124 if not self._is_timed_out(start_time):
Mate Lakat99f16632013-08-23 08:50:32 +0100125 continue
Jaroslav Hennerab327842012-09-11 15:44:29 +0200126 raise exceptions.TimeoutException(
Sean Dague14c68182013-04-14 15:34:30 -0400127 "Command: '{0}' executed on host '{1}'.".format(
128 cmd, self.host))
Jay Pipes8fe53922014-01-14 20:08:16 -0500129 if not ready[0]: # If there is nothing to read.
Jaroslav Hennerab327842012-09-11 15:44:29 +0200130 continue
131 out_chunk = err_chunk = None
132 if channel.recv_ready():
133 out_chunk = channel.recv(self.buf_size)
134 out_data += out_chunk,
135 if channel.recv_stderr_ready():
136 err_chunk = channel.recv_stderr(self.buf_size)
137 err_data += err_chunk,
138 if channel.closed and not err_chunk and not out_chunk:
139 break
140 exit_status = channel.recv_exit_status()
141 if 0 != exit_status:
142 raise exceptions.SSHExecCommandFailed(
Sean Dague14c68182013-04-14 15:34:30 -0400143 command=cmd, exit_status=exit_status,
144 strerror=''.join(err_data))
Jaroslav Hennerab327842012-09-11 15:44:29 +0200145 return ''.join(out_data)
Daryl Walleck1465d612011-11-02 02:22:15 -0500146
147 def test_connection_auth(self):
Attila Fazekasad7ef7d2013-11-20 10:12:53 +0100148 """Raises an exception when we can not connect to server via ssh."""
149 connection = self._get_ssh_connection()
150 connection.close()