llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

LNT server crashes with 500 Internal Server Error under heavy load

Open rengolin opened this issue 11 years ago • 30 comments

Bugzilla Link 23474
Version unspecified
OS Linux
CC @cmatthew,@kbeyls,@kbeyls,@rengolin,@tobiasgrosser,@tlattner

Extended Description

Collating all emails about the subject (Kristof, Chris, Daniel)

We have been looking a little bit at the potential underlying reason for why http://llvm.org/perf/ is instable, and have found some clues. I want to share them here to give people with more experience in the frameworks used by LNT (flask, sqlalchemy, wsgi, …) a chance to check if our reasoning below seems plausible.

Daniel noticed the following backtrace in the log after http://llvm.org/perf started giving “Internal Server Error” again: 2015-05-08 22:57:05,309 ERROR: Exception on /db_default/v4/nts/287/graph [GET] [in /opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py:1423] Traceback (most recent call last): File "/opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1461, in dispatch_request return self.view_functionsrule.endpoint File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/ui/decorators.py", line 67, in wrap result = f(**args) File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/ui/views.py", line 385, in v4_run_graph ts = request.get_testsuite() File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/ui/app.py", line 76, in get_testsuite testsuites = self.get_db().testsuite File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/ui/app.py", line 55, in get_db self.db = current_app.old_config.get_database(g.db_name, echo=echo) File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/config.py", line 148, in get_database return lnt.server.db.v4db.V4DB(db_entry.path, self, echo=echo) File "/opt/venv/perf/lib/python2.7/site-packages/LNT-0.4.1dev-py2.7.egg/lnt/server/db/v4db.py", line 108, in init .filter_by(id = lnt.testing.PASS).first() File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/query.py", line 2334, in first ret = list(self[0:1]) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/query.py", line 2201, in getitem return list(res) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/query.py", line 2405, in iter return self._execute_and_instances(context) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/query.py", line 2418, in _execute_and_instances close_with_result=True) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/query.py", line 2409, in _connection_from_session **kw) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/session.py", line 846, in connection close_with_result=close_with_result) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/session.py", line 850, in _connection_for_bind return self.transaction._connection_for_bind(engine) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/orm/session.py", line 315, in _connection_for_bind conn = bind.contextual_connect() File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/engine/base.py", line 1737, in contextual_connect self.pool.connect(), File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/pool.py", line 332, in connect return _ConnectionFairy._checkout(self) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/pool.py", line 630, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/pool.py", line 433, in checkout rec = pool._do_get() File "/opt/venv/perf/lib/python2.7/site-packages/SQLAlchemy-0.9.6-py2.7.egg/sqlalchemy/pool.py", line 945, in _do_get (self.size(), self.overflow(), self._timeout)) TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30

After browsing through the sqlalchemy documentation and bits of the LNT implementation, it seems so far that the following pieces may be the key parts that cause the problem shown in the log.

The SQLAlchemy documentation seems to recommend to have a sqlalchemy session per web request. Looking at the following pieces of LNT, I got the impression that instead a session is shared between many or all requests:

From ui/app.py, it shows Request.get_db() basically caches get_database from "config":

...

class Request(flask.Request):

...

def get_db(self):

...

    if self.db is None:

        echo = bool(self.args.get('db_log') or self.form.get('db_log'))

        self.db = current_app.old_config.get_database(g.db_name, echo=echo)

...

    return self.db

in config.py, it is shown that get_database returns a V4DB object by calling a constructor:

...

def get_database(self, name, echo=False):

...

    # Instantiate the appropriate database version.

    if db_entry.db_version == '0.4':

        return lnt.server.db.v4db.V4DB(db_entry.path, self,

                                       db_entry.baseline_revision,

                                       echo)

...

This constructor is in db/v4db.py:

...

class V4DB(object):

...

def __init__(self, path, config, baseline_revision=0, echo=False):

...

    self.session = sqlalchemy.orm.sessionmaker(self.engine)()

...

    # Add several shortcut aliases.

    self.add = self.session.add

    self.commit = self.session.commit

    self.query = self.session.query

    self.rollback = self.session.rollback

...

It seems like a single session object is created in this constructor that will ultimately be shared across all Requests. It seems that instead, the request.get_db method should create a new session for each request. And close that session when the request is finalized which probably needs to be done by hooking into something Flask-specific.

The self.add and following lines in the constructor show that it probably will be non-trivial to refactor code so that there will not be a single session per v4db object.

We’re not sure if making separate sessions per Request is going to solve the http://llvm.org/perf instability problems; but that’s the best idea we’ve got so far.

It has been a long time since I looked at this, but aren't we just caching the DB on the request object, thus ensuring there is one opened DB, and hence session, per request? The V4DB is essentially just wrapping the session.

