Debian Codegraph @

futurist/_green.py

raw
1 # Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 import sys
15
16 from futurist import _utils
17
18 try:
19 from eventlet import greenpool
20 from eventlet import patcher as greenpatcher
21 from eventlet import queue as greenqueue
22
23 from eventlet.green import threading as greenthreading
24 except ImportError:
25 greenpatcher, greenpool, greenqueue, greenthreading = (None, None,
26 None, None)
27
28
29 if _utils.EVENTLET_AVAILABLE:
30 # Aliases that we use and only expose vs the whole of eventlet...
31 Pool = greenpool.GreenPool
32 Queue = greenqueue.Queue
33 is_monkey_patched = greenpatcher.is_monkey_patched
34
35 class GreenThreading:
36
37 @staticmethod
38 def event_object(*args, **kwargs):
39 return greenthreading.Event(*args, **kwargs)
40
41 @staticmethod
42 def lock_object(*args, **kwargs):
43 return greenthreading.Lock(*args, **kwargs)
44
45 @staticmethod
46 def rlock_object(*args, **kwargs):
47 return greenthreading.RLock(*args, **kwargs)
48
49 @staticmethod
50 def condition_object(*args, **kwargs):
51 return greenthreading.Condition(*args, **kwargs)
52
53 threading = GreenThreading()
54 else:
55 threading = None
56 Pool = None
57 Queue = None
58 is_monkey_patched = lambda mod: False
59
60
61 class GreenWorker:
62 def __init__(self, work, work_queue):
63 self.work = work
64 self.work_queue = work_queue
65
66 def __call__(self):
67 # Run our main piece of work.
68 try:
69 self.work.run()
70 except SystemExit as e:
71 exc_info = sys.exc_info()
72 try:
73 while True:
74 try:
75 w = self.work_queue.get_nowait()
76 except greenqueue.Empty:
77 break
78
79 try:
80 w.fail(exc_info)
81 finally:
82 self.work_queue.task_done()
83 finally:
84 del exc_info
85 raise e
86
87 # Consume any delayed work before finishing (this is how we finish
88 # work that was to big for the pool size, but needs to be finished
89 # no matter).
90 while True:
91 try:
92 w = self.work_queue.get_nowait()
93 except greenqueue.Empty:
94 break
95 else:
96 try:
97 w.run()
98 finally:
99 self.work_queue.task_done()