Source

beanstalkt / beanstalkt / beanstalkt.py

  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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#!/usr/bin/env python
"""beanstalkt - An async beanstalkd client for Tornado"""

__license__ = """
Copyright (C) 2012-2013 Nephics AB

Parts of the code adopted from the beanstalkc project are:
    Copyright (C) 2008-2012 Andreas Bolka

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.
"""

__version__ = '0.5.0'

import socket
import time

from collections import deque

from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import stack_context


DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120  # Time (in seconds) To Run a job, min. 1 sec.
RECONNECT_TIMEOUT = 1  # Time (in seconds) between re-connection attempts


class Bunch:
    """Create a bunch to group a few variables.
    Undefined attributes have the default value of None.
    """
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __getattr__(self, name):
        return None


class BeanstalkException(Bunch, Exception):
    def __str__(self):
        return '{}: {} in reply to command {}'.format(
            self.__class__.__name__, self.status, self.request.cmd)


class UnexpectedResponse(BeanstalkException): pass
class CommandFailed(BeanstalkException): pass
class Buried(BeanstalkException): pass
class DeadlineSoon(BeanstalkException): pass
class TimedOut(BeanstalkException): pass


class Client(object):

    def __init__(self, host='localhost', port=11300,
                 connect_timeout=socket.getdefaulttimeout(), io_loop=None):
        self._connect_timeout = connect_timeout
        self.host = host
        self.port = port
        self.io_loop = io_loop or IOLoop.instance()
        self._stream = None
        self._using = 'default'  # current tube
        self._watching = set(['default'])   # set of watched tubes
        self._queue = deque()
        self._talking = False
        self._reconnect_cb = None

    def _reconnect(self):
        # wait some time before trying to re-connect
        self.io_loop.add_timeout(time.time() + RECONNECT_TIMEOUT,
                lambda: self.connect(self._reconnected))

    def _reconnected(self):
        # re-establish the used tube and tubes being watched
        watch = self._watching.difference(['default'])
        # ignore "default", if it is not in the client's watch list
        ignore = set(['default']).difference(self._watching)

        def do_next(_=None):
            try:
                if watch:
                    self.watch(watch.pop(), do_next)
                elif ignore:
                    self.ignore(ignore.pop(), do_next)
                elif self._using != 'default':
                    # change the tube used, and callback to user
                    self.use(self._using, self._reconnect_cb)
                elif self._reconnect_cb:
                    # callback to user
                    self._reconnect_cb()
            except:
                # ignored, as next re-connect will retry the operation
                pass

        do_next()

    def connect(self, callback=None):
        """Connect to beanstalkd server."""
        if not self.closed():
            return
        self._talking = False
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                socket.IPPROTO_TCP)
        self._stream = IOStream(self._socket, io_loop=self.io_loop)
        self._stream.set_close_callback(self._reconnect)
        self._stream.connect((self.host, self.port), callback)

    def set_reconnect_callback(self, callback):
        """Set callback to be called if connection has been lost and
        re-established again.

        If the connection is closed unexpectedly, the client will automatically
        attempt to re-connect with 1 second intervals. After re-connecting, the
        client will attempt to re-establish the used tube and watched tubes.
        """
        self._reconnect_cb = callback

    def close(self, callback=None):
        """Close connection to server."""
        if self._stream:
            self._stream.set_close_callback(callback)
        if self.closed():
            # already closed
            callback()
        else:
            self._stream.write('quit\r\n', self._stream.close)

    def closed(self):
        """"Returns True if the connection is closed."""
        return not self._stream or self._stream.closed()

    def _interact(self, request, callback):
        # put the interaction request into the FIFO queue
        cb = stack_context.wrap(callback)
        self._queue.append((request, cb))
        self._process_queue()

    def _process_queue(self):
        if self._talking or not self._queue:
            return
        # pop a request of the queue and perform the send-receive interaction
        self._talking = True
        with stack_context.NullContext():
            req, cb = self._queue.popleft()
            command = req.cmd + '\r\n'
            if req.body:
                command += req.body + '\r\n'

            # write command and body to socket stream
            self._stream.write(command,
                    # when command is written: read line from socket stream
                    lambda: self._stream.read_until('\r\n',
                    # when a line has been read: return status and results
                    lambda data: self._recv(req, data, cb)))

    def _recv(self, req, data, cb):
        # parse the data received as server response
        spl = data.split()
        status, values = spl[0], spl[1:]

        error = None
        err_args = dict(request=req, status=status, values=values)

        if req.ok and status in req.ok:
            # avoid raising a Buried exception when using the bury command
            pass
        elif status == 'BURIED':
            error = Buried(**err_args)
        elif status == 'TIMED_OUT':
            error = TimedOut(**err_args)
        elif status == 'DEADLINE_SOON':
            error = DeadlineSoon(**err_args)
        elif req.err and status in req.err:
            error = CommandFailed(**err_args)
        else:
            error = UnexpectedResponse(**err_args)

        resp = Bunch(req=req, status=status, values=values, error=error)

        if error or not req.read_body:
            # end the request and callback with results
            self._do_callback(cb, resp)
        else:
            # read the body including the terminating two bytes of crlf
            if len(values) == 2:
                job_id, size = int(values[0]), int(values[1])
                resp.job_id = int(job_id)
            else:
                size = int(values[0])
            self._stream.read_bytes(size + 2,
                    lambda data: self._recv_body(data[:-2], resp, cb))

    def _recv_body(self, data, resp, cb):
        if resp.req.parse_yaml:
            # parse the yaml encoded body
            self._parse_yaml(data, resp, cb)
        else:
            # don't parse body, it is a job!
            # end the request and callback with results
            resp.body = {'id': resp.job_id, 'body': data}
            self._do_callback(cb, resp)

    def _parse_yaml(self, data, resp, cb):
        # dirty parsing of yaml data
        # (assumes that data is a yaml encoded list or dict)
        spl = data.split('\n')[1:-1]
        if spl[0].startswith('- '):
            # it is a list
            resp.body = [s[2:] for s in spl]
        else:
            # it is a dict
            conv = lambda v: ((float(v) if '.' in v else int(v))
                if v.replace('.', '', 1).isdigit() else v)
            resp.body = dict((k, conv(v.strip())) for k, v in
                    (s.split(':') for s in spl))
        self._do_callback(cb, resp)

    def _do_callback(self, cb, resp):
        # end the request and process next item in the queue
        # and callback with results
        self._talking = False
        self.io_loop.add_callback(self._process_queue)

        if not cb:
            return

        # default is to callback with error state (None or exception)
        obj = None
        req = resp.req

        if resp.error:
            obj = resp.error

        elif req.read_value:
            # callback with an integer value or a string
            if resp.values[0].isdigit():
                obj = int(resp.values[0])
            else:
                obj = resp.values[0]

        elif req.read_body:
            # callback with the body (job or parsed yaml)
            obj = resp.body

        self.io_loop.add_callback(lambda: cb(obj))

    #
    #  Producer commands
    #

    def put(self, body, priority=DEFAULT_PRIORITY, delay=0, ttr=120,
            callback=None):
        """Put a job body (a byte string) into the current tube.

        The job can be delayed a number of seconds, before it is put in the
        ready queue, default is no delay.

        The job is assigned a Time To Run (ttr, in seconds), the mininum is
        1 sec., default is ttr=120 sec.

        Calls back with id when job is inserted. If an error occured,
        the callback gets a Buried or CommandFailed exception. The job is
        buried when either the body is too big, so server ran out of memory,
        or when the server is in draining mode.
        """
        request = Bunch(cmd='put {} {} {} {}'.format(priority, delay, ttr,
                len(body)), ok=['INSERTED'], err=['BURIED', 'JOB_TOO_BIG',
                'DRAINING'], body=body, read_value=True)
        self._interact(request, callback)

    def use(self, name, callback=None):
        """Use the tube with given name.

        Calls back with the name of the tube now being used.
        """
        def using(resp):
            if not isinstance(resp, Exception):
                self._using = resp
            if callback:
                callback(resp)

        request = Bunch(cmd='use {}'.format(name), ok=['USING'],
                read_value=True)
        self._interact(request, using)

    #
    #  Worker commands
    #

    def reserve(self, timeout=None, callback=None):
        """Reserve a job from one of the watched tubes, with optional timeout
        in seconds.

        Not specifying a timeout (timeout=None, the default) will make the
        client put the communication with beanstalkd on hold, until either a
        job is reserved, or a already reserved job is approaching it's TTR
        deadline. Commands issued while waiting for the "reserve" callback will
        be queued and sent in FIFO order, when communication is resumed.

        A timeout value of 0 will cause the server to immediately return either
        a response or TIMED_OUT. A positive value of timeout will limit the
        amount of time the client will will hold communication until a job
        becomes available.

        Calls back with a job dict (keys id and body). If the request timed out,
        the callback gets a TimedOut exception. If a reserved job has deadline
        within the next second, the callback gets a DeadlineSoon exception.
        """
        if timeout is not None:
            command = 'reserve-with-timeout {}'.format(timeout)
        else:
            command = 'reserve'
        request = Bunch(cmd=command, ok=['RESERVED'], err=['DEADLINE_SOON',
                'TIMED_OUT'], read_body=True)
        self._interact(request, callback)

    def delete(self, job_id, callback=None):
        """Delete job with given id.

        Calls back when job is deleted. If the job does not exist, or it is not
        neither reserved by the client, ready or buried; the callback gets a
        CommandFailed exception.
        """
        request = Bunch(cmd='delete {}'.format(job_id), ok=['DELETED'],
                err=['NOT_FOUND'])
        self._interact(request, callback)

    def release(self, job_id, priority=DEFAULT_PRIORITY, delay=0,
            callback=None):
        """Release a reserved job back into the ready queue.

        A new priority can be assigned to the job.

        It is also possible to specify a delay (in seconds) to wait before
        putting the job in the ready queue. The job will be in the "delayed"
        state during this time.

        Calls back when job is released. If the job was buried, the callback
        gets a Buried exception. If the job does not exist, or it is not
        reserved by the client, the callback gets a CommandFailed exception.
        """
        request = Bunch(cmd='release {} {} {}'.format(job_id, priority, delay),
                ok=['RELEASED'], err=['BURIED', 'NOT_FOUND'])
        self._interact(request, callback)

    def bury(self, job_id, priority=DEFAULT_PRIORITY, callback=None):
        """Bury job with given id.

        A new priority can be assigned to the job.

        Calls back when job is burried. If the job does not exist, or it is not
        reserved by the client, the callback gets a CommandFailed exception.
        """
        request = Bunch(cmd='bury {} {}'.format(job_id, priority),
                ok=['BURIED'], err=['NOT_FOUND'])
        self._interact(request, callback)

    def touch(self, job_id, callback=None):
        """Touch job with given id.

        This is for requesting more time to work on a reserved job before it
        expires.

        Calls back when job is touched. If the job does not exist, or it is not
        reserved by the client, the callback gets a CommandFailed exception.
        """
        request = Bunch(cmd='touch {}'.format(job_id), ok=['TOUCHED'],
                err=['NOT_FOUND'])
        self._interact(request, callback)

    def watch(self, name, callback=None):
        """Watch tube with given name.

        Calls back with number of tubes currently in the watch list.
        """
        def watching(count):
            if not isinstance(count, Exception):
                # add to the client's watch list
                self._watching.add(name)
            if callback:
                callback(count)

        request = Bunch(cmd='watch {}'.format(name), ok=['WATCHING'],
                read_value=True)
        self._interact(request, watching)

    def ignore(self, name, callback=None):
        """Stop watching tube with given name.

        Calls back with the number of tubes currently in the watch list. On an
        attempt to ignore the only tube in the watch list, the callback gets a
        CommandFailed exception.
        """
        def ignoring(count):
            if not isinstance(count, Exception) and name in self._watching:
                # remove from the client's watch list
                self._watching.remove(name)
            if callback:
                callback(count)

        request = Bunch(cmd='ignore {}'.format(name), ok=['WATCHING'],
                err=['NOT_IGNORED'], read_value=True)
        self._interact(request, ignoring)

    #
    #  Other commands
    #

    def _peek(self, variant, callback):
        # a shared gateway for the peek* commands
        request = Bunch(cmd='peek{}'.format(variant), ok=['FOUND'],
                err=['NOT_FOUND'], read_body=True)
        self._interact(request, callback)

    def peek(self, job_id, callback=None):
        """Peek at job with given id.

        Calls back with a job dict (keys id and body). If no job exists with
        that id, the callback gets a CommandFailed exception.
        """
        self._peek(' {}'.format(job_id), callback)

    def peek_ready(self, callback=None):
        """Peek at next ready job in the current tube.

        Calls back with a job dict (keys id and body). If no ready jobs exist,
        the callback gets a CommandFailed exception.
        """
        self._peek('-ready', callback)

    def peek_delayed(self, callback=None):
        """Peek at next delayed job in the current tube.

        Calls back with a job dict (keys id and body). If no delayed jobs exist,
        the callback gets a CommandFailed exception.
        """
        self._peek('-delayed', callback)

    def peek_buried(self, callback=None):
        """Peek at next buried job in the current tube.

        Calls back with a job dict (keys id and body). If no buried jobs exist,
        the callback gets a CommandFailed exception.
        """
        self._peek('-buried', callback)

    def kick(self, bound=1, callback=None):
        """Kick at most `bound` jobs into the ready queue from the current tube.

        Calls back with the number of jobs actually kicked.
        """
        request = Bunch(cmd='kick {}'.format(bound), ok=['KICKED'],
                read_value=True)
        self._interact(request, callback)

    def kick_job(self, job_id, callback=None):
        """Kick job with given id into the ready queue.
        (Requires Beanstalkd version >= 1.8)

        Calls back when job is kicked. If no job exists with that id, or if
        job is not in a kickable state, the callback gets a CommandFailed
        exception.
        """
        request = Bunch(cmd='kick-job {}'.format(job_id), ok=['KICKED'],
                err=['NOT_FOUND'])
        self._interact(request, callback)

    def stats_job(self, job_id, callback=None):
        """A dict of stats about the job with given id.

        If no job exists with that id, the callback gets a CommandFailed
        exception.
        """
        request = Bunch(cmd='stats-job {}'.format(job_id), ok=['OK'],
                err=['NOT_FOUND'], read_body=True, parse_yaml=True)
        self._interact(request, callback)

    def stats_tube(self, name, callback=None):
        """A dict of stats about the tube with given name.

        If no tube exists with that name, the callback gets a CommandFailed
        exception.
        """
        request = Bunch(cmd='stats-tube {}'.format(name), ok=['OK'],
                err=['NOT_FOUND'], read_body=True, parse_yaml=True)
        self._interact(request, callback)

    def stats(self, callback=None):
        """A dict of beanstalkd statistics."""
        request = Bunch(cmd='stats', ok=['OK'], read_body=True,
                parse_yaml=True)
        self._interact(request, callback)

    def list_tubes(self, callback=None):
        """List of all existing tubes."""
        request = Bunch(cmd='list-tubes', ok=['OK'], read_body=True,
                parse_yaml=True)
        self._interact(request, callback)

    def list_tube_used(self, callback=None):
        """Name of the tube currently being used."""
        request = Bunch(cmd='list-tube-used', ok=['USING'], read_value=True)
        self._interact(request, callback)

    def list_tubes_watched(self, callback=None):
        """List of tubes currently being watched."""
        request = Bunch(cmd='list-tubes-watched', ok=['OK'], read_body=True,
                parse_yaml=True)
        self._interact(request, callback)

    def pause_tube(self, name, delay, callback=None):
        """Delay any new job being reserved from the tube for a given time.

        The delay is an integer number of seconds to wait before reserving any
        more jobs from the queue.

        Calls back when tube is paused. If tube does not exists, the callback
        will get a CommandFailed exception.
        """
        request = Bunch(cmd='pause-tube {} {}'.format(name, delay),
                ok=['PAUSED'], err=['NOT_FOUND'])
        self._interact(request, callback)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.