I have been dealing with issues like this a lot recently with our internal LNT. Assuming this is the same issue, I’ll share what I have figured out so far. I run LNT from gunicorn, proxied with apache. We were getting a lot of timeouts on submissions, and exhausted database connections. In our case, we are using Postgres, and LNT would easily use all 100 connections Postgres creates by default. Apache like to mask these things by timing you out early.

I traced our issue back to the submitRun being extremely slow on about 1 in 5 submissions. I get a feeling it was the submissions for particular machines possibly some of the older machines, though I could not reproduce it reliably. I found that with timeout removed, some submissions were taking 200s to process, and a few were as long as 400s. I did this by putting print statements in our production server and watching the submit requests being processed. All this time is spent generating the field changes, I did not dig in any further than that. What was happening is that as we were running more runs, we had more and more submissions taking that long, and eventually the server would start throwing errors like this, because all database connections were in use doing submissions.

My solution: I jacked our timeouts way up (1000s) and upped our database connections even further. We do now process all our submissions, and I only feel sort of dirty when I think about it.

The real solution: we have to find out what is going in in field change generation that is sucking up so much time! Submit run is interesting, it is the only place in LNT were we write into the database, and we are doing a lot of processing of the data when it comes in.

rengolin avatar May 11 '15 12:05 rengolin

Hi Kristof,

I'm still seeing a lot of timeout messages. Maybe the patch needs to be pushed by an LNT restart? I'm not sure how that works, if someone knows, please do so.

rengolin avatar Oct 01 '15 12:10 rengolin

http://llvm.org/viewvc/llvm-project?rev=248789&view=rev makes sure that database connections do get closed explicitly when they are no longer going to be used.

The ability to run the LNT unit tests on Postgres, introduced in r24878 demonstrated that the V4Pages unit test, when run on Postgres, consistently triggered the following error message:

sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30

r248789 eliminates this error message by closing database connections at the end of their intended life; which for webui pages, is the end of the web request.

My non-perfect understanding is that the above error message on a web server should now only occur when there are many many concurrent web requests going on. Maybe this doesn't make a difference at all on an actual web server - depending on what the web server-specific middleware does with database connections. Anyway, closing the database connections was necessary when running the unit tests on Postgres - and it may or may not ameliorate the situation on production web servers.

kbeyls avatar Oct 01 '15 10:10 kbeyls

As an aside and just to complicate things, in r237188 I added the ability for you to apply more than one --submit flag. This allows results to be sent to more than one server, so now you don't have to choose. If one server fails, it still submits to the others, and LNT dies if all submissions fail.

I am going to allow the green dragon perf bots to submit to llvm.org/perf, and everyone is welcome to submit to http://llvm-lnt.herokuapp.com/db_default/submitRun.

cmatthew avatar May 12 '15 23:05 cmatthew

I recommend against increasing the timeout or number of concurrent connections. This will only increase the problem, with each process hanging the rest of the machine for minutes, hours.

There are two problems:

  1. Slow queries. We need to run explain / analyse on each one of them. Do we have a log of the queries, or just of the LNT errors? MySQL has a "slow queries" log, which helps a lot in identifying these issues. Postgres seems to have a similar utility:

http://www.heatware.net/databases/how-to-find-log-slow-queries-postgresql/

Once we have that log, let it roll, and then pick up the slow queries and run them with explain. Should give us the reasons why they're slow and we will be able to fix.

  1. Too many connections. I believe that this is just a reflection of the queries being slow. 15 concurrent connections is quite a lot. For normal webpages, this is like hundreds of concurrent users. With LNT, may be 1-to-1, so 15 concurrent users, which we don't have. We have two. Maybe three.

Bots take at least 30 minutes to round up to submit again, so we'd have to have many more bots than we have now to have a timeout problem.

I vote for logging the slow queries first.

rengolin avatar May 12 '15 23:05 rengolin

In the case of gunicorn, the connections are setup after the fork. I don’t know how mod_wsgi does it, I assume the same.

cmatthew avatar May 12 '15 23:05 cmatthew

There is also the following documentation on http://docs.sqlalchemy.org/en/latest/core/pooling.html#using-connection-pools-with-multiprocessing

"It’s critical that when using a connection pool, and by extension when using an Engine created via create_engine(), that the pooled connections are not shared to a forked process."

Not sure if this applies.

tobiasgrosser avatar May 12 '15 22:05 tobiasgrosser

Daniel has kindly provided us with with mod_wsgi config:

WSGI configuration for LLVM nightly test.

# The application entry point. WSGIScriptAlias /perf "/opt/perf/lnt.wsgi"
# Run in daemon mode.
WSGIDaemonProcess llvm.org processes=2 threads=15 maximum-requests=10000
WSGIProcessGroup llvm.org

