f35b925d106ee2b0bd38b60497a4f22c338a00b2
[csit.git] / resources / libraries / python / ssh.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 import StringIO
15 from time import time, sleep
16
17 import socket
18 import paramiko
19 from paramiko import RSAKey
20 from paramiko.ssh_exception import SSHException
21 from scp import SCPClient
22 from interruptingcow import timeout
23 from robot.api import logger
24 from robot.utils.asserts import assert_equal
25
26 __all__ = ["exec_cmd", "exec_cmd_no_error"]
27
28 # TODO: load priv key
29
30
31 class SSH(object):
32
33     __MAX_RECV_BUF = 10*1024*1024
34     __existing_connections = {}
35
36     def __init__(self):
37         self._ssh = None
38         self._node = None
39
40     @staticmethod
41     def _node_hash(node):
42         return hash(frozenset([node['host'], node['port']]))
43
44     def connect(self, node):
45         """Connect to node prior to running exec_command or scp.
46
47         If there already is a connection to the node, this method reuses it.
48         """
49         self._node = node
50         node_hash = self._node_hash(node)
51         if node_hash in SSH.__existing_connections:
52             self._ssh = SSH.__existing_connections[node_hash]
53             logger.debug('reusing ssh: {0}'.format(self._ssh))
54         else:
55             start = time()
56             pkey = None
57             if 'priv_key' in node:
58                 pkey = RSAKey.from_private_key(
59                         StringIO.StringIO(node['priv_key']))
60
61             self._ssh = paramiko.SSHClient()
62             self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
63
64             self._ssh.connect(node['host'], username=node['username'],
65                               password=node.get('password'), pkey=pkey,
66                               port=node['port'])
67
68             SSH.__existing_connections[node_hash] = self._ssh
69
70             logger.trace('connect took {} seconds'.format(time() - start))
71             logger.debug('new ssh: {0}'.format(self._ssh))
72
73         logger.debug('Connect peer: {0}'.
74                      format(self._ssh.get_transport().getpeername()))
75         logger.debug('Connections: {0}'.format(str(SSH.__existing_connections)))
76
77     def disconnect(self, node):
78         """Close SSH connection to the node.
79
80         :param node: The node to disconnect from.
81         :type node: dict
82         """
83         node_hash = self._node_hash(node)
84         if node_hash in SSH.__existing_connections:
85             logger.debug('Disconnecting peer: {}, {}'.
86                          format(node['host'], node['port']))
87             ssh = SSH.__existing_connections.pop(node_hash)
88             ssh.close()
89
90     def _reconnect(self):
91         node = self._node
92         self.disconnect(node)
93         self.connect(node)
94         logger.debug('Reconnecting peer done: {}'.
95                      format(self._ssh.get_transport().getpeername()))
96
97     def exec_command(self, cmd, timeout=10):
98         """Execute SSH command on a new channel on the connected Node.
99
100         :param cmd: Command to run on the Node.
101         :param timeout: Maximal time in seconds to wait while the command is
102         done. If is None then wait forever.
103         :type cmd: str
104         :type timeout: int
105         :return return_code, stdout, stderr
106         :rtype: tuple(int, str, str)
107         :raise socket.timeout: If command is not finished in timeout time.
108         """
109         start = time()
110         stdout = StringIO.StringIO()
111         stderr = StringIO.StringIO()
112         try:
113             chan = self._ssh.get_transport().open_session(timeout=5)
114         except AttributeError:
115             self._reconnect()
116             chan = self._ssh.get_transport().open_session(timeout=5)
117         except SSHException:
118             self._reconnect()
119             chan = self._ssh.get_transport().open_session(timeout=5)
120         chan.settimeout(timeout)
121         logger.trace('exec_command on {0}: {1}'
122                      .format(self._ssh.get_transport().getpeername(), cmd))
123
124         chan.exec_command(cmd)
125         while not chan.exit_status_ready() and timeout is not None:
126             if chan.recv_ready():
127                 stdout.write(chan.recv(self.__MAX_RECV_BUF))
128
129             if chan.recv_stderr_ready():
130                 stderr.write(chan.recv_stderr(self.__MAX_RECV_BUF))
131
132             if time() - start > timeout:
133                 raise socket.timeout(
134                     'Timeout exception.\n'
135                     'Current contents of stdout buffer: {0}\n'
136                     'Current contents of stderr buffer: {1}\n'
137                     .format(stdout.getvalue(), stderr.getvalue())
138                 )
139
140             sleep(0.1)
141         return_code = chan.recv_exit_status()
142
143         while chan.recv_ready():
144             stdout.write(chan.recv(self.__MAX_RECV_BUF))
145
146         while chan.recv_stderr_ready():
147             stderr.write(chan.recv_stderr(self.__MAX_RECV_BUF))
148
149         end = time()
150         logger.trace('exec_command on {0} took {1} seconds'.format(
151             self._ssh.get_transport().getpeername(), end-start))
152
153         logger.trace('chan_recv/_stderr took {} seconds'.format(time()-end))
154
155         logger.trace('return RC {}'.format(return_code))
156         logger.trace('return STDOUT {}'.format(stdout.getvalue()))
157         logger.trace('return STDERR {}'.format(stderr.getvalue()))
158         return return_code, stdout.getvalue(), stderr.getvalue()
159
160     def exec_command_sudo(self, cmd, cmd_input=None, timeout=30):
161         """Execute SSH command with sudo on a new channel on the connected Node.
162
163         :param cmd: Command to be executed.
164         :param cmd_input: Input redirected to the command.
165         :param timeout: Timeout.
166         :return: return_code, stdout, stderr
167
168         :Example:
169
170         >>> from ssh import SSH
171         >>> ssh = SSH()
172         >>> ssh.connect(node)
173         >>> # Execute command without input (sudo -S cmd)
174         >>> ssh.exec_command_sudo("ifconfig eth0 down")
175         >>> # Execute command with input (sudo -S cmd <<< "input")
176         >>> ssh.exec_command_sudo("vpp_api_test", "dump_interface_table")
177         """
178         if cmd_input is None:
179             command = 'sudo -S {c}'.format(c=cmd)
180         else:
181             command = 'sudo -S {c} <<< "{i}"'.format(c=cmd, i=cmd_input)
182         return self.exec_command(command, timeout)
183
184     def interactive_terminal_open(self, time_out=10):
185         """Open interactive terminal on a new channel on the connected Node.
186
187         :param time_out: Timeout in seconds.
188         :return: SSH channel with opened terminal.
189
190         .. warning:: Interruptingcow is used here, and it uses
191            signal(SIGALRM) to let the operating system interrupt program
192            execution. This has the following limitations: Python signal
193            handlers only apply to the main thread, so you cannot use this
194            from other threads. You must not use this in a program that
195            uses SIGALRM itself (this includes certain profilers)
196         """
197         chan = self._ssh.get_transport().open_session()
198         chan.get_pty()
199         chan.invoke_shell()
200         chan.settimeout(int(time_out))
201
202         buf = ''
203         try:
204             with timeout(time_out, exception=RuntimeError):
205                 while not buf.endswith(':~$ '):
206                     if chan.recv_ready():
207                         buf = chan.recv(4096)
208         except RuntimeError:
209             raise Exception('Open interactive terminal timeout.')
210         return chan
211
212     @staticmethod
213     def interactive_terminal_exec_command(chan, cmd, prompt,
214                                           time_out=10):
215         """Execute command on interactive terminal.
216
217         interactive_terminal_open() method has to be called first!
218
219         :param chan: SSH channel with opened terminal.
220         :param cmd: Command to be executed.
221         :param prompt: Command prompt, sequence of characters used to
222         indicate readiness to accept commands.
223         :param time_out: Timeout in seconds.
224         :return: Command output.
225
226         .. warning:: Interruptingcow is used here, and it uses
227            signal(SIGALRM) to let the operating system interrupt program
228            execution. This has the following limitations: Python signal
229            handlers only apply to the main thread, so you cannot use this
230            from other threads. You must not use this in a program that
231            uses SIGALRM itself (this includes certain profilers)
232         """
233         chan.sendall('{c}\n'.format(c=cmd))
234         buf = ''
235         try:
236             with timeout(time_out, exception=RuntimeError):
237                 while not buf.endswith(prompt):
238                     if chan.recv_ready():
239                         buf += chan.recv(4096)
240         except RuntimeError:
241             raise Exception("Exec '{c}' timeout.".format(c=cmd))
242         tmp = buf.replace(cmd.replace('\n', ''), '')
243         return tmp.replace(prompt, '')
244
245     @staticmethod
246     def interactive_terminal_close(chan):
247         """Close interactive terminal SSH channel.
248
249         :param: chan: SSH channel to be closed.
250         """
251         chan.close()
252
253     def scp(self, local_path, remote_path):
254         """Copy files from local_path to remote_path.
255
256         connect() method has to be called first!
257         """
258         logger.trace('SCP {0} to {1}:{2}'.format(
259             local_path, self._ssh.get_transport().getpeername(), remote_path))
260         # SCPCLient takes a paramiko transport as its only argument
261         scp = SCPClient(self._ssh.get_transport())
262         start = time()
263         scp.put(local_path, remote_path)
264         scp.close()
265         end = time()
266         logger.trace('SCP took {0} seconds'.format(end-start))
267
268
269 def exec_cmd(node, cmd, timeout=600, sudo=False):
270     """Convenience function to ssh/exec/return rc, out & err.
271
272     Returns (rc, stdout, stderr).
273     """
274     if node is None:
275         raise TypeError('Node parameter is None')
276     if cmd is None:
277         raise TypeError('Command parameter is None')
278     if len(cmd) == 0:
279         raise ValueError('Empty command parameter')
280
281     ssh = SSH()
282     try:
283         ssh.connect(node)
284     except Exception, e:
285         logger.error("Failed to connect to node" + str(e))
286         return None, None, None
287
288     try:
289         if not sudo:
290             (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=timeout)
291         else:
292             (ret_code, stdout, stderr) = ssh.exec_command_sudo(cmd,
293                                                                timeout=timeout)
294     except Exception, e:
295         logger.error(e)
296         return None, None, None
297
298     return ret_code, stdout, stderr
299
300
301 def exec_cmd_no_error(node, cmd, timeout=600, sudo=False):
302     """Convenience function to ssh/exec/return out & err.
303
304     Verifies that return code is zero.
305
306     Returns (stdout, stderr).
307     """
308     (rc, stdout, stderr) = exec_cmd(node, cmd, timeout=timeout, sudo=sudo)
309     assert_equal(rc, 0, 'Command execution failed: "{}"\n{}'.
310                  format(cmd, stderr))
311     return stdout, stderr