summaryrefslogtreecommitdiffstats
path: root/src/vppinfra/zvec.h
blob: 7d35a3fe41fe6aeff804899294fcab8f34995acf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/*
 * Copyright (c) 2015 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
  Copyright (c) 2001, 2002, 2003 Eliot Dresselhaus

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef included_zvec_h
#define included_zvec_h

#include <vppinfra/clib.h>
#include <vppinfra/error.h>	/* for ASSERT */
#include <vppinfra/format.h>

/* zvec: compressed vectors.

   Data is entropy coded with 32 bit "codings".

   Consider coding as bitmap, coding = 2^c_0 + 2^c_1 + ... + 2^c_n
   With c_0 < c_1 < ... < c_n.  coding == 0 represents c_n = BITS (uword).

   Unsigned integers i = 0 ... are represented as follows:

       0 <= i < 2^c_0       	(i << 1) | (1 << 0) binary:   i 1
   2^c_0 <= i < 2^c_0 + 2^c_1   (i << 2) | (1 << 1) binary: i 1 0
   ...                                              binary: i 0 ... 0

   Smaller numbers use less bits.  Coding is chosen so that encoding
   of given histogram of typical values gives smallest number of bits.
   The number and position of coding bits c_i are used to best fit the
   histogram of typical values.
*/

typedef struct
{
  /* Smallest coding for given histogram of typical data. */
  u32 coding;

  /* Number of data in histogram. */
  u32 n_data;

  /* Number of codes (unique values) in histogram. */
  u32 n_codes;

  /* Number of bits in smallest coding of data. */
  u32 min_coding_bits;

  /* Average number of bits per code. */
  f64 ave_coding_bits;
} zvec_coding_info_t;

/* Encode/decode data. */
uword zvec_encode (uword coding, uword data, uword * n_result_bits);
uword zvec_decode (uword coding, uword zdata, uword * n_zdata_bits);

format_function_t format_zvec_coding;

typedef u32 zvec_histogram_count_t;

#define zvec_coding_from_histogram(h,count_field,len,max_value_to_encode,zc) \
  _zvec_coding_from_histogram ((h), (len),				\
			       STRUCT_OFFSET_OF_VAR (h, count_field),	\
			       sizeof (h[0]),				\
			       max_value_to_encode,			\
			       (zc))

uword
_zvec_coding_from_histogram (void *_histogram,
			     uword histogram_len,
			     uword histogram_elt_count_offset,
			     uword histogram_elt_bytes,
			     uword max_value_to_encode,
			     zvec_coding_info_t * coding_info_return);

#define _(TYPE,IS_SIGNED)						\
  uword * zvec_encode_##TYPE (uword * zvec, uword * zvec_n_bits, uword coding, \
			   void * data, uword data_stride, uword n_data);

_(u8, /* is_signed */ 0);
_(u16, /* is_signed */ 0);
_(u32, /* is_signed */ 0);
_(u64, /* is_signed */ 0);
_(i8, /* is_signed */ 1);
_(i16, /* is_signed */ 1);
_(i32, /* is_signed */ 1);
_(i64, /* is_signed */ 1);

#undef _

#define _(TYPE,IS_SIGNED)			\
  void zvec_decode_##TYPE (uword * zvec,	\
			   uword * zvec_n_bits,	\
			   uword coding,	\
			   void * data,		\
			   uword data_stride,	\
			   uword n_data)

_(u8, /* is_signed */ 0);
_(u16, /* is_signed */ 0);
_(u32, /* is_signed */ 0);
_(u64, /* is_signed */ 0);
_(i8, /* is_signed */ 1);
_(i16, /* is_signed */ 1);
_(i32, /* is_signed */ 1);
_(i64, /* is_signed */ 1);

#undef _

/* Signed <=> unsigned conversion.
      -1, -2, -3, ... =>    1, 3, 5, ... odds
   0, +1, +2, +3, ... => 0, 2, 4, 6, ... evens */
always_inline uword
zvec_signed_to_unsigned (word s)
{
  uword a = s < 0;
  s = 2 * s + a;
  return a ? -s : s;
}

always_inline word
zvec_unsigned_to_signed (uword u)
{
  uword a = u & 1;
  u >>= 1;
  return a ? -u : u;
}