cmatthew avatar May 12 '15 22:05 cmatthew

Also, I benchmarked our server yesterday. We do have some long requests. Submissions take 10s-15s. If there are enough happening all at once it could lock out the threads.

cmatthew avatar May 12 '15 22:05 cmatthew

We did have an issue a while back where there was a deadlock in the submission code, I wonder if we are slowly deadlocking threads with close submissions.

I assume that llvm.org/perf is run with mod_wsgi, not the builtin web server. In that case it will be dependent on how the server is configured:

https://code.google.com/p/modwsgi/wiki/ProcessesAndThreading

cmatthew avatar May 12 '15 22:05 cmatthew

See http://docs.sqlalchemy.org/en/latest/core/pooling.html for background info.

The bottom line of why I was able to reproduce the error is that the for loops with the wget command line in the comments above create 200 concurrent web requests.

The default connection Pool implementation in sqlalchemy will use at most 15 different connections (so maximum 15 different web requests being processed). The default timeout a request waits when there are no more than connections available in the pool is 30 seconds. So, as long as not all 200 concurrent requests are completed in 30 seconds, some of them will timeout with error message: TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out

I'm wondering how come we sometimes have more than 15 concurrent requests on llvm.org/perf? At the moment, not that many users submit runs - which is the one long-ish running request type?

BTW, invoking create_engine to allow unlimited number of connections to the database to be created also doesn't work, as then you can easily run into the maximum number of database connections the postgres server allows: V4DB._engine[path] = sqlalchemy.create_engine(path, echo=echo, max_overflow=-1) lets me trigger the following error: OperationalError: (psycopg2.OperationalError) FATAL: remaining connection slots are reserved for non-replication superuser connections

So, I guess the best setting for number of concurrent database connections depends on how many concurrent connections the underlying postgres server can handle? Furthermore, it seems a mechanism should be used to not start more than that number of concurrent web requests? It seems with the builtin "lnt runserver --threaded" command, the number of concurrent Request objects that are created is not limited in any way. Would limiting that on llvm.org/perf be a solution?

kbeyls avatar May 12 '15 22:05 kbeyls

With a freshly created postgres database, with 1 json file for a LNT test-suite run, I couldn't reproduce the error with the wget line in the comments above. However by requesting a web page which presumably takes a little bit more time to construct, I could reproduce the error:

for j in 1 2 3 4 5 6 7 8 9 10; do for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do echo $i; wget -q -O /dev/null http:///db_default/v4/nts/global_status & done; done

This was run on a database created by running the following 3 commands first: lnt create --db-dir=postgresql://lnt:[email protected]/ --default-db=lnt4 --show-sql ./lnt_server_dirs4/ lnt import --commit=1 ./lnt_server_dirs4/ 28.json lnt runserver --threaded --show-db-pool --hostname=127.0.0.1 ./lnt_server_dirs4/

kbeyls avatar May 12 '15 17:05 kbeyls

Pretty consistent, ~6 errors / hour until 3 hours ago. Since then, nothing.

Interesting.

Did you add the close and restarted?

The LNT server is restarted/reloaded on each commit to LNT. Kristof's patch was not yet committed.

I only asked for a buildbot restart to stop my buildslaves to submit to llvm.org/perf.

Here's an example:

2015-05-12 06:30:16,721 ERROR: Exception on /db_default/v4/nts/20207 [GET] [in /opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app. py:1423] TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30

I did not cross-check the exact timing, but there have indeed be submissions that came in sufficiently close to probably be processed at the same time:

236969 2015-05-11 05:57:58 5:18:27 x86_64-penryn-O3-polly-detect-and-dependences-only__clang_DEV__x86_64:38 View Results 236969 2015-05-11 05:57:57 5:18:18 x86_64-penryn-O3-polly-detect-only__clang_DEV__x86_64:37 View Results

@​Kristof: I have the feeling you are on the right track and it great we can reproduce this outside of our production environment.

tobiasgrosser avatar May 12 '15 16:05 tobiasgrosser

$ for j in 1 2 3 4 5 6 7 8 9 10; do for i in 1 2 3 4 5 6 7 8 9; do echo $i; wget http://127.0.0.1:8000/db_default/v4/nts/machine/1 & done; done

Try 'ab' for that...

http://httpd.apache.org/docs/2.2/programs/ab.html

It's really good. :)

cheers, --renato

rengolin avatar May 12 '15 16:05 rengolin

I finally managed to reproduce the issue on a local setup using a postgres database as the backend. I haven't tried reproducing this with a sqlite backend.

One of the keys to reproduce this is to run the server multi-threaded, so multiple requests can be processed concurrently:

lnt runserver --threaded ./lnt_server_dirs/

Then doing concurrent web requests from the running server quickly results in the error message to be produced, and the server to start returning error 500:

