You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by be...@apache.org on 2017/11/20 03:47:16 UTC

[3/4] mesos git commit: Added http::Server.

Added http::Server.

Review: https://reviews.apache.org/r/61155


Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/c17152f6
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/c17152f6
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/c17152f6

Branch: refs/heads/master
Commit: c17152f6da44821fe9f1452e991d22307b8d2834
Parents: 37d3ee5
Author: Benjamin Hindman <be...@gmail.com>
Authored: Sat Jan 7 18:05:39 2017 -0800
Committer: Benjamin Hindman <be...@gmail.com>
Committed: Sun Nov 19 19:44:29 2017 -0800

----------------------------------------------------------------------
 3rdparty/libprocess/include/process/http.hpp | 142 +++++++--
 3rdparty/libprocess/src/http.cpp             | 346 +++++++++++++++++++++-
 3rdparty/libprocess/src/tests/http_tests.cpp | 232 ++++++++++++++-
 3 files changed, 688 insertions(+), 32 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mesos/blob/c17152f6/3rdparty/libprocess/include/process/http.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/include/process/http.hpp b/3rdparty/libprocess/include/process/http.hpp
index ba1b086..78cf2c3 100644
--- a/3rdparty/libprocess/include/process/http.hpp
+++ b/3rdparty/libprocess/include/process/http.hpp
@@ -1018,30 +1018,130 @@ template <typename F>
 Future<Nothing> serve(const network::Socket& s, F&& f)
 {
   return internal::serve(
-      s, std::function<Future<Response>(const Request&)>(std::forward<F>(f)));
+      s,
+      std::function<Future<Response>(const Request&)>(std::forward<F>(f)));
 }
 
 
-// TODO(benh): Eventually we probably want something like a `Server`
-// that will handle accepting new sockets and then calling `serve`. It
-// would also be valuable to introduce shutdown semantics that are
-// better than the current discard semantics on `serve`. For example:
-//
-// class Server
-// {
-//   struct ShutdownOptions
-//   {
-//     // During the grace period, no new connections will
-//     // be accepted. Existing connections will be closed
-//     // when currently received requests have been handled.
-//     // The server will shut down reads on each connection
-//     // to prevent new requests from arriving.
-//     Duration gracePeriod;
-//   };
-//
-//   // Shuts down the server.
-//   Future<Nothing> shutdown(Sever::ShutdownOptions options);
-// };
+// Forward declaration.
+class ServerProcess;
+
+
+class Server
+{
+public:
+  // Options for creating a server.
+  //
+  // NOTE: until GCC 5.0 default member initializers prevented the
+  // class from being an aggregate which prevented you from being able
+  // to use aggregate initialization, thus we introduce and use
+  // `DEFAULT_CREATE_OPTIONS` for the default parameter of `create`.
+  struct CreateOptions
+  {
+    Scheme scheme;
+    size_t backlog;
+  };
+
+  static CreateOptions DEFAULT_CREATE_OPTIONS()
+  {
+    return {
+      /* .scheme = */ Scheme::HTTP,
+      /* .backlog = */ 16384,
+    };
+  };
+
+  // Options for stopping a server.
+  //
+  // NOTE: see note above as to why we have `DEFAULT_STOP_OPTIONS`.
+  struct StopOptions
+  {
+    // During the grace period:
+    //   * No new sockets will be accepted (but on OS X they'll still queue).
+    //   * Existing sockets will be shut down for reads to prevent new
+    //     requests from arriving.
+    //   * Existing sockets will be shut down after already received
+    //     requests have their responses sent.
+    // After the grace period connections will be forcibly shut down.
+    Duration grace_period;
+  };
+
+  static StopOptions DEFAULT_STOP_OPTIONS()
+  {
+    return {
+      /* .grace_period = */ Seconds(0),
+    };
+  };
+
+  static Try<Server> create(
+      network::Socket socket,
+      std::function<Future<Response>(
+          const network::Socket& socket,
+          const Request&)>&& f,
+      const CreateOptions& options = DEFAULT_CREATE_OPTIONS());
+
+  template <typename F>
+  static Try<Server> create(
+      network::Socket socket,
+      F&& f,
+      const CreateOptions& options = DEFAULT_CREATE_OPTIONS())
+  {
+    return create(
+        std::move(socket),
+        std::function<Future<Response>(
+            const network::Socket&,
+            const Request&)>(std::forward<F>(f)),
+        options);
+  }
+
+  static Try<Server> create(
+      const network::Address& address,
+      std::function<Future<Response>(
+          const network::Socket&,
+          const Request&)>&& f,
+      const CreateOptions& options = DEFAULT_CREATE_OPTIONS());
+
+  template <typename F>
+  static Try<Server> create(
+      const network::Address& address,
+      F&& f,
+      const CreateOptions& options = DEFAULT_CREATE_OPTIONS())
+  {
+    return create(
+        address,
+        std::function<Future<Response>(
+            const network::Socket&,
+            const Request&)>(std::forward<F>(f)),
+        options);
+  }
+
+  // Movable but not copyable, not assignable.
+  Server(Server&& that) = default;
+  Server(const Server&) = delete;
+  Server& operator=(const Server&) = delete;
+
+  ~Server();
+
+  // Runs the server, returns nothing after the server has been
+  // stopped or a failure if one occured.
+  Future<Nothing> run();
+
+  // Returns after the server has been stopped and all existing
+  // connections have been closed.
+  Future<Nothing> stop(const StopOptions& options = DEFAULT_STOP_OPTIONS());
+
+  // Returns the bound address of the server.
+  Try<network::Address> address() const;
+
+private:
+  Server(
+      network::Socket&& socket,
+      std::function<Future<Response>(
+          const network::Socket&,
+          const Request&)>&& f);
+
+  network::Socket socket;
+  Owned<ServerProcess> process;
+};
 
 
 // Create a http Request from the specified parameters.

