This file is indexed.

/usr/lib/python3/dist-packages/partd/zmq.py is in python3-partd 0.3.8-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from __future__ import absolute_import, print_function

import zmq
import logging
from itertools import chain
from bisect import bisect
import socket
from operator import add
from time import sleep, time
from toolz import accumulate, topk, pluck, merge, keymap
import uuid
from collections import defaultdict
from contextlib import contextmanager
from threading import Thread, Lock
from datetime import datetime
from multiprocessing import Process
import traceback
import sys
from .dict import Dict
from .file import File
from .buffer import Buffer
from . import core
from .compatibility import Queue, Empty, unicode
from .utils import ignoring


tuple_sep = b'-|-'

logger = logging.getLogger(__name__)


@contextmanager
def logerrors():
    try:
        yield
    except Exception as e:
        logger.exception(e)
        raise


class Server(object):
    def __init__(self, partd=None, bind=None, start=True, block=False,
            hostname=None):
        self.context = zmq.Context()
        if partd is None:
            partd = Buffer(Dict(), File())
        self.partd = partd

        self.socket = self.context.socket(zmq.ROUTER)

        if hostname is None:
            hostname = socket.gethostname()
        if isinstance(bind, unicode):
            bind = bind.encode()
        if bind is None:
            port = self.socket.bind_to_random_port('tcp://*')
        else:
            self.socket.bind(bind)
            port = int(bind.split(':')[-1].rstrip('/'))
        self.address = ('tcp://%s:%d' % (hostname, port)).encode()

        self.status = 'created'

        self.partd.lock.acquire()
        self._lock = Lock()
        self._socket_lock = Lock()

        if start:
            self.start()

        if block:
            self.block()

    def start(self):
        if self.status != 'run':
            self.status = 'run'
            self._listen_thread = Thread(target=self.listen)
            self._listen_thread.start()
            logger.debug('Start server at %s', self.address)

    def block(self):
        """ Block until all threads close """
        try:
            self._listen_thread.join()
        except AttributeError:
            pass

    def listen(self):
        with logerrors():
            logger.debug('Start listening %s', self.address)
            while self.status != 'closed':
                if not self.socket.poll(100):
                    continue

                with self._socket_lock:
                    payload = self.socket.recv_multipart()

                address, command, payload = payload[0], payload[1], payload[2:]
                logger.debug('Server receives %s %s', address, command)
                if command == b'close':
                    logger.debug('Server closes')
                    self.ack(address)
                    self.status = 'closed'
                    break
                    # self.close()

                elif command == b'append':
                    keys, values = payload[::2], payload[1::2]
                    keys = list(map(deserialize_key, keys))
                    data = dict(zip(keys, values))
                    self.partd.append(data, lock=False)
                    logger.debug('Server appends %d keys', len(data))
                    self.ack(address)

                elif command == b'iset':
                    key, value = payload
                    key = deserialize_key(key)
                    self.partd.iset(key, value, lock=False)
                    self.ack(address)

                elif command == b'get':
                    keys = list(map(deserialize_key, payload))
                    logger.debug('get %s', keys)
                    result = self.get(keys)
                    self.send_to_client(address, result)
                    self.ack(address, flow_control=False)

                elif command == b'delete':
                    keys = list(map(deserialize_key, payload))
                    logger.debug('delete %s', keys)
                    self.partd.delete(keys, lock=False)
                    self.ack(address, flow_control=False)

                elif command == b'syn':
                    self.ack(address)

                elif command == b'drop':
                    self.drop()
                    self.ack(address)

                else:
                    logger.debug("Unknown command: %s", command)
                    raise ValueError("Unknown command: " + command)

    def send_to_client(self, address, result):
        with logerrors():
            if not isinstance(result, list):
                result = [result]
            with self._socket_lock:
                self.socket.send_multipart([address] + result)

    def ack(self, address, flow_control=True):
        with logerrors():
            logger.debug('Server sends ack')
            self.send_to_client(address, b'ack')

    def append(self, data):
        self.partd.append(data, lock=False)
        logger.debug('Server appends %d keys', len(data))

    def drop(self):
        with logerrors():
            self.partd.drop()

    def get(self, keys):
        with logerrors():
            logger.debug('Server gets keys: %s', keys)
            with self._lock:
                result = self.partd.get(keys, lock=False)
            return result

    def close(self):
        logger.debug('Server closes')
        self.status = 'closed'
        self.block()
        with ignoring(zmq.error.ZMQError):
            self.socket.close(1)
        with ignoring(zmq.error.ZMQError):
            self.context.destroy(3)
        self.partd.lock.release()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self.close()
        self.partd.__exit__(*args)


