Debian Codegraph @

Pyro5/utils/echoserver.py

raw
1 """
2 Echo server for test purposes.
3 This is usually invoked by starting this module as a script:
4
5 :command:`python -m Pyro5.test.echoserver`
6 or simply: :command:`pyro5-test-echoserver`
7
8
9 It is also possible to use the :class:`EchoServer` in user code
10 but that is not terribly useful.
11
12 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
13 """
14
15 import sys
16 import time
17 import threading
18 from argparse import ArgumentParser
19 from .. import config, core, server, nameserver
20
21
22 __all__ = ["EchoServer"]
23
24
25 @server.expose
26 class EchoServer(object):
27 """
28 The echo server object that is provided as a Pyro object by this module.
29 If its :attr:`verbose` attribute is set to ``True``, it will print messages as it receives calls.
30 """
31 _verbose = False
32 _must_shutdown = False
33
34 def echo(self, message):
35 """return the message"""
36 if self._verbose:
37 message_str = repr(message).encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
38 print("%s - echo: %s" % (time.asctime(), message_str))
39 return message
40
41 def error(self):
42 """generates a simple exception without text"""
43 if self._verbose:
44 print("%s - error: generating exception" % time.asctime())
45 raise ValueError("this is the generated error from echoserver echo() method")
46
47 def error_with_text(self):
48 """generates a simple exception with message"""
49 if self._verbose:
50 print("%s - error: generating exception" % time.asctime())
51 raise ValueError("the message of the error")
52
53 @server.oneway
54 def oneway_echo(self, message):
55 """just like echo, but oneway; the client won't wait for response"""
56 if self._verbose:
57 message_str = repr(message).encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
58 print("%s - oneway_echo: %s" % (time.asctime(), message_str))
59 return "bogus return value"
60
61 def slow(self):
62 """returns (and prints) a message after a certain delay"""
63 if self._verbose:
64 print("%s - slow: waiting a bit..." % time.asctime())
65 time.sleep(5)
66 if self._verbose:
67 print("%s - slow: returning result" % time.asctime())
68 return "Finally, an answer!"
69
70 def generator(self):
71 """a generator function that returns some elements on demand"""
72 yield "one"
73 yield "two"
74 yield "three"
75
76 def nan(self):
77 return float("nan")
78
79 def inf(self):
80 return float("inf")
81
82 @server.oneway
83 def oneway_slow(self):
84 """prints a message after a certain delay, and returns; but the client won't wait for it"""
85 if self._verbose:
86 print("%s - oneway_slow: waiting a bit..." % time.asctime())
87 time.sleep(5)
88 if self._verbose:
89 print("%s - oneway_slow: returning result" % time.asctime())
90 return "bogus return value"
91
92 def _private(self):
93 """a 'private' method that should not be accessible"""
94 return "should not be allowed"
95
96 def __private(self):
97 """another 'private' method that should not be accessible"""
98 return "should not be allowed"
99
100 def __dunder__(self):
101 """a double underscore method that should be accessible normally"""
102 return "should be allowed (dunder)"
103
104 def shutdown(self):
105 """called to signal the echo server to shut down"""
106 if self._verbose:
107 print("%s - shutting down" % time.asctime())
108 self._must_shutdown = True
109
110 @property
111 def verbose(self):
112 return self._verbose
113
114 @verbose.setter
115 def verbose(self, onoff):
116 self._verbose = bool(onoff)
117
118
119 class NameServer(threading.Thread):
120 def __init__(self, hostname):
121 super(NameServer, self).__init__()
122 self.daemon = True
123 self.hostname = hostname
124 self.started = threading.Event()
125
126 def run(self):
127 self.uri, self.ns_daemon, self.bc_server = nameserver.start_ns(self.hostname)
128 self.started.set()
129 if self.bc_server:
130 self.bc_server.runInThread()
131 self.ns_daemon.requestLoop()
132
133
134 def start_nameserver(host):
135 ns = NameServer(host)
136 ns.start()
137 ns.started.wait()
138 return ns
139
140
141 def main(args=None, returnWithoutLooping=False):
142 parser = ArgumentParser(description="Pyro test echo/nameserver command line launcher.")
143 parser.add_argument("-H", "--host", default="localhost", help="hostname to bind server on (default=%(default)s)")
144 parser.add_argument("-p", "--port", type=int, default=0, help="port to bind server on")
145 parser.add_argument("-u", "--unixsocket", help="Unix domain socket name to bind server on")
146 parser.add_argument("-n", "--naming", action="store_true", default=False, help="register with nameserver")
147 parser.add_argument("-N", "--nameserver", action="store_true", default=False, help="also start a nameserver")
148 parser.add_argument("-v", "--verbose", action="store_true", default=False, help="verbose output")
149 parser.add_argument("-q", "--quiet", action="store_true", default=False, help="don't output anything")
150 args = parser.parse_args(args)
151
152 if args.verbose:
153 args.quiet = False
154 if not args.quiet:
155 print("Starting Pyro's built-in test echo server.")
156 config.SERVERTYPE = "multiplex"
157
158 namesvr = None
159 if args.nameserver:
160 args.naming = True
161 namesvr = start_nameserver(args.host)
162
163 d = server.Daemon(host=args.host, port=args.port, unixsocket=args.unixsocket)
164 echo = EchoServer()
165 echo._verbose = args.verbose
166 objectName = "test.echoserver"
167 uri = d.register(echo, objectName)
168 if args.naming:
169 host, port = None, None
170 if namesvr is not None:
171 host, port = namesvr.uri.host, namesvr.uri.port
172 ns = core.locate_ns(host, port)
173 ns.register(objectName, uri)
174 if args.verbose:
175 print("using name server at %s" % ns._pyroUri)
176 if namesvr is not None:
177 if namesvr.bc_server:
178 print("broadcast server running at %s" % namesvr.bc_server.locationStr)
179 else:
180 print("not using a broadcast server")
181 else:
182 if args.verbose:
183 print("not using a name server.")
184 if not args.quiet:
185 print("object name: %s" % objectName)
186 print("echo uri: %s" % uri)
187 print("echoserver running.")
188
189 if returnWithoutLooping:
190 return d, echo, uri # for unit testing
191 else:
192 d.requestLoop(loopCondition=lambda: not echo._must_shutdown)
193 d.close()
194
195
196 if __name__ == "__main__":
197 main()