pax_global_header00006660000000000000000000000064124376065350014525gustar00rootroot0000000000000052 comment=26dbc84448dbfffbff3602a6cbc88ce9b74b8772 nanomsg-python-1.0/000077500000000000000000000000001243760653500143465ustar00rootroot00000000000000nanomsg-python-1.0/.gitignore000066400000000000000000000004571243760653500163440ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject nanomsg-python-1.0/.travis.yml000066400000000000000000000010201243760653500164500ustar00rootroot00000000000000language: python python: - "3.2" - "3.3" - "3.4" - "2.7" - "2.6" # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors install: - git clone --quiet --depth=100 "https://github.com/nanomsg/nanomsg.git" ~/builds/nanomsg && pushd ~/builds/nanomsg && ./autogen.sh && ./configure && make && sudo make install && popd; # command to run tests, e.g. python setup.py test script: LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib python setup.py test nanomsg-python-1.0/LICENSE000066400000000000000000000020671243760653500153600ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2013 Tony Simpson 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. nanomsg-python-1.0/README.md000066400000000000000000000030331243760653500156240ustar00rootroot00000000000000nanomsg-python ============== Python library for [nanomsg](http://nanomsg.org/) which does not compromise on usability or performance. Like nanomsg this library is still experimental, the API is fairly stable but if you plan to use it at this time be prepared to get your hands dirty, fixes and enhancements are very welcome. The following versions of Python are supported CPython 2.6+, 3.2+ and Pypy 2.1.0+ Bugs and change requests can be made [here](https://github.com/tonysimpson/nanomsg-python/issues). Example ======= ```python from __future__ import print_function from nanomsg import Socket, PAIR, PUB s1 = Socket(PAIR) s2 = Socket(PAIR) s1.bind('inproc://bob') s2.connect('inproc://bob') s1.send(b'hello nanomsg') print(s2.recv()) s1.close() s2.close() ``` Or if you don't mind nesting you can use Socket as a context manager ```python with Socket(PUB) as pub_socket: .... do something with pub_socket # socket is closed ``` The lower level API is also available if you need the additional control or performance, but it is harder to use. Error checking left out for brevity. ```python from nanomsg import wrapper as nn_wrapper from nanomsg import PAIR, AF_SP s1 = nn_wrapper.nn_socket(AF_SP, PAIR) s2 = nn_wrapper.nn_socket(AF_SP, PAIR) nn_wrapper.nn_bind(s1, 'inproc://bob') nn_wrapper.nn_connect(s2, 'inproc://bob') nn_wrapper.nn_send(s1, b'hello nanomsg', 0) result, buffer = nn_wrapper.nn_recv(s2, 0) print(bytes(buffer)) nn_wrapper.nn_term() ``` License ======= MIT Authors ======= [Tony Simpson](https://github.com/tonysimpson) nanomsg-python-1.0/_nanomsg_cpy/000077500000000000000000000000001243760653500170225ustar00rootroot00000000000000nanomsg-python-1.0/_nanomsg_cpy/wrapper.c000066400000000000000000000332141243760653500206510ustar00rootroot00000000000000#include #include #include #include #ifdef WITH_NANOCONFIG #include #endif #if PY_MAJOR_VERSION >= 3 #define IS_PY3K #endif /* This might be a good idea or not */ #ifndef NO_CONCURRENY #define CONCURRENCY_POINT_BEGIN Py_BEGIN_ALLOW_THREADS #define CONCURRENCY_POINT_END Py_END_ALLOW_THREADS #else #define CONCURRENCY_POINT_BEGIN #define CONCURRENCY_POINT_END #endif /* defined to allow the same source for 2.6+ and 3.2+ */ #ifdef IS_PY3K #define Py_TPFLAGS_HAVE_CLASS 0L #define Py_TPFLAGS_HAVE_NEWBUFFER 0L #endif const static char MODULE_NAME[] = "_nanomsg_cpy"; typedef struct { PyObject_HEAD void *msg; size_t size; } Message; static void Message_dealloc(Message* self) { if (self->msg != NULL) { nn_freemsg(self->msg); } Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* Message_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyErr_Format(PyExc_TypeError, "cannot create '%.100s' instances us nn_alloc instead", type->tp_name); return NULL; } static PyMemberDef Message_members[] = { {NULL} /* Sentinel */ }; static PyMethodDef Message_methods[] = { {NULL} /* Sentinel */ }; int Message_getbuffer(Message *self, Py_buffer *view, int flags) { if( self->msg == NULL) { PyErr_BadInternalCall(); return -1; } return PyBuffer_FillInfo(view, (PyObject*)self, self->msg, self->size, 0, flags); } #ifndef IS_PY3K static int Message_getreadbuffer(Message *self, int segment, void **ptrptr) { if(segment != 0 || self->msg == NULL) { PyErr_BadInternalCall(); return -1; } *ptrptr = ((Message*)self)->msg; return ((Message*)self)->size; } static int Message_getwritebuffer(Message *self, int segment, void **ptrptr) { if(segment != 0 || self->msg == NULL) { PyErr_BadInternalCall(); return -1; } *ptrptr = ((Message*)self)->msg; return ((Message*)self)->size; } static int Message_getsegcountproc(PyObject *self, int *lenp) { if (lenp != NULL) { *lenp = ((Message*)self)->size; } return 1; } #endif static PyBufferProcs Message_bufferproces = { #ifndef IS_PY3K (readbufferproc)Message_getreadbuffer, (writebufferproc)Message_getwritebuffer, (segcountproc)Message_getsegcountproc, NULL, #endif (getbufferproc)Message_getbuffer, NULL }; static PyObject * Message_repr(Message * obj) { return PyUnicode_FromFormat("<_nanomsg_cpy.Message size %zu, address %p >", obj->size, obj->msg); } static PyObject * Message_str(Message * obj) { return PyBytes_FromStringAndSize(obj->msg, obj->size); } static PyTypeObject MessageType = { PyVarObject_HEAD_INIT(NULL, 0) "_nanomsg_cpy.Message", /*tp_name*/ sizeof(Message), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Message_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Message_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ (reprfunc)Message_str, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &Message_bufferproces, /*tp_as_buffer*/ Py_TPFLAGS_HAVE_CLASS | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_IS_ABSTRACT, /*tp_flags*/ "nanomsg allocated message wrapper supporting buffer protocol", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Message_methods, /* tp_methods */ Message_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ Message_new, /* tp_new */ }; static PyObject * _nanomsg_cpy_nn_errno(PyObject *self, PyObject *args) { return Py_BuildValue("i", nn_errno()); } static PyObject * _nanomsg_cpy_nn_strerror(PyObject *self, PyObject *args) { int error_number; if (!PyArg_ParseTuple(args, "i", &error_number)) return NULL; return Py_BuildValue("s", nn_strerror(error_number)); } static PyObject * _nanomsg_cpy_nn_socket(PyObject *self, PyObject *args) { int domain, protocol; if (!PyArg_ParseTuple(args, "ii", &domain, &protocol)) return NULL; return Py_BuildValue("i", nn_socket(domain, protocol)); } static PyObject * _nanomsg_cpy_nn_close(PyObject *self, PyObject *args) { int nn_result, socket; if (!PyArg_ParseTuple(args, "i", &socket)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_close(socket); CONCURRENCY_POINT_END return Py_BuildValue("i", nn_result); } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_close(PyObject *self, PyObject *args) { int nn_result, socket; if (!PyArg_ParseTuple(args, "i", &socket)) return NULL; CONCURRENCY_POINT_BEGIN nc_close(socket); CONCURRENCY_POINT_END Py_RETURN_NONE; } #endif static const char _nanomsg_cpy_nn_setsockopt__doc__[] = "set a socket option\n" "\n" "socket - socket number\n" "level - option level\n" "option - option\n" "value - a readable byte buffer (not a Unicode string) containing the value\n" "returns - 0 on success or < 0 on error\n\n"; static PyObject * _nanomsg_cpy_nn_setsockopt(PyObject *self, PyObject *args) { int nn_result, socket, level, option; Py_buffer value; if (!PyArg_ParseTuple(args, "iiis*", &socket, &level, &option, &value)) return NULL; nn_result = nn_setsockopt(socket, level, option, value.buf, value.len); PyBuffer_Release(&value); return Py_BuildValue("i", nn_result); } static const char _nanomsg_cpy_nn_getsockopt__doc__[] = "retrieve a socket option\n" "\n" "socket - socket number\n" "level - option level\n" "option - option\n" "value - a writable byte buffer (e.g. a bytearray) which the option value " "will be copied to.\n" "returns - number of bytes copied or on error nunber < 0\n\n"; static PyObject * _nanomsg_cpy_nn_getsockopt(PyObject *self, PyObject *args) { int nn_result, socket, level, option; size_t length; Py_buffer value; if (!PyArg_ParseTuple(args, "iiiw*", &socket, &level, &option, &value)) return NULL; length = value.len; nn_result = nn_getsockopt(socket, level, option, value.buf, &length); PyBuffer_Release(&value); return Py_BuildValue("in", nn_result, length); } static PyObject * _nanomsg_cpy_nn_bind(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nn_bind(socket, address)); } static PyObject * _nanomsg_cpy_nn_connect(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nn_connect(socket, address)); } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_configure(PyObject *self, PyObject *args) { int socket; const char *address; if (!PyArg_ParseTuple(args, "is", &socket, &address)) return NULL; return Py_BuildValue("i", nc_configure(socket, address)); } #endif static PyObject * _nanomsg_cpy_nn_shutdown(PyObject *self, PyObject *args) { int nn_result, socket, endpoint; if (!PyArg_ParseTuple(args, "ii", &socket, &endpoint)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_shutdown(socket, endpoint); CONCURRENCY_POINT_END return Py_BuildValue("i", nn_result); } static PyObject * _nanomsg_cpy_nn_send(PyObject *self, PyObject *args) { int nn_result, socket, flags; Py_buffer buffer; if (!PyArg_ParseTuple(args, "is*i", &socket, &buffer, &flags)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_send(socket, buffer.buf, buffer.len, flags); CONCURRENCY_POINT_END PyBuffer_Release(&buffer); return Py_BuildValue("i", nn_result); } static PyObject * _nanomsg_cpy_nn_recv(PyObject *self, PyObject *args) { int nn_result, socket, flags; Py_buffer buffer; Message* message; if(PyTuple_GET_SIZE(args) == 2) { if (!PyArg_ParseTuple(args, "ii", &socket, &flags)) return NULL; message = (Message*)PyType_GenericAlloc(&MessageType, 0); if(message == NULL) { return NULL; } CONCURRENCY_POINT_BEGIN nn_result = nn_recv(socket, &message->msg, NN_MSG, flags); CONCURRENCY_POINT_END if (nn_result < 0) { Py_DECREF((PyObject*)message); return Py_BuildValue("is", nn_result, NULL); } message->size = nn_result; return Py_BuildValue("iN", nn_result, message); } else { if(!PyArg_ParseTuple(args, "iw*i", &socket, &buffer, &flags)) return NULL; CONCURRENCY_POINT_BEGIN nn_result = nn_recv(socket, buffer.buf, buffer.len, flags); CONCURRENCY_POINT_END PyBuffer_Release(&buffer); return Py_BuildValue("iO", nn_result, PyTuple_GET_ITEM(args, 1)); } } static PyObject * _nanomsg_cpy_nn_device(PyObject *self, PyObject *args) { int socket_1, socket_2; if (!PyArg_ParseTuple(args, "ii", &socket_1, &socket_2)) return NULL; return Py_BuildValue("i", nn_device(socket_1, socket_2)); } static PyObject * _nanomsg_cpy_nn_term(PyObject *self, PyObject *args) { nn_term(); Py_RETURN_NONE; } #ifdef WITH_NANOCONFIG static PyObject * _nanomsg_cpy_nc_term(PyObject *self, PyObject *args) { nc_term(); Py_RETURN_NONE; } #endif static PyObject * _nanomsg_cpy_nn_allocmsg(PyObject *self, PyObject *args) { size_t size; int type; Message *message; if (!PyArg_ParseTuple(args, "ni", &size, &type)) return NULL; message = (Message*)PyType_GenericAlloc(&MessageType, 0); message->msg = nn_allocmsg(size, type); if (message->msg == NULL) { Py_DECREF((PyObject*)message); Py_RETURN_NONE; } message->size = size; return (PyObject*)message; } const char *nn_symbol (int i, int *value); static PyObject * _nanomsg_cpy_nn_symbols(PyObject *self, PyObject *args) { PyObject* py_list; const char *name; int value, i; py_list = PyList_New(0); for(i = 0; /*break inside loop */ ; i++) { name = nn_symbol(i,&value); if(name == NULL) { break; } PyList_Append(py_list, Py_BuildValue("si", name, value)); } return (PyObject*)py_list; } static PyMethodDef module_methods[] = { {"nn_errno", _nanomsg_cpy_nn_errno, METH_VARARGS, "retrieve the current errno"}, {"nn_strerror", _nanomsg_cpy_nn_strerror, METH_VARARGS, "convert an error number into human-readable string"}, {"nn_socket", _nanomsg_cpy_nn_socket, METH_VARARGS, "create an SP socket"}, {"nn_close", _nanomsg_cpy_nn_close, METH_VARARGS, "close an SP socket"}, {"nn_setsockopt", _nanomsg_cpy_nn_setsockopt, METH_VARARGS, _nanomsg_cpy_nn_setsockopt__doc__}, {"nn_getsockopt", _nanomsg_cpy_nn_getsockopt, METH_VARARGS, _nanomsg_cpy_nn_getsockopt__doc__}, {"nn_bind", _nanomsg_cpy_nn_bind, METH_VARARGS, "add a local endpoint to the socket"}, {"nn_connect", _nanomsg_cpy_nn_connect, METH_VARARGS, "add a remote endpoint to the socket"}, {"nn_shutdown", _nanomsg_cpy_nn_shutdown, METH_VARARGS, "remove an endpoint from a socket"}, {"nn_send", _nanomsg_cpy_nn_send, METH_VARARGS, "send a message"}, {"nn_recv", _nanomsg_cpy_nn_recv, METH_VARARGS, "receive a message"}, {"nn_device", _nanomsg_cpy_nn_device, METH_VARARGS, "start a device"}, {"nn_term", _nanomsg_cpy_nn_term, METH_VARARGS, "notify all sockets about process termination"}, {"nn_allocmsg", _nanomsg_cpy_nn_allocmsg, METH_VARARGS, "allocate a message"}, {"nn_symbols", _nanomsg_cpy_nn_symbols, METH_VARARGS, "query the names and values of nanomsg symbols"}, #ifdef WITH_NANOCONFIG {"nc_configure", _nanomsg_cpy_nc_configure, METH_VARARGS, "configure socket using nanoconfig"}, {"nc_close", _nanomsg_cpy_nc_close, METH_VARARGS, "close an SP socket configured with nn_configure"}, {"nc_term", _nanomsg_cpy_nc_term, METH_VARARGS, "shut down nanoconfig worker thread"}, #endif {NULL, NULL, 0, NULL} }; #ifndef IS_PY3K PyMODINIT_FUNC init_nanomsg_cpy(void) { PyObject* m; if (PyType_Ready(&MessageType) < 0) return; m = Py_InitModule(MODULE_NAME, module_methods); if (m == NULL) return; Py_INCREF(&MessageType); PyModule_AddObject(m, "Message", (PyObject *)&MessageType); } #else static struct PyModuleDef _nanomsg_cpy_module = { PyModuleDef_HEAD_INIT, MODULE_NAME, NULL, -1, module_methods }; PyMODINIT_FUNC PyInit__nanomsg_cpy(void) { PyObject* m; if (PyType_Ready(&MessageType) < 0) return NULL; m = PyModule_Create(&_nanomsg_cpy_module); if(m != NULL) { PyModule_AddObject(m, "Message", (PyObject *)&MessageType); } return m; } #endif nanomsg-python-1.0/_nanomsg_ctypes/000077500000000000000000000000001243760653500175365ustar00rootroot00000000000000nanomsg-python-1.0/_nanomsg_ctypes/__init__.py000066400000000000000000000201321243760653500216450ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function,\ unicode_literals import ctypes import platform import sys if sys.platform in ('win32', 'cygwin'): _functype = ctypes.WINFUNCTYPE _lib = ctypes.windll.nanomsg else: _functype = ctypes.CFUNCTYPE _lib = ctypes.cdll.LoadLibrary('libnanomsg.so') def _c_func_wrapper_factory(cdecl_text): def move_pointer_and_strip(type_def, name): if '*' in name: type_def += ' ' + name[:name.rindex('*')+1] name = name.rsplit('*', 1)[1] return type_def.strip(), name.strip() def type_lookup(type_def): types = { 'void': None, 'char *': ctypes.c_char_p, 'int': ctypes.c_int, 'int *': ctypes.POINTER(ctypes.c_int), 'void *': ctypes.c_void_p, 'size_t': ctypes.c_size_t, 'size_t *': ctypes.POINTER(ctypes.c_size_t), 'struct nn_msghdr *': ctypes.c_void_p, } type_def_without_const = type_def.replace('const ','') if type_def_without_const in types: return types[type_def_without_const] elif (type_def_without_const.endswith('*') and type_def_without_const[:-1] in types): return ctypes.POINTER(types[type_def_without_const[:-1]]) else: raise KeyError(type_def) return types[type_def.replace('const ','')] a, b = [i.strip() for i in cdecl_text.split('(',1)] params, _ = b.rsplit(')',1) rtn_type, name = move_pointer_and_strip(*a.rsplit(' ', 1)) param_spec = [] for param in params.split(','): if param != 'void': param_spec.append(move_pointer_and_strip(*param.rsplit(' ', 1))) func = _functype(type_lookup(rtn_type), *[type_lookup(type_def) for type_def, _ in param_spec])( (name, _lib), tuple((2 if '**' in type_def else 1, name) for type_def, name in param_spec) ) func.__name__ = name return func _C_HEADER = """ NN_EXPORT int nn_errno (void); NN_EXPORT const char *nn_strerror (int errnum); NN_EXPORT const char *nn_symbol (int i, int *value); NN_EXPORT void nn_term (void); NN_EXPORT void *nn_allocmsg (size_t size, int type); NN_EXPORT int nn_freemsg (void *msg); NN_EXPORT int nn_socket (int domain, int protocol); NN_EXPORT int nn_close (int s); NN_EXPORT int nn_setsockopt (int s, int level, int option, const void \ *optval, size_t optvallen); NN_EXPORT int nn_getsockopt (int s, int level, int option, void *optval, \ size_t *optvallen); NN_EXPORT int nn_bind (int s, const char *addr); NN_EXPORT int nn_connect (int s, const char *addr); NN_EXPORT int nn_shutdown (int s, int how); NN_EXPORT int nn_send (int s, const void *buf, size_t len, int flags); NN_EXPORT int nn_recv (int s, void *buf, size_t len, int flags); NN_EXPORT int nn_sendmsg (int s, const struct nn_msghdr *msghdr, int flags); NN_EXPORT int nn_recvmsg (int s, struct nn_msghdr *msghdr, int flags); NN_EXPORT int nn_device (int s1, int s2);\ """.replace('NN_EXPORT', '') for cdecl_text in _C_HEADER.splitlines(): if cdecl_text.strip(): func = _c_func_wrapper_factory(cdecl_text) globals()['_' + func.__name__] = func def nn_symbols(): "query the names and values of nanomsg symbols" value = ctypes.c_int() name_value_pairs = [] i = 0 while True: name = _nn_symbol(i, ctypes.byref(value)) if name is None: break i += 1 name_value_pairs.append((name.decode('ascii'), value.value)) return name_value_pairs nn_errno = _nn_errno nn_errno.__doc__ = "retrieve the current errno" nn_strerror = _nn_strerror nn_strerror.__doc__ = "convert an error number into human-readable string" nn_socket = _nn_socket nn_socket.__doc__ = "create an SP socket" nn_close = _nn_close nn_close.__doc__ = "close an SP socket" nn_bind = _nn_bind nn_bind.__doc__ = "add a local endpoint to the socket" nn_connect = _nn_connect nn_connect.__doc__ = "add a remote endpoint to the socket" nn_shutdown = _nn_shutdown nn_shutdown.__doc__ = "remove an endpoint from a socket" def create_writable_buffer(size): """Returns a writable buffer. This is the ctypes implementation. """ return (ctypes.c_ubyte*size)() def nn_setsockopt(socket, level, option, value): """set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error """ try: return _nn_setsockopt(socket, level, option, ctypes.addressof(value), len(value)) except (TypeError, AttributeError): buf_value = ctypes.create_string_buffer(value) return _nn_setsockopt(socket, level, option, ctypes.addressof(buf_value), len(value)) def nn_getsockopt(socket, level, option, value): """retrieve a socket option socket - socket number level - option level option - option value - a writable byte buffer (e.g. a bytearray) which the option value will be copied to returns - number of bytes copied or on error nunber < 0 """ if memoryview(value).readonly: raise TypeError('Writable buffer is required') size_t_size = ctypes.c_size_t(len(value)) rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value), ctypes.byref(size_t_size)) return (rtn, size_t_size.value) def nn_send(socket, msg, flags): "send a message" try: return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags) except (TypeError, AttributeError): buf_msg = ctypes.create_string_buffer(msg) return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags) def _create_message(address, length): class Message(ctypes.Union): _fields_ = [('_buf', ctypes.c_ubyte*length)] _len = length _address = address def __repr__(self): return '<_nanomsg_cpy.Message size %d, address 0x%x >' % ( self._len, self._address ) def __str__(self): return bytes(buffer(self)) def __del__(self): _nn_freemsg(self._address) self._len = 0 self._address = 0 return Message.from_address(address) def nn_allocmsg(size, type): "allocate a message" pointer = _nn_allocmsg(size, type) if pointer is None: return None return _create_message(pointer, size) def nn_recv(socket, *args): "receive a message" if len(args) == 1: flags, = args pointer = ctypes.c_void_p() rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1), flags) if rtn < 0: return rtn, None else: return rtn, _create_message(pointer.value, rtn) elif len(args) == 2: msg_buf, flags = args mv_buf = memoryview(msg_buf) if mv_buf.readonly: raise TypeError('Writable buffer is required') rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags) return rtn, msg_buf nn_device = _nn_device nn_device.__doc__ = "start a device" nn_term = _nn_term nn_term.__doc__ = "notify all sockets about process termination" try: if sys.platform in ('win32', 'cygwin'): _nclib = ctypes.windll.nanoconfig else: _nclib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: pass # No nanoconfig, sorry else: # int nc_configure (int s, const char *addr) nc_configure = _functype(ctypes.c_int, ctypes.c_int, ctypes.c_char_p)( ('nc_configure', _nclib), ((1, 's'), (1, 'addr'))) nc_configure.__doc__ = "configure socket using nanoconfig" # void nc_close(int s); nc_close = _functype(None, ctypes.c_int)( ('nc_close', _nclib), ((1, 's'),)) nc_close.__doc__ = "close an SP socket configured with nn_configure" # void nc_term(); nc_term = _functype(None)( ('nc_term', _nclib), ()) nc_term.__doc__ = "shutdown nanoconfig worker thread" nanomsg-python-1.0/nanomsg/000077500000000000000000000000001243760653500160105ustar00rootroot00000000000000nanomsg-python-1.0/nanomsg/__init__.py000066400000000000000000000276351243760653500201360ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function, unicode_literals from .version import __version__ from struct import Struct as _Struct import warnings from . import wrapper try: buffer except NameError: buffer = memoryview # py3 nanoconfig_started = False #Import contants into module with NN_ prefix stripped for name, value in wrapper.nn_symbols(): if name.startswith('NN_'): name = name[3:] globals()[name] = value if hasattr(wrapper, 'create_writable_buffer'): create_writable_buffer = wrapper.create_writable_buffer else: def create_writable_buffer(size): """Returns a writable buffer""" return bytearray(size) def create_message_buffer(size, type): """Create a message buffer""" rtn = wrapper.nn_allocmsg(size, type) if rtn is None: raise NanoMsgAPIError() return rtn class NanoMsgError(Exception): """Base Exception for all errors in the nanomsg python package """ pass class NanoMsgAPIError(NanoMsgError): """Exception for all errors reported by the C API. msg and errno are from nanomsg C library. """ __slots__ = ('msg', 'errno') def __init__(self): errno = wrapper.nn_errno() msg = wrapper.nn_strerror(errno) NanoMsgError.__init__(self, msg) self.errno, self.msg = errno, msg def _nn_check_positive_rtn(rtn): if rtn < 0: raise NanoMsgAPIError() return rtn class Device(object): """Create a nanomsg device to relay messages between sockets. If only one socket is supplied the device loops messages on that socket. """ def __init__(self, socket1, socket2=None): self._fd1 = socket1.fd self._fd2 = -1 if socket2 is None else socket2.fd def start(self): """Run the device in the current thread. This will not return until the device stops due to error or termination. """ _nn_check_positive_rtn(wrapper.nn_device(self._fd1, self._fd2)) def terminate_all(): """Close all sockets and devices""" global nanoconfig_started if nanoconfig_started: wrapper.nc_term() nanoconfig_started = False wrapper.nn_term() class Socket(object): """Class wrapping nanomsg socket. protocol should be a nanomsg protocol constant e.g. nanomsg.PAIR This class supports being used as a context manager which should gaurentee it is closed. e.g.: import time from nanomsg import PUB, Socket with Socket(PUB) as pub_socket: pub_socket.bind('tcp://127.0.0.1:49234') for i in range(100): pub_socket.send(b'hello all') time.sleep(0.5) #pub_socket is closed Socket.bind and Socket.connect return subclass of Endpoint which allow you to shutdown selected endpoints. The constructor also allows you to wrap existing sockets by passing in the socket fd instead of the protocol e.g.: from nanomsg import AF_SP, PAIR, Socket from nanomsg import wrapper as nn socket_fd = nn.nn_socket(AF_SP, PAIR) socket = Socket(socket_fd=socket_fd) """ _INT_PACKER = _Struct(str('i')) class _Endpoint(object): def __init__(self, socket, endpoint_id, address): self._endpoint_id = endpoint_id self._fdocket = socket self._address = address @property def address(self): return self._address def shutdown(self): self._fdocket._endpoints.remove(self) _nn_check_positive_rtn(nn_shutdown(self._fdocket._s, self._endpoint_id)) def __repr__(self): return '<%s socket %r, id %r, addresss %r>' % ( self.__class__.__name__, self._fdocket, self._endpoint_id, self._address ) class BindEndpoint(_Endpoint): pass class ConnectEndpoint(_Endpoint): pass class NanoconfigEndpoint(_Endpoint): def shutdown(self): raise NotImplementedError( "Shutdown of nanoconfig endpoint is not supported") def __init__(self, protocol=None, socket_fd=None, domain=AF_SP): if protocol is not None and socket_fd is not None: raise NanoMsgError('Only one of protocol or socket_fd should be ' 'passed to the Socket constructor') if protocol is not None: self._fd = _nn_check_positive_rtn( wrapper.nn_socket(domain, protocol) ) else: self._fd = socket_fd self._endpoints = [] def _get_send_fd(self): return self.get_int_option(SOL_SOCKET, SNDFD) def _get_recv_fd(self): return self.get_int_option(SOL_SOCKET, RCVFD) def _get_linger(self): return self.get_int_option(SOL_SOCKET, LINGER) def _set_linger(self, value): return self.set_int_option(SOL_SOCKET, LINGER, value) def _get_send_buffer_size(self): return self.get_int_option(SOL_SOCKET, SNDBUF) def _set_send_buffer_size(self, value): return self.set_int_option(SOL_SOCKET, SNDBUF, value) def _get_recv_buffer_size(self): return self.get_int_option(SOL_SOCKET, RCVBUF) def _set_recv_buffer_size(self, value): return self.set_int_option(SOL_SOCKET, RCVBUF, value) def _get_send_timeout(self): return self.get_int_option(SOL_SOCKET, SNDTIMEO) def _set_send_timeout(self, value): return self.set_int_option(SOL_SOCKET, SNDTIMEO, value) def _get_recv_timeout(self): return self.get_int_option(SOL_SOCKET, RCVTIMEO) def _set_recv_timeout(self, value): return self.set_int_option(SOL_SOCKET, RCVTIMEO, value) def _get_reconnect_interval(self): return self.get_int_option(SOL_SOCKET, RECONNECT_IVL) def _set_reconnect_interval(self, value): return self.set_int_option(SOL_SOCKET, RECONNECT_IVL, value) def _get_reconnect_interval_max(self): return self.get_int_option(SOL_SOCKET, RECONNECT_IVL_MAX) def _set_reconnect_interval_max(self, value): return self.set_int_option(SOL_SOCKET, RECONNECT_IVL_MAX, value) send_fd = property(_get_send_fd, doc='Send file descripter') recv_fd = property(_get_recv_fd, doc='Receive file descripter') linger = property(_get_linger, _set_linger, doc='Socket linger in ' 'milliseconds (0.001 seconds)') recv_buffer_size = property(_get_recv_buffer_size, _set_recv_buffer_size, doc='Receive buffer size in bytes') send_buffer_size = property(_get_send_buffer_size, _set_send_timeout, doc='Send buffer size in bytes') send_timeout = property(_get_send_timeout, _set_send_timeout, doc='Send timeout in milliseconds (0.001 seconds)') recv_timeout = property(_get_recv_timeout, _set_recv_timeout, doc='Receive timeout in milliseconds (0.001 ' 'seconds)') reconnect_interval = property( _get_reconnect_interval, _set_reconnect_interval, doc='Base interval between connection failure and reconnect' ' attempt in milliseconds (0.001 seconds).' ) reconnect_interval_max = property( _get_reconnect_interval_max, _set_reconnect_interval_max, doc='Max reconnect interval - see C API documentation.' ) @property def fd(self): """Socket file descripter. Not this is not an OS file descripter (see .send_fd, .recv_fd). """ return self._fd @property def endpoints(self): """Endpoints list """ return list(self._endpoints) @property def uses_nanoconfig(self): return (self._endpoints and isinstance(self._endpoints[0], Socket.NanoconfigEndpoint)) def bind(self, address): """Add a local endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_bind(self._fd, address) ) ep = Socket.BindEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def connect(self, address): """Add a remote endpoint to the socket""" if self.uses_nanoconfig: raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nn_connect(self.fd, address) ) ep = Socket.ConnectEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def configure(self, address): """Configure socket's addresses with nanoconfig""" global nanoconfig_started if len(self._endpoints): raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nc_configure(self.fd, address) ) if not nanoconfig_started: nanoconfig_started = True ep = Socket.NanoconfigEndpoint(self, endpoint_id, address) self._endpoints.append(ep) return ep def close(self): """Close the socket""" if self.is_open(): fd = self._fd self._fd = -1 if self.uses_nanoconfig: wrapper.nc_close(fd) else: _nn_check_positive_rtn(wrapper.nn_close(fd)) def is_open(self): """Returns true if the socket has a valid socket id. If the underlying socket is closed by some other means than Socket.close this method may return True when the socket is actually closed. """ return self.fd >= 0 def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn] def set_string_option(self, level, option, value): _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option, value)) def set_int_option(self, level, option, value): buf = create_writable_buffer(Socket._INT_PACKER.size) Socket._INT_PACKER.pack_into(buf, 0, value) _nn_check_positive_rtn(wrapper.nn_setsockopt(self.fd, level, option, buf)) def get_int_option(self, level, option): size = Socket._INT_PACKER.size buf = create_writable_buffer(size) rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf) _nn_check_positive_rtn(rtn) if length != size: raise NanoMsgError(('Returned option size (%r) should be the same' ' as size of int (%r)') % (rtn, size)) return Socket._INT_PACKER.unpack_from(buffer(buf))[0] def get_string_option(self, level, option, max_len=16*1024): buf = create_writable_buffer(max_len) rtn, length = wrapper.nn_getsockopt(self._fd, level, option, buf) _nn_check_positive_rtn(rtn) return bytes(buffer(buf))[:length] def send(self, msg, flags=0): """Send a message""" _nn_check_positive_rtn(wrapper.nn_send(self.fd, msg, flags)) def __enter__(self): return self def __exit__(self, *args): self.close() def __repr__(self): return '<%s fd %r, connected to %r, bound to %r>' % ( self.__class__.__name__, self.fd, [i.address for i in self.endpoints if type(i) is Socket.BindEndpoint], [i.address for i in self.endpoints if type(i) is Socket.ConnectEndpoint], ) def __del__(self): try: self.close() except NanoMsgError: pass nanomsg-python-1.0/nanomsg/version.py000066400000000000000000000000251243760653500200440ustar00rootroot00000000000000 __version__ = '1.0' nanomsg-python-1.0/nanomsg/wrapper.py000066400000000000000000000003171243760653500200430ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function, unicode_literals from nanomsg_wrappers import load_wrapper as _load_wrapper _wrapper = _load_wrapper() globals().update(_wrapper.__dict__) nanomsg-python-1.0/nanomsg_wrappers/000077500000000000000000000000001243760653500177335ustar00rootroot00000000000000nanomsg-python-1.0/nanomsg_wrappers/__init__.py000066400000000000000000000017541243760653500220530ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function, unicode_literals from platform import python_implementation import pkgutil import importlib import warnings _choice = None def set_wrapper_choice(name): global _choice _choice = name def load_wrapper(): if _choice is not None: return importlib.import_module('_nanomsg_' + _choice) default = get_default_for_platform() try: return importlib.import_module('_nanomsg_' + default) except ImportError: warnings.warn(("Could not load the default wrapper for your platform: " "%s, performance may be affected!") % (default,)) return importlib.import_module('_nanomsg_ctypes') def get_default_for_platform(): if python_implementation() == 'CPython': return 'cpy' else: return 'ctypes' def list_wrappers(): return [module_name.split('_',2)[-1] for _, module_name, _ in pkgutil.iter_modules() if module_name.startswith('_nanomsg_')] nanomsg-python-1.0/setup.py000066400000000000000000000055401243760653500160640ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function,\ unicode_literals import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup, Extension from distutils.core import Extension from distutils.errors import DistutilsError from distutils.command.build_ext import build_ext with open(os.path.join('nanomsg','version.py')) as f: exec(f.read()) class skippable_build_ext(build_ext): def run(self): try: build_ext.run(self) except Exception as e: print() print("=" * 79) print("WARNING : CPython API extension could not be built.") print() print("Exception was : %r" % (e,)) print() print( "If you need the extensions (they may be faster than " "alternative on some" ) print(" platforms) check you have a compiler configured with all" " the necessary") print(" headers and libraries.") print("=" * 79) print() try: import ctypes if sys.platform in ('win32', 'cygwin'): _lib = ctypes.windll.nanoconfig else: _lib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: # Building without nanoconfig cpy_extension = Extension(str('_nanomsg_cpy'), sources=[str('_nanomsg_cpy/wrapper.c')], libraries=[str('nanomsg')], ) else: # Building with nanoconfig cpy_extension = Extension(str('_nanomsg_cpy'), define_macros=[('WITH_NANOCONFIG', '1')], sources=[str('_nanomsg_cpy/wrapper.c')], libraries=[str('nanomsg'), str('nanoconfig')], ) install_requires = [] try: import importlib except ImportError: install_requires.append('importlib') setup( name='nanomsg', version=__version__, packages=[str('nanomsg'), str('_nanomsg_ctypes'), str('nanomsg_wrappers')], ext_modules=[cpy_extension], cmdclass = {'build_ext': skippable_build_ext}, install_requires=install_requires, description='Python library for nanomsg.', classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", ], author='Tony Simpson', author_email='agjasimpson@gmail.com', url='https://github.com/tonysimpson/nanomsg-python', keywords=['nanomsg', 'driver'], license='MIT', test_suite="tests", ) nanomsg-python-1.0/test_utils/000077500000000000000000000000001243760653500165455ustar00rootroot00000000000000nanomsg-python-1.0/test_utils/soaktest.py000066400000000000000000000017601243760653500207600ustar00rootroot00000000000000import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( SUB, PUB, SUB_SUBSCRIBE, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") from nanomsg import Socket, BUS, PAIR import sys import random from itertools import count with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) for i in count(1): msg = b''.join(chr(random.randint(0,255)) for i in range(1024*1024)) socket1.send(msg) res = socket2.recv() print i if msg != res: for num, (c1, c2) in enumerate(zip(msg, res)): if c1 != c2: print 'diff at', num, repr(c1), repr(c2) sys.exit() nanomsg-python-1.0/test_utils/throughput.py000066400000000000000000000034131243760653500213310ustar00rootroot00000000000000from __future__ import division, absolute_import, print_function,\ unicode_literals import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform WRAPPER = os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform()) set_wrapper_choice(WRAPPER) from nanomsg import ( PAIR, Socket, create_message_buffer ) from nanomsg.wrapper import ( nn_send, nn_recv ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") import time BUFFER_SIZE = eval(os.environ.get('NANOMSG_PY_TEST_BUFFER_SIZE', "1024")) msg = create_message_buffer(BUFFER_SIZE, 0) DURATION = 10 print(('Working NANOMSG_PY_TEST_BUFFER_SIZE %d NANOMSG_PY_TEST_WRAPPER %r ' 'NANOMSG_PY_TEST_ADDRESS %r') % (BUFFER_SIZE, WRAPPER, SOCKET_ADDRESS)) count = 0 start_t = time.time() with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) while time.time() < start_t + DURATION: c = chr(count % 255) memoryview(msg)[0] = c socket1.send(msg) res = socket2.recv(msg) assert res[0] == c count += 1 stop_t = time.time() print('Socket API throughput with checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,)) count = 0 start_t = time.time() with Socket(PAIR) as socket1: with Socket(PAIR) as socket2: socket1.bind(SOCKET_ADDRESS) socket2.connect(SOCKET_ADDRESS) while time.time() < start_t + DURATION: nn_send(socket1.fd, msg, 0) nn_recv(socket2.fd, msg, 0) count += 1 stop_t = time.time() print('Raw thoughtput no checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,)) nanomsg-python-1.0/tests/000077500000000000000000000000001243760653500155105ustar00rootroot00000000000000nanomsg-python-1.0/tests/__init__.py000066400000000000000000000000001243760653500176070ustar00rootroot00000000000000nanomsg-python-1.0/tests/test_general_socket_methods.py000066400000000000000000000027031243760653500236330ustar00rootroot00000000000000import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( PAIR, Socket, LINGER, SOL_SOCKET ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") LINGER_DEFAULT_VALUE = 1000 class TestGeneralSocketMethods(unittest.TestCase): def setUp(self): self.socket = Socket(PAIR) def tearDown(self): self.socket.close() def test_bind(self): endpoint = self.socket.bind(SOCKET_ADDRESS) self.assertNotEqual(None, endpoint) def test_connect(self): endpoint = self.socket.connect(SOCKET_ADDRESS) self.assertNotEqual(None, endpoint) def test_is_open_is_true_when_open(self): self.assertTrue(self.socket.is_open()) def test_is_open_is_false_when_closed(self): self.socket.close() self.assertFalse(self.socket.is_open()) def test_set_int_option(self): expected = 500 self.socket.set_int_option(SOL_SOCKET, LINGER, expected) actual = self.socket.get_int_option(SOL_SOCKET, LINGER) self.assertEqual(expected, actual) def test_get_int_option(self): actual = self.socket.get_int_option(SOL_SOCKET, LINGER) self.assertEqual(LINGER_DEFAULT_VALUE, actual) if __name__ == '__main__': unittest.main() nanomsg-python-1.0/tests/test_pair.py000066400000000000000000000026671243760653500200670ustar00rootroot00000000000000import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( PAIR, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") class TestPairSockets(unittest.TestCase): def test_send_recv(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'ABC' s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) def test_send_recv_with_embeded_nulls(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'ABC\x00DEFEDDSS' s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) def test_send_recv_large_message(self): with Socket(PAIR) as s1: with Socket(PAIR) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) sent = b'B'*(1024*1024) s2.send(sent) recieved = s1.recv() self.assertEqual(sent, recieved) if __name__ == '__main__': unittest.main() nanomsg-python-1.0/tests/test_pubsub.py000066400000000000000000000017431243760653500204260ustar00rootroot00000000000000import unittest import os from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())) from nanomsg import ( SUB, PUB, SUB_SUBSCRIBE, Socket ) SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a") class TestPubSubSockets(unittest.TestCase): def test_subscribe_works(self): with Socket(PUB) as s1: with Socket(SUB) as s2: s1.bind(SOCKET_ADDRESS) s2.connect(SOCKET_ADDRESS) s2.set_string_option(SUB, SUB_SUBSCRIBE, 'test') s1.send('test') s2.recv() s1.send('a') # should not get received expected = b'test121212' s1.send(expected) actual = s2.recv() self.assertEquals(expected, actual) if __name__ == '__main__': unittest.main()