http://git-wip-us.apache.org/repos/asf/mesos/blob/c17152f6/3rdparty/libprocess/src/http.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/src/http.cpp b/3rdparty/libprocess/src/http.cpp
index fa3dde6..eb4cd58 100644
--- a/3rdparty/libprocess/src/http.cpp
+++ b/3rdparty/libprocess/src/http.cpp
@@ -31,6 +31,7 @@
 #include <tuple>
 #include <vector>
 
+#include <process/after.hpp>
 #include <process/collect.hpp>
 #include <process/defer.hpp>
 #include <process/dispatch.hpp>
@@ -43,6 +44,7 @@
 #include <process/process.hpp>
 #include <process/queue.hpp>
 #include <process/socket.hpp>
+#include <process/state_machine.hpp>
 
 #include <stout/foreach.hpp>
 #include <stout/ip.hpp>
@@ -61,6 +63,7 @@
 
 using std::deque;
 using std::istringstream;
+using std::list;
 using std::map;
 using std::ostream;
 using std::ostringstream;
@@ -1401,7 +1404,8 @@ Future<Connection> connect(const network::Address& address, Scheme scheme)
   }
 
   Try<network::Socket> socket = network::Socket::create(
-      address.family(), kind);
+      address.family(),
+      kind);
 
   if (socket.isError()) {
     return Failure("Failed to create socket: " + socket.error());
@@ -1702,15 +1706,29 @@ Future<Nothing> send(
         Request* request = item->request;
         Future<Response> response = item->response;
 
-        return response
-          // TODO(benh):
-          // .recover([]() {
-          //   return InternalServerError("Discarded response");
-          // })
-          .repair([](const Future<Response>& response) {
-            // TODO(benh): Is this severe enough that we should close
-            // the connection?
-            return InternalServerError(response.failure());
+        // We do an `await` here so that we won't wait forever in the
+        // event that we've discarded the loop but `response` is
+        // abandoned or taking too long.
+        return await(response)
+          .recover([](const Future<Future<Response>>& future)
+              -> Future<Response> {
+            if (future.isFailed()) {
+              return InternalServerError(
+                  "Failed to wait for response: " + future.failure());
+            }
+
+            // Either `response` was abandoned or the loop has been
+            // discarded so we return `ServiceUnavailable` so we can
+            // continue the loop or break out if we've been discarded.
+            return ServiceUnavailable();
+          })
+          .then([](const Future<Response>& future) -> Response {
+            if (future.isFailed()) {
+              return InternalServerError(future.failure());
+            } else if (future.isDiscarded()) {
+              return ServiceUnavailable();
+            }
+            return future.get();
           })
           .then([=](const Response& response) {
             // TODO(benh): Should any generated InternalServerError
@@ -1918,6 +1936,314 @@ Future<Nothing> serve(
 } // namespace internal {
 
 
+class ServerProcess : public Process<ServerProcess>
+{
+public:
+  ServerProcess(
+      network::Socket&& socket,
+      std::function<Future<Response>(
+          const network::Socket&,
+          const Request&)>&& f)
+    : socket(std::move(socket)),
+      f(std::move(f)),
+      state(State::INITIALIZED) {}
+
+  // `Server` implementation.
+  Future<Nothing> run()
+  {
+    return state.transition<State::INITIALIZED, State::RUNNING>([=]() {
+        // Start the accept loop and store the future so we can later
+        // discard it when we need to stop the server.
+        accepting = loop(
+          self(),
+          [=]() {
+            return socket.accept();
+          },
+          [=](const network::Socket& socket) -> ControlFlow<Nothing> {
+            // If we've transitioned to STOPPING we should break. It
+            // may seem like we should never get here because we
+            // discard the accept loop before we transition to
+            // STOPPING but it's possible that we've already
+            // dispatched this lambda and it is only now getting
+            // invoked. It's critical that we break because after we
+            // transition to STOPPING we assume that `clients` will
+            // not be modified by the accept loop.
+            if (state.is<State::STOPPING>()) {
+              return Break();
+            }
+
+            Client client = {
+              /* .socket = */ socket,
+              /* .serving = */ http::serve(
+                  socket,
+                  [=](const Request& request) {
+                    return f(socket, request);
+                  })
+            };
+
+            clients.put(socket, client);
+
+            client.serving
+              .onAny(defer(self(), [=](const Future<Nothing>&) {
+                clients.erase(socket);
+              }));
+
+            return Continue();
+          });
+
+      // We return a _discardable_ `accepting` so the caller can stop
+      // running a server by "discarding the run", for example:
+      //
+      //   Future<Nothing> run = server.run();
+      //   run.discard();
+      //
+      // Even if we returned an _undiscardable_ `accepting` we still
+      // need to do a `recover()` on it in the event that the accept
+      // loop fails (or is abandoned) so we can stop the server (if it
+      // isn't already being stopped). If `accepting` completes
+      // successfully then we must be stopping so just wait until
+      // we've stopped!
+      return accepting
+        .then(defer(self(), [=]() {
+          return state.when<State::STOPPED>();
+        }))
+        .recover(defer(self(), [=](const Future<Nothing>& future) {
+          // If the accept loop completes because it is abandoned,
+          // discarded, or failed we want to stop the server if it
+          // isn't already being stopped. In fact, someone stopping
+          // the server might be the reason we're executing this
+          // callback because `stop()` discards `accepting`.
+          //
+          // If we're not already stopping, i.e., the state is
+          // RUNNING, then it's safe to assume that the accept loop
+          // has (1) failed or (2) been discarded because someone did
+          // a discard on the future returned from `run()`. In either
+          // of these cases we initiate a `stop()` ourselves and after
+          // that completes return a failure capturing the reason we
+          // had to initiate the stop.
+          if (state.is<State::RUNNING>()) {
+            return stop(Server::DEFAULT_STOP_OPTIONS())
+              .then([=]() -> Future<Nothing> {
+                return Failure(stringify(future));
+              });
+          }
+
+          // Otherwise we must already be stopping so just wait till
+          // we're stopped.
+          return state.when<State::STOPPED>();
+        }));
+    });
+  }
+
+  Future<Nothing> stop(const Server::StopOptions& options)
+  {
+    return state.transition<State::RUNNING, State::STOPPING>([=]() {
+      // We make stopping be undiscardable to ensure that we properly
+      // cleanup. This has the added benefit of simplifying having to
+      // reason about how discards may propagate here when someone
+      // discards the future returned from `run()` after they've
+      // already called `stop()`.
+      return undiscardable([=]() {
+        accepting.discard();
+
+        // In addition to discarding the accept loop we also attempt
+        // to stop accepting new clients via shutting down the
+        // socket. Shutting down the socket on Linux will keep further
+        // connections from being established even though we haven't
+        // closed the socket but on OS X connections will keep queuing
+        // (in fact, calling `shutdown()` is an error, hence we don't
+        // check the return value).
+        socket.shutdown(network::Socket::Shutdown::READ_WRITE);
+
+        // TODO(benh): ideally we also try and shut down the read end
+        // of existing clients to signal that we won't handle any new
+        // requests. Note that doing this is expected by the
+        // specification, see section 8.1.4 in
+        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html. Something
+        // like:
+        //
+        // foreachvalue (Client& client, clients) {
+        //   client.socket.shutdown(network::Socket::Shutdown::READ);
+        // }
+        //
+        // Doing this is non-trivial, however, because in practice
+        // what most servers do is continue to read any partial
+        // requests until some point at which no more requests appear
+        // to be coming in. This will require significant changes in
+        // `http::serve()`, hence it's left as a TODO.
+
+        // Wait for the current clients to finish (we know no more
+        // clients will get added because we set `stopping` and the
+        // accept loop will respect that (see `run()`).
+        return await(lambda::map(
+            [](Client&& client) {
+              return client.serving;
+            },
+            clients.values()))
+          // After the grace period expires discard all the clients
+          // and then keep waiting.
+          .after(options.grace_period,
+                 defer(self(), [=](Future<list<Future<Nothing>>> f) {
+                   f.discard();
+                   return await(lambda::map(
+                       [](Client&& client) {
+                         client.serving.discard();
+                         return client.serving;
+                       },
+                       clients.values()));
+                 }))
+          .then(defer(self(), [=]() {
+            clients.clear();
+
+            // We `await()` the accept loop because we don't care how
+            // it completes, we just want it to complete.
+            return await(accepting)
+              .then(defer(self(), [=]() -> Future<Nothing> {
+                return state.transition<State::STOPPING, State::STOPPED>();
+              }));
+          }));
+      }());
+    },
+    "Server must be started in order to be stopped");
+  }
+
+protected:
+  virtual void finalize()
+  {
+    // If we started the accept loop then discard it and any clients
+    // we are already serving.
+    accepting.discard();
+
+    // NOTE: we know that no more sockets will be accepted because
+    // the accept loop is on `self()` and we're in `finalize()`.
+    foreachvalue (Client& client, clients) {
+      client.serving.discard();
+    }
+
+    clients.clear();
+  }
+
+private:
+  network::Socket socket;
+  std::function<Future<Response>(const network::Socket&, const Request&)> f;
+
+  enum class State
+  {
+    INITIALIZED,
+    RUNNING,
+    STOPPING,
+    STOPPED,
+  };
+
+  StateMachine<State> state;
+
+  Future<Nothing> accepting;
+
+  struct Client
+  {
+    network::Socket socket;
+    Future<Nothing> serving;
+  };
+
+  hashmap<int, Client> clients;
+};
+
+
+Try<Server> Server::create(
+    network::Socket socket,
+    std::function<Future<Response>(const network::Socket&, const Request&)>&& f,
+    const CreateOptions& options)
+{
+  // NOTE: we start listening on the socket here so that a client can
+  // attempt to connect to the server even before `Server::run` has
+  // been called. If we postpone calling `Socket::listen` until we
+  // invoke `Server::run` there is a race between when `Server::run`
+  // returns and when `Socket::listen` actually gets called because
+  // `Server::run` dispatches to `ServerProcess::run`. This is likely
+  // not a problem in practice but is definitely problematic with
+  // tests that try and start making connections immediately after
+  // `Server::run` has returned but potentially before
+  // `Socket::listen` has been invoked.
+  Try<Nothing> listen = socket.listen(options.backlog);
+  if (listen.isError()) {
+    return Error("Failed to listen on socket: " + listen.error());
+  }
+
+  return Server(std::move(socket), std::move(f));
+}
+
+
+Try<Server> Server::create(
+    const network::Address& address,
+    std::function<Future<Response>(const network::Socket&, const Request&)>&& f,
+    const Server::CreateOptions& options)
+{
+  SocketImpl::Kind kind = [&]() {
+    switch (options.scheme) {
+      case Scheme::HTTP: return SocketImpl::Kind::POLL;
+#ifdef USE_SSL_SOCKET
+      case Scheme::HTTPS: return SocketImpl::Kind::SSL;
+#endif
+    }
+  }();
+
+  Try<network::Socket> socket = network::Socket::create(
+      address.family(),
+      kind);
+
+  if (socket.isError()) {
+    return Error("Failed to create socket: " + socket.error());
+  }
+
+  Try<network::Address> bind = socket->bind(address);
+  if (bind.isError()) {
+    return Error(
+        "Failed to bind to address '" + stringify(address) + "': "
+        + bind.error());
+  }
+
+  return create(socket.get(), std::move(f), options);
+}
+
+
+Server::Server(
+    network::Socket&& socket,
+    std::function<Future<Response>(const network::Socket&, const Request&)>&& f)
+  : socket(socket),
+    process(new ServerProcess(std::move(socket), std::move(f)))
+{
+  spawn(*process);
+}
+
+
+Server::~Server()
+{
+  // `process` may be a `nullptr` if we've moved `this`.
+  if (process.get() != nullptr) {
+    terminate(*process);
+    wait(*process);
+  }
+}
+
+
+Future<Nothing> Server::run()
+{
+  return dispatch(*process, &ServerProcess::run);
+}
+
+
+Future<Nothing> Server::stop(const Server::StopOptions& options)
+{
+  return dispatch(*process, &ServerProcess::stop, options);
+}
+
+
+Try<network::Address> Server::address() const
+{
+  return socket.address();
+}
+
+
 Request createRequest(
     const URL& url,
     const string& method,

http://git-wip-us.apache.org/repos/asf/mesos/blob/c17152f6/3rdparty/libprocess/src/tests/http_tests.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/src/tests/http_tests.cpp b/3rdparty/libprocess/src/tests/http_tests.cpp
index ef84967..a025a87 100644
--- a/3rdparty/libprocess/src/tests/http_tests.cpp
+++ b/3rdparty/libprocess/src/tests/http_tests.cpp
@@ -55,8 +55,8 @@
 #include "encoder.hpp"
 
 namespace authentication = process::http::authentication;
-namespace ID = process::ID;
 namespace http = process::http;
+namespace ID = process::ID;
 namespace inet = process::network::inet;
 namespace inet4 = process::network::inet4;
 namespace network = process::network;
@@ -2332,3 +2332,233 @@ TEST_F(HttpServeTest, Unix)
   AWAIT_READY(serve);
 }
 #endif // __WINDOWS__
+
+
+// Ensures that the server does not re-order responses if handlers
+// complete the responses out of order.
+TEST(HttpServerTest, Pipeline)
+{
+  class Handler
+  {
+  public:
+    MOCK_METHOD1(handle, Future<http::Response>(const http::Request&));
+  } handler;
+
+  Try<http::Server> server = http::Server::create(
+      inet4::Address::ANY_ANY(),
+      [&](const network::Socket&, const http::Request& request) {
+        return handler.handle(request);
+      });
+
+  ASSERT_SOME(server);
+
+  Future<Nothing> run = server->run();
+
+  Try<inet::Address> address =
+    network::convert<inet::Address>(server->address());
+
+  ASSERT_SOME(address);
+
+  Future<http::Connection> connect =
+    http::connect(address.get(), http::Scheme::HTTP);
+
+  AWAIT_ASSERT_READY(connect);
+
+  http::Connection connection = connect.get();
+
+  Promise<http::Response> promise1;
+  Future<http::Request> request1;
+
+  Promise<http::Response> promise2;
+  Future<http::Request> request2;
+
+  Promise<http::Response> promise3;
+  Future<http::Request> request3;
+
+  EXPECT_CALL(handler, handle(_))
+    .WillOnce(DoAll(FutureArg<0>(&request1), Return(promise1.future())))
+    .WillOnce(DoAll(FutureArg<0>(&request2), Return(promise2.future())))
+    .WillOnce(DoAll(FutureArg<0>(&request3), Return(promise3.future())))
+    .WillRepeatedly(Return(http::OK()));
+
+  http::URL url("http", address->hostname().get(), address->port, "/");
+
+  http::Request request;
+  request.method = "GET";
+  request.url = url;
+  request.keepAlive = true;
+
+  Future<http::Response> response1 = connection.send(request);
+  Future<http::Response> response2 = connection.send(request);
+  Future<http::Response> response3 = connection.send(request);
+
+  AWAIT_EXPECT_READY(request1);
+  AWAIT_EXPECT_READY(request2);
+  AWAIT_EXPECT_READY(request3);
+
+  ASSERT_TRUE(response1.isPending());
+  ASSERT_TRUE(response2.isPending());
+  ASSERT_TRUE(response3.isPending());
+
+  promise3.set(http::OK("3"));
+
+  ASSERT_TRUE(response1.isPending());
+  ASSERT_TRUE(response2.isPending());
+  ASSERT_TRUE(response3.isPending());
+
+  promise1.set(http::OK("1"));
+
+  AWAIT_ASSERT_READY(response1);
+  EXPECT_EQ("1", response1->body);
+
+  ASSERT_TRUE(response2.isPending());
+  ASSERT_TRUE(response3.isPending());
+
+  promise2.set(http::OK("2"));
+
+  AWAIT_ASSERT_READY(response2);
+  EXPECT_EQ("2", response2->body);
+
+  AWAIT_ASSERT_READY(response3);
+  EXPECT_EQ("3", response3->body);
+
+  AWAIT_READY(connection.disconnect());
+
+  ASSERT_TRUE(run.isPending());
+
+  AWAIT_EXPECT_READY(server->stop());
+
+  AWAIT_EXPECT_READY(run);
+}
+
+
+// Tests that we can't stop a server that's not running.
+TEST(HttpServerTest, StopNotRunning)
+{
+  class Handler
+  {
+  public:
+    MOCK_METHOD1(handle, Future<http::Response>(const http::Request&));
+  } handler;
+
+  Try<http::Server> server = http::Server::create(
+      inet4::Address::ANY_ANY(),
+      [&](const network::Socket&, const http::Request& request) {
+        return handler.handle(request);
+      });
+
+  ASSERT_SOME(server);
+
+  AWAIT_EXPECT_FAILED(server->stop());
+}
+
+
+// Tests that we can discard a server that we started running and it
+// will return a failure after the server has stopped.
+TEST(HttpServerTest, Discard)
+{
+  class Handler
+  {
+  public:
+    MOCK_METHOD1(handle, Future<http::Response>(const http::Request&));
+  } handler;
+
+  Try<http::Server> server = http::Server::create(
+      inet4::Address::ANY_ANY(),
+      [&](const network::Socket&, const http::Request& request) {
+        return handler.handle(request);
+      });
+
+  ASSERT_SOME(server);
+
+  EXPECT_CALL(handler, handle(_))
+    .Times(0);
+
+  Future<Nothing> run = server->run();
+
+  Try<inet::Address> address =
+    network::convert<inet::Address>(server->address());
+
+  ASSERT_SOME(address);
+
+  // NOTE: we can't guarantee that after the call to `server->run()`
+  // the server is actually running because the actor might not yet
+  // have received the asynchronous dispatch. Thus, we need some
+  // happens before guarantee that the server is running which we get
+  // by making a connection. We then use that connection to properly
+  // test that we shutdown each client below.
+  Future<http::Connection> connect =
+    http::connect(address.get(), http::Scheme::HTTP);
+
+  AWAIT_ASSERT_READY(connect);
+
+  http::Connection connection = connect.get();
+
+  Future<Nothing> disconnected = connection.disconnected();
+
+  EXPECT_TRUE(disconnected.isPending());
+
+  run.discard();
+
+  AWAIT_EXPECT_READY(disconnected);
+
+  AWAIT_EXPECT_FAILED(run);
+}
+
+
+// Tests that if the server gets finalized due to the process getting
+// cleaned up but nobody called `Server::stop()` then we'll shutdown
+// existing clients and the future returned from `Server::run()` will
+// be abandoned.
+TEST(HttpServerTest, Finalize)
+{
+  Future<Nothing> run = Nothing();
+  Future<Nothing> disconnected = Nothing();
+
+  {
+    class Handler
+    {
+    public:
+      MOCK_METHOD1(handle, Future<http::Response>(const http::Request&));
+    } handler;
+
+    Try<http::Server> server = http::Server::create(
+        inet4::Address::ANY_ANY(),
+        [&](const network::Socket&, const http::Request& request) {
+          return handler.handle(request);
+        });
+
+    ASSERT_SOME(server);
+
+    EXPECT_CALL(handler, handle(_))
+      .Times(0);
+
+    run = server->run();
+
+    Try<inet::Address> address =
+      network::convert<inet::Address>(server->address());
+
+    ASSERT_SOME(address);
+
+    // NOTE: we can't guarantee that after the call to `server->run()`
+    // the server is actually running because the actor might not yet
+    // have received the asynchronous dispatch. Thus, we need some
+    // happens before guarantee that the server is running which we
+    // get by making a connection. We then use that connection to
+    // properly test that we shutdown each client below.
+    Future<http::Connection> connect =
+      http::connect(address.get(), http::Scheme::HTTP);
+
+    AWAIT_ASSERT_READY(connect);
+
+    http::Connection connection = connect.get();
+
+    disconnected = connection.disconnected();
+
+    EXPECT_TRUE(disconnected.isPending());
+  }
+
+  AWAIT_EXPECT_READY(disconnected);
+
+  AWAIT_EXPECT_ABANDONED(run);
+}