2 ## Copyright (c) 2010-2020 Intel Corporation
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
8 ## http://www.apache.org/licenses/LICENSE-2.0
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.
17 from __future__ import print_function
18 from __future__ import division
20 from builtins import map
21 from builtins import range
22 from past.utils import old_div
23 from builtins import object
28 from rapid_log import RapidLog
29 from rapid_sshclient import SSHClient
31 class prox_ctrl(object):
32 def __init__(self, ip, key=None, user=None, password = None):
36 self._password = password
38 self._sshclient = SSHClient(ip = ip, user = user, password = password,
39 rsa_private_key = key)
44 def test_connection(self):
46 RapidLog.debug("Trying to connect to machine \
47 on %s, attempt: %d" % (self._ip, attempts))
50 self.run_cmd('test -e /opt/rapid/system_ready_for_rapid')
52 except RuntimeWarning as ex:
53 RapidLog.debug("RuntimeWarning %d:\n%s"
54 % (ex.returncode, ex.output.strip()))
57 RapidLog.exception("Failed to connect to instance after %d\
58 attempts:\n%s" % (attempts, ex))
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)
64 def connect_socket(self):
66 RapidLog.debug("Trying to connect to PROX (just launched) on %s, \
67 attempt: %d" % (self._ip, attempts))
70 sock = self.prox_sock()
75 RapidLog.exception("Failed to connect to PROX on %s after %d \
76 attempts" % (self._ip, attempts))
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)
84 for sock in self._proxsock:
87 def run_cmd(self, command):
88 self._sshclient.run_cmd(command)
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.
94 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
96 sock.connect((self._ip, port))
97 prox = prox_sock(sock)
98 self._proxsock.append(prox)
103 def scp_put(self, src, dst):
104 self._sshclient.scp_put(src, dst)
106 def scp_get(self, src, dst):
107 self._sshclient.scp_get('/home/' + self._user + src, dst)
109 class prox_sock(object):
110 def __init__(self, sock):
115 if self._sock is not None:
119 def start(self, cores):
120 self._send('start %s' % ','.join(map(str, cores)))
122 def stop(self, cores):
123 self._send('stop %s' % ','.join(map(str, cores)))
125 def speed(self, speed, cores, tasks=[0]):
128 self._send('speed %s %s %s' % (core, task, speed))
130 def reset_stats(self):
131 self._send('reset stats')
133 def lat_stats(self, cores, tasks=[0]):
135 result['lat_min'] = 999999999
136 result['lat_max'] = result['lat_avg'] = 0
137 result['buckets'] = [0] * 128
138 result['mis_ordered'] = 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))))
146 stats = self._recv().split(',')
147 if 'is not measuring' in stats[0]:
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 \
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)
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(',')
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]
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))))
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")
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])
223 return rx, rx_non_dp, tx, tx_non_dp, drop, tx_fail, tsc, hz
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 \
233 raise Exception("multi port stats error")
234 for statistics in result:
235 stats = statistics.split(',')
236 port_id = int(stats[0])
239 no_mbufs += int(stats[3])
240 errors += int(stats[4])
242 return rx, tx, no_mbufs, errors, tsc
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))
248 def set_size(self, cores, task, pkt_size):
249 self._send('pkt_size %s %s %s' % (','.join(map(str, cores)), task,
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))))
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))
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)
268 self._sock.sendall(cmd.encode() + b'\n')
269 except ConnectionResetError as e:
270 RapidLog.error('Pipe reset by Prox instance: traffic too high?')
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")
278 pos = self._rcvd.find(b'\n')
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?')