#endif /* included_zvec_h */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
span class="o">== '_': if not (attr.startswith('__') and attr.endswith('__')): raise AttributeError('tried to get private attribute: %s ', attr) self._path.append(attr) return self def __setattr__(self, attr, val): if attr[0] == '_': if not (attr.startswith('__') and attr.endswith('__')): super(RemoteClassAttr, self).__setattr__(attr, val) return self._path.append(attr) self._remote._remote_exec(RemoteClass.SETATTR, self.path_to_str(), value=val) def __call__(self, *args, **kwargs): return self._remote._remote_exec(RemoteClass.CALL, self.path_to_str(), *args, **kwargs) class RemoteClass(Process): """ This class can wrap around and adapt the interface of another class, and then delegate its execution to a newly forked child process. Usage: #. Create a remotely executed instance of MyClass. :: object = RemoteClass(MyClass, arg1='foo', arg2='bar') object.start_remote() #. Access the object normally as if it was an instance of your class. :: object.my_attribute = 20 print object.my_attribute print object.my_method(object.my_attribute) object.my_attribute.nested_attribute = 'test' #. If you need the value of a remote attribute, use .get_remote_value method. This method is automatically called when needed in the context of a remotely executed class. E.g. :: if (object.my_attribute.get_remote_value() > 20): object.my_attribute2 = object.my_attribute #. Destroy the instance. :: object.quit_remote() object.terminate() """ GET = 0 # Get attribute remotely CALL = 1 # Call method remotely SETATTR = 2 # Set attribute remotely REPR = 3 # Get representation of a remote object STR = 4 # Get string representation of a remote object QUIT = 5 # Quit remote execution PIPE_PARENT = 0 # Parent end of the pipe PIPE_CHILD = 1 # Child end of the pipe DEFAULT_TIMEOUT = 2 # default timeout for an operation to execute def __init__(self, cls, *args, **kwargs): super(RemoteClass, self).__init__() self._cls = cls self._args = args self._kwargs = kwargs self._timeout = RemoteClass.DEFAULT_TIMEOUT self._pipe = Pipe() # pipe for input/output arguments def __repr__(self): return reprlib.repr(RemoteClassAttr(self, None)) def __str__(self): return str(RemoteClassAttr(self, None)) def __call__(self, *args, **kwargs): return self.RemoteClassAttr(self, None)() def __getattr__(self, attr): if attr[0] == '_' or not self.is_alive(): if not (attr.startswith('__') and attr.endswith('__')): if hasattr(super(RemoteClass, self), '__getattr__'): return super(RemoteClass, self).__getattr__(attr) raise AttributeError('missing: %s', attr) return RemoteClassAttr(self, attr) def __setattr__(self, attr, val): if attr[0] == '_' or not self.is_alive(): if not (attr.startswith('__') and attr.endswith('__')): super(RemoteClass, self).__setattr__(attr, val) return setattr(RemoteClassAttr(self, None), attr, val) def _remote_exec(self, op, path=None, *args, **kwargs): """ Execute given operation on a given, possibly nested, member remotely. """ # automatically resolve remote objects in the arguments mutable_args = list(args) for i, val in enumerate(mutable_args): if isinstance(val, RemoteClass) or \ isinstance(val, RemoteClassAttr): mutable_args[i] = val.get_remote_value() args = tuple(mutable_args) for key, val in kwargs.items(): if isinstance(val, RemoteClass) or \ isinstance(val, RemoteClassAttr): kwargs[key] = val.get_remote_value() # send request args = self._make_serializable(args) kwargs = self._make_serializable(kwargs) self._pipe[RemoteClass.PIPE_PARENT].send((op, path, args, kwargs)) timeout = self._timeout # adjust timeout specifically for the .sleep method if path is not None and path.split('.')[-1] == 'sleep': if args and isinstance(args[0], (long, int)): timeout += args[0] elif 'timeout' in kwargs: timeout += kwargs['timeout'] if not self._pipe[RemoteClass.PIPE_PARENT].poll(timeout): return None try: rv = self._pipe[RemoteClass.PIPE_PARENT].recv() rv = self._deserialize(rv) return rv except EOFError: return None def _get_local_object(self, path): """ Follow the path to obtain a reference on the addressed nested attribute """ obj = self._instance for attr in path: obj = getattr(obj, attr) return obj def _get_local_value(self, path): try: return self._get_local_object(path) except AttributeError: return None def _call_local_method(self, path, *args, **kwargs): try: method = self._get_local_object(path) return method(*args, **kwargs) except AttributeError: return None def _set_local_attr(self, path, value): try: obj = self._get_local_object(path[:-1]) setattr(obj, path[-1], value) except AttributeError: pass return None def _get_local_repr(self, path): try: obj = self._get_local_object(path) return reprlib.repr(obj) except AttributeError: return None def _get_local_str(self, path): try: obj = self._get_local_object(path) return str(obj) except AttributeError: return None def _serializable(self, obj): """ Test if the given object is serializable """ try: dumps(obj) return True except: return False def _make_obj_serializable(self, obj): """ Make a serializable copy of an object. Members which are difficult/impossible to serialize are stripped. """ if self._serializable(obj): return obj # already serializable copy = SerializableClassCopy() """ Dictionaries can hold complex values, so we split keys and values into separate lists and serialize them individually. """ if (type(obj) is dict): copy.type = type(obj) copy.k_list = list() copy.v_list = list() for k, v in obj.items(): copy.k_list.append(self._make_serializable(k)) copy.v_list.append(self._make_serializable(v)) return copy # copy at least serializable attributes and properties for name, member in inspect.getmembers(obj): # skip private members and non-writable dunder methods. if name[0] == '_': if name in ['__weakref__']: continue if name in ['__dict__']: continue if not (name.startswith('__') and name.endswith('__')): continue if callable(member) and not isinstance(member, property): continue if not self._serializable(member): member = self._make_serializable(member) setattr(copy, name, member) return copy def _make_serializable(self, obj): """ Make a serializable copy of an object or a list/tuple of objects. Members which are difficult/impossible to serialize are stripped. """ if (type(obj) is list) or (type(obj) is tuple): rv = [] for item in obj: rv.append(self._make_serializable(item)) if type(obj) is tuple: rv = tuple(rv) return rv elif (isinstance(obj, IntEnum) or isinstance(obj, IntFlag)): return obj.value else: return self._make_obj_serializable(obj) def _deserialize_obj(self, obj): if (hasattr(obj, 'type')): if obj.type is dict: _obj = dict() for k, v in zip(obj.k_list, obj.v_list): _obj[self._deserialize(k)] = self._deserialize(v) return _obj return obj def _deserialize(self, obj): if (type(obj) is list) or (type(obj) is tuple): rv = [] for item in obj: rv.append(self._deserialize(item)) if type(obj) is tuple: rv = tuple(rv) return rv else: return self._deserialize_obj(obj) def start_remote(self): """ Start remote execution """ self.start() def quit_remote(self): """ Quit remote execution """ self._remote_exec(RemoteClass.QUIT, None) def get_remote_value(self): """ Get value of a remotely held object """ return RemoteClassAttr(self, None).get_remote_value() def set_request_timeout(self, timeout): """ Change request timeout """ self._timeout = timeout def run(self): """ Create instance of the wrapped class and execute operations on it as requested by the parent process. """ self._instance = self._cls(*self._args, **self._kwargs) while True: try: rv = None # get request from the parent process (op, path, args, kwargs) = self._pipe[RemoteClass.PIPE_CHILD].recv() args = self._deserialize(args) kwargs = self._deserialize(kwargs) path = path.split('.') if path else [] if op == RemoteClass.GET: rv = self._get_local_value(path) elif op == RemoteClass.CALL: rv = self._call_local_method(path, *args, **kwargs) elif op == RemoteClass.SETATTR and 'value' in kwargs: self._set_local_attr(path, kwargs['value']) elif op == RemoteClass.REPR: rv = self._get_local_repr(path) elif op == RemoteClass.STR: rv = self._get_local_str(path) elif op == RemoteClass.QUIT: break else: continue # send return value if not self._serializable(rv): rv = self._make_serializable(rv) self._pipe[RemoteClass.PIPE_CHILD].send(rv) except EOFError: break self._instance = None # destroy the instance @unittest.skip("Remote Vpp Test Case Class") class RemoteVppTestCase(VppTestCase): """ Re-use VppTestCase to create remote VPP segment In your test case:: @classmethod def setUpClass(cls): # fork new process before client connects to VPP cls.remote_test = RemoteClass(RemoteVppTestCase) # start remote process cls.remote_test.start_remote() # set up your test case super(MyTestCase, cls).setUpClass() # set up remote test cls.remote_test.setUpClass(cls.tempdir) @classmethod def tearDownClass(cls): # tear down remote test cls.remote_test.tearDownClass() # stop remote process cls.remote_test.quit_remote() # tear down your test case super(MyTestCase, cls).tearDownClass() """ def __init__(self): super(RemoteVppTestCase, self).__init__("emptyTest") # Note: __del__ is a 'Finalizer" not a 'Destructor'. # https://docs.python.org/3/reference/datamodel.html#object.__del__ def __del__(self): if hasattr(self, "vpp"): self.vpp.poll() if self.vpp.returncode is None: self.vpp.terminate() self.vpp.communicate() @classmethod def setUpClass(cls, tempdir): # disable features unsupported in remote VPP orig_env = dict(os.environ) if 'STEP' in os.environ: del os.environ['STEP'] if 'DEBUG' in os.environ: del os.environ['DEBUG'] cls.tempdir_prefix = os.path.basename(tempdir) + "/" super(RemoteVppTestCase, cls).setUpClass() os.environ = orig_env @classmethod def tearDownClass(cls): super(RemoteVppTestCase, cls).tearDownClass() @unittest.skip("Empty test") def emptyTest(self): """ Do nothing """ pass def setTestFunctionInfo(self, name, doc): """ Store the name and documentation string of currently executed test in the main VPP for logging purposes. """ self._testMethodName = name self._testMethodDoc = doc