Skip to content

Commit

Permalink
Merge bitcoin#14670: http: Fix HTTP server shutdown
Browse files Browse the repository at this point in the history
28479f9 qa: Test bitcond shutdown (João Barbosa)
8d3f46e http: Remove timeout to exit event loop (João Barbosa)
e98a9ee http: Remove unnecessary event_base_loopexit call (João Barbosa)
6b13580 http: Unlisten sockets after all workers quit (João Barbosa)
18e9685 http: Send "Connection: close" header if shutdown is requested (João Barbosa)
02e1e4e rpc: Add wait argument to stop (João Barbosa)

Pull request description:

  Fixes bitcoin#11777. Reverts bitcoin#11006. Replaces bitcoin#13501.

  With this change the HTTP server will exit gracefully, meaning that all requests will finish processing and sending the response, even if this means to wait more than 2 seconds (current time allowed to exit the event loop).

  Another small change is that connections are accepted even when the server is stopping, but HTTP requests are rejected. This can be improved later, especially if chunked replies are implemented.

  Briefly, before this PR, this is the order or events when a request arrives (RPC `stop`):
   1. `bufferevent_disable(..., EV_READ)`
   2. `StartShutdown()`
   3. `evhttp_del_accept_socket(...)`
   4. `ThreadHTTP` terminates (event loop exits) because there are no active or pending events thanks to 1. and 3.
   5. client doesn't get the response thanks to 4.

  This can be verified by applying
  ```diff
       // Event loop will exit after current HTTP requests have been handled, so
       // this reply will get back to the client.
       StartShutdown();
  +    MilliSleep(2000);
       return "Bitcoin server stopping";
   }
  ```
  and checking the log output:
  ```
      Received a POST request for / from 127.0.0.1:62443
      ThreadRPCServer method=stop user=__cookie__
      Interrupting HTTP server
  **  Exited http event loop
      Interrupting HTTP RPC server
      Interrupting RPC
      tor: Thread interrupt
      Shutdown: In progress...
      torcontrol thread exit
      Stopping HTTP RPC server
      addcon thread exit
      opencon thread exit
      Unregistering HTTP handler for / (exactmatch 1)
      Unregistering HTTP handler for /wallet/ (exactmatch 0)
      Stopping RPC
      RPC stopped.
      Stopping HTTP server
      Waiting for HTTP worker threads to exit
      msghand thread exit
      net thread exit

      ... sleep 2 seconds ...

      Waiting for HTTP event thread to exit
      Stopped HTTP server
  ```

  For this reason point 3. is moved right after all HTTP workers quit. In that moment HTTP replies are queued in the event loop which keeps spinning util all connections are closed. In order to trigger the server side close with keep alive connections (implicit in HTTP/1.1) the header `Connection: close` is sent if shutdown was requested. This can be tested by
  ```
  bitcoind -regtest
  nc localhost 18443
  POST / HTTP/1.1
  Authorization: Basic ...
  Content-Type: application/json
  Content-Length: 44

  {"jsonrpc": "2.0","method":"stop","id":123}
  ```

  Summing up, this PR:
   - removes explicit event loop exit — event loop exits once there are no active or pending events
   - changes the moment the listening sockets are removed — explained above
   - sends header `Connection: close` on active requests when shutdown was requested which is relevant when it's a persistent connection (default in HTTP 1.1) — libevent is aware of this header and closes the connection gracefully
   - removes event loop explicit break after 2 seconds timeout

Tree-SHA512: 4dac1e86abe388697c1e2dedbf31fb36a394cfafe5e64eadbf6ed01d829542785a8c3b91d1ab680d3f03f912d14fc87176428041141441d25dcb6c98a1e069d8
  • Loading branch information
laanwj authored and HariQuick committed Jun 23, 2021
1 parent 2d500ee commit 7df7b4f
Show file tree
Hide file tree
Showing 6 changed files with 7 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/httpserver.cpp
Expand Up @@ -11,6 +11,7 @@
#include <utilstrencodings.h>
#include <netbase.h>
#include <rpc/protocol.h> // For HTTP status codes
#include <shutdown.h>
#include <sync.h>
#include <ui_interface.h>

Expand Down
2 changes: 2 additions & 0 deletions src/rpc/client.cpp
Expand Up @@ -191,6 +191,8 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "echojson", 9, "arg9" },
{ "rescanblockchain", 0, "start_height"},
{ "rescanblockchain", 1, "stop_height"},
{ "createwallet", 1, "disable_private_keys"},
{ "getnodeaddresses", 0, "count"},
{ "stop", 0, "wait" },
};

Expand Down
2 changes: 1 addition & 1 deletion src/rpc/server.cpp
Expand Up @@ -314,7 +314,7 @@ UniValue stop(const JSONRPCRequest& jsonRequest)
if (jsonRequest.params[0].isNum()) {
MilliSleep(jsonRequest.params[0].get_int());
}
return "Dash Core server stopping";
return "Bitcoin server stopping";
}

static UniValue uptime(const JSONRPCRequest& jsonRequest)
Expand Down
2 changes: 1 addition & 1 deletion test/functional/test_framework/test_framework.py
Expand Up @@ -332,7 +332,7 @@ def start_nodes(self, extra_args=None, stderr=None, *args, **kwargs):
for node in self.nodes:
coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)

def stop_node(self, i, wait=0):
def stop_node(self, i,expected_stderr='', wait=0):
"""Stop a dashd test node"""
self.nodes[i].stop_node(wait=wait)
self.nodes[i].wait_until_stopped()
Expand Down
2 changes: 1 addition & 1 deletion test/functional/test_framework/test_node.py
Expand Up @@ -190,7 +190,7 @@ def get_wallet_rpc(self, wallet_name):
wallet_path = "wallet/{}".format(urllib.parse.quote(wallet_name))
return self.rpc / wallet_path

def stop_node(self, wait=0):
def stop_node(self,expected_stderr='', wait=0):
"""Stop the node."""
if not self.running:
return
Expand Down
1 change: 1 addition & 0 deletions test/functional/test_runner.py
Expand Up @@ -177,6 +177,7 @@
'feature_blocksdir.py',
'feature_config_args.py',
'feature_help.py',
'feature_shutdown.py',
# Don't append tests at the end to avoid merge conflicts
# Put them in a random line within the section that fits their approximate run-time
]
Expand Down

0 comments on commit 7df7b4f

Please sign in to comment.