Using paramiko for all ssh & scp
[samplevnf.git] / VNFs / DPPD-PROX / helper-scripts / rapid / prox_ctrl.py
1 ##
2 ## Copyright (c) 2010-2020 Intel Corporation
3 ##
4 ## Licensed under the Apache License, Version 2.0 (the "License");
5 ## you may not use this file except in compliance with the License.
6 ## You may obtain 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,
12 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ## See the License for the specific language governing permissions and
14 ## limitations under the License.
15 ##
16
17 from __future__ import print_function
18 from __future__ import division
19
20 from builtins import map
21 from builtins import range
22 from past.utils import old_div
23 from builtins import object
24 import os
25 import time
26 import subprocess
27 import socket
28 from rapid_log import RapidLog
29 from rapid_sshclient import SSHClient
30
31 class prox_ctrl(object):
32     def __init__(self, ip, key=None, user=None, password = None):
33         self._ip   = ip
34         self._key  = key
35         self._user = user
36         self._password = password
37         self._proxsock = []
38         self._sshclient = SSHClient(ip = ip, user = user, password = password,
39                 rsa_private_key = key)
40
41     def ip(self):
42         return self._ip
43
44     def test_connection(self):
45         attempts = 1
46         RapidLog.debug("Trying to connect to machine \
47                 on %s, attempt: %d" % (self._ip, attempts))
48         while True:
49             try:
50                 self.run_cmd('test -e /opt/rapid/system_ready_for_rapid')
51                 break
52             except RuntimeWarning as ex:
53                 RapidLog.debug("RuntimeWarning %d:\n%s"
54                     % (ex.returncode, ex.output.strip()))
55                 attempts += 1
56                 if attempts > 20:
57                     RapidLog.exception("Failed to connect to instance after %d\
58                             attempts:\n%s" % (attempts, ex))
59                 time.sleep(2)
60                 RapidLog.debug("Trying to connect to machine \
61                        on %s, attempt: %d" % (self._ip, attempts))
62         RapidLog.debug("Connected to machine on %s" % self._ip)
63
64     def connect_socket(self):
65         attempts = 1
66         RapidLog.debug("Trying to connect to PROX (just launched) on %s, \
67                 attempt: %d" % (self._ip, attempts))
68         sock = None
69         while True:
70             sock = self.prox_sock()
71             if sock is not None:
72                 break
73             attempts += 1
74             if attempts > 20:
75                 RapidLog.exception("Failed to connect to PROX on %s after %d \
76                         attempts" % (self._ip, attempts))
77             time.sleep(2)
78             RapidLog.debug("Trying to connect to PROX (just launched) on %s, \
79                     attempt: %d" % (self._ip, attempts))
80         RapidLog.info("Connected to PROX on %s" % self._ip)
81         return sock
82
83     def close(self):
84         for sock in self._proxsock:
85             sock.quit()
86
87     def run_cmd(self, command):
88         self._sshclient.run_cmd(command)
89
90     def prox_sock(self, port=8474):
91         """Connect to the PROX instance on remote system.
92         Return a prox_sock object on success, None on failure.
93         """
94         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
95         try:
96             sock.connect((self._ip, port))
97             prox = prox_sock(sock)
98             self._proxsock.append(prox)
99             return prox
100         except:
101             return None
102
103     def scp_put(self, src, dst):
104         self._sshclient.scp_put(src, dst)
105
106     def scp_get(self, src, dst):
107         self._sshclient.scp_get('/home/' + self._user + src, dst)
108
109 class prox_sock(object):
110     def __init__(self, sock):
111         self._sock = sock
112         self._rcvd = b''
113
114     def __del__(self):
115         if self._sock is not None:
116             self._sock.close()
117             self._sock = None
118
119     def start(self, cores):
120         self._send('start %s' % ','.join(map(str, cores)))
121
122     def stop(self, cores):
123         self._send('stop %s' % ','.join(map(str, cores)))
124
125     def speed(self, speed, cores, tasks=[0]):
126         for core in cores:
127             for task in tasks:
128                 self._send('speed %s %s %s' % (core, task, speed))
129
130     def reset_stats(self):
131         self._send('reset stats')
132
133     def lat_stats(self, cores, tasks=[0]):
134         result = {}
135         result['lat_min'] = 999999999
136         result['lat_max'] = result['lat_avg'] = 0
137         result['buckets'] = [0] * 128
138         result['mis_ordered'] = 0
139         result['extent'] = 0
140         result['duplicate'] = 0
141         number_tasks_returning_stats = 0
142         self._send('lat all stats %s %s' % (','.join(map(str, cores)),
143             ','.join(map(str, tasks))))
144         for core in cores:
145             for task in tasks:
146                 stats = self._recv().split(',')
147             if 'is not measuring' in stats[0]:
148                 continue
149             if stats[0].startswith('error'):
150                 RapidLog.critical("lat stats error: unexpected reply from PROX\
151                         (potential incompatibility between scripts and PROX)")
152                 raise Exception("lat stats error")
153             number_tasks_returning_stats += 1
154             result['lat_min'] = min(int(stats[0]),result['lat_min'])
155             result['lat_max'] = max(int(stats[1]),result['lat_max'])
156             result['lat_avg'] += int(stats[2])
157             #min_since begin = int(stats[3])
158             #max_since_begin = int(stats[4])
159             result['lat_tsc'] = int(stats[5])
160             # Taking the last tsc as the timestamp since
161             # PROX will return the same tsc for each
162             # core/task combination
163             result['lat_hz'] = int(stats[6])
164             #coreid = int(stats[7])
165             #taskid = int(stats[8])
166             result['mis_ordered'] += int(stats[9])
167             result['extent'] += int(stats[10])
168             result['duplicate'] += int(stats[11])
169             stats = self._recv().split(':')
170             if stats[0].startswith('error'):
171                 RapidLog.critical("lat stats error: unexpected lat bucket \
172                         reply (potential incompatibility between scripts \
173                         and PROX)")
174                 raise Exception("lat bucket reply error")
175             result['buckets'][0] = int(stats[1])
176             for i in range(1, 128):
177                 stats = self._recv().split(':')
178                 result['buckets'][i] += int(stats[1])
179         result['lat_avg'] = old_div(result['lat_avg'],
180                 number_tasks_returning_stats)
181         self._send('stats latency(0).used')
182         used = float(self._recv())
183         self._send('stats latency(0).total')
184         total = float(self._recv())
185         result['lat_used'] = old_div(used,total)
186         return (result)
187
188     def irq_stats(self, core, bucket, task=0):
189         self._send('stats task.core(%s).task(%s).irq(%s)' %
190                 (core, task, bucket))
191         stats = self._recv().split(',')
192         return int(stats[0])
193
194     def show_irq_buckets(self, core, task=0):
195         rx = tx = drop = tsc = hz = 0
196         self._send('show irq buckets %s %s' % (core,task))
197         buckets = self._recv().split(';')
198         buckets = buckets[:-1]
199         return buckets
200
201     def core_stats(self, cores, tasks=[0]):
202         rx = tx = drop = tsc = hz = rx_non_dp = tx_non_dp = tx_fail = 0
203         self._send('dp core stats %s %s' % (','.join(map(str, cores)),
204             ','.join(map(str, tasks))))
205         for core in cores:
206             for task in tasks:
207                 stats = self._recv().split(',')
208                 if stats[0].startswith('error'):
209                     if stats[0].startswith('error: invalid syntax'):
210                         RapidLog.critical("dp core stats error: unexpected \
211                                 invalid syntax (potential incompatibility \
212                                 between scripts and PROX)")
213                         raise Exception("dp core stats error")
214                     continue
215                 rx += int(stats[0])
216                 tx += int(stats[1])
217                 rx_non_dp += int(stats[2])
218                 tx_non_dp += int(stats[3])
219                 drop += int(stats[4])
220                 tx_fail += int(stats[5])
221                 tsc = int(stats[6])
222                 hz = int(stats[7])
223         return rx, rx_non_dp, tx, tx_non_dp, drop, tx_fail, tsc, hz
224
225     def multi_port_stats(self, ports=[0]):
226         rx = tx = port_id = tsc = no_mbufs = errors = 0
227         self._send('multi port stats %s' % (','.join(map(str, ports))))
228         result = self._recv().split(';')
229         if result[0].startswith('error'):
230             RapidLog.critical("multi port stats error: unexpected invalid \
231                     syntax (potential incompatibility between scripts and \
232                     PROX)")
233             raise Exception("multi port stats error")
234         for statistics in result:
235             stats = statistics.split(',')
236             port_id = int(stats[0])
237             rx += int(stats[1])
238             tx += int(stats[2])
239             no_mbufs += int(stats[3])
240             errors += int(stats[4])
241             tsc = int(stats[5])
242         return rx, tx, no_mbufs, errors, tsc
243
244     def set_random(self, cores, task, offset, mask, length):
245         self._send('set random %s %s %s %s %s' % (','.join(map(str, cores)),
246             task, offset, mask, length))
247
248     def set_size(self, cores, task, pkt_size):
249         self._send('pkt_size %s %s %s' % (','.join(map(str, cores)), task,
250             pkt_size))
251
252     def set_imix(self, cores, task, imix):
253         self._send('imix %s %s %s' % (','.join(map(str, cores)), task,
254             ','.join(map(str,imix))))
255
256     def set_value(self, cores, task, offset, value, length):
257         self._send('set value %s %s %s %s %s' % (','.join(map(str, cores)),
258             task, offset, value, length))
259
260     def quit_prox(self):
261         self._send('quit')
262
263     def _send(self, cmd):
264         """Append LF and send command to the PROX instance."""
265         if self._sock is None:
266             raise RuntimeError("PROX socket closed, cannot send '%s'" % cmd)
267         try:
268             self._sock.sendall(cmd.encode() + b'\n')
269         except ConnectionResetError as e:
270             RapidLog.error('Pipe reset by Prox instance: traffic too high?')
271             raise
272
273     def _recv(self):
274         """Receive response from PROX instance, return it with LF removed."""
275         if self._sock is None:
276             raise RuntimeError("PROX socket closed, cannot receive anymore")
277         try:
278             pos = self._rcvd.find(b'\n')
279             while pos == -1:
280                 self._rcvd += self._sock.recv(256)
281                 pos = self._rcvd.find(b'\n')
282             rsp = self._rcvd[:pos]
283             self._rcvd = self._rcvd[pos+1:]
284         except ConnectionResetError as e:
285             RapidLog.error('Pipe reset by Prox instance: traffic too high?')
286             raise
287         return rsp.decode()