copy wangle back into folly
[folly.git] / folly / wangle / bootstrap / ServerBootstrap.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/wangle/bootstrap/ServerBootstrap.h>
17 #include <folly/wangle/concurrent/NamedThreadFactory.h>
18 #include <folly/wangle/channel/Handler.h>
19 #include <folly/io/async/EventBaseManager.h>
20
21 namespace folly {
22
23 void ServerWorkerPool::threadStarted(
24   folly::wangle::ThreadPoolExecutor::ThreadHandle* h) {
25   auto worker = acceptorFactory_->newAcceptor(exec_->getEventBase(h));
26   workers_.insert({h, worker});
27
28   for(auto socket : *sockets_) {
29     socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
30       [this, worker, socket](){
31         socketFactory_->addAcceptCB(
32           socket, worker.get(), worker->getEventBase());
33     });
34   }
35 }
36
37 void ServerWorkerPool::threadStopped(
38   folly::wangle::ThreadPoolExecutor::ThreadHandle* h) {
39   auto worker = workers_.find(h);
40   CHECK(worker != workers_.end());
41
42   for (auto socket : *sockets_) {
43     socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
44       [&]() {
45         socketFactory_->removeAcceptCB(
46           socket, worker->second.get(), nullptr);
47     });
48   }
49
50   if (!worker->second->getEventBase()->isInEventBaseThread()) {
51     worker->second->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
52       [=]() {
53         worker->second->dropAllConnections();
54       });
55   } else {
56     worker->second->dropAllConnections();
57   }
58
59   workers_.erase(worker);
60 }
61
62 } // namespace