add ssh module
[yardstick.git] / yardstick / ssh.py
1 # Copyright 2013: Mirantis Inc.
2 # 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
16 # yardstick comment: this is a modified copy of rally/rally/common/sshutils.py
17
18 """High level ssh library.
19
20 Usage examples:
21
22 Execute command and get output:
23
24     ssh = sshclient.SSH("root", "example.com", port=33)
25     status, stdout, stderr = ssh.execute("ps ax")
26     if status:
27         raise Exception("Command failed with non-zero status.")
28     print stdout.splitlines()
29
30 Execute command with huge output:
31
32     class PseudoFile(object):
33         def write(chunk):
34             if "error" in chunk:
35                 email_admin(chunk)
36
37     ssh = sshclient.SSH("root", "example.com")
38     ssh.run("tail -f /var/log/syslog", stdout=PseudoFile(), timeout=False)
39
40 Execute local script on remote side:
41
42     ssh = sshclient.SSH("user", "example.com")
43     status, out, err = ssh.execute("/bin/sh -s arg1 arg2",
44                                    stdin=open("~/myscript.sh", "r"))
45
46 Upload file:
47
48     ssh = sshclient.SSH("user", "example.com")
49     ssh.run("cat > ~/upload/file.gz", stdin=open("/store/file.gz", "rb"))
50
51 Eventlet:
52
53     eventlet.monkey_patch(select=True, time=True)
54     or
55     eventlet.monkey_patch()
56     or
57     sshclient = eventlet.import_patched("opentstack.common.sshclient")
58
59 """
60
61 import select
62 import socket
63 import time
64
65 import paramiko
66 import six
67 import logging
68
69 LOG = logging.getLogger(__name__)
70
71
72 class SSHError(Exception):
73     pass
74
75
76 class SSHTimeout(SSHError):
77     pass
78
79
80 class SSH(object):
81     """Represent ssh connection."""
82
83     def __init__(self, user, host, port=22, pkey=None,
84                  key_filename=None, password=None):
85         """Initialize SSH client.
86
87         :param user: ssh username
88         :param host: hostname or ip address of remote ssh server
89         :param port: remote ssh port
90         :param pkey: RSA or DSS private key string or file object
91         :param key_filename: private key filename
92         :param password: password
93         """
94
95         self.user = user
96         self.host = host
97         self.port = port
98         self.pkey = self._get_pkey(pkey) if pkey else None
99         self.password = password
100         self.key_filename = key_filename
101         self._client = False
102
103     def _get_pkey(self, key):
104         if isinstance(key, six.string_types):
105             key = six.moves.StringIO(key)
106         errors = []
107         for key_class in (paramiko.rsakey.RSAKey, paramiko.dsskey.DSSKey):
108             try:
109                 return key_class.from_private_key(key)
110             except paramiko.SSHException as e:
111                 errors.append(e)
112         raise SSHError("Invalid pkey: %s" % (errors))
113
114     def _get_client(self):
115         if self._client:
116             return self._client
117         try:
118             self._client = paramiko.SSHClient()
119             self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
120             self._client.connect(self.host, username=self.user,
121                                  port=self.port, pkey=self.pkey,
122                                  key_filename=self.key_filename,
123                                  password=self.password, timeout=1)
124             return self._client
125         except Exception as e:
126             message = ("Exception %(exception_type)s was raised "
127                        "during connect. Exception value is: %(exception)r")
128             self._client = False
129             raise SSHError(message % {"exception": e,
130                                       "exception_type": type(e)})
131
132     def close(self):
133         self._client.close()
134         self._client = False
135
136     def run(self, cmd, stdin=None, stdout=None, stderr=None,
137             raise_on_error=True, timeout=3600):
138         """Execute specified command on the server.
139
140         :param cmd:             Command to be executed.
141         :param stdin:           Open file or string to pass to stdin.
142         :param stdout:          Open file to connect to stdout.
143         :param stderr:          Open file to connect to stderr.
144         :param raise_on_error:  If False then exit code will be return. If True
145                                 then exception will be raized if non-zero code.
146         :param timeout:         Timeout in seconds for command execution.
147                                 Default 1 hour. No timeout if set to 0.
148         """
149
150         client = self._get_client()
151
152         if isinstance(stdin, six.string_types):
153             stdin = six.moves.StringIO(stdin)
154
155         return self._run(client, cmd, stdin=stdin, stdout=stdout,
156                          stderr=stderr, raise_on_error=raise_on_error,
157                          timeout=timeout)
158
159     def _run(self, client, cmd, stdin=None, stdout=None, stderr=None,
160              raise_on_error=True, timeout=3600):
161
162         transport = client.get_transport()
163         session = transport.open_session()
164         session.exec_command(cmd)
165         start_time = time.time()
166
167         data_to_send = ""
168         stderr_data = None
169
170         # If we have data to be sent to stdin then `select' should also
171         # check for stdin availability.
172         if stdin and not stdin.closed:
173             writes = [session]
174         else:
175             writes = []
176
177         while True:
178             # Block until data can be read/write.
179             r, w, e = select.select([session], writes, [session], 1)
180
181             if session.recv_ready():
182                 data = session.recv(4096)
183                 LOG.debug("stdout: %r" % data)
184                 if stdout is not None:
185                     stdout.write(data)
186                 continue
187
188             if session.recv_stderr_ready():
189                 stderr_data = session.recv_stderr(4096)
190                 LOG.debug("stderr: %r" % stderr_data)
191                 if stderr is not None:
192                     stderr.write(stderr_data)
193                 continue
194
195             if session.send_ready():
196                 if stdin is not None and not stdin.closed:
197                     if not data_to_send:
198                         data_to_send = stdin.read(4096)
199                         if not data_to_send:
200                             stdin.close()
201                             session.shutdown_write()
202                             writes = []
203                             continue
204                     sent_bytes = session.send(data_to_send)
205                     # LOG.debug("sent: %s" % data_to_send[:sent_bytes])
206                     data_to_send = data_to_send[sent_bytes:]
207
208             if session.exit_status_ready():
209                 break
210
211             if timeout and (time.time() - timeout) > start_time:
212                 args = {"cmd": cmd, "host": self.host}
213                 raise SSHTimeout("Timeout executing command "
214                                  "'%(cmd)s' on host %(host)s" % args)
215             if e:
216                 raise SSHError("Socket error.")
217
218         exit_status = session.recv_exit_status()
219         if 0 != exit_status and raise_on_error:
220             fmt = "Command '%(cmd)s' failed with exit_status %(status)d."
221             details = fmt % {"cmd": cmd, "status": exit_status}
222             if stderr_data:
223                 details += " Last stderr data: '%s'." % stderr_data
224             raise SSHError(details)
225         return exit_status
226
227     def execute(self, cmd, stdin=None, timeout=3600):
228         """Execute the specified command on the server.
229
230         :param cmd:     Command to be executed.
231         :param stdin:   Open file to be sent on process stdin.
232         :param timeout: Timeout for execution of the command.
233
234         :returns: tuple (exit_status, stdout, stderr)
235         """
236         stdout = six.moves.StringIO()
237         stderr = six.moves.StringIO()
238
239         exit_status = self.run(cmd, stderr=stderr,
240                                stdout=stdout, stdin=stdin,
241                                timeout=timeout, raise_on_error=False)
242         stdout.seek(0)
243         stderr.seek(0)
244         return (exit_status, stdout.read(), stderr.read())
245
246     def wait(self, timeout=120, interval=1):
247         """Wait for the host will be available via ssh."""
248         start_time = time.time()
249         while True:
250             try:
251                 return self.execute("uname")
252             except (socket.error, SSHError) as e:
253                 LOG.debug("Ssh is still unavailable: %r" % e)
254                 time.sleep(interval)
255             if time.time() > (start_time + timeout):
256                 raise SSHTimeout("Timeout waiting for '%s'" % self.host)