Support run cyclictest on BareMetal
[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 from scp import SCPClient
67 import six
68 import logging
69
70 LOG = logging.getLogger(__name__)
71
72
73 class SSHError(Exception):
74     pass
75
76
77 class SSHTimeout(SSHError):
78     pass
79
80
81 class SSH(object):
82     """Represent ssh connection."""
83
84     def __init__(self, user, host, port=22, pkey=None,
85                  key_filename=None, password=None):
86         """Initialize SSH client.
87
88         :param user: ssh username
89         :param host: hostname or ip address of remote ssh server
90         :param port: remote ssh port
91         :param pkey: RSA or DSS private key string or file object
92         :param key_filename: private key filename
93         :param password: password
94         """
95
96         self.user = user
97         self.host = host
98         self.port = port
99         self.pkey = self._get_pkey(pkey) if pkey else None
100         self.password = password
101         self.key_filename = key_filename
102         self._client = False
103
104     def _get_pkey(self, key):
105         if isinstance(key, six.string_types):
106             key = six.moves.StringIO(key)
107         errors = []
108         for key_class in (paramiko.rsakey.RSAKey, paramiko.dsskey.DSSKey):
109             try:
110                 return key_class.from_private_key(key)
111             except paramiko.SSHException as e:
112                 errors.append(e)
113         raise SSHError("Invalid pkey: %s" % (errors))
114
115     def _get_client(self):
116         if self._client:
117             return self._client
118         try:
119             self._client = paramiko.SSHClient()
120             self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
121             self._client.connect(self.host, username=self.user,
122                                  port=self.port, pkey=self.pkey,
123                                  key_filename=self.key_filename,
124                                  password=self.password, timeout=1)
125             return self._client
126         except Exception as e:
127             message = ("Exception %(exception_type)s was raised "
128                        "during connect. Exception value is: %(exception)r")
129             self._client = False
130             raise SSHError(message % {"exception": e,
131                                       "exception_type": type(e)})
132
133     def close(self):
134         self._client.close()
135         self._client = False
136
137     def run(self, cmd, stdin=None, stdout=None, stderr=None,
138             raise_on_error=True, timeout=3600):
139         """Execute specified command on the server.
140
141         :param cmd:             Command to be executed.
142         :param stdin:           Open file or string to pass to stdin.
143         :param stdout:          Open file to connect to stdout.
144         :param stderr:          Open file to connect to stderr.
145         :param raise_on_error:  If False then exit code will be return. If True
146                                 then exception will be raized if non-zero code.
147         :param timeout:         Timeout in seconds for command execution.
148                                 Default 1 hour. No timeout if set to 0.
149         """
150
151         client = self._get_client()
152
153         if isinstance(stdin, six.string_types):
154             stdin = six.moves.StringIO(stdin)
155
156         return self._run(client, cmd, stdin=stdin, stdout=stdout,
157                          stderr=stderr, raise_on_error=raise_on_error,
158                          timeout=timeout)
159
160     def _run(self, client, cmd, stdin=None, stdout=None, stderr=None,
161              raise_on_error=True, timeout=3600):
162
163         transport = client.get_transport()
164         session = transport.open_session()
165         session.exec_command(cmd)
166         start_time = time.time()
167
168         data_to_send = ""
169         stderr_data = None
170
171         # If we have data to be sent to stdin then `select' should also
172         # check for stdin availability.
173         if stdin and not stdin.closed:
174             writes = [session]
175         else:
176             writes = []
177
178         while True:
179             # Block until data can be read/write.
180             r, w, e = select.select([session], writes, [session], 1)
181
182             if session.recv_ready():
183                 data = session.recv(4096)
184                 LOG.debug("stdout: %r" % data)
185                 if stdout is not None:
186                     stdout.write(data)
187                 continue
188
189             if session.recv_stderr_ready():
190                 stderr_data = session.recv_stderr(4096)
191                 LOG.debug("stderr: %r" % stderr_data)
192                 if stderr is not None:
193                     stderr.write(stderr_data)
194                 continue
195
196             if session.send_ready():
197                 if stdin is not None and not stdin.closed:
198                     if not data_to_send:
199                         data_to_send = stdin.read(4096)
200                         if not data_to_send:
201                             stdin.close()
202                             session.shutdown_write()
203                             writes = []
204                             continue
205                     sent_bytes = session.send(data_to_send)
206                     # LOG.debug("sent: %s" % data_to_send[:sent_bytes])
207                     data_to_send = data_to_send[sent_bytes:]
208
209             if session.exit_status_ready():
210                 break
211
212             if timeout and (time.time() - timeout) > start_time:
213                 args = {"cmd": cmd, "host": self.host}
214                 raise SSHTimeout("Timeout executing command "
215                                  "'%(cmd)s' on host %(host)s" % args)
216             if e:
217                 raise SSHError("Socket error.")
218
219         exit_status = session.recv_exit_status()
220         if 0 != exit_status and raise_on_error:
221             fmt = "Command '%(cmd)s' failed with exit_status %(status)d."
222             details = fmt % {"cmd": cmd, "status": exit_status}
223             if stderr_data:
224                 details += " Last stderr data: '%s'." % stderr_data
225             raise SSHError(details)
226         return exit_status
227
228     def execute(self, cmd, stdin=None, timeout=3600):
229         """Execute the specified command on the server.
230
231         :param cmd:     Command to be executed.
232         :param stdin:   Open file to be sent on process stdin.
233         :param timeout: Timeout for execution of the command.
234
235         :returns: tuple (exit_status, stdout, stderr)
236         """
237         stdout = six.moves.StringIO()
238         stderr = six.moves.StringIO()
239
240         exit_status = self.run(cmd, stderr=stderr,
241                                stdout=stdout, stdin=stdin,
242                                timeout=timeout, raise_on_error=False)
243         stdout.seek(0)
244         stderr.seek(0)
245         return (exit_status, stdout.read(), stderr.read())
246
247     def wait(self, timeout=120, interval=1):
248         """Wait for the host will be available via ssh."""
249         start_time = time.time()
250         while True:
251             try:
252                 return self.execute("uname")
253             except (socket.error, SSHError) as e:
254                 LOG.debug("Ssh is still unavailable: %r" % e)
255                 time.sleep(interval)
256             if time.time() > (start_time + timeout):
257                 raise SSHTimeout("Timeout waiting for '%s'" % self.host)
258
259     def put(self, files, remote_path=b'.', recursive=False):
260         client = self._get_client()
261
262         with SCPClient(client.get_transport()) as scp:
263             scp.put(files, remote_path, recursive)