blob: 1ff2789ecbc3e020b6752b8649ee6bb52dd7fe9e [file] [log] [blame]
[email protected]a796bcec2010-03-22 17:17:261// Copyright (c) 2010 The Chromium Authors. All rights reserved.
[email protected]ff579d42009-06-24 15:47:022// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/socket/client_socket_pool_base.h"
6
7#include "base/compiler_specific.h"
[email protected]fd4fe0b2010-02-08 23:02:158#include "base/format_macros.h"
[email protected]ff579d42009-06-24 15:47:029#include "base/message_loop.h"
[email protected]6b624c62010-03-14 08:37:3210#include "base/stats_counters.h"
[email protected]ff579d42009-06-24 15:47:0211#include "base/stl_util-inl.h"
[email protected]fd4fe0b2010-02-08 23:02:1512#include "base/string_util.h"
[email protected]ff579d42009-06-24 15:47:0213#include "base/time.h"
[email protected]9e743cd2010-03-16 07:03:5314#include "net/base/net_log.h"
[email protected]ff579d42009-06-24 15:47:0215#include "net/base/net_errors.h"
16#include "net/socket/client_socket_handle.h"
17
18using base::TimeDelta;
19
20namespace {
21
22// The timeout value, in seconds, used to clean up idle sockets that can't be
23// reused.
24//
25// Note: It's important to close idle sockets that have received data as soon
26// as possible because the received data may cause BSOD on Windows XP under
27// some conditions. See http://crbug.com/4606.
28const int kCleanupInterval = 10; // DO NOT INCREASE THIS TIMEOUT.
29
[email protected]ff579d42009-06-24 15:47:0230} // namespace
31
32namespace net {
33
[email protected]2ab05b52009-07-01 23:57:5834ConnectJob::ConnectJob(const std::string& group_name,
[email protected]974ebd62009-08-03 23:14:3435 base::TimeDelta timeout_duration,
[email protected]fd7b7c92009-08-20 19:38:3036 Delegate* delegate,
[email protected]9e743cd2010-03-16 07:03:5337 const BoundNetLog& net_log)
[email protected]2ab05b52009-07-01 23:57:5838 : group_name_(group_name),
[email protected]974ebd62009-08-03 23:14:3439 timeout_duration_(timeout_duration),
[email protected]2ab05b52009-07-01 23:57:5840 delegate_(delegate),
[email protected]a2006ece2010-04-23 16:44:0241 net_log_(net_log),
42 idle_(true) {
[email protected]2ab05b52009-07-01 23:57:5843 DCHECK(!group_name.empty());
[email protected]2ab05b52009-07-01 23:57:5844 DCHECK(delegate);
[email protected]06650c52010-06-03 00:49:1745 net_log.BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]2ab05b52009-07-01 23:57:5846}
47
[email protected]fd7b7c92009-08-20 19:38:3048ConnectJob::~ConnectJob() {
[email protected]06650c52010-06-03 00:49:1749 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]fd7b7c92009-08-20 19:38:3050}
[email protected]2ab05b52009-07-01 23:57:5851
[email protected]974ebd62009-08-03 23:14:3452int ConnectJob::Connect() {
53 if (timeout_duration_ != base::TimeDelta())
54 timer_.Start(timeout_duration_, this, &ConnectJob::OnTimeout);
[email protected]fd7b7c92009-08-20 19:38:3055
[email protected]a2006ece2010-04-23 16:44:0256 idle_ = false;
[email protected]fd7b7c92009-08-20 19:38:3057
[email protected]06650c52010-06-03 00:49:1758 LogConnectStart();
59
[email protected]fd7b7c92009-08-20 19:38:3060 int rv = ConnectInternal();
61
62 if (rv != ERR_IO_PENDING) {
[email protected]06650c52010-06-03 00:49:1763 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:3064 delegate_ = NULL;
[email protected]fd7b7c92009-08-20 19:38:3065 }
66
67 return rv;
68}
69
[email protected]06650c52010-06-03 00:49:1770void ConnectJob::set_socket(ClientSocket* socket) {
71 if (socket) {
72 net_log().AddEvent(NetLog::TYPE_CONNECT_JOB_SET_SOCKET,
73 new NetLogSourceParameter("source_dependency",
74 socket->NetLog().source()));
75 }
76 socket_.reset(socket);
77}
78
[email protected]fd7b7c92009-08-20 19:38:3079void ConnectJob::NotifyDelegateOfCompletion(int rv) {
80 // The delegate will delete |this|.
81 Delegate *delegate = delegate_;
82 delegate_ = NULL;
83
[email protected]06650c52010-06-03 00:49:1784 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:3085 delegate->OnConnectJobComplete(rv, this);
[email protected]974ebd62009-08-03 23:14:3486}
87
[email protected]a796bcec2010-03-22 17:17:2688void ConnectJob::ResetTimer(base::TimeDelta remaining_time) {
89 timer_.Stop();
90 timer_.Start(remaining_time, this, &ConnectJob::OnTimeout);
91}
92
[email protected]06650c52010-06-03 00:49:1793void ConnectJob::LogConnectStart() {
94 net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT,
95 new NetLogStringParameter("group_name", group_name_));
96}
97
98void ConnectJob::LogConnectCompletion(int net_error) {
99 scoped_refptr<NetLog::EventParameters> params;
100 if (net_error != OK)
101 params = new NetLogIntegerParameter("net_error", net_error);
102 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT, params);
103}
104
[email protected]974ebd62009-08-03 23:14:34105void ConnectJob::OnTimeout() {
[email protected]6e713f02009-08-06 02:56:40106 // Make sure the socket is NULL before calling into |delegate|.
107 set_socket(NULL);
[email protected]fd7b7c92009-08-20 19:38:30108
[email protected]ec11be62010-04-28 19:28:09109 net_log_.AddEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_TIMED_OUT, NULL);
[email protected]fd7b7c92009-08-20 19:38:30110
111 NotifyDelegateOfCompletion(ERR_TIMED_OUT);
[email protected]974ebd62009-08-03 23:14:34112}
113
[email protected]d80a4322009-08-14 07:07:49114namespace internal {
115
[email protected]fd4fe0b2010-02-08 23:02:15116ClientSocketPoolBaseHelper::Request::Request(
117 ClientSocketHandle* handle,
118 CompletionCallback* callback,
119 RequestPriority priority,
[email protected]9e743cd2010-03-16 07:03:53120 const BoundNetLog& net_log)
[email protected]fd4fe0b2010-02-08 23:02:15121 : handle_(handle), callback_(callback), priority_(priority),
[email protected]9e743cd2010-03-16 07:03:53122 net_log_(net_log) {}
[email protected]fd4fe0b2010-02-08 23:02:15123
124ClientSocketPoolBaseHelper::Request::~Request() {}
125
[email protected]d80a4322009-08-14 07:07:49126ClientSocketPoolBaseHelper::ClientSocketPoolBaseHelper(
[email protected]211d2172009-07-22 15:48:53127 int max_sockets,
[email protected]ff579d42009-06-24 15:47:02128 int max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16129 base::TimeDelta unused_idle_socket_timeout,
130 base::TimeDelta used_idle_socket_timeout,
[email protected]a554a8262010-05-20 00:13:52131 ConnectJobFactory* connect_job_factory,
132 NetworkChangeNotifier* network_change_notifier)
[email protected]ff579d42009-06-24 15:47:02133 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53134 connecting_socket_count_(0),
135 handed_out_socket_count_(0),
[email protected]d7027bb2010-05-10 18:58:54136 num_releasing_sockets_(0),
[email protected]211d2172009-07-22 15:48:53137 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02138 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16139 unused_idle_socket_timeout_(unused_idle_socket_timeout),
140 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]211d2172009-07-22 15:48:53141 may_have_stalled_group_(false),
[email protected]100d5fb92009-12-21 21:08:35142 connect_job_factory_(connect_job_factory),
[email protected]a554a8262010-05-20 00:13:52143 network_change_notifier_(network_change_notifier),
[email protected]7c28e9a2010-03-20 01:16:13144 backup_jobs_enabled_(false),
[email protected]a7e38572010-06-07 18:22:24145 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
146 pool_generation_number_(0) {
[email protected]211d2172009-07-22 15:48:53147 DCHECK_LE(0, max_sockets_per_group);
148 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52149
150 if (network_change_notifier_)
151 network_change_notifier_->AddObserver(this);
[email protected]211d2172009-07-22 15:48:53152}
[email protected]ff579d42009-06-24 15:47:02153
[email protected]d80a4322009-08-14 07:07:49154ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]4d3b05d2010-01-27 21:27:29155 CancelAllConnectJobs();
156
[email protected]ff579d42009-06-24 15:47:02157 // Clean up any idle sockets. Assert that we have no remaining active
158 // sockets or pending requests. They should have all been cleaned up prior
159 // to the manager being destroyed.
160 CloseIdleSockets();
[email protected]6b624c62010-03-14 08:37:32161 CHECK(group_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29162 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52163
164 if (network_change_notifier_)
165 network_change_notifier_->RemoveObserver(this);
[email protected]ff579d42009-06-24 15:47:02166}
167
168// InsertRequestIntoQueue inserts the request into the queue based on
169// priority. Highest priorities are closest to the front. Older requests are
170// prioritized over requests of equal priority.
171//
172// static
[email protected]d80a4322009-08-14 07:07:49173void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
174 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02175 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31176 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02177 ++it;
178 pending_requests->insert(it, r);
179}
180
[email protected]fd7b7c92009-08-20 19:38:30181// static
182const ClientSocketPoolBaseHelper::Request*
183ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
184 RequestQueue::iterator it, RequestQueue* pending_requests) {
185 const Request* req = *it;
[email protected]fd7b7c92009-08-20 19:38:30186 pending_requests->erase(it);
187 return req;
188}
189
[email protected]d80a4322009-08-14 07:07:49190int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02191 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49192 const Request* request) {
[email protected]ec11be62010-04-28 19:28:09193 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]fd4fe0b2010-02-08 23:02:15194 Group& group = group_map_[group_name];
195 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17196 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09197 request->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]e7e99322010-05-04 23:30:17198 delete request;
199 } else {
[email protected]fd4fe0b2010-02-08 23:02:15200 InsertRequestIntoQueue(request, &group.pending_requests);
[email protected]e7e99322010-05-04 23:30:17201 }
[email protected]fd4fe0b2010-02-08 23:02:15202 return rv;
203}
204
205int ClientSocketPoolBaseHelper::RequestSocketInternal(
206 const std::string& group_name,
207 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49208 DCHECK_GE(request->priority(), 0);
209 CompletionCallback* const callback = request->callback();
210 CHECK(callback);
211 ClientSocketHandle* const handle = request->handle();
212 CHECK(handle);
[email protected]ff579d42009-06-24 15:47:02213 Group& group = group_map_[group_name];
214
[email protected]65552102010-04-09 22:58:10215 // Try to reuse a socket.
216 while (!group.idle_sockets.empty()) {
217 IdleSocket idle_socket = group.idle_sockets.back();
218 group.idle_sockets.pop_back();
219 DecrementIdleCount();
220 if (idle_socket.socket->IsConnectedAndIdle()) {
221 // We found one we can reuse!
222 base::TimeDelta idle_time =
223 base::TimeTicks::Now() - idle_socket.start_time;
224 HandOutSocket(
225 idle_socket.socket, idle_socket.used, handle, idle_time, &group,
226 request->net_log());
227 return OK;
228 }
229 delete idle_socket.socket;
230 }
231
[email protected]43a21b82010-06-10 21:30:54232 // Can we make another active socket now?
233 if (!group.HasAvailableSocketSlot(max_sockets_per_group_)) {
234 request->net_log().AddEvent(
235 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
236 return ERR_IO_PENDING;
237 }
238
239 if (ReachedMaxSocketsLimit()) {
240 if (idle_socket_count() > 0) {
241 CloseOneIdleSocket();
242 } else {
243 // We could check if we really have a stalled group here, but it requires
244 // a scan of all groups, so just flip a flag here, and do the check later.
245 may_have_stalled_group_ = true;
246 request->net_log().AddEvent(
247 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
248 return ERR_IO_PENDING;
249 }
250 }
251
[email protected]5edbf8d2010-01-13 18:44:11252 // See if we already have enough connect jobs or sockets that will be released
253 // soon.
[email protected]4d3b05d2010-01-27 21:27:29254 if (group.HasReleasingSockets()) {
[email protected]5edbf8d2010-01-13 18:44:11255 return ERR_IO_PENDING;
256 }
257
[email protected]ff579d42009-06-24 15:47:02258 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58259 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17260 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02261
[email protected]2ab05b52009-07-01 23:57:58262 int rv = connect_job->Connect();
263 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17264 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2ab05b52009-07-01 23:57:58265 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
[email protected]9e743cd2010-03-16 07:03:53266 handle, base::TimeDelta(), &group, request->net_log());
[email protected]2ab05b52009-07-01 23:57:58267 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32268 // If we don't have any sockets in this group, set a timer for potentially
269 // creating a new one. If the SYN is lost, this backup socket may complete
270 // before the slow socket, improving end user latency.
[email protected]7c28e9a2010-03-20 01:16:13271 if (group.IsEmpty() && !group.backup_job && backup_jobs_enabled_) {
[email protected]6b624c62010-03-14 08:37:32272 group.backup_job = connect_job_factory_->NewConnectJob(group_name,
273 *request,
[email protected]06650c52010-06-03 00:49:17274 this);
[email protected]6b624c62010-03-14 08:37:32275 StartBackupSocketTimer(group_name);
276 }
277
[email protected]211d2172009-07-22 15:48:53278 connecting_socket_count_++;
279
[email protected]5fc08e32009-07-15 17:09:57280 ConnectJob* job = connect_job.release();
[email protected]5fc08e32009-07-15 17:09:57281 group.jobs.insert(job);
[email protected]a2006ece2010-04-23 16:44:02282 } else {
[email protected]06650c52010-06-03 00:49:17283 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]a2006ece2010-04-23 16:44:02284 if (group.IsEmpty())
285 group_map_.erase(group_name);
[email protected]2ab05b52009-07-01 23:57:58286 }
[email protected]ff579d42009-06-24 15:47:02287
[email protected]2ab05b52009-07-01 23:57:58288 return rv;
[email protected]ff579d42009-06-24 15:47:02289}
290
[email protected]06650c52010-06-03 00:49:17291// static
292void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
293 const NetLog::Source& connect_job_source, const Request* request) {
294 request->net_log().AddEvent(
295 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
296 new NetLogSourceParameter("source_dependency", connect_job_source));
297}
298
[email protected]6b624c62010-03-14 08:37:32299void ClientSocketPoolBaseHelper::StartBackupSocketTimer(
300 const std::string& group_name) {
301 CHECK(ContainsKey(group_map_, group_name));
302 Group& group = group_map_[group_name];
303
304 // Only allow one timer pending to create a backup socket.
305 if (group.backup_task)
306 return;
307
308 group.backup_task = method_factory_.NewRunnableMethod(
309 &ClientSocketPoolBaseHelper::OnBackupSocketTimerFired, group_name);
310 MessageLoop::current()->PostDelayedTask(FROM_HERE, group.backup_task,
311 ConnectRetryIntervalMs());
312}
313
314void ClientSocketPoolBaseHelper::OnBackupSocketTimerFired(
315 const std::string& group_name) {
316 CHECK(ContainsKey(group_map_, group_name));
317
318 Group& group = group_map_[group_name];
319
320 CHECK(group.backup_task);
321 group.backup_task = NULL;
322
323 CHECK(group.backup_job);
324
[email protected]c901f6d2010-04-27 17:48:28325 // If our backup job is waiting on DNS, or if we can't create any sockets
326 // right now due to limits, just reset the timer.
[email protected]6b624c62010-03-14 08:37:32327 CHECK(group.jobs.size());
[email protected]c901f6d2010-04-27 17:48:28328 if (ReachedMaxSocketsLimit() ||
329 !group.HasAvailableSocketSlot(max_sockets_per_group_) ||
330 (*group.jobs.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
[email protected]6b624c62010-03-14 08:37:32331 StartBackupSocketTimer(group_name);
332 return;
333 }
334
[email protected]ec11be62010-04-28 19:28:09335 group.backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED,
336 NULL);
[email protected]6b624c62010-03-14 08:37:32337 SIMPLE_STATS_COUNTER("socket.backup_created");
338 int rv = group.backup_job->Connect();
[email protected]c83658c2010-03-24 08:19:34339 connecting_socket_count_++;
340 group.jobs.insert(group.backup_job);
341 ConnectJob* job = group.backup_job;
342 group.backup_job = NULL;
343 if (rv != ERR_IO_PENDING)
344 OnConnectJobComplete(rv, job);
[email protected]6b624c62010-03-14 08:37:32345}
346
[email protected]d80a4322009-08-14 07:07:49347void ClientSocketPoolBaseHelper::CancelRequest(
348 const std::string& group_name, const ClientSocketHandle* handle) {
[email protected]b6501d3d2010-06-03 23:53:34349 // Running callbacks can cause the last outside reference to be released.
350 // Hold onto a reference.
351 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
352
[email protected]ff579d42009-06-24 15:47:02353 CHECK(ContainsKey(group_map_, group_name));
354
355 Group& group = group_map_[group_name];
356
[email protected]ff579d42009-06-24 15:47:02357 // Search pending_requests for matching handle.
358 RequestQueue::iterator it = group.pending_requests.begin();
359 for (; it != group.pending_requests.end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49360 if ((*it)->handle() == handle) {
[email protected]fd7b7c92009-08-20 19:38:30361 const Request* req = RemoveRequestFromQueue(it, &group.pending_requests);
[email protected]ec11be62010-04-28 19:28:09362 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
363 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]fd7b7c92009-08-20 19:38:30364 delete req;
[email protected]a796bcec2010-03-22 17:17:26365 // Let one connect job connect and become idle for potential future use.
[email protected]4d3b05d2010-01-27 21:27:29366 if (group.jobs.size() > group.pending_requests.size() + 1) {
[email protected]974ebd62009-08-03 23:14:34367 // TODO(willchan): Cancel the job in the earliest LoadState.
[email protected]4d3b05d2010-01-27 21:27:29368 RemoveConnectJob(*group.jobs.begin(), &group);
[email protected]974ebd62009-08-03 23:14:34369 OnAvailableSocketSlot(group_name, &group);
370 }
[email protected]ff579d42009-06-24 15:47:02371 return;
372 }
373 }
[email protected]ff579d42009-06-24 15:47:02374}
375
[email protected]d80a4322009-08-14 07:07:49376void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24377 ClientSocket* socket,
378 int id) {
[email protected]5edbf8d2010-01-13 18:44:11379 Group& group = group_map_[group_name];
380 group.num_releasing_sockets++;
[email protected]d7027bb2010-05-10 18:58:54381 num_releasing_sockets_++;
[email protected]5edbf8d2010-01-13 18:44:11382 DCHECK_LE(group.num_releasing_sockets, group.active_socket_count);
[email protected]ff579d42009-06-24 15:47:02383 // Run this asynchronously to allow the caller to finish before we let
384 // another to begin doing work. This also avoids nasty recursion issues.
385 // NOTE: We cannot refer to the handle argument after this method returns.
386 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
[email protected]a7e38572010-06-07 18:22:24387 this, &ClientSocketPoolBaseHelper::DoReleaseSocket, group_name, socket, id));
[email protected]ff579d42009-06-24 15:47:02388}
389
[email protected]d80a4322009-08-14 07:07:49390void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02391 CleanupIdleSockets(true);
392}
393
[email protected]d80a4322009-08-14 07:07:49394int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02395 const std::string& group_name) const {
396 GroupMap::const_iterator i = group_map_.find(group_name);
397 CHECK(i != group_map_.end());
398
399 return i->second.idle_sockets.size();
400}
401
[email protected]d80a4322009-08-14 07:07:49402LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02403 const std::string& group_name,
404 const ClientSocketHandle* handle) const {
405 if (!ContainsKey(group_map_, group_name)) {
406 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
407 << " for handle: " << handle;
408 return LOAD_STATE_IDLE;
409 }
410
411 // Can't use operator[] since it is non-const.
412 const Group& group = group_map_.find(group_name)->second;
413
[email protected]ff579d42009-06-24 15:47:02414 // Search pending_requests for matching handle.
415 RequestQueue::const_iterator it = group.pending_requests.begin();
[email protected]5fc08e32009-07-15 17:09:57416 for (size_t i = 0; it != group.pending_requests.end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49417 if ((*it)->handle() == handle) {
[email protected]4d3b05d2010-01-27 21:27:29418 if (i < group.jobs.size()) {
[email protected]5fc08e32009-07-15 17:09:57419 LoadState max_state = LOAD_STATE_IDLE;
420 for (ConnectJobSet::const_iterator job_it = group.jobs.begin();
421 job_it != group.jobs.end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21422 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57423 }
424 return max_state;
425 } else {
426 // TODO(wtc): Add a state for being on the wait list.
427 // See http://www.crbug.com/5077.
428 return LOAD_STATE_IDLE;
429 }
[email protected]ff579d42009-06-24 15:47:02430 }
431 }
432
433 NOTREACHED();
434 return LOAD_STATE_IDLE;
435}
436
[email protected]d80a4322009-08-14 07:07:49437bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16438 base::TimeTicks now,
439 base::TimeDelta timeout) const {
440 bool timed_out = (now - start_time) >= timeout;
[email protected]5fc08e32009-07-15 17:09:57441 return timed_out ||
442 !(used ? socket->IsConnectedAndIdle() : socket->IsConnected());
[email protected]ff579d42009-06-24 15:47:02443}
444
[email protected]d80a4322009-08-14 07:07:49445void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02446 if (idle_socket_count_ == 0)
447 return;
448
449 // Current time value. Retrieving it once at the function start rather than
450 // inside the inner loop, since it shouldn't change by any meaningful amount.
451 base::TimeTicks now = base::TimeTicks::Now();
452
453 GroupMap::iterator i = group_map_.begin();
454 while (i != group_map_.end()) {
455 Group& group = i->second;
456
457 std::deque<IdleSocket>::iterator j = group.idle_sockets.begin();
458 while (j != group.idle_sockets.end()) {
[email protected]9bf28db2009-08-29 01:35:16459 base::TimeDelta timeout =
460 j->used ? used_idle_socket_timeout_ : unused_idle_socket_timeout_;
461 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02462 delete j->socket;
463 j = group.idle_sockets.erase(j);
464 DecrementIdleCount();
465 } else {
466 ++j;
467 }
468 }
469
470 // Delete group if no longer needed.
[email protected]2ab05b52009-07-01 23:57:58471 if (group.IsEmpty()) {
[email protected]ff579d42009-06-24 15:47:02472 group_map_.erase(i++);
473 } else {
474 ++i;
475 }
476 }
477}
478
[email protected]d80a4322009-08-14 07:07:49479void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02480 if (++idle_socket_count_ == 1)
481 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49482 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02483}
484
[email protected]d80a4322009-08-14 07:07:49485void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02486 if (--idle_socket_count_ == 0)
487 timer_.Stop();
488}
489
[email protected]d80a4322009-08-14 07:07:49490void ClientSocketPoolBaseHelper::DoReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24491 ClientSocket* socket,
492 int id) {
[email protected]b6501d3d2010-06-03 23:53:34493 // Running callbacks can cause the last outside reference to be released.
494 // Hold onto a reference.
495 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
496
[email protected]ff579d42009-06-24 15:47:02497 GroupMap::iterator i = group_map_.find(group_name);
498 CHECK(i != group_map_.end());
499
500 Group& group = i->second;
501
[email protected]5edbf8d2010-01-13 18:44:11502 group.num_releasing_sockets--;
503 DCHECK_GE(group.num_releasing_sockets, 0);
504
[email protected]b1f031dd2010-03-02 23:19:33505 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53506 handed_out_socket_count_--;
507
[email protected]b1f031dd2010-03-02 23:19:33508 CHECK_GT(group.active_socket_count, 0);
[email protected]2ab05b52009-07-01 23:57:58509 group.active_socket_count--;
[email protected]ff579d42009-06-24 15:47:02510
[email protected]d7027bb2010-05-10 18:58:54511 CHECK_GT(num_releasing_sockets_, 0);
512 num_releasing_sockets_--;
513
[email protected]a7e38572010-06-07 18:22:24514 const bool can_reuse = socket->IsConnectedAndIdle() &&
515 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02516 if (can_reuse) {
[email protected]5fc08e32009-07-15 17:09:57517 AddIdleSocket(socket, true /* used socket */, &group);
[email protected]ff579d42009-06-24 15:47:02518 } else {
519 delete socket;
520 }
521
[email protected]4f2abec2010-02-03 18:10:16522 // If there are no more releasing sockets, then we might have to process
523 // multiple available socket slots, since we stalled their processing until
[email protected]d7027bb2010-05-10 18:58:54524 // all sockets have been released. Note that ProcessPendingRequest() will
525 // invoke user callbacks, so |num_releasing_sockets_| may change.
526 //
527 // This code has been known to infinite loop. Set a counter and CHECK to make
528 // sure it doesn't get ridiculously high.
[email protected]4f2abec2010-02-03 18:10:16529
[email protected]d7027bb2010-05-10 18:58:54530 int iterations = 0;
531 while (num_releasing_sockets_ == 0) {
532 CHECK_LT(iterations, 1000) << "Probably stuck in an infinite loop.";
533 std::string top_group_name;
534 Group* top_group = NULL;
535 int stalled_group_count = FindTopStalledGroup(&top_group, &top_group_name);
536 if (stalled_group_count >= 1) {
537 if (ReachedMaxSocketsLimit()) {
[email protected]43a21b82010-06-10 21:30:54538 if (idle_socket_count() > 0) {
539 CloseOneIdleSocket();
540 } else {
541 // We can't activate more sockets since we're already at our global
542 // limit.
543 may_have_stalled_group_ = true;
544 return;
545 }
[email protected]d7027bb2010-05-10 18:58:54546 }
547
548 ProcessPendingRequest(top_group_name, top_group);
549 } else {
550 may_have_stalled_group_ = false;
[email protected]4f2abec2010-02-03 18:10:16551 return;
[email protected]d7027bb2010-05-10 18:58:54552 }
[email protected]616925a2010-03-02 19:02:38553
[email protected]d7027bb2010-05-10 18:58:54554 iterations++;
[email protected]4f2abec2010-02-03 18:10:16555 }
[email protected]ff579d42009-06-24 15:47:02556}
557
[email protected]211d2172009-07-22 15:48:53558// Search for the highest priority pending request, amongst the groups that
559// are not at the |max_sockets_per_group_| limit. Note: for requests with
560// the same priority, the winner is based on group hash ordering (and not
561// insertion order).
[email protected]d80a4322009-08-14 07:07:49562int ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
563 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53564 Group* top_group = NULL;
565 const std::string* top_group_name = NULL;
566 int stalled_group_count = 0;
567 for (GroupMap::iterator i = group_map_.begin();
568 i != group_map_.end(); ++i) {
569 Group& group = i->second;
570 const RequestQueue& queue = group.pending_requests;
571 if (queue.empty())
572 continue;
[email protected]6427fe22010-04-16 22:27:41573 bool has_unused_slot =
574 group.HasAvailableSocketSlot(max_sockets_per_group_) &&
575 group.pending_requests.size() > group.jobs.size();
576 if (has_unused_slot) {
[email protected]211d2172009-07-22 15:48:53577 stalled_group_count++;
[email protected]6427fe22010-04-16 22:27:41578 bool has_higher_priority = !top_group ||
579 group.TopPendingPriority() < top_group->TopPendingPriority();
580 if (has_higher_priority) {
581 top_group = &group;
582 top_group_name = &i->first;
583 }
[email protected]211d2172009-07-22 15:48:53584 }
585 }
586 if (top_group) {
587 *group = top_group;
588 *group_name = *top_group_name;
589 }
590 return stalled_group_count;
591}
592
[email protected]d80a4322009-08-14 07:07:49593void ClientSocketPoolBaseHelper::OnConnectJobComplete(
594 int result, ConnectJob* job) {
[email protected]b6501d3d2010-06-03 23:53:34595 // Running callbacks can cause the last outside reference to be released.
596 // Hold onto a reference.
597 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
598
[email protected]2ab05b52009-07-01 23:57:58599 DCHECK_NE(ERR_IO_PENDING, result);
600 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02601 GroupMap::iterator group_it = group_map_.find(group_name);
602 CHECK(group_it != group_map_.end());
603 Group& group = group_it->second;
604
[email protected]6b624c62010-03-14 08:37:32605 // We've had a connect on the socket; discard any pending backup job
606 // for this group and kill the pending task.
607 group.CleanupBackupJob();
608
[email protected]5fc08e32009-07-15 17:09:57609 scoped_ptr<ClientSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02610
[email protected]9e743cd2010-03-16 07:03:53611 BoundNetLog job_log = job->net_log();
[email protected]4d3b05d2010-01-27 21:27:29612 RemoveConnectJob(job, &group);
[email protected]5fc08e32009-07-15 17:09:57613
[email protected]4d3b05d2010-01-27 21:27:29614 if (result == OK) {
615 DCHECK(socket.get());
[email protected]fd7b7c92009-08-20 19:38:30616 if (!group.pending_requests.empty()) {
[email protected]4d3b05d2010-01-27 21:27:29617 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]fd7b7c92009-08-20 19:38:30618 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17619 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29620 HandOutSocket(
621 socket.release(), false /* unused socket */, r->handle(),
[email protected]9e743cd2010-03-16 07:03:53622 base::TimeDelta(), &group, r->net_log());
[email protected]06650c52010-06-03 00:49:17623 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]4d3b05d2010-01-27 21:27:29624 r->callback()->Run(result);
[email protected]5fc08e32009-07-15 17:09:57625 } else {
[email protected]4d3b05d2010-01-27 21:27:29626 AddIdleSocket(socket.release(), false /* unused socket */, &group);
627 OnAvailableSocketSlot(group_name, &group);
[email protected]5fc08e32009-07-15 17:09:57628 }
[email protected]94c20472010-01-14 08:14:36629 } else {
[email protected]4d3b05d2010-01-27 21:27:29630 DCHECK(!socket.get());
631 if (!group.pending_requests.empty()) {
632 scoped_ptr<const Request> r(RemoveRequestFromQueue(
633 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17634 LogBoundConnectJobToRequest(job_log.source(), r.get());
635 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL,
636 new NetLogIntegerParameter("net_error", result));
[email protected]4d3b05d2010-01-27 21:27:29637 r->callback()->Run(result);
638 }
639 MaybeOnAvailableSocketSlot(group_name);
[email protected]ff579d42009-06-24 15:47:02640 }
[email protected]ff579d42009-06-24 15:47:02641}
642
[email protected]a7e38572010-06-07 18:22:24643void ClientSocketPoolBaseHelper::Flush() {
644 pool_generation_number_++;
[email protected]b6501d3d2010-06-03 23:53:34645 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52646 CloseIdleSockets();
647}
648
[email protected]4d3b05d2010-01-27 21:27:29649void ClientSocketPoolBaseHelper::RemoveConnectJob(const ConnectJob *job,
650 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33651 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53652 connecting_socket_count_--;
653
[email protected]4d3b05d2010-01-27 21:27:29654 DCHECK(job);
655 delete job;
[email protected]5fc08e32009-07-15 17:09:57656
657 if (group) {
658 DCHECK(ContainsKey(group->jobs, job));
659 group->jobs.erase(job);
660 }
[email protected]ff579d42009-06-24 15:47:02661}
662
[email protected]d80a4322009-08-14 07:07:49663void ClientSocketPoolBaseHelper::MaybeOnAvailableSocketSlot(
[email protected]2ab05b52009-07-01 23:57:58664 const std::string& group_name) {
665 GroupMap::iterator it = group_map_.find(group_name);
666 if (it != group_map_.end()) {
667 Group& group = it->second;
668 if (group.HasAvailableSocketSlot(max_sockets_per_group_))
669 OnAvailableSocketSlot(group_name, &group);
670 }
671}
[email protected]ff579d42009-06-24 15:47:02672
[email protected]d80a4322009-08-14 07:07:49673void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
674 const std::string& group_name, Group* group) {
[email protected]211d2172009-07-22 15:48:53675 if (may_have_stalled_group_) {
676 std::string top_group_name;
[email protected]bed37d442009-08-20 19:58:20677 Group* top_group = NULL;
[email protected]211d2172009-07-22 15:48:53678 int stalled_group_count = FindTopStalledGroup(&top_group, &top_group_name);
[email protected]d7027bb2010-05-10 18:58:54679 if (stalled_group_count == 0 ||
680 (stalled_group_count == 1 && top_group->num_releasing_sockets == 0)) {
[email protected]211d2172009-07-22 15:48:53681 may_have_stalled_group_ = false;
[email protected]d7027bb2010-05-10 18:58:54682 }
[email protected]93054cc12010-06-08 06:12:41683 if (stalled_group_count >= 1)
[email protected]211d2172009-07-22 15:48:53684 ProcessPendingRequest(top_group_name, top_group);
685 } else if (!group->pending_requests.empty()) {
[email protected]ff579d42009-06-24 15:47:02686 ProcessPendingRequest(group_name, group);
687 // |group| may no longer be valid after this point. Be careful not to
688 // access it again.
[email protected]2ab05b52009-07-01 23:57:58689 } else if (group->IsEmpty()) {
[email protected]ff579d42009-06-24 15:47:02690 // Delete |group| if no longer needed. |group| will no longer be valid.
[email protected]ff579d42009-06-24 15:47:02691 group_map_.erase(group_name);
[email protected]ff579d42009-06-24 15:47:02692 }
693}
694
[email protected]d80a4322009-08-14 07:07:49695void ClientSocketPoolBaseHelper::ProcessPendingRequest(
696 const std::string& group_name, Group* group) {
[email protected]e7e99322010-05-04 23:30:17697 int rv = RequestSocketInternal(group_name, *group->pending_requests.begin());
[email protected]ff579d42009-06-24 15:47:02698
[email protected]2ab05b52009-07-01 23:57:58699 if (rv != ERR_IO_PENDING) {
[email protected]e7e99322010-05-04 23:30:17700 scoped_ptr<const Request> r(RemoveRequestFromQueue(
701 group->pending_requests.begin(), &group->pending_requests));
[email protected]06650c52010-06-03 00:49:17702
703 scoped_refptr<NetLog::EventParameters> params;
704 if (rv != OK)
705 params = new NetLogIntegerParameter("net_error", rv);
706 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, params);
[email protected]d80a4322009-08-14 07:07:49707 r->callback()->Run(rv);
[email protected]2ab05b52009-07-01 23:57:58708 if (rv != OK) {
709 // |group| may be invalid after the callback, we need to search
710 // |group_map_| again.
711 MaybeOnAvailableSocketSlot(group_name);
712 }
[email protected]2ab05b52009-07-01 23:57:58713 }
714}
715
[email protected]d80a4322009-08-14 07:07:49716void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]2ab05b52009-07-01 23:57:58717 ClientSocket* socket,
718 bool reused,
719 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29720 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15721 Group* group,
[email protected]9e743cd2010-03-16 07:03:53722 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58723 DCHECK(socket);
724 handle->set_socket(socket);
725 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29726 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24727 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53728
[email protected]d13f51b2010-04-27 23:20:45729 if (reused) {
[email protected]ec11be62010-04-28 19:28:09730 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45731 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]ec11be62010-04-28 19:28:09732 new NetLogIntegerParameter(
733 "idle_ms", static_cast<int>(idle_time.InMilliseconds())));
[email protected]fd4fe0b2010-02-08 23:02:15734 }
[email protected]d13f51b2010-04-27 23:20:45735
[email protected]06650c52010-06-03 00:49:17736 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
737 new NetLogSourceParameter(
738 "source_dependency", socket->NetLog().source()));
[email protected]fd4fe0b2010-02-08 23:02:15739
[email protected]211d2172009-07-22 15:48:53740 handed_out_socket_count_++;
[email protected]2ab05b52009-07-01 23:57:58741 group->active_socket_count++;
[email protected]ff579d42009-06-24 15:47:02742}
743
[email protected]d80a4322009-08-14 07:07:49744void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]5fc08e32009-07-15 17:09:57745 ClientSocket* socket, bool used, Group* group) {
746 DCHECK(socket);
747 IdleSocket idle_socket;
748 idle_socket.socket = socket;
749 idle_socket.start_time = base::TimeTicks::Now();
750 idle_socket.used = used;
751
752 group->idle_sockets.push_back(idle_socket);
753 IncrementIdleCount();
754}
755
[email protected]d80a4322009-08-14 07:07:49756void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]5fc08e32009-07-15 17:09:57757 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
758 Group& group = i->second;
[email protected]4d3b05d2010-01-27 21:27:29759 connecting_socket_count_ -= group.jobs.size();
[email protected]5fc08e32009-07-15 17:09:57760 STLDeleteElements(&group.jobs);
761
[email protected]6b624c62010-03-14 08:37:32762 if (group.backup_task) {
763 group.backup_task->Cancel();
764 group.backup_task = NULL;
765 }
766
[email protected]5fc08e32009-07-15 17:09:57767 // Delete group if no longer needed.
768 if (group.IsEmpty()) {
[email protected]5fc08e32009-07-15 17:09:57769 group_map_.erase(i++);
770 } else {
771 ++i;
772 }
773 }
774}
775
[email protected]d80a4322009-08-14 07:07:49776bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53777 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54778 int total = handed_out_socket_count_ + connecting_socket_count_ +
779 idle_socket_count();
[email protected]211d2172009-07-22 15:48:53780 DCHECK_LE(total, max_sockets_);
[email protected]c901f6d2010-04-27 17:48:28781 if (total < max_sockets_)
782 return false;
783 LOG(WARNING) << "ReachedMaxSocketsLimit: " << total << "/" << max_sockets_;
784 return true;
[email protected]211d2172009-07-22 15:48:53785}
786
[email protected]43a21b82010-06-10 21:30:54787void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
788 CHECK_GT(idle_socket_count(), 0);
789
790 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
791 Group& group = i->second;
792
793 if (!group.idle_sockets.empty()) {
794 std::deque<IdleSocket>::iterator j = group.idle_sockets.begin();
795 delete j->socket;
796 group.idle_sockets.erase(j);
797 DecrementIdleCount();
798 if (group.IsEmpty())
799 group_map_.erase(i);
800
801 return;
802 }
803 }
804
805 LOG(DFATAL) << "No idle socket found to close!.";
806}
807
[email protected]d80a4322009-08-14 07:07:49808} // namespace internal
809
[email protected]ff579d42009-06-24 15:47:02810} // namespace net