blob: 40daa353d9c427bfd53c956a6d21d1e0456471c7 [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]66761b952010-06-25 21:30:38131 ConnectJobFactory* connect_job_factory)
[email protected]ff579d42009-06-24 15:47:02132 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53133 connecting_socket_count_(0),
134 handed_out_socket_count_(0),
[email protected]d7027bb2010-05-10 18:58:54135 num_releasing_sockets_(0),
[email protected]211d2172009-07-22 15:48:53136 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02137 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16138 unused_idle_socket_timeout_(unused_idle_socket_timeout),
139 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]211d2172009-07-22 15:48:53140 may_have_stalled_group_(false),
[email protected]100d5fb92009-12-21 21:08:35141 connect_job_factory_(connect_job_factory),
[email protected]7c28e9a2010-03-20 01:16:13142 backup_jobs_enabled_(false),
[email protected]a7e38572010-06-07 18:22:24143 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
144 pool_generation_number_(0) {
[email protected]211d2172009-07-22 15:48:53145 DCHECK_LE(0, max_sockets_per_group);
146 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52147
[email protected]66761b952010-06-25 21:30:38148 NetworkChangeNotifier::AddObserver(this);
[email protected]211d2172009-07-22 15:48:53149}
[email protected]ff579d42009-06-24 15:47:02150
[email protected]d80a4322009-08-14 07:07:49151ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]4d3b05d2010-01-27 21:27:29152 CancelAllConnectJobs();
153
[email protected]ff579d42009-06-24 15:47:02154 // Clean up any idle sockets. Assert that we have no remaining active
155 // sockets or pending requests. They should have all been cleaned up prior
156 // to the manager being destroyed.
157 CloseIdleSockets();
[email protected]6b624c62010-03-14 08:37:32158 CHECK(group_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29159 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52160
[email protected]66761b952010-06-25 21:30:38161 NetworkChangeNotifier::RemoveObserver(this);
[email protected]ff579d42009-06-24 15:47:02162}
163
164// InsertRequestIntoQueue inserts the request into the queue based on
165// priority. Highest priorities are closest to the front. Older requests are
166// prioritized over requests of equal priority.
167//
168// static
[email protected]d80a4322009-08-14 07:07:49169void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
170 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02171 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31172 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02173 ++it;
174 pending_requests->insert(it, r);
175}
176
[email protected]fd7b7c92009-08-20 19:38:30177// static
178const ClientSocketPoolBaseHelper::Request*
179ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
180 RequestQueue::iterator it, RequestQueue* pending_requests) {
181 const Request* req = *it;
[email protected]fd7b7c92009-08-20 19:38:30182 pending_requests->erase(it);
183 return req;
184}
185
[email protected]d80a4322009-08-14 07:07:49186int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02187 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49188 const Request* request) {
[email protected]ec11be62010-04-28 19:28:09189 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]fd4fe0b2010-02-08 23:02:15190 Group& group = group_map_[group_name];
191 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17192 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09193 request->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]e7e99322010-05-04 23:30:17194 delete request;
195 } else {
[email protected]fd4fe0b2010-02-08 23:02:15196 InsertRequestIntoQueue(request, &group.pending_requests);
[email protected]e7e99322010-05-04 23:30:17197 }
[email protected]fd4fe0b2010-02-08 23:02:15198 return rv;
199}
200
201int ClientSocketPoolBaseHelper::RequestSocketInternal(
202 const std::string& group_name,
203 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49204 DCHECK_GE(request->priority(), 0);
205 CompletionCallback* const callback = request->callback();
206 CHECK(callback);
207 ClientSocketHandle* const handle = request->handle();
208 CHECK(handle);
[email protected]ff579d42009-06-24 15:47:02209 Group& group = group_map_[group_name];
210
[email protected]65552102010-04-09 22:58:10211 // Try to reuse a socket.
212 while (!group.idle_sockets.empty()) {
213 IdleSocket idle_socket = group.idle_sockets.back();
214 group.idle_sockets.pop_back();
215 DecrementIdleCount();
216 if (idle_socket.socket->IsConnectedAndIdle()) {
217 // We found one we can reuse!
218 base::TimeDelta idle_time =
219 base::TimeTicks::Now() - idle_socket.start_time;
220 HandOutSocket(
221 idle_socket.socket, idle_socket.used, handle, idle_time, &group,
222 request->net_log());
223 return OK;
224 }
225 delete idle_socket.socket;
226 }
227
[email protected]43a21b82010-06-10 21:30:54228 // Can we make another active socket now?
229 if (!group.HasAvailableSocketSlot(max_sockets_per_group_)) {
230 request->net_log().AddEvent(
231 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
232 return ERR_IO_PENDING;
233 }
234
235 if (ReachedMaxSocketsLimit()) {
236 if (idle_socket_count() > 0) {
237 CloseOneIdleSocket();
238 } else {
239 // We could check if we really have a stalled group here, but it requires
240 // a scan of all groups, so just flip a flag here, and do the check later.
241 may_have_stalled_group_ = true;
242 request->net_log().AddEvent(
243 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
244 return ERR_IO_PENDING;
245 }
246 }
247
[email protected]5edbf8d2010-01-13 18:44:11248 // See if we already have enough connect jobs or sockets that will be released
249 // soon.
[email protected]4d3b05d2010-01-27 21:27:29250 if (group.HasReleasingSockets()) {
[email protected]5edbf8d2010-01-13 18:44:11251 return ERR_IO_PENDING;
252 }
253
[email protected]ff579d42009-06-24 15:47:02254 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58255 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17256 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02257
[email protected]2ab05b52009-07-01 23:57:58258 int rv = connect_job->Connect();
259 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17260 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2ab05b52009-07-01 23:57:58261 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
[email protected]9e743cd2010-03-16 07:03:53262 handle, base::TimeDelta(), &group, request->net_log());
[email protected]2ab05b52009-07-01 23:57:58263 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32264 // If we don't have any sockets in this group, set a timer for potentially
265 // creating a new one. If the SYN is lost, this backup socket may complete
266 // before the slow socket, improving end user latency.
[email protected]7c28e9a2010-03-20 01:16:13267 if (group.IsEmpty() && !group.backup_job && backup_jobs_enabled_) {
[email protected]6b624c62010-03-14 08:37:32268 group.backup_job = connect_job_factory_->NewConnectJob(group_name,
269 *request,
[email protected]06650c52010-06-03 00:49:17270 this);
[email protected]6b624c62010-03-14 08:37:32271 StartBackupSocketTimer(group_name);
272 }
273
[email protected]211d2172009-07-22 15:48:53274 connecting_socket_count_++;
275
[email protected]5fc08e32009-07-15 17:09:57276 ConnectJob* job = connect_job.release();
[email protected]5fc08e32009-07-15 17:09:57277 group.jobs.insert(job);
[email protected]a2006ece2010-04-23 16:44:02278 } else {
[email protected]06650c52010-06-03 00:49:17279 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]a2006ece2010-04-23 16:44:02280 if (group.IsEmpty())
281 group_map_.erase(group_name);
[email protected]2ab05b52009-07-01 23:57:58282 }
[email protected]ff579d42009-06-24 15:47:02283
[email protected]2ab05b52009-07-01 23:57:58284 return rv;
[email protected]ff579d42009-06-24 15:47:02285}
286
[email protected]06650c52010-06-03 00:49:17287// static
288void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
289 const NetLog::Source& connect_job_source, const Request* request) {
290 request->net_log().AddEvent(
291 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
292 new NetLogSourceParameter("source_dependency", connect_job_source));
293}
294
[email protected]6b624c62010-03-14 08:37:32295void ClientSocketPoolBaseHelper::StartBackupSocketTimer(
296 const std::string& group_name) {
297 CHECK(ContainsKey(group_map_, group_name));
298 Group& group = group_map_[group_name];
299
300 // Only allow one timer pending to create a backup socket.
301 if (group.backup_task)
302 return;
303
304 group.backup_task = method_factory_.NewRunnableMethod(
305 &ClientSocketPoolBaseHelper::OnBackupSocketTimerFired, group_name);
306 MessageLoop::current()->PostDelayedTask(FROM_HERE, group.backup_task,
307 ConnectRetryIntervalMs());
308}
309
310void ClientSocketPoolBaseHelper::OnBackupSocketTimerFired(
311 const std::string& group_name) {
312 CHECK(ContainsKey(group_map_, group_name));
313
314 Group& group = group_map_[group_name];
315
316 CHECK(group.backup_task);
317 group.backup_task = NULL;
318
319 CHECK(group.backup_job);
320
[email protected]c901f6d2010-04-27 17:48:28321 // If our backup job is waiting on DNS, or if we can't create any sockets
322 // right now due to limits, just reset the timer.
[email protected]6b624c62010-03-14 08:37:32323 CHECK(group.jobs.size());
[email protected]c901f6d2010-04-27 17:48:28324 if (ReachedMaxSocketsLimit() ||
325 !group.HasAvailableSocketSlot(max_sockets_per_group_) ||
326 (*group.jobs.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
[email protected]6b624c62010-03-14 08:37:32327 StartBackupSocketTimer(group_name);
328 return;
329 }
330
[email protected]ec11be62010-04-28 19:28:09331 group.backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED,
332 NULL);
[email protected]6b624c62010-03-14 08:37:32333 SIMPLE_STATS_COUNTER("socket.backup_created");
334 int rv = group.backup_job->Connect();
[email protected]c83658c2010-03-24 08:19:34335 connecting_socket_count_++;
336 group.jobs.insert(group.backup_job);
337 ConnectJob* job = group.backup_job;
338 group.backup_job = NULL;
339 if (rv != ERR_IO_PENDING)
340 OnConnectJobComplete(rv, job);
[email protected]6b624c62010-03-14 08:37:32341}
342
[email protected]d80a4322009-08-14 07:07:49343void ClientSocketPoolBaseHelper::CancelRequest(
344 const std::string& group_name, const ClientSocketHandle* handle) {
[email protected]b6501d3d2010-06-03 23:53:34345 // Running callbacks can cause the last outside reference to be released.
346 // Hold onto a reference.
347 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
348
[email protected]ff579d42009-06-24 15:47:02349 CHECK(ContainsKey(group_map_, group_name));
350
351 Group& group = group_map_[group_name];
352
[email protected]ff579d42009-06-24 15:47:02353 // Search pending_requests for matching handle.
354 RequestQueue::iterator it = group.pending_requests.begin();
355 for (; it != group.pending_requests.end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49356 if ((*it)->handle() == handle) {
[email protected]fd7b7c92009-08-20 19:38:30357 const Request* req = RemoveRequestFromQueue(it, &group.pending_requests);
[email protected]ec11be62010-04-28 19:28:09358 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
359 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]fd7b7c92009-08-20 19:38:30360 delete req;
[email protected]a796bcec2010-03-22 17:17:26361 // Let one connect job connect and become idle for potential future use.
[email protected]4d3b05d2010-01-27 21:27:29362 if (group.jobs.size() > group.pending_requests.size() + 1) {
[email protected]974ebd62009-08-03 23:14:34363 // TODO(willchan): Cancel the job in the earliest LoadState.
[email protected]4d3b05d2010-01-27 21:27:29364 RemoveConnectJob(*group.jobs.begin(), &group);
[email protected]974ebd62009-08-03 23:14:34365 OnAvailableSocketSlot(group_name, &group);
366 }
[email protected]ff579d42009-06-24 15:47:02367 return;
368 }
369 }
[email protected]ff579d42009-06-24 15:47:02370}
371
[email protected]d80a4322009-08-14 07:07:49372void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24373 ClientSocket* socket,
374 int id) {
[email protected]5edbf8d2010-01-13 18:44:11375 Group& group = group_map_[group_name];
376 group.num_releasing_sockets++;
[email protected]d7027bb2010-05-10 18:58:54377 num_releasing_sockets_++;
[email protected]5edbf8d2010-01-13 18:44:11378 DCHECK_LE(group.num_releasing_sockets, group.active_socket_count);
[email protected]ff579d42009-06-24 15:47:02379 // Run this asynchronously to allow the caller to finish before we let
380 // another to begin doing work. This also avoids nasty recursion issues.
381 // NOTE: We cannot refer to the handle argument after this method returns.
[email protected]66761b952010-06-25 21:30:38382 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
383 &ClientSocketPoolBaseHelper::DoReleaseSocket, group_name, socket, id));
[email protected]ff579d42009-06-24 15:47:02384}
385
[email protected]d80a4322009-08-14 07:07:49386void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02387 CleanupIdleSockets(true);
388}
389
[email protected]d80a4322009-08-14 07:07:49390int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02391 const std::string& group_name) const {
392 GroupMap::const_iterator i = group_map_.find(group_name);
393 CHECK(i != group_map_.end());
394
395 return i->second.idle_sockets.size();
396}
397
[email protected]d80a4322009-08-14 07:07:49398LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02399 const std::string& group_name,
400 const ClientSocketHandle* handle) const {
401 if (!ContainsKey(group_map_, group_name)) {
402 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
403 << " for handle: " << handle;
404 return LOAD_STATE_IDLE;
405 }
406
407 // Can't use operator[] since it is non-const.
408 const Group& group = group_map_.find(group_name)->second;
409
[email protected]ff579d42009-06-24 15:47:02410 // Search pending_requests for matching handle.
411 RequestQueue::const_iterator it = group.pending_requests.begin();
[email protected]5fc08e32009-07-15 17:09:57412 for (size_t i = 0; it != group.pending_requests.end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49413 if ((*it)->handle() == handle) {
[email protected]4d3b05d2010-01-27 21:27:29414 if (i < group.jobs.size()) {
[email protected]5fc08e32009-07-15 17:09:57415 LoadState max_state = LOAD_STATE_IDLE;
416 for (ConnectJobSet::const_iterator job_it = group.jobs.begin();
417 job_it != group.jobs.end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21418 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57419 }
420 return max_state;
421 } else {
422 // TODO(wtc): Add a state for being on the wait list.
423 // See http://www.crbug.com/5077.
424 return LOAD_STATE_IDLE;
425 }
[email protected]ff579d42009-06-24 15:47:02426 }
427 }
428
429 NOTREACHED();
430 return LOAD_STATE_IDLE;
431}
432
[email protected]d80a4322009-08-14 07:07:49433bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16434 base::TimeTicks now,
435 base::TimeDelta timeout) const {
436 bool timed_out = (now - start_time) >= timeout;
[email protected]5fc08e32009-07-15 17:09:57437 return timed_out ||
438 !(used ? socket->IsConnectedAndIdle() : socket->IsConnected());
[email protected]ff579d42009-06-24 15:47:02439}
440
[email protected]d80a4322009-08-14 07:07:49441void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02442 if (idle_socket_count_ == 0)
443 return;
444
445 // Current time value. Retrieving it once at the function start rather than
446 // inside the inner loop, since it shouldn't change by any meaningful amount.
447 base::TimeTicks now = base::TimeTicks::Now();
448
449 GroupMap::iterator i = group_map_.begin();
450 while (i != group_map_.end()) {
451 Group& group = i->second;
452
453 std::deque<IdleSocket>::iterator j = group.idle_sockets.begin();
454 while (j != group.idle_sockets.end()) {
[email protected]9bf28db2009-08-29 01:35:16455 base::TimeDelta timeout =
456 j->used ? used_idle_socket_timeout_ : unused_idle_socket_timeout_;
457 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02458 delete j->socket;
459 j = group.idle_sockets.erase(j);
460 DecrementIdleCount();
461 } else {
462 ++j;
463 }
464 }
465
466 // Delete group if no longer needed.
[email protected]2ab05b52009-07-01 23:57:58467 if (group.IsEmpty()) {
[email protected]ff579d42009-06-24 15:47:02468 group_map_.erase(i++);
469 } else {
470 ++i;
471 }
472 }
473}
474
[email protected]d80a4322009-08-14 07:07:49475void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02476 if (++idle_socket_count_ == 1)
477 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49478 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02479}
480
[email protected]d80a4322009-08-14 07:07:49481void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02482 if (--idle_socket_count_ == 0)
483 timer_.Stop();
484}
485
[email protected]d80a4322009-08-14 07:07:49486void ClientSocketPoolBaseHelper::DoReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24487 ClientSocket* socket,
488 int id) {
[email protected]b6501d3d2010-06-03 23:53:34489 // Running callbacks can cause the last outside reference to be released.
490 // Hold onto a reference.
491 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
492
[email protected]ff579d42009-06-24 15:47:02493 GroupMap::iterator i = group_map_.find(group_name);
494 CHECK(i != group_map_.end());
495
496 Group& group = i->second;
497
[email protected]5edbf8d2010-01-13 18:44:11498 group.num_releasing_sockets--;
499 DCHECK_GE(group.num_releasing_sockets, 0);
500
[email protected]b1f031dd2010-03-02 23:19:33501 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53502 handed_out_socket_count_--;
503
[email protected]b1f031dd2010-03-02 23:19:33504 CHECK_GT(group.active_socket_count, 0);
[email protected]2ab05b52009-07-01 23:57:58505 group.active_socket_count--;
[email protected]ff579d42009-06-24 15:47:02506
[email protected]d7027bb2010-05-10 18:58:54507 CHECK_GT(num_releasing_sockets_, 0);
508 num_releasing_sockets_--;
509
[email protected]a7e38572010-06-07 18:22:24510 const bool can_reuse = socket->IsConnectedAndIdle() &&
511 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02512 if (can_reuse) {
[email protected]5fc08e32009-07-15 17:09:57513 AddIdleSocket(socket, true /* used socket */, &group);
[email protected]ff579d42009-06-24 15:47:02514 } else {
515 delete socket;
516 }
517
[email protected]4f2abec2010-02-03 18:10:16518 // If there are no more releasing sockets, then we might have to process
519 // multiple available socket slots, since we stalled their processing until
[email protected]d7027bb2010-05-10 18:58:54520 // all sockets have been released. Note that ProcessPendingRequest() will
521 // invoke user callbacks, so |num_releasing_sockets_| may change.
522 //
523 // This code has been known to infinite loop. Set a counter and CHECK to make
524 // sure it doesn't get ridiculously high.
[email protected]4f2abec2010-02-03 18:10:16525
[email protected]d7027bb2010-05-10 18:58:54526 int iterations = 0;
527 while (num_releasing_sockets_ == 0) {
528 CHECK_LT(iterations, 1000) << "Probably stuck in an infinite loop.";
529 std::string top_group_name;
530 Group* top_group = NULL;
531 int stalled_group_count = FindTopStalledGroup(&top_group, &top_group_name);
532 if (stalled_group_count >= 1) {
533 if (ReachedMaxSocketsLimit()) {
[email protected]43a21b82010-06-10 21:30:54534 if (idle_socket_count() > 0) {
535 CloseOneIdleSocket();
536 } else {
537 // We can't activate more sockets since we're already at our global
538 // limit.
539 may_have_stalled_group_ = true;
540 return;
541 }
[email protected]d7027bb2010-05-10 18:58:54542 }
543
544 ProcessPendingRequest(top_group_name, top_group);
545 } else {
546 may_have_stalled_group_ = false;
[email protected]4f2abec2010-02-03 18:10:16547 return;
[email protected]d7027bb2010-05-10 18:58:54548 }
[email protected]616925a2010-03-02 19:02:38549
[email protected]d7027bb2010-05-10 18:58:54550 iterations++;
[email protected]4f2abec2010-02-03 18:10:16551 }
[email protected]ff579d42009-06-24 15:47:02552}
553
[email protected]211d2172009-07-22 15:48:53554// Search for the highest priority pending request, amongst the groups that
555// are not at the |max_sockets_per_group_| limit. Note: for requests with
556// the same priority, the winner is based on group hash ordering (and not
557// insertion order).
[email protected]d80a4322009-08-14 07:07:49558int ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
559 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53560 Group* top_group = NULL;
561 const std::string* top_group_name = NULL;
562 int stalled_group_count = 0;
563 for (GroupMap::iterator i = group_map_.begin();
564 i != group_map_.end(); ++i) {
565 Group& group = i->second;
566 const RequestQueue& queue = group.pending_requests;
567 if (queue.empty())
568 continue;
[email protected]6427fe22010-04-16 22:27:41569 bool has_unused_slot =
570 group.HasAvailableSocketSlot(max_sockets_per_group_) &&
571 group.pending_requests.size() > group.jobs.size();
572 if (has_unused_slot) {
[email protected]211d2172009-07-22 15:48:53573 stalled_group_count++;
[email protected]6427fe22010-04-16 22:27:41574 bool has_higher_priority = !top_group ||
575 group.TopPendingPriority() < top_group->TopPendingPriority();
576 if (has_higher_priority) {
577 top_group = &group;
578 top_group_name = &i->first;
579 }
[email protected]211d2172009-07-22 15:48:53580 }
581 }
582 if (top_group) {
583 *group = top_group;
584 *group_name = *top_group_name;
585 }
586 return stalled_group_count;
587}
588
[email protected]d80a4322009-08-14 07:07:49589void ClientSocketPoolBaseHelper::OnConnectJobComplete(
590 int result, ConnectJob* job) {
[email protected]b6501d3d2010-06-03 23:53:34591 // Running callbacks can cause the last outside reference to be released.
592 // Hold onto a reference.
593 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
594
[email protected]2ab05b52009-07-01 23:57:58595 DCHECK_NE(ERR_IO_PENDING, result);
596 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02597 GroupMap::iterator group_it = group_map_.find(group_name);
598 CHECK(group_it != group_map_.end());
599 Group& group = group_it->second;
600
[email protected]6b624c62010-03-14 08:37:32601 // We've had a connect on the socket; discard any pending backup job
602 // for this group and kill the pending task.
603 group.CleanupBackupJob();
604
[email protected]5fc08e32009-07-15 17:09:57605 scoped_ptr<ClientSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02606
[email protected]9e743cd2010-03-16 07:03:53607 BoundNetLog job_log = job->net_log();
[email protected]4d3b05d2010-01-27 21:27:29608 RemoveConnectJob(job, &group);
[email protected]5fc08e32009-07-15 17:09:57609
[email protected]4d3b05d2010-01-27 21:27:29610 if (result == OK) {
611 DCHECK(socket.get());
[email protected]fd7b7c92009-08-20 19:38:30612 if (!group.pending_requests.empty()) {
[email protected]4d3b05d2010-01-27 21:27:29613 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]fd7b7c92009-08-20 19:38:30614 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17615 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29616 HandOutSocket(
617 socket.release(), false /* unused socket */, r->handle(),
[email protected]9e743cd2010-03-16 07:03:53618 base::TimeDelta(), &group, r->net_log());
[email protected]06650c52010-06-03 00:49:17619 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]4d3b05d2010-01-27 21:27:29620 r->callback()->Run(result);
[email protected]5fc08e32009-07-15 17:09:57621 } else {
[email protected]4d3b05d2010-01-27 21:27:29622 AddIdleSocket(socket.release(), false /* unused socket */, &group);
623 OnAvailableSocketSlot(group_name, &group);
[email protected]5fc08e32009-07-15 17:09:57624 }
[email protected]94c20472010-01-14 08:14:36625 } else {
[email protected]4d3b05d2010-01-27 21:27:29626 DCHECK(!socket.get());
627 if (!group.pending_requests.empty()) {
628 scoped_ptr<const Request> r(RemoveRequestFromQueue(
629 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17630 LogBoundConnectJobToRequest(job_log.source(), r.get());
631 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL,
632 new NetLogIntegerParameter("net_error", result));
[email protected]4d3b05d2010-01-27 21:27:29633 r->callback()->Run(result);
634 }
635 MaybeOnAvailableSocketSlot(group_name);
[email protected]ff579d42009-06-24 15:47:02636 }
[email protected]ff579d42009-06-24 15:47:02637}
638
[email protected]66761b952010-06-25 21:30:38639void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
640 Flush();
641}
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