| 1 |
""" |
| 2 |
HTTP gateway: connects the web browser's world of javascript+http and Pyro. |
| 3 |
Creates a stateless HTTP server that essentially is a proxy for the Pyro objects behind it. |
| 4 |
It exposes the Pyro objects through a HTTP interface and uses the JSON serializer, |
| 5 |
so that you can immediately process the response data in the browser. |
| 6 |
|
| 7 |
You can start this module as a script from the command line, to easily get a |
| 8 |
http gateway server running: |
| 9 |
|
| 10 |
:command:`python -m Pyro5.utils.httpgateway` |
| 11 |
or simply: :command:`pyro5-httpgateway` |
| 12 |
|
| 13 |
It is also possible to import the 'pyro_app' function and stick that into a WSGI |
| 14 |
server of your choice, to have more control. |
| 15 |
|
| 16 |
The javascript code in the web page of the gateway server works with the same-origin |
| 17 |
browser policy because it is served by the gateway itself. If you want to access it |
| 18 |
from scripts in different sites, you have to work around this or embed the gateway app |
| 19 |
in your site. Non-browser clients that access the http api have no problems. |
| 20 |
See the `http` example for two of such clients (node.js and python). |
| 21 |
|
| 22 |
Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]). |
| 23 |
""" |
| 24 |
|
| 25 |
import sys |
| 26 |
import re |
| 27 |
import urllib.parse |
| 28 |
import uuid |
| 29 |
import json |
| 30 |
from wsgiref.simple_server import make_server |
| 31 |
from argparse import ArgumentParser |
| 32 |
import traceback |
| 33 |
from .. import __version__, config, errors, client, core, protocol, serializers, callcontext |
| 34 |
|
| 35 |
__all__ = ["pyro_app", "main"] |
| 36 |
_nameserver = None |
| 37 |
|
| 38 |
|
| 39 |
def get_nameserver(): |
| 40 |
global _nameserver |
| 41 |
if not _nameserver: |
| 42 |
_nameserver = core.locate_ns() |
| 43 |
try: |
| 44 |
_nameserver.ping() |
| 45 |
return _nameserver |
| 46 |
except errors.ConnectionClosedError: |
| 47 |
_nameserver = None |
| 48 |
print("Connection with nameserver lost, reconnecting...") |
| 49 |
return get_nameserver() |
| 50 |
|
| 51 |
|
| 52 |
def cors_response_header(header, cors): |
| 53 |
header.append(('Access-Control-Allow-Origin', cors)) |
| 54 |
header.append(('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')) |
| 55 |
header.append(('Access-Control-Allow-Headers', 'Content-Type')) |
| 56 |
return header |
| 57 |
|
| 58 |
def invalid_request(start_response): |
| 59 |
"""Called if invalid http method.""" |
| 60 |
start_response('405 Method Not Allowed', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 61 |
return [b'Error 405: Method Not Allowed'] |
| 62 |
|
| 63 |
def option_request(start_response): |
| 64 |
"""OPTION Call with CORS""" |
| 65 |
start_response('200 OK', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 66 |
return [b'200 OK'] |
| 67 |
|
| 68 |
def not_found(start_response): |
| 69 |
"""Called if Url not found.""" |
| 70 |
start_response('404 Not Found', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 71 |
return [b'Error 404: Not Found'] |
| 72 |
|
| 73 |
|
| 74 |
def redirect(start_response, target): |
| 75 |
"""Called to do a redirect""" |
| 76 |
start_response('302 Found', [('Location', target)]) |
| 77 |
return [] |
| 78 |
|
| 79 |
|
| 80 |
index_page_template = """<!DOCTYPE html> |
| 81 |
<html> |
| 82 |
<head> |
| 83 |
<title>Pyro HTTP gateway</title> |
| 84 |
<style type="text/css"> |
| 85 |
html {{ color: #202020; background-color: white; }} |
| 86 |
body {{ margin: 1em; }} |
| 87 |
table, th, td {{border: 1px solid #bbf; padding: 4px;}} |
| 88 |
table {{border-collapse: collapse;}} |
| 89 |
pre {{border: 1px solid #bbf; padding: 1ex; margin: 1ex; white-space: pre-wrap;}} |
| 90 |
#title-logo {{ float: left; margin: 0 1em 0 0; }} |
| 91 |
</style> |
| 92 |
</head> |
| 93 |
<body> |
| 94 |
<script> |
| 95 |
"use strict"; |
| 96 |
async function pyro_call(name, method, params) {{ |
| 97 |
// http header examples: |
| 98 |
// "X-Pyro-Correlation-Id": "11112222-1111-2222-3333-222244449999" |
| 99 |
// "X-Pyro-Gateway-Key": "secret-key" |
| 100 |
// "X-Pyro-Options": "oneway" |
| 101 |
let api_url = name+"/"+method |
| 102 |
if(params) api_url += "?"+(new URLSearchParams(params).toString()) |
| 103 |
document.getElementById("pyro_call").innerText = "GET "+api_url; |
| 104 |
await fetch(api_url, {{ |
| 105 |
method: 'GET', |
| 106 |
headers: {{ |
| 107 |
'Accept': 'application/json', |
| 108 |
'Content-Type': 'application/json' |
| 109 |
}} |
| 110 |
}} ) |
| 111 |
.then(async res => {{ |
| 112 |
if(res.status>=400) {{ |
| 113 |
const err = "SERVER ERROR "+res.status+"\\n"+(await res.text()) |
| 114 |
document.getElementById("pyro_response").innerText = err |
| 115 |
throw err |
| 116 |
}} else {{ |
| 117 |
return res.json() |
| 118 |
}} |
| 119 |
}}) |
| 120 |
.then(json_result => document.getElementById("pyro_response").innerText = JSON.stringify(json_result, null, 4)) |
| 121 |
}} |
| 122 |
</script> |
| 123 |
<div id="title-logo"><img src="http://pyro5.readthedocs.io/en/stable/_static/pyro.png"></div> |
| 124 |
<div id="title-text"> |
| 125 |
<h1>Pyro HTTP gateway</h1> |
| 126 |
<p> |
| 127 |
Use http+json to talk to Pyro objects. |
| 128 |
<a href="http://pyro5.readthedocs.io/en/stable/tipstricks.html#pyro-via-http-and-json">Docs.</a> |
| 129 |
</p> |
| 130 |
</div> |
| 131 |
<p><em>Note: performance isn't maxed; it is stateless. Does a name lookup and uses a new Pyro proxy for each request.</em></p> |
| 132 |
<h2>Currently exposed contents of name server on {hostname}:</h2> |
| 133 |
<p>(Limited to 10 entries, exposed name pattern = '{ns_regex}')</p> |
| 134 |
{name_server_contents_list} |
| 135 |
<p>Name server examples: (these examples are working if you expose the Pyro.NameServer object)</p> |
| 136 |
<ul> |
| 137 |
<li><a href="javascript:void();" onclick="pyro_call('Pyro.NameServer','$meta'); return false;">Pyro.NameServer/$meta</a> |
| 138 |
-- gives meta info of the name server (methods)</li> |
| 139 |
<li><a href="javascript:void();" onclick="pyro_call('Pyro.NameServer','list'); return false;">Pyro.NameServer/list</a> |
| 140 |
-- lists the contents of the name server</li> |
| 141 |
<li><a href="javascript:void();" |
| 142 |
onclick="pyro_call('Pyro.NameServer','list', {{'prefix':'test.'}}); return false;"> |
| 143 |
Pyro.NameServer/list?prefix=test.</a> -- lists the contents of the name server starting with 'test.'</li> |
| 144 |
<li><a href="javascript:void();" |
| 145 |
onclick="pyro_call('Pyro.NameServer','lookup', {{'name':'Pyro.NameServer'}}); return false;"> |
| 146 |
Pyro.NameServer/lookup?name=Pyro.NameServer</a> -- perform lookup method of the name server</li> |
| 147 |
<li><a href="javascript:void();" |
| 148 |
onclick="pyro_call('Pyro.NameServer','lookup', {{'name':'test.echoserver'}}); return false;"> |
| 149 |
Pyro.NameServer/lookup?name=test.echoserver</a> -- perform lookup method of the echo server</li> |
| 150 |
</ul> |
| 151 |
<p>Echoserver examples: (these examples are working if you expose the test.echoserver object)</p> |
| 152 |
<ul> |
| 153 |
<li><a href="javascript:void();" onclick="pyro_call('test.echoserver','error'); return false;">test.echoserver/error</a> |
| 154 |
-- perform error call on echoserver</li> |
| 155 |
<li><a href="javascript:void();" |
| 156 |
onclick="pyro_call('test.echoserver','echo', {{'message':'Hi there, browser script!'}}); return false;"> |
| 157 |
test.echoserver/echo?message=Hi there, browser script!</a> -- perform echo call on echoserver</li> |
| 158 |
</ul> |
| 159 |
<h2>Pyro response data (via Ajax):</h2> |
| 160 |
Call: <pre id="pyro_call"> </pre> |
| 161 |
Response: <pre id="pyro_response"> </pre> |
| 162 |
<p>Pyro version: {pyro_version} — © Irmen de Jong</p> |
| 163 |
</body> |
| 164 |
</html> |
| 165 |
""" |
| 166 |
|
| 167 |
|
| 168 |
def return_homepage(environ, start_response): |
| 169 |
try: |
| 170 |
nameserver = get_nameserver() |
| 171 |
except errors.NamingError as x: |
| 172 |
print("Name server error:", x) |
| 173 |
start_response('500 Internal Server Error', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 174 |
return [b"Cannot connect to the Pyro name server. Is it running? Refresh page to retry."] |
| 175 |
start_response('200 OK', cors_response_header([('Content-Type', 'text/html')], pyro_app.cors)) |
| 176 |
|
| 177 |
nslist = ["<table><tr><th>Name</th><th>methods</th><th>attributes (zero-param methods)</th></tr>"] |
| 178 |
names = sorted(list(nameserver.list(regex=pyro_app.ns_regex).keys())[:10]) |
| 179 |
with client.BatchProxy(nameserver) as nsbatch: |
| 180 |
for name in names: |
| 181 |
nsbatch.lookup(name) |
| 182 |
for name, uri in zip(names, nsbatch()): |
| 183 |
attributes = "-" |
| 184 |
try: |
| 185 |
with client.Proxy(uri) as proxy: |
| 186 |
proxy._pyroBind() |
| 187 |
methods = " ".join(proxy._pyroMethods) or "-" |
| 188 |
attributes = [ |
| 189 |
"<a href=\"javascript:void();\" onclick=\"pyro_call('{name}','{attribute}'); return false;\">{attribute}</a>" |
| 190 |
.format(name=name, attribute=attribute) |
| 191 |
for attribute in proxy._pyroAttrs |
| 192 |
] |
| 193 |
attributes = " ".join(attributes) or "-" |
| 194 |
except errors.PyroError as x: |
| 195 |
stderr = environ["wsgi.errors"] |
| 196 |
print("ERROR getting metadata for {0}:".format(uri), file=stderr) |
| 197 |
traceback.print_exc(file=stderr) |
| 198 |
methods = "??error:%s??" % str(x) |
| 199 |
nslist.append( |
| 200 |
"<tr><td><a href=\"javascript:void();\" onclick=\"pyro_call('{name}','$meta'); " |
| 201 |
"return false;\">{name}</a></td><td>{methods}</td><td>{attributes}</td></tr>" |
| 202 |
.format(name=name, methods=methods, attributes=attributes)) |
| 203 |
nslist.append("</table>") |
| 204 |
index_page = index_page_template.format(ns_regex=pyro_app.ns_regex, |
| 205 |
name_server_contents_list="".join(nslist), |
| 206 |
pyro_version=__version__, |
| 207 |
hostname=nameserver._pyroUri.location) |
| 208 |
return [index_page.encode("utf-8")] |
| 209 |
|
| 210 |
|
| 211 |
def process_pyro_request(environ, path, parameters, start_response): |
| 212 |
|
| 213 |
pyro_options = environ.get("HTTP_X_PYRO_OPTIONS", "").split(",") |
| 214 |
if not path: |
| 215 |
return return_homepage(environ, start_response) |
| 216 |
matches = re.match(r"(.+)/(.+)", path) |
| 217 |
if not matches: |
| 218 |
return not_found(start_response) |
| 219 |
object_name, method = matches.groups() |
| 220 |
if pyro_app.gateway_key: |
| 221 |
gateway_key = environ.get("HTTP_X_PYRO_GATEWAY_KEY", "") or parameters.get("$key", "") |
| 222 |
gateway_key = gateway_key.encode("utf-8") |
| 223 |
if gateway_key != pyro_app.gateway_key: |
| 224 |
start_response('403 Forbidden', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 225 |
return [b"403 Forbidden - incorrect gateway api key"] |
| 226 |
if "$key" in parameters: |
| 227 |
del parameters["$key"] |
| 228 |
if pyro_app.ns_regex and not re.match(pyro_app.ns_regex, object_name): |
| 229 |
start_response('403 Forbidden', cors_response_header([('Content-Type', 'text/plain')], pyro_app.cors)) |
| 230 |
return [b"403 Forbidden - access to the requested object has been denied"] |
| 231 |
try: |
| 232 |
nameserver = get_nameserver() |
| 233 |
uri = nameserver.lookup(object_name) |
| 234 |
with client.Proxy(uri) as proxy: |
| 235 |
header_corr_id = environ.get("HTTP_X_PYRO_CORRELATION_ID", "") |
| 236 |
if header_corr_id: |
| 237 |
callcontext.current_context.correlation_id = uuid.UUID(header_corr_id) # use the correlation id from the request header |
| 238 |
else: |
| 239 |
callcontext.current_context.correlation_id = uuid.uuid4() # set new correlation id |
| 240 |
proxy._pyroGetMetadata() |
| 241 |
if "oneway" in pyro_options: |
| 242 |
proxy._pyroOneway.add(method) |
| 243 |
if method == "$meta": |
| 244 |
result = {"methods": tuple(proxy._pyroMethods), "attributes": tuple(proxy._pyroAttrs)} |
| 245 |
reply = json.dumps(result).encode("utf-8") |
| 246 |
start_response('200 OK', cors_response_header([ |
| 247 |
('Content-Type', 'application/json; charset=utf-8'), |
| 248 |
('X-Pyro-Correlation-Id', str(callcontext.current_context.correlation_id)) |
| 249 |
], pyro_app.cors)) |
| 250 |
return [reply] |
| 251 |
else: |
| 252 |
proxy._pyroRawWireResponse = True # we want to access the raw response json |
| 253 |
if method in proxy._pyroAttrs: |
| 254 |
# retrieve the attribute |
| 255 |
assert not parameters, "attribute lookup can't have query parameters" |
| 256 |
msg = getattr(proxy, method) |
| 257 |
else: |
| 258 |
# call the remote method |
| 259 |
msg = getattr(proxy, method)(**parameters) |
| 260 |
|
| 261 |
if msg is None or "oneway" in pyro_options: |
| 262 |
# was a oneway call, no response available |
| 263 |
start_response('200 OK', cors_response_header([ |
| 264 |
('Content-Type', 'application/json; charset=utf-8'), |
| 265 |
('X-Pyro-Correlation-Id', str(callcontext.current_context.correlation_id)) |
| 266 |
], pyro_app.cors)) |
| 267 |
return [] |
| 268 |
elif msg.flags & protocol.FLAGS_EXCEPTION: |
| 269 |
# got an exception response so send a 500 status |
| 270 |
start_response('500 Internal Server Error', cors_response_header([ |
| 271 |
('Content-Type', 'application/json; charset=utf-8') |
| 272 |
], pyro_app.cors)) |
| 273 |
return [msg.data] |
| 274 |
else: |
| 275 |
# normal response |
| 276 |
start_response('200 OK', cors_response_header([ |
| 277 |
('Content-Type', 'application/json; charset=utf-8'), |
| 278 |
('X-Pyro-Correlation-Id', str(callcontext.current_context.correlation_id)) |
| 279 |
], pyro_app.cors)) |
| 280 |
return [msg.data] |
| 281 |
except Exception as x: |
| 282 |
stderr = environ["wsgi.errors"] |
| 283 |
print("ERROR handling {0} with params {1}:".format(path, parameters), file=stderr) |
| 284 |
traceback.print_exc(file=stderr) |
| 285 |
start_response('500 Internal Server Error', cors_response_header([('Content-Type', 'application/json; charset=utf-8')], pyro_app.cors)) |
| 286 |
reply = json.dumps(serializers.SerializerBase.class_to_dict(x)).encode("utf-8") |
| 287 |
return [reply] |
| 288 |
|
| 289 |
|
| 290 |
def pyro_app(environ, start_response): |
| 291 |
""" |
| 292 |
The WSGI app function that is used to process the requests. |
| 293 |
You can stick this into a wsgi server of your choice, or use the main() method |
| 294 |
to use the default wsgiref server. |
| 295 |
""" |
| 296 |
|
| 297 |
config.SERIALIZER = "json" # we only talk json through the http proxy |
| 298 |
config.COMMTIMEOUT = pyro_app.comm_timeout |
| 299 |
method = environ.get("REQUEST_METHOD") |
| 300 |
path = environ.get('PATH_INFO', '').lstrip('/') |
| 301 |
|
| 302 |
if not path: |
| 303 |
return redirect(start_response, "/pyro/") |
| 304 |
|
| 305 |
if path.startswith("pyro/"): |
| 306 |
if method in ("GET", "POST", "OPTIONS"): |
| 307 |
if method in ("OPTIONS"): |
| 308 |
return option_request(start_response) |
| 309 |
else: |
| 310 |
"""GET POST""" |
| 311 |
parameters = singlyfy_parameters(urllib.parse.parse_qs(environ["QUERY_STRING"])) |
| 312 |
return process_pyro_request(environ, path[5:], parameters, start_response) |
| 313 |
else: |
| 314 |
return invalid_request(start_response) |
| 315 |
|
| 316 |
return not_found(start_response) |
| 317 |
|
| 318 |
|
| 319 |
def singlyfy_parameters(parameters): |
| 320 |
""" |
| 321 |
Makes a parsed querystring parameter dictionary into a dict where the values that |
| 322 |
are just a list of a single value, are converted to just that single value. |
| 323 |
""" |
| 324 |
for key, value in parameters.items(): |
| 325 |
if isinstance(value, (list, tuple)) and len(value) == 1: |
| 326 |
parameters[key] = value[0] |
| 327 |
return parameters |
| 328 |
|
| 329 |
|
| 330 |
pyro_app.ns_regex = r"http\." |
| 331 |
pyro_app.cors = "" |
| 332 |
pyro_app.gateway_key = None |
| 333 |
pyro_app.comm_timeout = config.COMMTIMEOUT |
| 334 |
|
| 335 |
|
| 336 |
def main(args=None): |
| 337 |
parser = ArgumentParser(description="Pyro http gateway command line launcher.") |
| 338 |
parser.add_argument("-H", "--host", default="localhost", help="hostname to bind server on (default=%(default)s)") |
| 339 |
parser.add_argument("-c", "--cors", default="*", help="Allow cross origin domain/url") |
| 340 |
parser.add_argument("-p", "--port", type=int, default=8080, help="port to bind server on (default=%(default)d)") |
| 341 |
parser.add_argument("-e", "--expose", default=pyro_app.ns_regex, help="a regex of object names to expose (default=%(default)s)") |
| 342 |
parser.add_argument("-g", "--gatewaykey", help="the api key to use to connect to the gateway itself") |
| 343 |
parser.add_argument("-t", "--timeout", type=float, default=pyro_app.comm_timeout, |
| 344 |
help="Pyro timeout value to use (COMMTIMEOUT setting, default=%(default)f)") |
| 345 |
|
| 346 |
options = parser.parse_args(args) |
| 347 |
pyro_app.gateway_key = (options.gatewaykey or "").encode("utf-8") |
| 348 |
pyro_app.ns_regex = options.expose |
| 349 |
pyro_app.cors = options.cors |
| 350 |
pyro_app.comm_timeout = config.COMMTIMEOUT = options.timeout |
| 351 |
|
| 352 |
if pyro_app.ns_regex: |
| 353 |
print("Exposing objects with names matching: ", pyro_app.ns_regex) |
| 354 |
else: |
| 355 |
print("Warning: exposing all objects (no expose regex set)") |
| 356 |
try: |
| 357 |
ns = get_nameserver() |
| 358 |
except errors.PyroError: |
| 359 |
print("Not yet connected to a name server.") |
| 360 |
else: |
| 361 |
print("Connected to name server at: ", ns._pyroUri) |
| 362 |
|
| 363 |
server = make_server(options.host, options.port, pyro_app) |
| 364 |
print("Pyro HTTP gateway running on http://{0}:{1}/pyro/".format(*server.socket.getsockname())) |
| 365 |
server.serve_forever() |
| 366 |
server.server_close() |
| 367 |
return 0 |
| 368 |
|
| 369 |
|
| 370 |
if __name__ == "__main__": |
| 371 |
sys.exit(main()) |