-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoteObject.py
248 lines (201 loc) · 7.73 KB
/
RemoteObject.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
import Pyro.core, Pyro.util, Pyro.naming
import sys
import threading
import socket
import os
import signal
# change me as appropriate when you run the app!
default_ns_host = '192.168.150.1'
class MyThread(threading.Thread):
"""this is a wrapper for threading.Thread that improves
the syntax for creating and starting threads.
"""
def __init__(self, target, *args):
threading.Thread.__init__(self, target = target, args = args)
self.start()
class Watcher:
"""this class solves two problems with multithreaded
programs in Python, (1) a signal might be delivered
to any thread (which is just a malfeature) and (2) if
the thread that gets the signal is waiting, the signal
is ignored (which is a bug).
The watcher is a concurrent process (not thread) that
waits for a signal and then kills the process that contains the
active threads. See Appendix A of The Little Book of Semaphores.
I have only tested this on Linux. I would expect it to
work on OS X and not work on Windows.
"""
def __init__(self, callback = None):
""" Creates a child thread, which returns. The parent
thread waits for a KeyboardInterrupt and then kills
the child thread.
"""
self.child = os.fork()
if self.child == 0:
return
else:
self.watch(callback)
def watch(self, callback = None):
try:
os.wait()
except KeyboardInterrupt:
# I put the capital B in KeyBoardInterrupt so I can
# tell when the Watcher gets the SIGINT
if callback:
callback()
print 'KeyBoardInterrupt'
self.kill()
sys.exit()
def kill(self):
try:
os.kill(self.child, signal.SIGKILL)
except OSError: pass
def get_ip_addr():
port = 9090
"""get the real IP address of this machine"""
csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
csock.connect((default_ns_host, port))
(addr, port) = csock.getsockname()
csock.close()
return addr
class NameServer:
"""the NameServer object represents the name server running
on a remote host and provides methods for interacting with it"""
def __init__(self, ns_host=default_ns_host):
"""locate the name server on the given host"""
self.ns_host = ns_host
self.ns = Pyro.naming.NameServerLocator().getNS(ns_host)
def get_proxy(self, name):
"""look up a remote object by name and create a proxy for it"""
try:
uri = self.ns.resolve(name)
except Pyro.errors.NamingError:
type, value, traceback = sys.exc_info()
print 'Pyro NamingError:', value
sys.exit(1)
return Pyro.core.getProxyForURI(uri)
def query(self, name, group = None):
"""check whether the given name is registered in the given group.
return 1 if the name is a remote object, 0 if it is a group,
and -1 if it doesn't exist."""
t = self.ns.list(group)
for k, v in t:
if k == name:
return v
return -1
def create_group(self, name):
"""create a group with the given name"""
self.ns.createGroup(name)
def get_remote_object_list(self, prefix = '', group = None):
"""return a list of the remote objects in the given group
that start with the given prefix"""
t = self.ns.list(group)
u = [s for (s, n) in t if n == 1 and s.startswith(prefix)]
return u
def clear(self, prefix = '', group = None):
"""unregister all objects in the given group that start
with the given prefix"""
t = self.ns.list(group)
print t
for (s, n) in t:
if not s.startswith(prefix): continue
if n == 1:
if group:
s = '%s.%s' % (group, s)
print s
self.ns.unregister(s)
class RemoteObject(Pyro.core.ObjBase):
"""objects that want to be available remotely should inherit
from this class, and either (1) don't override __init__ or
(2) call RemoteObject.__init__ explicitly"""
def __init__(self, name = None, ns = None):
Pyro.core.ObjBase.__init__(self)
if name == None:
name = 'remote_object' + str(id(self))
self.name = name
if ns == None:
ns = NameServer()
self.connect(ns, name)
def connect(self, ns, name):
"""connect to the given name server with the given name"""
# create the daemon (the attribute is spelled "demon" to
# avoid a name collision)
addr = get_ip_addr()
self.demon = Pyro.core.Daemon(host=addr)
self.demon.useNameServer(ns.ns)
# instantiate the object and advertise it
try:
print 'Connecting remote object', name
self.uri = self.demon.connect(self, name)
except Pyro.errors.NamingError:
print 'Pyro NamingError: name already exists or is illegal'
sys.exit(1)
return self.name
def requestLoop(self):
"""run the request loop until an exception occurs"""
try:
self.demon.requestLoop()
except:
self.cleanup()
if sys.exc_type != KeyboardInterrupt:
raise sys.exc_type, sys.exc_value
def cleanup(self):
"""remove this object from the name server"""
print 'Shutting down remote object', self.name
try:
self.demon.disconnect(self)
except KeyError:
print "tried to remove a name that wasn't on the name server"
self.stopLoop()
self.demon.shutdown()
def threadLoop(self):
"""run the request loop in a separate thread"""
self.thread = threading.Thread(target = self.stoppableLoop)
self.thread.start()
def stoppableLoop(self):
"""run handleRequests until another thread clears self.running"""
self.running = 1
try:
while self.running:
self.demon.handleRequests(0.1)
finally:
self.cleanup()
def stopLoop(self):
"""if threadLoop is running, stop it"""
self.running = 0
def join(self):
"""wait for the threadLoop to complete"""
if hasattr(self, 'thread'):
self.thread.join()
def main(script, name = 'remote_object', group = 'test', *args):
# find the name server
ns = NameServer()
# if it doesn't have a group named test, make one
if ns.query(group) == -1:
print 'Making group %s...' % group
ns.create_group(group)
# create a remote object and connect it
full_name = '%s.%s' % (group, name)
server = RemoteObject(full_name, ns)
# confirm that the group and object are on the name server
print group, ns.query(group)
print full_name, ns.query(name, group)
print group, ns.get_remote_object_list(group=group)
# create a Watcher and then run the server loop in a thread
watcher = Watcher(server.cleanup)
child = MyThread(client_code, full_name, server)
server.stoppableLoop()
print 'Server done.'
def client_code(full_name, server):
# get a proxy for this object
# and invoke a method on it
ns = NameServer()
proxy = ns.get_proxy(full_name)
print proxy.__hash__()
# stop the server
server.stopLoop()
server.join()
# child thread completes
print 'Thread complete.'
if __name__ == '__main__':
main(*sys.argv)