Rationnals
----------
Web servers can serve some resources (e.g. static files) right away
without any interaction with the web application. The network model of
most web servers makes them capable of handling thousands of
simultaneous requests when it comes to intensive IO operations such as
streaming data from a file. The network model of Odoo is different: it
is capable of a lot of processing power but can only serve a handful of
requests at a time, i.e. Odoo (with some help from postgres) is
optimized for CPU operations, not IO.
Some users don't configure their web server, they use a basic
configuration that relay all requests to Odoo. The result is that many
Odoo HTTP Workers can be busy streaming static files instead of
processing other requests. This can lead to a worker starvation, i.e.
all workers are busy streaming files and cannot process new requests.
X-Sendfile
----------
In this work, we add the support for the [X-Sendfile] header family,
they are multiples http headers that can be used by the web application
to communicate with the web server in order to delegate the delivery of
files stored on the file system. Odoo still receives the request but it
does no more stream the file content from within its HTTP worker,
instead it skips the response body altogether and sets the `X-Sendfile`
special header with the path of the file on the filesystem. The web
server intercepts that special header, open the file and stream it.
Using those headers, we can use the best of both the web application and
the web server. The web application is still responsible to locate the
resource and verify the access rights, the web server is still
responsible of streaming the content.
Using X-Sendfile is opt-in via the `--x-sendfile` CLI flag. We set both
`X-Sendfile` (apache) and `X-Accel-Redirect` (nginx). If you are using
apache, make sure `mod_xsendfile` is enabled. If you are using NGINX
you have to add the following location block:
location /web/filestore { # custom path, hardcoded within Odoo
# Prevent access from the outside world, i.e. makes this
# route only accessible via X-Accel. MANDATORY!!!
internal;
# Give access to the filestore using this server's
# permissions. Odoo is in charge of verifying the access
# rights.
alias /path/to/odoo/data-dir/filestore;
}
The Odoo [deployment documentation] has been updated accordingly.
[X-Sendfile]: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/
[deployment documentation]: https://www.odoo.com/documentation/master/administration/install/deploy.html#serving-static-files-and-attachments
Changes to the API
------------------
To benefit most from X-Sendfile, all APIs related to streaming content
over HTTP has to be adapted. They are: (1) `request._serve_static`,
(2) `ir.http._serve_fallback`, (3) `/web/content` and (4) `/web/image`.
Each used it own way to deliver content: (1) `_serve_static` was using
`send_file` (flask's send_file that as been vendored with odoo 10
years ago and not maintenained since then), (2) _serve_fallback was
handcrafting a `werkzeug.wrappers.Response`, (3) /web/content-image were
using the "binary server" `ir.http.binary_content` API.
I has been decided to remove all 3 APIs and to merge the code inside of
the new `http.Stream` object and the `ir.binary` helper model.
A Stream wraps what is going to be sent to the browser, it can be a path
to a file on the locale filesystem, a blob of raw data or an URL to an
external resource. The Stream also holds various metadata that are
mainly used for caching. The preferred way to create a Stream is via one
of its three factories so that all the metadata are set. The factories
are: `from_path`, `from_attachment` and `from_binary_field`. A stream
instance exposes a single method `get_response()` used to create the
corresponding HTTP response object out of the stream.
Inside of `ir.http` were a few methods that were not related to the http
routing and formed what was called the "binary server". All those
methods have been removed and the feature have been refactored inside of
the new `ir.binary` model. The removed methods are:
- `_xmlid_to_obj`
- `_get_record_and_check`
- `_binary_ir_attachment_redirect_content`
- `_binary_record_content`
- `_binary_set_headers`
- `binary_content`
- `_response_by_status`
- `_get_content_common`
- `_content_image`
- `_content_image_get_response`
- `_placeholder_image_get_response`
The new `ir.binary` abstract model exposes the following utilities:
**`_find_record`**
Find an attachment or a record with a binary-field out of an xmlid or
out of a pair record-model/record-id. Check the access rights and the
access token.
**`_get_stream_from`**
Create a Stream from an attachment or a record with a binary-field.
**`_get_image_stream_from`**
Same as `_get_stream_from` but adapted for images. It sets a sensible
ETag on the stream and has image resizing support.
**`_placeholder`**
Get the image placeholder blob.
Testing
-------
It is possible to test the web server configuration using the
`test_http` module. Install the module then run the unittest using the
`webserver` test-tag. By default it attempts to connect to a web-server
running on `http://localhost:80`, you can change this URL by setting the
`WEB_SERVER_URL` environment variable.
odoo-bin -i test_http --stop-after-init
WEB_SERVER_URL='http://localhost:80' odoo-bin --test-tags webserver --stop-after-init
closes odoo/odoo#88134
Task: 2801675
Related: odoo/documentation#2083
Related: odoo/enterprise#26191
Signed-off-by: Julien Castiaux <juc@odoo.com>
168 lines
6.3 KiB
Python
168 lines
6.3 KiB
Python
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
|
import json
|
|
import logging
|
|
import werkzeug
|
|
from odoo import http
|
|
from odoo.exceptions import AccessError, UserError
|
|
from odoo.http import request
|
|
from odoo.tools import replace_exceptions
|
|
|
|
from odoo.addons.web.controllers.utils import ensure_db
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
|
|
CT_JSON = {'Content-Type': 'application/json; charset=utf-8'}
|
|
WSGI_SAFE_KEYS = {'PATH_INFO', 'QUERY_STRING', 'RAW_URI', 'SCRIPT_NAME', 'wsgi.url_scheme'}
|
|
|
|
|
|
class TestHttp(http.Controller):
|
|
|
|
# =====================================================
|
|
# Greeting
|
|
# =====================================================
|
|
@http.route(['/test_http/greeting', '/test_http/greeting-none'], type='http', auth='none')
|
|
def greeting_none(self):
|
|
return "Tek'ma'te"
|
|
|
|
@http.route('/test_http/greeting-public', type='http', auth='public')
|
|
def greeting_public(self):
|
|
assert request.env.user, "ORM should be initialized"
|
|
return "Tek'ma'te"
|
|
|
|
@http.route('/test_http/greeting-user', type='http', auth='user')
|
|
def greeting_user(self):
|
|
assert request.env.user, "ORM should be initialized"
|
|
return "Tek'ma'te"
|
|
|
|
@http.route('/test_http/wsgi_environ', type='http', auth='none')
|
|
def wsgi_environ(self):
|
|
environ = {
|
|
key: val for key, val in request.httprequest.environ.items()
|
|
if (key.startswith('HTTP_') # headers
|
|
or key.startswith('REMOTE_')
|
|
or key.startswith('REQUEST_')
|
|
or key.startswith('SERVER_')
|
|
or key.startswith('werkzeug.proxy_fix.')
|
|
or key in WSGI_SAFE_KEYS)
|
|
}
|
|
|
|
return request.make_response(
|
|
json.dumps(environ, indent=4),
|
|
headers=list(CT_JSON.items())
|
|
)
|
|
|
|
# =====================================================
|
|
# Echo-Reply
|
|
# =====================================================
|
|
@http.route('/test_http/echo-http-get', type='http', auth='none', methods=['GET'])
|
|
def echo_http_get(self, **kwargs):
|
|
return str(kwargs)
|
|
|
|
@http.route('/test_http/echo-http-post', type='http', auth='none', methods=['POST'], csrf=False)
|
|
def echo_http_post(self, **kwargs):
|
|
return str(kwargs)
|
|
|
|
@http.route('/test_http/echo-http-csrf', type='http', auth='none', methods=['POST'], csrf=True)
|
|
def echo_http_csrf(self, **kwargs):
|
|
return str(kwargs)
|
|
|
|
@http.route('/test_http/echo-json', type='json', auth='none', methods=['POST'], csrf=False)
|
|
def echo_json(self, **kwargs):
|
|
return kwargs
|
|
|
|
@http.route('/test_http/echo-json-context', type='json', auth='user', methods=['POST'], csrf=False)
|
|
def echo_json_context(self, **kwargs):
|
|
return request.env.context
|
|
|
|
@http.route('/test_http/echo-json-over-http', type='http', auth='none', methods=['POST'], csrf=False)
|
|
def echo_json_over_http(self):
|
|
try:
|
|
data = request.get_json_data()
|
|
except ValueError as exc:
|
|
raise werkzeug.exceptions.BadRequest("Invalid JSON data") from exc
|
|
return request.make_json_response(data)
|
|
|
|
# =====================================================
|
|
# Models
|
|
# =====================================================
|
|
@http.route('/test_http/<model("test_http.galaxy"):galaxy>', auth='public')
|
|
def galaxy(self, galaxy):
|
|
if not galaxy.exists():
|
|
raise UserError('The Ancients did not settle there.')
|
|
|
|
return http.request.render('test_http.tmpl_galaxy', {
|
|
'galaxy': galaxy,
|
|
'stargates': http.request.env['test_http.stargate'].search([
|
|
('galaxy_id', '=', galaxy.id)
|
|
]),
|
|
})
|
|
|
|
@http.route('/test_http/<model("test_http.galaxy"):galaxy>/<model("test_http.stargate"):gate>', auth='user')
|
|
def stargate(self, galaxy, gate):
|
|
if not gate.exists():
|
|
raise UserError("The goa'uld destroyed the gate")
|
|
|
|
return http.request.render('test_http.tmpl_stargate', {
|
|
'gate': gate
|
|
})
|
|
|
|
# =====================================================
|
|
# Cors
|
|
# =====================================================
|
|
@http.route('/test_http/cors_http_default', type='http', auth='none', cors='*')
|
|
def cors_http(self):
|
|
return "Hello"
|
|
|
|
@http.route('/test_http/cors_http_methods', type='http', auth='none', methods=['GET', 'PUT'], cors='*')
|
|
def cors_http_verbs(self, **kwargs):
|
|
return "Hello"
|
|
|
|
@http.route('/test_http/cors_json', type='json', auth='none', cors='*')
|
|
def cors_json(self, **kwargs):
|
|
return {}
|
|
|
|
# =====================================================
|
|
# Dual nodb/db
|
|
# =====================================================
|
|
@http.route('/test_http/ensure_db', type='http', auth='none')
|
|
def ensure_db_endpoint(self, db=None):
|
|
ensure_db()
|
|
assert request.db, "There should be a database"
|
|
return request.db
|
|
|
|
# =====================================================
|
|
# Session
|
|
# =====================================================
|
|
@http.route('/test_http/geoip', type='http', auth='none')
|
|
def geoip(self):
|
|
return str(request.geoip)
|
|
|
|
@http.route('/test_http/save_session', type='http', auth='none')
|
|
def touch(self):
|
|
request.session.touch()
|
|
return ''
|
|
|
|
# =====================================================
|
|
# Errors
|
|
# =====================================================
|
|
@http.route('/test_http/json_value_error', type='json', auth='none')
|
|
def json_value_error(self):
|
|
raise ValueError('Unknown destination')
|
|
|
|
@http.route('/test_http/hide_errors/decorator', type='http', auth='none')
|
|
@replace_exceptions(AccessError, by=werkzeug.exceptions.NotFound())
|
|
def hide_errors_decorator(self, error):
|
|
if error == 'AccessError':
|
|
raise AccessError("Wrong iris code")
|
|
if error == 'UserError':
|
|
raise UserError("Walter is AFK")
|
|
|
|
@http.route('/test_http/hide_errors/context-manager', type='http', auth='none')
|
|
def hide_errors_context_manager(self, error):
|
|
with replace_exceptions(AccessError, by=werkzeug.exceptions.NotFound()):
|
|
if error == 'AccessError':
|
|
raise AccessError("Wrong iris code")
|
|
if error == 'UserError':
|
|
raise UserError("Walter is AFK")
|