blob: f584996c9647dbe383876428eca9961892c50245 [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]6b624c62010-03-14 08:37:32145 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
[email protected]211d2172009-07-22 15:48:53146 DCHECK_LE(0, max_sockets_per_group);
147 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52148
149 if (network_change_notifier_)
150 network_change_notifier_->AddObserver(this);
[email protected]211d2172009-07-22 15:48:53151}
[email protected]ff579d42009-06-24 15:47:02152
[email protected]d80a4322009-08-14 07:07:49153ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]4d3b05d2010-01-27 21:27:29154 CancelAllConnectJobs();
155
[email protected]ff579d42009-06-24 15:47:02156 // Clean up any idle sockets. Assert that we have no remaining active
157 // sockets or pending requests. They should have all been cleaned up prior
158 // to the manager being destroyed.
159 CloseIdleSockets();
[email protected]6b624c62010-03-14 08:37:32160 CHECK(group_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29161 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52162
163 if (network_change_notifier_)
164 network_change_notifier_->RemoveObserver(this);
[email protected]ff579d42009-06-24 15:47:02165}
166
167// InsertRequestIntoQueue inserts the request into the queue based on
168// priority. Highest priorities are closest to the front. Older requests are
169// prioritized over requests of equal priority.
170//
171// static
[email protected]d80a4322009-08-14 07:07:49172void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
173 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02174 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31175 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02176 ++it;
177 pending_requests->insert(it, r);
178}
179
[email protected]fd7b7c92009-08-20 19:38:30180// static
181const ClientSocketPoolBaseHelper::Request*
182ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
183 RequestQueue::iterator it, RequestQueue* pending_requests) {
184 const Request* req = *it;
[email protected]fd7b7c92009-08-20 19:38:30185 pending_requests->erase(it);
186 return req;
187}
188
[email protected]d80a4322009-08-14 07:07:49189int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02190 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49191 const Request* request) {
[email protected]ec11be62010-04-28 19:28:09192 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]fd4fe0b2010-02-08 23:02:15193 Group& group = group_map_[group_name];
194 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17195 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09196 request->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]e7e99322010-05-04 23:30:17197 delete request;
198 } else {
[email protected]fd4fe0b2010-02-08 23:02:15199 InsertRequestIntoQueue(request, &group.pending_requests);
[email protected]e7e99322010-05-04 23:30:17200 }
[email protected]fd4fe0b2010-02-08 23:02:15201 return rv;
202}
203
204int ClientSocketPoolBaseHelper::RequestSocketInternal(
205 const std::string& group_name,
206 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49207 DCHECK_GE(request->priority(), 0);
208 CompletionCallback* const callback = request->callback();
209 CHECK(callback);
210 ClientSocketHandle* const handle = request->handle();
211 CHECK(handle);
[email protected]ff579d42009-06-24 15:47:02212 Group& group = group_map_[group_name];
213
[email protected]4751c742010-05-19 02:44:36214 // Can we make another active socket now?
215 if (ReachedMaxSocketsLimit() ||
216 !group.HasAvailableSocketSlot(max_sockets_per_group_)) {
217 if (ReachedMaxSocketsLimit()) {
218 // We could check if we really have a stalled group here, but it requires
219 // a scan of all groups, so just flip a flag here, and do the check later.
220 may_have_stalled_group_ = true;
221
222 request->net_log().AddEvent(NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS,
223 NULL);
224 } else {
225 request->net_log().AddEvent(
226 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
227 }
228 return ERR_IO_PENDING;
229 }
230
[email protected]65552102010-04-09 22:58:10231 // Try to reuse a socket.
232 while (!group.idle_sockets.empty()) {
233 IdleSocket idle_socket = group.idle_sockets.back();
234 group.idle_sockets.pop_back();
235 DecrementIdleCount();
236 if (idle_socket.socket->IsConnectedAndIdle()) {
237 // We found one we can reuse!
238 base::TimeDelta idle_time =
239 base::TimeTicks::Now() - idle_socket.start_time;
240 HandOutSocket(
241 idle_socket.socket, idle_socket.used, handle, idle_time, &group,
242 request->net_log());
243 return OK;
244 }
245 delete idle_socket.socket;
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,
373 ClientSocket* socket) {
[email protected]5edbf8d2010-01-13 18:44:11374 Group& group = group_map_[group_name];
375 group.num_releasing_sockets++;
[email protected]d7027bb2010-05-10 18:58:54376 num_releasing_sockets_++;
[email protected]5edbf8d2010-01-13 18:44:11377 DCHECK_LE(group.num_releasing_sockets, group.active_socket_count);
[email protected]ff579d42009-06-24 15:47:02378 // Run this asynchronously to allow the caller to finish before we let
379 // another to begin doing work. This also avoids nasty recursion issues.
380 // NOTE: We cannot refer to the handle argument after this method returns.
381 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
[email protected]d80a4322009-08-14 07:07:49382 this, &ClientSocketPoolBaseHelper::DoReleaseSocket, group_name, socket));
[email protected]ff579d42009-06-24 15:47:02383}
384
[email protected]d80a4322009-08-14 07:07:49385void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02386 CleanupIdleSockets(true);
387}
388
[email protected]d80a4322009-08-14 07:07:49389int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02390 const std::string& group_name) const {
391 GroupMap::const_iterator i = group_map_.find(group_name);
392 CHECK(i != group_map_.end());
393
394 return i->second.idle_sockets.size();
395}
396
[email protected]d80a4322009-08-14 07:07:49397LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02398 const std::string& group_name,
399 const ClientSocketHandle* handle) const {
400 if (!ContainsKey(group_map_, group_name)) {
401 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
402 << " for handle: " << handle;
403 return LOAD_STATE_IDLE;
404 }
405
406 // Can't use operator[] since it is non-const.
407 const Group& group = group_map_.find(group_name)->second;
408
[email protected]ff579d42009-06-24 15:47:02409 // Search pending_requests for matching handle.
410 RequestQueue::const_iterator it = group.pending_requests.begin();
[email protected]5fc08e32009-07-15 17:09:57411 for (size_t i = 0; it != group.pending_requests.end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49412 if ((*it)->handle() == handle) {
[email protected]4d3b05d2010-01-27 21:27:29413 if (i < group.jobs.size()) {
[email protected]5fc08e32009-07-15 17:09:57414 LoadState max_state = LOAD_STATE_IDLE;
415 for (ConnectJobSet::const_iterator job_it = group.jobs.begin();
416 job_it != group.jobs.end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21417 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57418 }
419 return max_state;
420 } else {
421 // TODO(wtc): Add a state for being on the wait list.
422 // See http://www.crbug.com/5077.
423 return LOAD_STATE_IDLE;
424 }
[email protected]ff579d42009-06-24 15:47:02425 }
426 }
427
428 NOTREACHED();
429 return LOAD_STATE_IDLE;
430}
431
[email protected]d80a4322009-08-14 07:07:49432bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16433 base::TimeTicks now,
434 base::TimeDelta timeout) const {
435 bool timed_out = (now - start_time) >= timeout;
[email protected]5fc08e32009-07-15 17:09:57436 return timed_out ||
437 !(used ? socket->IsConnectedAndIdle() : socket->IsConnected());
[email protected]ff579d42009-06-24 15:47:02438}
439
[email protected]d80a4322009-08-14 07:07:49440void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02441 if (idle_socket_count_ == 0)
442 return;
443
444 // Current time value. Retrieving it once at the function start rather than
445 // inside the inner loop, since it shouldn't change by any meaningful amount.
446 base::TimeTicks now = base::TimeTicks::Now();
447
448 GroupMap::iterator i = group_map_.begin();
449 while (i != group_map_.end()) {
450 Group& group = i->second;
451
452 std::deque<IdleSocket>::iterator j = group.idle_sockets.begin();
453 while (j != group.idle_sockets.end()) {
[email protected]9bf28db2009-08-29 01:35:16454 base::TimeDelta timeout =
455 j->used ? used_idle_socket_timeout_ : unused_idle_socket_timeout_;
456 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02457 delete j->socket;
458 j = group.idle_sockets.erase(j);
459 DecrementIdleCount();
460 } else {
461 ++j;
462 }
463 }
464
465 // Delete group if no longer needed.
[email protected]2ab05b52009-07-01 23:57:58466 if (group.IsEmpty()) {
[email protected]ff579d42009-06-24 15:47:02467 group_map_.erase(i++);
468 } else {
469 ++i;
470 }
471 }
472}
473
[email protected]d80a4322009-08-14 07:07:49474void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02475 if (++idle_socket_count_ == 1)
476 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49477 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02478}
479
[email protected]d80a4322009-08-14 07:07:49480void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02481 if (--idle_socket_count_ == 0)
482 timer_.Stop();
483}
484
[email protected]d80a4322009-08-14 07:07:49485void ClientSocketPoolBaseHelper::DoReleaseSocket(const std::string& group_name,
486 ClientSocket* socket) {
[email protected]b6501d3d2010-06-03 23:53:34487 // Running callbacks can cause the last outside reference to be released.
488 // Hold onto a reference.
489 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
490
[email protected]ff579d42009-06-24 15:47:02491 GroupMap::iterator i = group_map_.find(group_name);
492 CHECK(i != group_map_.end());
493
494 Group& group = i->second;
495
[email protected]5edbf8d2010-01-13 18:44:11496 group.num_releasing_sockets--;
497 DCHECK_GE(group.num_releasing_sockets, 0);
498
[email protected]b1f031dd2010-03-02 23:19:33499 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53500 handed_out_socket_count_--;
501
[email protected]b1f031dd2010-03-02 23:19:33502 CHECK_GT(group.active_socket_count, 0);
[email protected]2ab05b52009-07-01 23:57:58503 group.active_socket_count--;
[email protected]ff579d42009-06-24 15:47:02504
[email protected]d7027bb2010-05-10 18:58:54505 CHECK_GT(num_releasing_sockets_, 0);
506 num_releasing_sockets_--;
507
[email protected]ff579d42009-06-24 15:47:02508 const bool can_reuse = socket->IsConnectedAndIdle();
509 if (can_reuse) {
[email protected]5fc08e32009-07-15 17:09:57510 AddIdleSocket(socket, true /* used socket */, &group);
[email protected]ff579d42009-06-24 15:47:02511 } else {
512 delete socket;
513 }
514
[email protected]4f2abec2010-02-03 18:10:16515 // If there are no more releasing sockets, then we might have to process
516 // multiple available socket slots, since we stalled their processing until
[email protected]d7027bb2010-05-10 18:58:54517 // all sockets have been released. Note that ProcessPendingRequest() will
518 // invoke user callbacks, so |num_releasing_sockets_| may change.
519 //
520 // This code has been known to infinite loop. Set a counter and CHECK to make
521 // sure it doesn't get ridiculously high.
[email protected]4f2abec2010-02-03 18:10:16522
[email protected]d7027bb2010-05-10 18:58:54523 int iterations = 0;
524 while (num_releasing_sockets_ == 0) {
525 CHECK_LT(iterations, 1000) << "Probably stuck in an infinite loop.";
526 std::string top_group_name;
527 Group* top_group = NULL;
528 int stalled_group_count = FindTopStalledGroup(&top_group, &top_group_name);
529 if (stalled_group_count >= 1) {
530 if (ReachedMaxSocketsLimit()) {
[email protected]4751c742010-05-19 02:44:36531 // We can't activate more sockets since we're already at our global
532 // limit.
533 may_have_stalled_group_ = true;
534 return;
[email protected]d7027bb2010-05-10 18:58:54535 }
536
537 ProcessPendingRequest(top_group_name, top_group);
538 } else {
539 may_have_stalled_group_ = false;
[email protected]4f2abec2010-02-03 18:10:16540 return;
[email protected]d7027bb2010-05-10 18:58:54541 }
[email protected]616925a2010-03-02 19:02:38542
[email protected]d7027bb2010-05-10 18:58:54543 iterations++;
[email protected]4f2abec2010-02-03 18:10:16544 }
[email protected]ff579d42009-06-24 15:47:02545}
546
[email protected]211d2172009-07-22 15:48:53547// Search for the highest priority pending request, amongst the groups that
548// are not at the |max_sockets_per_group_| limit. Note: for requests with
549// the same priority, the winner is based on group hash ordering (and not
550// insertion order).
[email protected]d80a4322009-08-14 07:07:49551int ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
552 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53553 Group* top_group = NULL;
554 const std::string* top_group_name = NULL;
555 int stalled_group_count = 0;
556 for (GroupMap::iterator i = group_map_.begin();
557 i != group_map_.end(); ++i) {
558 Group& group = i->second;
559 const RequestQueue& queue = group.pending_requests;
560 if (queue.empty())
561 continue;
[email protected]6427fe22010-04-16 22:27:41562 bool has_unused_slot =
563 group.HasAvailableSocketSlot(max_sockets_per_group_) &&
564 group.pending_requests.size() > group.jobs.size();
565 if (has_unused_slot) {
[email protected]211d2172009-07-22 15:48:53566 stalled_group_count++;
[email protected]6427fe22010-04-16 22:27:41567 bool has_higher_priority = !top_group ||
568 group.TopPendingPriority() < top_group->TopPendingPriority();
569 if (has_higher_priority) {
570 top_group = &group;
571 top_group_name = &i->first;
572 }
[email protected]211d2172009-07-22 15:48:53573 }
574 }
575 if (top_group) {
576 *group = top_group;
577 *group_name = *top_group_name;
578 }
579 return stalled_group_count;
580}
581
[email protected]d80a4322009-08-14 07:07:49582void ClientSocketPoolBaseHelper::OnConnectJobComplete(
583 int result, ConnectJob* job) {
[email protected]b6501d3d2010-06-03 23:53:34584 // Running callbacks can cause the last outside reference to be released.
585 // Hold onto a reference.
586 scoped_refptr<ClientSocketPoolBaseHelper> ref_holder(this);
587
[email protected]2ab05b52009-07-01 23:57:58588 DCHECK_NE(ERR_IO_PENDING, result);
589 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02590 GroupMap::iterator group_it = group_map_.find(group_name);
591 CHECK(group_it != group_map_.end());
592 Group& group = group_it->second;
593
[email protected]6b624c62010-03-14 08:37:32594 // We've had a connect on the socket; discard any pending backup job
595 // for this group and kill the pending task.
596 group.CleanupBackupJob();
597
[email protected]5fc08e32009-07-15 17:09:57598 scoped_ptr<ClientSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02599
[email protected]9e743cd2010-03-16 07:03:53600 BoundNetLog job_log = job->net_log();
[email protected]4d3b05d2010-01-27 21:27:29601 RemoveConnectJob(job, &group);
[email protected]5fc08e32009-07-15 17:09:57602
[email protected]4d3b05d2010-01-27 21:27:29603 if (result == OK) {
604 DCHECK(socket.get());
[email protected]fd7b7c92009-08-20 19:38:30605 if (!group.pending_requests.empty()) {
[email protected]4d3b05d2010-01-27 21:27:29606 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]fd7b7c92009-08-20 19:38:30607 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17608 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29609 HandOutSocket(
610 socket.release(), false /* unused socket */, r->handle(),
[email protected]9e743cd2010-03-16 07:03:53611 base::TimeDelta(), &group, r->net_log());
[email protected]06650c52010-06-03 00:49:17612 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]4d3b05d2010-01-27 21:27:29613 r->callback()->Run(result);
[email protected]5fc08e32009-07-15 17:09:57614 } else {
[email protected]4d3b05d2010-01-27 21:27:29615 AddIdleSocket(socket.release(), false /* unused socket */, &group);
616 OnAvailableSocketSlot(group_name, &group);
[email protected]5fc08e32009-07-15 17:09:57617 }
[email protected]94c20472010-01-14 08:14:36618 } else {
[email protected]4d3b05d2010-01-27 21:27:29619 DCHECK(!socket.get());
620 if (!group.pending_requests.empty()) {
621 scoped_ptr<const Request> r(RemoveRequestFromQueue(
622 group.pending_requests.begin(), &group.pending_requests));
[email protected]06650c52010-06-03 00:49:17623 LogBoundConnectJobToRequest(job_log.source(), r.get());
624 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL,
625 new NetLogIntegerParameter("net_error", result));
[email protected]4d3b05d2010-01-27 21:27:29626 r->callback()->Run(result);
627 }
628 MaybeOnAvailableSocketSlot(group_name);
[email protected]ff579d42009-06-24 15:47:02629 }
[email protected]ff579d42009-06-24 15:47:02630}
631
[email protected]a554a8262010-05-20 00:13:52632void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
[email protected]b6501d3d2010-06-03 23:53:34633 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52634 CloseIdleSockets();
635}
636
[email protected]4d3b05d2010-01-27 21:27:29637void ClientSocketPoolBaseHelper::RemoveConnectJob(const ConnectJob *job,
638 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33639 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53640 connecting_socket_count_--;
641
[email protected]4d3b05d2010-01-27 21:27:29642 DCHECK(job);
643 delete job;
[email protected]5fc08e32009-07-15 17:09:57644
645 if (group) {
646 DCHECK(ContainsKey(group->jobs, job));
647 group->jobs.erase(job);
648 }
[email protected]ff579d42009-06-24 15:47:02649}
650
[email protected]d80a4322009-08-14 07:07:49651void ClientSocketPoolBaseHelper::MaybeOnAvailableSocketSlot(
[email protected]2ab05b52009-07-01 23:57:58652 const std::string& group_name) {
653 GroupMap::iterator it = group_map_.find(group_name);
654 if (it != group_map_.end()) {
655 Group& group = it->second;
656 if (group.HasAvailableSocketSlot(max_sockets_per_group_))
657 OnAvailableSocketSlot(group_name, &group);
658 }
659}
[email protected]ff579d42009-06-24 15:47:02660
[email protected]d80a4322009-08-14 07:07:49661void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
662 const std::string& group_name, Group* group) {
[email protected]211d2172009-07-22 15:48:53663 if (may_have_stalled_group_) {
664 std::string top_group_name;
[email protected]bed37d442009-08-20 19:58:20665 Group* top_group = NULL;
[email protected]211d2172009-07-22 15:48:53666 int stalled_group_count = FindTopStalledGroup(&top_group, &top_group_name);
[email protected]d7027bb2010-05-10 18:58:54667 if (stalled_group_count == 0 ||
668 (stalled_group_count == 1 && top_group->num_releasing_sockets == 0)) {
[email protected]211d2172009-07-22 15:48:53669 may_have_stalled_group_ = false;
[email protected]d7027bb2010-05-10 18:58:54670 }
[email protected]4751c742010-05-19 02:44:36671 if (stalled_group_count >= 1)
[email protected]211d2172009-07-22 15:48:53672 ProcessPendingRequest(top_group_name, top_group);
673 } else if (!group->pending_requests.empty()) {
[email protected]ff579d42009-06-24 15:47:02674 ProcessPendingRequest(group_name, group);
675 // |group| may no longer be valid after this point. Be careful not to
676 // access it again.
[email protected]2ab05b52009-07-01 23:57:58677 } else if (group->IsEmpty()) {
[email protected]ff579d42009-06-24 15:47:02678 // Delete |group| if no longer needed. |group| will no longer be valid.
[email protected]ff579d42009-06-24 15:47:02679 group_map_.erase(group_name);
[email protected]ff579d42009-06-24 15:47:02680 }
681}
682
[email protected]d80a4322009-08-14 07:07:49683void ClientSocketPoolBaseHelper::ProcessPendingRequest(
684 const std::string& group_name, Group* group) {
[email protected]e7e99322010-05-04 23:30:17685 int rv = RequestSocketInternal(group_name, *group->pending_requests.begin());
[email protected]ff579d42009-06-24 15:47:02686
[email protected]2ab05b52009-07-01 23:57:58687 if (rv != ERR_IO_PENDING) {
[email protected]e7e99322010-05-04 23:30:17688 scoped_ptr<const Request> r(RemoveRequestFromQueue(
689 group->pending_requests.begin(), &group->pending_requests));
[email protected]06650c52010-06-03 00:49:17690
691 scoped_refptr<NetLog::EventParameters> params;
692 if (rv != OK)
693 params = new NetLogIntegerParameter("net_error", rv);
694 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, params);
[email protected]d80a4322009-08-14 07:07:49695 r->callback()->Run(rv);
[email protected]2ab05b52009-07-01 23:57:58696 if (rv != OK) {
697 // |group| may be invalid after the callback, we need to search
698 // |group_map_| again.
699 MaybeOnAvailableSocketSlot(group_name);
700 }
[email protected]2ab05b52009-07-01 23:57:58701 }
702}
703
[email protected]d80a4322009-08-14 07:07:49704void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]2ab05b52009-07-01 23:57:58705 ClientSocket* socket,
706 bool reused,
707 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29708 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15709 Group* group,
[email protected]9e743cd2010-03-16 07:03:53710 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58711 DCHECK(socket);
712 handle->set_socket(socket);
713 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29714 handle->set_idle_time(idle_time);
[email protected]211d2172009-07-22 15:48:53715
[email protected]d13f51b2010-04-27 23:20:45716 if (reused) {
[email protected]ec11be62010-04-28 19:28:09717 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45718 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]ec11be62010-04-28 19:28:09719 new NetLogIntegerParameter(
720 "idle_ms", static_cast<int>(idle_time.InMilliseconds())));
[email protected]fd4fe0b2010-02-08 23:02:15721 }
[email protected]d13f51b2010-04-27 23:20:45722
[email protected]06650c52010-06-03 00:49:17723 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
724 new NetLogSourceParameter(
725 "source_dependency", socket->NetLog().source()));
[email protected]fd4fe0b2010-02-08 23:02:15726
[email protected]211d2172009-07-22 15:48:53727 handed_out_socket_count_++;
[email protected]2ab05b52009-07-01 23:57:58728 group->active_socket_count++;
[email protected]ff579d42009-06-24 15:47:02729}
730
[email protected]d80a4322009-08-14 07:07:49731void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]5fc08e32009-07-15 17:09:57732 ClientSocket* socket, bool used, Group* group) {
733 DCHECK(socket);
734 IdleSocket idle_socket;
735 idle_socket.socket = socket;
736 idle_socket.start_time = base::TimeTicks::Now();
737 idle_socket.used = used;
738
739 group->idle_sockets.push_back(idle_socket);
740 IncrementIdleCount();
741}
742
[email protected]d80a4322009-08-14 07:07:49743void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]5fc08e32009-07-15 17:09:57744 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
745 Group& group = i->second;
[email protected]4d3b05d2010-01-27 21:27:29746 connecting_socket_count_ -= group.jobs.size();
[email protected]5fc08e32009-07-15 17:09:57747 STLDeleteElements(&group.jobs);
748
[email protected]6b624c62010-03-14 08:37:32749 if (group.backup_task) {
750 group.backup_task->Cancel();
751 group.backup_task = NULL;
752 }
753
[email protected]5fc08e32009-07-15 17:09:57754 // Delete group if no longer needed.
755 if (group.IsEmpty()) {
[email protected]5fc08e32009-07-15 17:09:57756 group_map_.erase(i++);
757 } else {
758 ++i;
759 }
760 }
761}
762
[email protected]d80a4322009-08-14 07:07:49763bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53764 // Each connecting socket will eventually connect and be handed out.
[email protected]4751c742010-05-19 02:44:36765 int total = handed_out_socket_count_ + connecting_socket_count_;
[email protected]211d2172009-07-22 15:48:53766 DCHECK_LE(total, max_sockets_);
[email protected]c901f6d2010-04-27 17:48:28767 if (total < max_sockets_)
768 return false;
769 LOG(WARNING) << "ReachedMaxSocketsLimit: " << total << "/" << max_sockets_;
770 return true;
[email protected]211d2172009-07-22 15:48:53771}
772
[email protected]d80a4322009-08-14 07:07:49773} // namespace internal
774
[email protected]ff579d42009-06-24 15:47:02775} // namespace net