$ for j in 1 2 3 4 5 6 7 8 9 10; do for i in 1 2 3 4 5 6 7 8 9; do echo $i; wget http://127.0.0.1:8000/db_default/v4/nts/machine/1 & done; done

This was on an instance with about 10K runs submitted, all from a single machine.

After running the above command line once or twice, I started seeing the TimeoutError. Even when the del statement to close the session (see my last comment above) has been inserted :(

kbeyls avatar May 12 '15 16:05 kbeyls

Pretty consistent, ~6 errors / hour until 3 hours ago. Since then, nothing.

Did you add the close and restarted?

Here's an example:

2015-05-12 06:30:16,721 ERROR: Exception on /db_default/v4/nts/20207 [GET] [in /opt/venv/perf/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py:1423] TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30

rengolin avatar May 12 '15 16:05 rengolin

"Why is the server running out of DB connections?" -> I don't know.

I couldn't reproduce the "TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30" error on my local setup.

However, I've instrumented sqlalchemy with a few print-debug statements to see if sqlalchemy sessions did get closed or not when using the LNT website. It's clear that the sessions are not closed. Therefore, my best guess at the moment is that there may be a not-often used code path that gets triggered when using some webviews that results in the sessions to retain a connection from the connection pool. It does seem that on the few webpages I've tried, the connection used by a session got returned to the pool, even if the session wasn't closed. ...or maybe this happens when a request times out...

Adding the following code does result in sessions being closed when a web request is completed. I'm not all sure however if doing this in a del method is the right way to do it.

It does not seem like a big hack and probably also won't hurt. I would almost propose to just commit it and see if it helps.

I also moved on Monday morning my own LNT testers to a private server and llvm.org/perf is now back online (correlated?). I want to note that I have been running these servers for a very long time (and report a run every 5 commits). At the beginning llvm.org/perf was reasonable stable and only over time it seemed to get slower. Maybe the problematic behaviour only shows up on really large databases?

Renato any news from the error log? Have there been any errors since the builbot restart last night (and my LNT buildslaves being moved away).

Interesting to see is that even though llvm.org/perf was offline for a long time, it seems we have many/all? of the performance results in the db.

tobiasgrosser avatar May 12 '15 16:05 tobiasgrosser

"Why is the server running out of DB connections?" -> I don't know.

I couldn't reproduce the "TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30" error on my local setup.

However, I've instrumented sqlalchemy with a few print-debug statements to see if sqlalchemy sessions did get closed or not when using the LNT website. It's clear that the sessions are not closed. Therefore, my best guess at the moment is that there may be a not-often used code path that gets triggered when using some webviews that results in the sessions to retain a connection from the connection pool. It does seem that on the few webpages I've tried, the connection used by a session got returned to the pool, even if the session wasn't closed. ...or maybe this happens when a request times out...

Adding the following code does result in sessions being closed when a web request is completed. I'm not all sure however if doing this in a del method is the right way to do it.

diff --git a/lnt/server/db/v4db.py b/lnt/server/db/v4db.py index 9e61b49..b4796c9 100644 --- a/lnt/server/db/v4db.py +++ b/lnt/server/db/v4db.py @@ -151,6 +151,10 @@ class V4DB(object): return sum([ts.query(ts.Test).count() for ts in self.testsuite.values()])

  • def close(self):

  •    if self.session is not None:
    
  •        self.session.close()
    
  • def importDataFromDict(self, data, config=None): # Select the database to import into. # diff --git a/lnt/server/ui/app.py b/lnt/server/ui/app.py index 1660100..e86886d 100644 @@ -81,6 +83,11 @@ class Request(flask.Request):

       return self.testsuite
    
  • def del(self):

  •    print "Request.__del__ called()"
    
  •    if self.db is not None:
    
  •        self.db.close()
    

class App(flask.Flask): @​staticmethod def create_with_instance(instance):

kbeyls avatar May 12 '15 15:05 kbeyls

Ah, Kristof mentioned that he was submitting the same json over and over again, so it would have the same rev every time. So the slowdown is expected in that case. LNT will use all the data at the current in the field change calculation.

Now that I think of it, we had a bug in the rev naming which was causing all of our runs to get the same rev, and that is when our LNT server was hanging.

I have added a warning to the code in r237057 since I think this is almost always an error.

So, back to the original exception... why is the public server running out of db connections.

cmatthew avatar May 11 '15 23:05 cmatthew

I think that should be all the runs with the same rev as the run just submitted. That should not be that many. In most cases under 10 i'd guess. It would depend on how many machines are submitting at that rev.

cmatthew avatar May 11 '15 22:05 cmatthew

And what should be "runs on current rev"?

From Kristof's dump, it's about 1000 entries!

rengolin avatar May 11 '15 22:05 rengolin