stats: support multiple works for error counters
[vpp.git] / src / vpp-api / python / vpp_papi / vpp_stats.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 from cffi import FFI
5 import time
6
7 ffi = FFI()
8 ffi.cdef("""
9 typedef uint64_t counter_t;
10 typedef struct {
11   counter_t packets;
12   counter_t bytes;
13 } vlib_counter_t;
14
15 typedef enum {
16   STAT_DIR_TYPE_ILLEGAL = 0,
17   STAT_DIR_TYPE_SCALAR_INDEX,
18   STAT_DIR_TYPE_COUNTER_VECTOR_SIMPLE,
19   STAT_DIR_TYPE_COUNTER_VECTOR_COMBINED,
20   STAT_DIR_TYPE_ERROR_INDEX,
21   STAT_DIR_TYPE_NAME_VECTOR,
22 } stat_directory_type_t;
23
24 typedef struct
25 {
26   stat_directory_type_t type;
27   union {
28     uint64_t offset;
29     uint64_t index;
30     uint64_t value;
31   };
32   uint64_t offset_vector;
33   char name[128]; // TODO change this to pointer to "somewhere"
34 } stat_segment_directory_entry_t;
35
36 typedef struct
37 {
38   char *name;
39   stat_directory_type_t type;
40   union
41   {
42     double scalar_value;
43     counter_t *error_vector;
44     counter_t **simple_counter_vec;
45     vlib_counter_t **combined_counter_vec;
46     uint8_t **name_vector;
47   };
48 } stat_segment_data_t;
49
50 typedef struct
51 {
52   uint64_t epoch;
53   uint64_t in_progress;
54   uint64_t directory_offset;
55   uint64_t error_offset;
56   uint64_t stats_offset;
57 } stat_segment_shared_header_t;
58
59 typedef struct
60 {
61   uint64_t current_epoch;
62   stat_segment_shared_header_t *shared_header;
63   stat_segment_directory_entry_t *directory_vector;
64   ssize_t memory_size;
65 } stat_client_main_t;
66
67 stat_client_main_t * stat_client_get(void);
68 void stat_client_free(stat_client_main_t * sm);
69 int stat_segment_connect_r (char *socket_name, stat_client_main_t * sm);
70 int stat_segment_connect (char *socket_name);
71 void stat_segment_disconnect_r (stat_client_main_t * sm);
72 void stat_segment_disconnect (void);
73
74 uint32_t *stat_segment_ls_r (uint8_t ** patterns, stat_client_main_t * sm);
75 uint32_t *stat_segment_ls (uint8_t ** pattern);
76 stat_segment_data_t *stat_segment_dump_r (uint32_t * stats, stat_client_main_t * sm);
77 stat_segment_data_t *stat_segment_dump (uint32_t * counter_vec);
78 void stat_segment_data_free (stat_segment_data_t * res);
79
80 double stat_segment_heartbeat_r (stat_client_main_t * sm);
81 int stat_segment_vec_len(void *vec);
82 uint8_t **stat_segment_string_vector(uint8_t **string_vector, char *string);
83 char *stat_segment_index_to_name_r (uint32_t index, stat_client_main_t * sm);
84 void free(void *ptr);
85 """)
86
87
88 # Utility functions
89 def make_string_vector(api, strings):
90     vec = ffi.NULL
91     if type(strings) is not list:
92         strings = [strings]
93     for s in strings:
94         vec = api.stat_segment_string_vector(vec, ffi.new("char []",
95                                                           s.encode('utf-8')))
96     return vec
97
98
99 def make_string_list(api, vec):
100     vec_len = api.stat_segment_vec_len(vec)
101     return [ffi.string(vec[i]) for i in range(vec_len)]
102
103
104 # 2-dimensonal array of thread, index
105 def simple_counter_vec_list(api, e):
106     vec = []
107     for thread in range(api.stat_segment_vec_len(e)):
108         len_interfaces = api.stat_segment_vec_len(e[thread])
109         if_per_thread = [e[thread][interfaces]
110                          for interfaces in range(len_interfaces)]
111         vec.append(if_per_thread)
112     return vec
113
114
115 def vlib_counter_dict(c):
116     return {'packets': c.packets,
117             'bytes': c.bytes}
118
119
120 def combined_counter_vec_list(api, e):
121     vec = []
122     for thread in range(api.stat_segment_vec_len(e)):
123         len_interfaces = api.stat_segment_vec_len(e[thread])
124         if_per_thread = [vlib_counter_dict(e[thread][interfaces])
125                          for interfaces in range(len_interfaces)]
126         vec.append(if_per_thread)
127     return vec
128
129 def error_vec_list(api, e):
130     vec = []
131     for thread in range(api.stat_segment_vec_len(e)):
132         vec.append(e[thread])
133     return vec
134
135 def name_vec_list(api, e):
136     return [ffi.string(e[i]).decode('utf-8') for i in range(api.stat_segment_vec_len(e)) if e[i] != ffi.NULL]
137
138 def stat_entry_to_python(api, e):
139     # Scalar index
140     if e.type == 1:
141         return e.scalar_value
142     if e.type == 2:
143         return simple_counter_vec_list(api, e.simple_counter_vec)
144     if e.type == 3:
145         return combined_counter_vec_list(api, e.combined_counter_vec)
146     if e.type == 4:
147         return error_vec_list(api, e.error_vector)
148     if e.type == 5:
149         return name_vec_list(api, e.name_vector)
150     raise NotImplementedError()
151
152
153 class VPPStatsIOError(IOError):
154     message = "Stat segment client connection returned: " \
155               "%(retval)s %(strerror)s."
156
157     strerror = {-1: "Stat client couldn't open socket",
158                 -2: "Stat client socket open but couldn't connect",
159                 -3: "Receiving file descriptor failed",
160                 -4: "mmap fstat failed",
161                 -5: "mmap map failed"
162                 }
163
164     def __init__(self, message=None, **kwargs):
165         if 'retval' in kwargs:
166             self.retval = kwargs['retval']
167             kwargs['strerror'] = self.strerror[int(self.retval)]
168
169         if not message:
170             try:
171                 message = self.message % kwargs
172             except Exception as e:
173                 message = self.message
174         else:
175             message = message % kwargs
176
177         super(VPPStatsIOError, self).__init__(message)
178
179
180 class VPPStatsClientLoadError(RuntimeError):
181     pass
182
183
184 class VPPStats(object):
185     VPPStatsIOError = VPPStatsIOError
186
187     default_socketname = '/var/run/vpp/stats.sock'
188     sharedlib_name = 'libvppapiclient.so'
189
190     def __init__(self, socketname=default_socketname, timeout=10):
191         try:
192             self.api = ffi.dlopen(VPPStats.sharedlib_name)
193         except Exception:
194             raise VPPStatsClientLoadError("Could not open: %s" %
195                                           VPPStats.sharedlib_name)
196         self.client = self.api.stat_client_get()
197
198         poll_end_time = time.time() + timeout
199         while time.time() < poll_end_time:
200             rv = self.api.stat_segment_connect_r(socketname.encode('utf-8'),
201                                                  self.client)
202             if rv == 0:
203                 break
204
205         if rv != 0:
206             raise VPPStatsIOError(retval=rv)
207
208     def heartbeat(self):
209         return self.api.stat_segment_heartbeat_r(self.client)
210
211     def ls(self, patterns):
212         return self.api.stat_segment_ls_r(make_string_vector(self.api,
213                                                              patterns),
214                                           self.client)
215
216     def lsstr(self, patterns):
217         rv = self.api.stat_segment_ls_r(make_string_vector(self.api,
218                                                            patterns),
219                                         self.client)
220
221         if rv == ffi.NULL:
222             raise VPPStatsIOError()
223         return [ffi.string(self.api.stat_segment_index_to_name_r(rv[i], self.client)).decode('utf-8')
224                 for i in range(self.api.stat_segment_vec_len(rv))]
225
226     def dump(self, counters):
227         stats = {}
228         rv = self.api.stat_segment_dump_r(counters, self.client)
229         # Raise exception and retry
230         if rv == ffi.NULL:
231             raise VPPStatsIOError()
232         rv_len = self.api.stat_segment_vec_len(rv)
233
234         for i in range(rv_len):
235             n = ffi.string(rv[i].name).decode('utf-8')
236             e = stat_entry_to_python(self.api, rv[i])
237             if e is not None:
238                 stats[n] = e
239         return stats
240
241     def get_counter(self, name):
242         retries = 0
243         while True:
244             try:
245                 d = self.ls(name)
246                 s = self.dump(d)
247                 if len(s) > 1:
248                     raise AttributeError('Matches multiple counters {}'
249                                          .format(name))
250                 k, v = s.popitem()
251                 return v
252             except VPPStatsIOError as e:
253                 if retries > 10:
254                     return None
255                 retries += 1
256
257     def get_err_counter(self, name):
258         """Get an error counter. The errors from each worker thread
259            are summed"""
260         return sum(self.get_counter(name))
261
262     def disconnect(self):
263         self.api.stat_segment_disconnect_r(self.client)
264         self.api.stat_client_free(self.client)
265
266     def set_errors(self):
267         '''Return all errors counters > 0'''
268         retries = 0
269         while True:
270             try:
271                 error_names = self.ls(['/err/'])
272                 error_counters = self.dump(error_names)
273                 break
274             except VPPStatsIOError as e:
275                 if retries > 10:
276                     return None
277                 retries += 1
278
279         return {k: sum(error_counters[k])
280                 for k in error_counters.keys() if sum(error_counters[k])}
281
282     def set_errors_str(self):
283         '''Return all errors counters > 0 pretty printed'''
284         s = 'ERRORS:\n'
285         error_counters = self.set_errors()
286         for k in sorted(error_counters):
287             s += '{:<60}{:>10}\n'.format(k, error_counters[k])
288         return s