def keys_to_flush(lengths, fraction=0.1, maxcount=100000):
    """ Which keys to remove

    >>> lengths = {'a': 20, 'b': 10, 'c': 15, 'd': 15,
    ...            'e': 10, 'f': 25, 'g': 5}
    >>> keys_to_flush(lengths, 0.5)
    ['f', 'a']
    """
    top = topk(max(len(lengths) // 2, 1),
               lengths.items(),
               key=1)
    total = sum(lengths.values())
    cutoff = min(maxcount, max(1,
                   bisect(list(accumulate(add, pluck(1, top))),
                          total * fraction)))
    result = [k for k, v in top[:cutoff]]
    assert result
    return result


def serialize_key(key):
    """

    >>> serialize_key('x')
    'x'
    >>> serialize_key(('a', 'b', 1))
    'a-|-b-|-1'
    """
    if isinstance(key, tuple):
        return tuple_sep.join(map(serialize_key, key))
    if isinstance(key, bytes):
        return key
    if isinstance(key, str):
        return key.encode()
    return str(key).encode()


def deserialize_key(text):
    """

    >>> deserialize_key('x')
    'x'
    >>> deserialize_key('a-|-b-|-1')
    ('a', 'b', '1')
    """
    if tuple_sep in text:
        return tuple(text.split(tuple_sep))
    else:
        return text


from .core import Interface
from .file import File


class Client(Interface):
    def __init__(self, address=None, create_server=False, **kwargs):
        self.address = address
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.DEALER)
        logger.debug('Client connects to %s', address)
        self.socket.connect(address)
        self.send(b'syn', [], ack_required=False)
        self.lock = NotALock()  # Server sequentializes everything
        Interface.__init__(self)

    def __getstate__(self):
        return {'address': self.address}

    def __setstate__(self, state):
        self.__init__(state['address'])
        logger.debug('Reconstruct client from pickled state')

    def send(self, command, payload, recv=False, ack_required=True):
        if ack_required:
            ack = self.socket.recv_multipart()
            assert ack == [b'ack']
        logger.debug('Client sends command: %s', command)
        self.socket.send_multipart([command] + payload)
        if recv:
            result = self.socket.recv_multipart()
        else:
            result = None
        return result

    def _get(self, keys, lock=None):
        """

        Lock argument is ignored.  Everything is sequential (I think)
        """
        logger.debug('Client gets %s %s', self.address, keys)
        keys = list(map(serialize_key, keys))
        return self.send(b'get', keys, recv=True)

    def append(self, data, lock=None):
        logger.debug('Client appends %s %s', self.address, str(len(data)) + ' keys')
        data = keymap(serialize_key, data)
        payload = list(chain.from_iterable(data.items()))
        self.send(b'append', payload)

    def _delete(self, keys, lock=None):
        logger.debug('Client deletes %s %s', self.address, str(len(keys)) + ' keys')
        keys = list(map(serialize_key, keys))
        self.send(b'delete', keys)

    def _iset(self, key, value):
        self.send(b'iset', [serialize_key(key), value])

    def drop(self):
        self.send(b'drop', [])
        sleep(0.05)

    def close_server(self):
        self.send(b'close', [])

    def close(self):
        if hasattr(self, 'server_process'):
            with ignoring(zmq.error.ZMQError):
                self.close_server()
            self.server_process.join()
        with ignoring(zmq.error.ZMQError):
            self.socket.close(1)
        with ignoring(zmq.error.ZMQError):
            self.context.destroy(1)

    def __exit__(self, type, value, traceback):
        self.drop()
        self.close()

    def __del__(self):
        self.close()


class NotALock(object):
    def acquire(self): pass
    def release(self): pass

    def __enter__(self):
        return self

    def __exit__(self, *args):
        pass