Completed
Push — master ( 91ab3c...4eddf2 )
by Olivier
04:29
created

SocketWrapper.read()   A

Complexity

Conditions 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
c 2
b 0
f 0
dl 0
loc 15
ccs 12
cts 12
cp 1
crap 4
rs 9.2
1 1
import logging
2 1
import os
3 1
from concurrent.futures import Future
4 1
import functools
5 1
import threading
6 1
from socket import error as SocketError
7
8 1
try:
9
    # we prefer to use bundles asyncio version, otherwise fallback to trollius
10 1
    import asyncio
11
except ImportError:
12
    import trollius as asyncio
13
14
15 1
from opcua.ua.uaerrors import UaError
16
17
18 1
class ServiceError(UaError):
19 1
    def __init__(self, code):
20 1
        super(ServiceError, self).__init__('UA Service Error')
21 1
        self.code = code
22
23
24 1
class NotEnoughData(UaError):
25 1
    pass
26
27
28 1
class SocketClosedException(UaError):
29 1
    pass
30
31
32 1
class Buffer(object):
33
34
    """
35
    alternative to io.BytesIO making debug easier
36
    and added a few conveniance methods
37
    """
38
39 1
    def __init__(self, data, start_pos=0, size=-1):
40
        # self.logger = logging.getLogger(__name__)
41 1
        self._data = data
42 1
        self._cur_pos = start_pos
43 1
        if size == -1:
44 1
            size = len(data) - start_pos
45 1
        self._size = size
46
47 1
    def __str__(self):
48
        return "Buffer(size:{0}, data:{1})".format(
49
            self._size,
50
            self._data[self._cur_pos:self._cur_pos + self._size])
51 1
    __repr__ = __str__
52
53 1
    def __len__(self):
54 1
        return self._size
55
56 1
    def read(self, size):
57
        """
58
        read and pop number of bytes for buffer
59
        """
60 1
        if size > self._size:
61
            raise NotEnoughData("Not enough data left in buffer, request for {0}, we have {1}".format(size, self))
62
        # self.logger.debug("Request for %s bytes, from %s", size, self)
63 1
        self._size -= size
64 1
        pos = self._cur_pos
65 1
        self._cur_pos += size
66 1
        data = self._data[pos:self._cur_pos]
67
        # self.logger.debug("Returning: %s ", data)
68 1
        return data
69
70 1
    def copy(self, size=-1):
71
        """
72
        return a shadow copy, optionnaly only copy 'size' bytes
73
        """
74 1
        if size == -1 or size > self._size:
75 1
            size = self._size
76 1
        return Buffer(self._data, self._cur_pos, size)
77
78 1
    def skip(self, size):
79
        """
80
        skip size bytes in buffer
81
        """
82 1
        if size > self._size:
83
            raise NotEnoughData("Not enough data left in buffer, request for {0}, we have {1}".format(size, self))
84 1
        self._size -= size
85 1
        self._cur_pos += size
86
87
88 1
class SocketWrapper(object):
89
    """
90
    wrapper to make it possible to have same api for
91
    normal sockets, socket from asyncio, StringIO, etc....
92
    """
93
94 1
    def __init__(self, sock):
95 1
        self.socket = sock
96
97 1
    def read(self, size):
98
        """
99
        Receive up to size bytes from socket
100
        """
101 1
        data = b''
102 1
        while size > 0:
103 1
            try:
104 1
                chunk = self.socket.recv(size)
105 1
            except (OSError, SocketError) as ex:
106 1
                raise SocketClosedException("Server socket has closed", ex)
107 1
            if not chunk:
108 1
                raise SocketClosedException("Server socket has closed")
109 1
            data += chunk
110 1
            size -= len(chunk)
111 1
        return data
112
113 1
    def write(self, data):
114 1
        self.socket.sendall(data)
115
116
117 1
def create_nonce(size=32):
118 1
    return os.urandom(size)
119
120
121 1
class ThreadLoop(threading.Thread):
122
    """
123
    run an asyncio loop in a thread
124
    """
125
126 1
    def __init__(self):
127 1
        threading.Thread.__init__(self)
128 1
        self.logger = logging.getLogger(__name__)
129 1
        self.loop = None
130 1
        self._cond = threading.Condition()
131
132 1
    def start(self):
133 1
        with self._cond:
134 1
            threading.Thread.start(self)
135 1
            self._cond.wait()
136
137 1
    def run(self):
138 1
        self.logger.debug("Starting subscription thread")
139 1
        self.loop = asyncio.new_event_loop()
140 1
        asyncio.set_event_loop(self.loop)
141 1
        with self._cond:
142 1
            self._cond.notify_all()
143 1
        self.loop.run_forever()
144 1
        self.logger.debug("subscription thread ended")
145
146 1
    def create_server(self, proto, hostname, port):
147 1
        return self.loop.create_server(proto, hostname, port)
148
149 1
    def stop(self):
150
        """
151
        stop subscription loop, thus the subscription thread
152
        """
153 1
        self.loop.call_soon_threadsafe(self.loop.stop)
154
155 1
    def call_soon(self, callback):
156 1
        self.loop.call_soon_threadsafe(callback)
157
158 1
    def call_later(self, delay, callback):
159
        """
160
        threadsafe call_later from asyncio
161
        """
162 1
        p = functools.partial(self.loop.call_later, delay, callback)
163 1
        self.loop.call_soon_threadsafe(p)
164
165 1
    def _create_task(self, future, coro, cb=None):
166
        #task = self.loop.create_task(coro)
167 1
        task = asyncio.async(coro, loop=self.loop) 
168 1
        if cb:
169 1
            task.add_done_callback(cb)
170 1
        future.set_result(task)
171
172 1
    def create_task(self, coro, cb=None):
173
        """
174
        threadsafe create_task from asyncio
175
        """
176 1
        future = Future()
177 1
        p = functools.partial(self._create_task, future, coro, cb)
178 1
        self.loop.call_soon_threadsafe(p)
179 1
        return future.result()
180
181 1
    def run_coro_and_wait(self, coro):
182 1
        cond = threading.Condition()
183 1
        def cb(_):
184 1
            with cond:
185 1
                cond.notify_all()
186 1
        with cond:
187 1
            task = self.create_task(coro, cb)
188 1
            cond.wait()
189 1
        return task.result()
190
191 1
    def _run_until_complete(self, future, coro):
192
        task = self.loop.run_until_complete(coro)
193
        future.set_result(task)
194
195 1
    def run_until_complete(self, coro):
196
        """
197
        threadsafe run_until_completed from asyncio
198
        """
199
        future = Future()
200
        p = functools.partial(self._run_until_complete, future, coro)
201
        self.loop.call_soon_threadsafe(p)
202
        return future.result()
203
204
205
206