forked from progrium/ginkgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
206 lines (167 loc) · 6.15 KB
/
Copy pathcore.py
File metadata and controls
206 lines (167 loc) · 6.15 KB
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
import functools
import runpy
from .util import AbstractStateMachine
from .util import defaultproperty
def require_ready(func):
""" Decorator that blocks the call until the service is ready """
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
try:
self.state.wait("ready", self.ready_timeout)
except Exception, e:
pass
if not self.ready:
raise RuntimeWarning("Service must be ready to call this method.")
return func(self, *args, **kwargs)
return wrapped
def autospawn(func):
""" Decorator that will spawn the call in a local greenlet """
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
self.spawn(func, self, *args, **kwargs)
return wrapped
class ServiceStateMachine(AbstractStateMachine):
""" +------+
| init |
+--+---+
|
v
+-------------------+
+--->| start() |
| |-------------------| +-------------------+
| | starting +---+--->| stop() |
| +-------------------+ | |-------------------|
| | | | stopping |
| v | +-------------------+
| +-----------+ | |
| | ready() | | |
| |-----------| | v
| | ready +-------+ +-------------+
| +-----------+ | stopped() |
| |-------------|
+------------------------------------+ stopped |
+-------------+
http://www.asciiflow.com/#7278337222084818599/1920677602
"""
initial_state = "init"
allow_wait = ["ready", "stopped"]
event_start = \
["init", "stopped"], "starting", "pre_start"
event_ready = \
["starting"], "ready", "post_start"
event_stop = \
["ready", "starting"], "stopping", "pre_stop"
event_stopped = \
["stopping"], "stopped", "post_stop"
class BasicService(object):
_statemachine_class = ServiceStateMachine
_children = defaultproperty(list)
start_timeout = defaultproperty(int, 2)
start_before = defaultproperty(bool, False)
def pre_init(self):
pass
def __new__(cls, *args, **kwargs):
s = super(BasicService, cls).__new__(cls, *args, **kwargs)
s.pre_init()
s.state = cls._statemachine_class(s)
return s
@property
def service_name(self):
return self.__class__.__name__
@property
def ready(self):
return self.state.current == 'ready'
def add_service(self, service):
"""Add a child service to this service
The service added will be started when this service starts, before
its :meth:`_start` method is called. It will also be stopped when this
service stops, before its :meth:`_stop` method is called.
"""
self._children.append(service)
def remove_service(self, service):
"""Remove a child service from this service"""
self._children.remove(service)
def start(self, block_until_ready=True):
"""Starts children and then this service. By default it blocks until ready."""
self.state("start")
if self.start_before:
self.do_start()
for child in self._children:
if child.state.current not in ["ready", "starting"]:
child.start(block_until_ready)
if not self.start_before:
ready = not self.do_start()
if not ready and block_until_ready is True:
self.state.wait("ready", self.start_timeout)
elif ready:
self.state("ready")
else:
self.state("ready")
def pre_start(self):
pass
def do_start(self):
"""Empty implementation of service start. Implement me!
Return `service.NOT_READY` to block until :meth:`set_ready` is
called (or `ready_timeout` is reached).
"""
return
def post_start(self):
pass
def stop(self):
"""Stop child services in reverse order and then this service"""
if self.state.current in ["init", "stopped"]:
return
ready_before_stop = self.ready
self.state("stop")
for child in reversed(self._children):
child.stop()
if ready_before_stop:
self.do_stop()
self.state("stopped")
def pre_stop(self):
pass
def post_stop(self):
pass
def do_stop(self):
"""Empty implementation of service stop. Implement me!"""
return
def reload(self):
for child in self._children:
child.reload()
self.do_reload()
def do_reload(self):
"""Empty implementation of service reload. Implement me!"""
pass
def serve_forever(self):
"""Start the service if it hasn't been already started and wait until it's stopped."""
try:
self.start()
except RuntimeWarning, e:
# If it can't start because it's
# already started, just move on
pass
# This is done to recursively get services to wait on stopped.
# Services based on BasicService will not wait because they
# have no async manager and assume no event loop or threads.
for child in self._children:
child.serve_forever()
self.state.wait("stopped")
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
class Service(BasicService):
async = 'ginkgo.async.gevent'
def pre_init(self):
try:
mod = runpy.run_module(self.async)
self.async = mod['AsyncManager']()
self.add_service(self.async)
except NotImplementedError: #(ImportError, KeyError):
raise RuntimeError(
"Unable to load async manager from {}".format(self.async))
def spawn(self, *args, **kwargs):
return self.async.spawn(*args, **kwargs)
def spawn_later(self, *args, **kwargs):
return self.async.spawn_later(*args, **kwargs)