blob: ddcbba62841b7995cf81bd8c25b7498b98e9ea47 [file] [log] [blame]
[email protected]5acdce12011-03-30 13:00:201// Copyright (c) 2011 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]835d7c82010-10-14 04:38:3810#include "base/metrics/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]9349cfb2010-08-31 18:00:5314#include "base/values.h"
[email protected]9e743cd2010-03-16 07:03:5315#include "net/base/net_log.h"
[email protected]ff579d42009-06-24 15:47:0216#include "net/base/net_errors.h"
17#include "net/socket/client_socket_handle.h"
18
19using base::TimeDelta;
20
21namespace {
22
23// The timeout value, in seconds, used to clean up idle sockets that can't be
24// reused.
25//
26// Note: It's important to close idle sockets that have received data as soon
27// as possible because the received data may cause BSOD on Windows XP under
28// some conditions. See http://crbug.com/4606.
29const int kCleanupInterval = 10; // DO NOT INCREASE THIS TIMEOUT.
30
[email protected]c847c2a2011-04-08 13:56:1431// Indicate whether or not we should establish a new transport layer connection
32// after a certain timeout has passed without receiving an ACK.
[email protected]06d94042010-08-25 01:45:2233bool g_connect_backup_jobs_enabled = true;
34
[email protected]ff579d42009-06-24 15:47:0235} // namespace
36
37namespace net {
38
[email protected]2ab05b52009-07-01 23:57:5839ConnectJob::ConnectJob(const std::string& group_name,
[email protected]974ebd62009-08-03 23:14:3440 base::TimeDelta timeout_duration,
[email protected]fd7b7c92009-08-20 19:38:3041 Delegate* delegate,
[email protected]9e743cd2010-03-16 07:03:5342 const BoundNetLog& net_log)
[email protected]2ab05b52009-07-01 23:57:5843 : group_name_(group_name),
[email protected]974ebd62009-08-03 23:14:3444 timeout_duration_(timeout_duration),
[email protected]2ab05b52009-07-01 23:57:5845 delegate_(delegate),
[email protected]a2006ece2010-04-23 16:44:0246 net_log_(net_log),
[email protected]2c2bef152010-10-13 00:55:0347 idle_(true),
48 preconnect_state_(NOT_PRECONNECT) {
[email protected]2ab05b52009-07-01 23:57:5849 DCHECK(!group_name.empty());
[email protected]2ab05b52009-07-01 23:57:5850 DCHECK(delegate);
[email protected]06650c52010-06-03 00:49:1751 net_log.BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]2ab05b52009-07-01 23:57:5852}
53
[email protected]fd7b7c92009-08-20 19:38:3054ConnectJob::~ConnectJob() {
[email protected]06650c52010-06-03 00:49:1755 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]fd7b7c92009-08-20 19:38:3056}
[email protected]2ab05b52009-07-01 23:57:5857
[email protected]2c2bef152010-10-13 00:55:0358void ConnectJob::Initialize(bool is_preconnect) {
59 if (is_preconnect)
60 preconnect_state_ = UNUSED_PRECONNECT;
61 else
62 preconnect_state_ = NOT_PRECONNECT;
63}
64
[email protected]974ebd62009-08-03 23:14:3465int ConnectJob::Connect() {
66 if (timeout_duration_ != base::TimeDelta())
67 timer_.Start(timeout_duration_, this, &ConnectJob::OnTimeout);
[email protected]fd7b7c92009-08-20 19:38:3068
[email protected]a2006ece2010-04-23 16:44:0269 idle_ = false;
[email protected]fd7b7c92009-08-20 19:38:3070
[email protected]06650c52010-06-03 00:49:1771 LogConnectStart();
72
[email protected]fd7b7c92009-08-20 19:38:3073 int rv = ConnectInternal();
74
75 if (rv != ERR_IO_PENDING) {
[email protected]06650c52010-06-03 00:49:1776 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:3077 delegate_ = NULL;
[email protected]fd7b7c92009-08-20 19:38:3078 }
79
80 return rv;
81}
82
[email protected]2c2bef152010-10-13 00:55:0383void ConnectJob::UseForNormalRequest() {
84 DCHECK_EQ(UNUSED_PRECONNECT, preconnect_state_);
85 preconnect_state_ = USED_PRECONNECT;
86}
87
[email protected]3268023f2011-05-05 00:08:1088void ConnectJob::set_socket(StreamSocket* socket) {
[email protected]06650c52010-06-03 00:49:1789 if (socket) {
[email protected]00cd9c42010-11-02 20:15:5790 net_log().AddEvent(NetLog::TYPE_CONNECT_JOB_SET_SOCKET, make_scoped_refptr(
91 new NetLogSourceParameter("source_dependency",
92 socket->NetLog().source())));
[email protected]06650c52010-06-03 00:49:1793 }
94 socket_.reset(socket);
95}
96
[email protected]fd7b7c92009-08-20 19:38:3097void ConnectJob::NotifyDelegateOfCompletion(int rv) {
98 // The delegate will delete |this|.
99 Delegate *delegate = delegate_;
100 delegate_ = NULL;
101
[email protected]06650c52010-06-03 00:49:17102 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:30103 delegate->OnConnectJobComplete(rv, this);
[email protected]974ebd62009-08-03 23:14:34104}
105
[email protected]a796bcec2010-03-22 17:17:26106void ConnectJob::ResetTimer(base::TimeDelta remaining_time) {
107 timer_.Stop();
108 timer_.Start(remaining_time, this, &ConnectJob::OnTimeout);
109}
110
[email protected]06650c52010-06-03 00:49:17111void ConnectJob::LogConnectStart() {
112 net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT,
[email protected]00cd9c42010-11-02 20:15:57113 make_scoped_refptr(new NetLogStringParameter("group_name", group_name_)));
[email protected]06650c52010-06-03 00:49:17114}
115
116void ConnectJob::LogConnectCompletion(int net_error) {
[email protected]d7fd1782011-02-08 19:16:43117 net_log().EndEventWithNetErrorCode(
118 NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT, net_error);
[email protected]06650c52010-06-03 00:49:17119}
120
[email protected]974ebd62009-08-03 23:14:34121void ConnectJob::OnTimeout() {
[email protected]6e713f02009-08-06 02:56:40122 // Make sure the socket is NULL before calling into |delegate|.
123 set_socket(NULL);
[email protected]fd7b7c92009-08-20 19:38:30124
[email protected]ec11be62010-04-28 19:28:09125 net_log_.AddEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_TIMED_OUT, NULL);
[email protected]fd7b7c92009-08-20 19:38:30126
127 NotifyDelegateOfCompletion(ERR_TIMED_OUT);
[email protected]974ebd62009-08-03 23:14:34128}
129
[email protected]d80a4322009-08-14 07:07:49130namespace internal {
131
[email protected]fd4fe0b2010-02-08 23:02:15132ClientSocketPoolBaseHelper::Request::Request(
133 ClientSocketHandle* handle,
134 CompletionCallback* callback,
135 RequestPriority priority,
[email protected]5acdce12011-03-30 13:00:20136 bool ignore_limits,
[email protected]2c2bef152010-10-13 00:55:03137 Flags flags,
[email protected]9e743cd2010-03-16 07:03:53138 const BoundNetLog& net_log)
[email protected]2431756e2010-09-29 20:26:13139 : handle_(handle),
140 callback_(callback),
141 priority_(priority),
[email protected]5acdce12011-03-30 13:00:20142 ignore_limits_(ignore_limits),
[email protected]2c2bef152010-10-13 00:55:03143 flags_(flags),
[email protected]9e743cd2010-03-16 07:03:53144 net_log_(net_log) {}
[email protected]fd4fe0b2010-02-08 23:02:15145
146ClientSocketPoolBaseHelper::Request::~Request() {}
147
[email protected]d80a4322009-08-14 07:07:49148ClientSocketPoolBaseHelper::ClientSocketPoolBaseHelper(
[email protected]211d2172009-07-22 15:48:53149 int max_sockets,
[email protected]ff579d42009-06-24 15:47:02150 int max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16151 base::TimeDelta unused_idle_socket_timeout,
152 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38153 ConnectJobFactory* connect_job_factory)
[email protected]ff579d42009-06-24 15:47:02154 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53155 connecting_socket_count_(0),
156 handed_out_socket_count_(0),
157 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02158 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16159 unused_idle_socket_timeout_(unused_idle_socket_timeout),
160 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]100d5fb92009-12-21 21:08:35161 connect_job_factory_(connect_job_factory),
[email protected]06d94042010-08-25 01:45:22162 connect_backup_jobs_enabled_(false),
[email protected]2431756e2010-09-29 20:26:13163 pool_generation_number_(0),
164 method_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
[email protected]211d2172009-07-22 15:48:53165 DCHECK_LE(0, max_sockets_per_group);
166 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52167
[email protected]232a5812011-03-04 22:42:08168 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]211d2172009-07-22 15:48:53169}
[email protected]ff579d42009-06-24 15:47:02170
[email protected]d80a4322009-08-14 07:07:49171ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]2431756e2010-09-29 20:26:13172 // Clean up any idle sockets and pending connect jobs. Assert that we have no
173 // remaining active sockets or pending requests. They should have all been
174 // cleaned up prior to |this| being destroyed.
175 Flush();
176 DCHECK(group_map_.empty());
[email protected]05ea9ff2010-07-15 19:08:21177 DCHECK(pending_callback_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29178 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52179
[email protected]232a5812011-03-04 22:42:08180 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]ff579d42009-06-24 15:47:02181}
182
183// InsertRequestIntoQueue inserts the request into the queue based on
184// priority. Highest priorities are closest to the front. Older requests are
185// prioritized over requests of equal priority.
186//
187// static
[email protected]d80a4322009-08-14 07:07:49188void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
189 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02190 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31191 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02192 ++it;
193 pending_requests->insert(it, r);
194}
195
[email protected]fd7b7c92009-08-20 19:38:30196// static
197const ClientSocketPoolBaseHelper::Request*
198ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
[email protected]417da102011-03-11 17:45:05199 const RequestQueue::iterator& it, Group* group) {
[email protected]fd7b7c92009-08-20 19:38:30200 const Request* req = *it;
[email protected]3f00be82010-09-27 19:50:02201 group->mutable_pending_requests()->erase(it);
202 // If there are no more requests, we kill the backup timer.
203 if (group->pending_requests().empty())
[email protected]e4d9a9722011-05-12 00:16:00204 group->CleanupBackupJob();
[email protected]fd7b7c92009-08-20 19:38:30205 return req;
206}
207
[email protected]d80a4322009-08-14 07:07:49208int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02209 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49210 const Request* request) {
[email protected]2c2bef152010-10-13 00:55:03211 CHECK(request->callback());
212 CHECK(request->handle());
213
[email protected]ec11be62010-04-28 19:28:09214 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]aed99ef02010-08-26 14:04:32215 Group* group = GetOrCreateGroup(group_name);
[email protected]eb5a99382010-07-11 03:18:26216
[email protected]fd4fe0b2010-02-08 23:02:15217 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17218 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:43219 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21220 CHECK(!request->handle()->is_initialized());
[email protected]e7e99322010-05-04 23:30:17221 delete request;
222 } else {
[email protected]aed99ef02010-08-26 14:04:32223 InsertRequestIntoQueue(request, group->mutable_pending_requests());
[email protected]e7e99322010-05-04 23:30:17224 }
[email protected]fd4fe0b2010-02-08 23:02:15225 return rv;
226}
227
[email protected]2c2bef152010-10-13 00:55:03228void ClientSocketPoolBaseHelper::RequestSockets(
229 const std::string& group_name,
230 const Request& request,
231 int num_sockets) {
232 DCHECK(!request.callback());
233 DCHECK(!request.handle());
234
235 if (num_sockets > max_sockets_per_group_) {
[email protected]2c2bef152010-10-13 00:55:03236 num_sockets = max_sockets_per_group_;
237 }
238
239 request.net_log().BeginEvent(
240 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS,
[email protected]00cd9c42010-11-02 20:15:57241 make_scoped_refptr(new NetLogIntegerParameter(
242 "num_sockets", num_sockets)));
[email protected]2c2bef152010-10-13 00:55:03243
244 Group* group = GetOrCreateGroup(group_name);
245
[email protected]3c819f522010-12-02 02:03:12246 // RequestSocketsInternal() may delete the group.
247 bool deleted_group = false;
248
[email protected]d7fd1782011-02-08 19:16:43249 int rv = OK;
[email protected]2c2bef152010-10-13 00:55:03250 for (int num_iterations_left = num_sockets;
251 group->NumActiveSocketSlots() < num_sockets &&
252 num_iterations_left > 0 ; num_iterations_left--) {
[email protected]d7fd1782011-02-08 19:16:43253 rv = RequestSocketInternal(group_name, &request);
[email protected]2c2bef152010-10-13 00:55:03254 if (rv < 0 && rv != ERR_IO_PENDING) {
255 // We're encountering a synchronous error. Give up.
[email protected]3c819f522010-12-02 02:03:12256 if (!ContainsKey(group_map_, group_name))
257 deleted_group = true;
258 break;
259 }
260 if (!ContainsKey(group_map_, group_name)) {
261 // Unexpected. The group should only be getting deleted on synchronous
262 // error.
263 NOTREACHED();
264 deleted_group = true;
[email protected]2c2bef152010-10-13 00:55:03265 break;
266 }
267 }
268
[email protected]3c819f522010-12-02 02:03:12269 if (!deleted_group && group->IsEmpty())
[email protected]2c2bef152010-10-13 00:55:03270 RemoveGroup(group_name);
271
[email protected]d7fd1782011-02-08 19:16:43272 if (rv == ERR_IO_PENDING)
273 rv = OK;
274 request.net_log().EndEventWithNetErrorCode(
275 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS, rv);
[email protected]2c2bef152010-10-13 00:55:03276}
277
[email protected]fd4fe0b2010-02-08 23:02:15278int ClientSocketPoolBaseHelper::RequestSocketInternal(
279 const std::string& group_name,
280 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49281 DCHECK_GE(request->priority(), 0);
[email protected]d80a4322009-08-14 07:07:49282 ClientSocketHandle* const handle = request->handle();
[email protected]2c2bef152010-10-13 00:55:03283 const bool preconnecting = !handle;
[email protected]aed99ef02010-08-26 14:04:32284 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02285
[email protected]2c2bef152010-10-13 00:55:03286 if (!(request->flags() & NO_IDLE_SOCKETS)) {
287 // Try to reuse a socket.
288 if (AssignIdleSocketToGroup(request, group))
289 return OK;
290 }
291
292 if (!preconnecting && group->TryToUsePreconnectConnectJob())
293 return ERR_IO_PENDING;
[email protected]65552102010-04-09 22:58:10294
[email protected]43a21b82010-06-10 21:30:54295 // Can we make another active socket now?
[email protected]5acdce12011-03-30 13:00:20296 if (!group->HasAvailableSocketSlot(max_sockets_per_group_) &&
297 !request->ignore_limits()) {
[email protected]43a21b82010-06-10 21:30:54298 request->net_log().AddEvent(
299 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
300 return ERR_IO_PENDING;
301 }
302
[email protected]5acdce12011-03-30 13:00:20303 if (ReachedMaxSocketsLimit() && !request->ignore_limits()) {
[email protected]43a21b82010-06-10 21:30:54304 if (idle_socket_count() > 0) {
[email protected]dcbe168a2010-12-02 03:14:46305 bool closed = CloseOneIdleSocketExceptInGroup(group);
306 if (preconnecting && !closed)
307 return ERR_PRECONNECT_MAX_SOCKET_LIMIT;
[email protected]43a21b82010-06-10 21:30:54308 } else {
309 // We could check if we really have a stalled group here, but it requires
310 // a scan of all groups, so just flip a flag here, and do the check later.
[email protected]43a21b82010-06-10 21:30:54311 request->net_log().AddEvent(
312 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
313 return ERR_IO_PENDING;
314 }
315 }
316
[email protected]ff579d42009-06-24 15:47:02317 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58318 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17319 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02320
[email protected]2c2bef152010-10-13 00:55:03321 connect_job->Initialize(preconnecting);
[email protected]2ab05b52009-07-01 23:57:58322 int rv = connect_job->Connect();
323 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17324 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2c2bef152010-10-13 00:55:03325 if (!preconnecting) {
326 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
327 handle, base::TimeDelta(), group, request->net_log());
328 } else {
329 AddIdleSocket(connect_job->ReleaseSocket(), group);
330 }
[email protected]2ab05b52009-07-01 23:57:58331 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32332 // If we don't have any sockets in this group, set a timer for potentially
333 // creating a new one. If the SYN is lost, this backup socket may complete
334 // before the slow socket, improving end user latency.
[email protected]2c2bef152010-10-13 00:55:03335 if (connect_backup_jobs_enabled_ &&
[email protected]e4d9a9722011-05-12 00:16:00336 group->IsEmpty() && !group->HasBackupJob()) {
[email protected]aed99ef02010-08-26 14:04:32337 group->StartBackupSocketTimer(group_name, this);
[email protected]2c2bef152010-10-13 00:55:03338 }
[email protected]6b624c62010-03-14 08:37:32339
[email protected]211d2172009-07-22 15:48:53340 connecting_socket_count_++;
341
[email protected]aed99ef02010-08-26 14:04:32342 group->AddJob(connect_job.release());
[email protected]a2006ece2010-04-23 16:44:02343 } else {
[email protected]06650c52010-06-03 00:49:17344 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]3268023f2011-05-05 00:08:10345 StreamSocket* error_socket = NULL;
[email protected]fd2e53e2011-01-14 20:40:52346 if (!preconnecting) {
347 DCHECK(handle);
348 connect_job->GetAdditionalErrorState(handle);
349 error_socket = connect_job->ReleaseSocket();
350 }
[email protected]e772db3f2010-07-12 18:11:13351 if (error_socket) {
352 HandOutSocket(error_socket, false /* not reused */, handle,
[email protected]aed99ef02010-08-26 14:04:32353 base::TimeDelta(), group, request->net_log());
354 } else if (group->IsEmpty()) {
355 RemoveGroup(group_name);
[email protected]05ea9ff2010-07-15 19:08:21356 }
[email protected]2ab05b52009-07-01 23:57:58357 }
[email protected]ff579d42009-06-24 15:47:02358
[email protected]2ab05b52009-07-01 23:57:58359 return rv;
[email protected]ff579d42009-06-24 15:47:02360}
361
[email protected]05ea9ff2010-07-15 19:08:21362bool ClientSocketPoolBaseHelper::AssignIdleSocketToGroup(
[email protected]aed99ef02010-08-26 14:04:32363 const Request* request, Group* group) {
[email protected]e1b54dc2010-10-06 21:27:22364 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
365 std::list<IdleSocket>::iterator idle_socket_it = idle_sockets->end();
366
367 // Iterate through the idle sockets forwards (oldest to newest)
368 // * Delete any disconnected ones.
369 // * If we find a used idle socket, assign to |idle_socket|. At the end,
370 // the |idle_socket_it| will be set to the newest used idle socket.
371 for (std::list<IdleSocket>::iterator it = idle_sockets->begin();
372 it != idle_sockets->end();) {
373 if (!it->socket->IsConnectedAndIdle()) {
374 DecrementIdleCount();
375 delete it->socket;
376 it = idle_sockets->erase(it);
377 continue;
[email protected]eb5a99382010-07-11 03:18:26378 }
[email protected]e1b54dc2010-10-06 21:27:22379
380 if (it->socket->WasEverUsed()) {
381 // We found one we can reuse!
[email protected]ea678b02011-06-24 18:21:37382 idle_socket_it = it;
[email protected]e1b54dc2010-10-06 21:27:22383 }
384
385 ++it;
[email protected]eb5a99382010-07-11 03:18:26386 }
[email protected]e1b54dc2010-10-06 21:27:22387
388 // If we haven't found an idle socket, that means there are no used idle
389 // sockets. Pick the oldest (first) idle socket (FIFO).
390
391 if (idle_socket_it == idle_sockets->end() && !idle_sockets->empty())
392 idle_socket_it = idle_sockets->begin();
393
394 if (idle_socket_it != idle_sockets->end()) {
395 DecrementIdleCount();
396 base::TimeDelta idle_time =
397 base::TimeTicks::Now() - idle_socket_it->start_time;
398 IdleSocket idle_socket = *idle_socket_it;
399 idle_sockets->erase(idle_socket_it);
400 HandOutSocket(
401 idle_socket.socket,
402 idle_socket.socket->WasEverUsed(),
403 request->handle(),
404 idle_time,
405 group,
406 request->net_log());
407 return true;
408 }
409
[email protected]eb5a99382010-07-11 03:18:26410 return false;
411}
412
[email protected]06650c52010-06-03 00:49:17413// static
414void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
415 const NetLog::Source& connect_job_source, const Request* request) {
416 request->net_log().AddEvent(
417 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
[email protected]00cd9c42010-11-02 20:15:57418 make_scoped_refptr(new NetLogSourceParameter(
419 "source_dependency", connect_job_source)));
[email protected]06650c52010-06-03 00:49:17420}
421
[email protected]d80a4322009-08-14 07:07:49422void ClientSocketPoolBaseHelper::CancelRequest(
[email protected]05ea9ff2010-07-15 19:08:21423 const std::string& group_name, ClientSocketHandle* handle) {
424 PendingCallbackMap::iterator callback_it = pending_callback_map_.find(handle);
425 if (callback_it != pending_callback_map_.end()) {
426 int result = callback_it->second.result;
427 pending_callback_map_.erase(callback_it);
[email protected]3268023f2011-05-05 00:08:10428 StreamSocket* socket = handle->release_socket();
[email protected]05ea9ff2010-07-15 19:08:21429 if (socket) {
430 if (result != OK)
431 socket->Disconnect();
432 ReleaseSocket(handle->group_name(), socket, handle->id());
433 }
434 return;
435 }
[email protected]b6501d3d2010-06-03 23:53:34436
[email protected]ff579d42009-06-24 15:47:02437 CHECK(ContainsKey(group_map_, group_name));
438
[email protected]aed99ef02010-08-26 14:04:32439 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02440
[email protected]ff579d42009-06-24 15:47:02441 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32442 RequestQueue::iterator it = group->mutable_pending_requests()->begin();
443 for (; it != group->pending_requests().end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49444 if ((*it)->handle() == handle) {
[email protected]2c2bef152010-10-13 00:55:03445 scoped_ptr<const Request> req(RemoveRequestFromQueue(it, group));
[email protected]ec11be62010-04-28 19:28:09446 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
447 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]eb5a99382010-07-11 03:18:26448
449 // We let the job run, unless we're at the socket limit.
[email protected]aed99ef02010-08-26 14:04:32450 if (group->jobs().size() && ReachedMaxSocketsLimit()) {
451 RemoveConnectJob(*group->jobs().begin(), group);
[email protected]eb5a99382010-07-11 03:18:26452 CheckForStalledSocketGroups();
[email protected]974ebd62009-08-03 23:14:34453 }
[email protected]eb5a99382010-07-11 03:18:26454 break;
[email protected]ff579d42009-06-24 15:47:02455 }
456 }
[email protected]ff579d42009-06-24 15:47:02457}
458
[email protected]2abfe90a2010-08-25 17:49:51459bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const {
460 return ContainsKey(group_map_, group_name);
461}
462
[email protected]d80a4322009-08-14 07:07:49463void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02464 CleanupIdleSockets(true);
[email protected]06f92462010-08-31 19:24:14465 DCHECK_EQ(0, idle_socket_count_);
[email protected]ff579d42009-06-24 15:47:02466}
467
[email protected]d80a4322009-08-14 07:07:49468int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02469 const std::string& group_name) const {
470 GroupMap::const_iterator i = group_map_.find(group_name);
471 CHECK(i != group_map_.end());
472
[email protected]aed99ef02010-08-26 14:04:32473 return i->second->idle_sockets().size();
[email protected]ff579d42009-06-24 15:47:02474}
475
[email protected]d80a4322009-08-14 07:07:49476LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02477 const std::string& group_name,
478 const ClientSocketHandle* handle) const {
[email protected]05ea9ff2010-07-15 19:08:21479 if (ContainsKey(pending_callback_map_, handle))
480 return LOAD_STATE_CONNECTING;
481
[email protected]ff579d42009-06-24 15:47:02482 if (!ContainsKey(group_map_, group_name)) {
483 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
484 << " for handle: " << handle;
485 return LOAD_STATE_IDLE;
486 }
487
488 // Can't use operator[] since it is non-const.
[email protected]aed99ef02010-08-26 14:04:32489 const Group& group = *group_map_.find(group_name)->second;
[email protected]ff579d42009-06-24 15:47:02490
[email protected]ff579d42009-06-24 15:47:02491 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32492 RequestQueue::const_iterator it = group.pending_requests().begin();
493 for (size_t i = 0; it != group.pending_requests().end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49494 if ((*it)->handle() == handle) {
[email protected]aed99ef02010-08-26 14:04:32495 if (i < group.jobs().size()) {
[email protected]5fc08e32009-07-15 17:09:57496 LoadState max_state = LOAD_STATE_IDLE;
[email protected]aed99ef02010-08-26 14:04:32497 for (ConnectJobSet::const_iterator job_it = group.jobs().begin();
498 job_it != group.jobs().end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21499 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57500 }
501 return max_state;
502 } else {
503 // TODO(wtc): Add a state for being on the wait list.
504 // See http://www.crbug.com/5077.
505 return LOAD_STATE_IDLE;
506 }
[email protected]ff579d42009-06-24 15:47:02507 }
508 }
509
510 NOTREACHED();
511 return LOAD_STATE_IDLE;
512}
513
[email protected]ba00b492010-09-08 14:53:38514DictionaryValue* ClientSocketPoolBaseHelper::GetInfoAsValue(
[email protected]59d7a5a2010-08-30 16:44:27515 const std::string& name, const std::string& type) const {
516 DictionaryValue* dict = new DictionaryValue();
517 dict->SetString("name", name);
518 dict->SetString("type", type);
519 dict->SetInteger("handed_out_socket_count", handed_out_socket_count_);
520 dict->SetInteger("connecting_socket_count", connecting_socket_count_);
521 dict->SetInteger("idle_socket_count", idle_socket_count_);
522 dict->SetInteger("max_socket_count", max_sockets_);
523 dict->SetInteger("max_sockets_per_group", max_sockets_per_group_);
524 dict->SetInteger("pool_generation_number", pool_generation_number_);
525
526 if (group_map_.empty())
527 return dict;
528
529 DictionaryValue* all_groups_dict = new DictionaryValue();
530 for (GroupMap::const_iterator it = group_map_.begin();
531 it != group_map_.end(); it++) {
532 const Group* group = it->second;
533 DictionaryValue* group_dict = new DictionaryValue();
534
535 group_dict->SetInteger("pending_request_count",
536 group->pending_requests().size());
537 if (!group->pending_requests().empty()) {
538 group_dict->SetInteger("top_pending_priority",
539 group->TopPendingPriority());
540 }
541
542 group_dict->SetInteger("active_socket_count", group->active_socket_count());
[email protected]0496f9a32010-09-30 16:08:07543
544 ListValue* idle_socket_list = new ListValue();
[email protected]e1b54dc2010-10-06 21:27:22545 std::list<IdleSocket>::const_iterator idle_socket;
[email protected]0496f9a32010-09-30 16:08:07546 for (idle_socket = group->idle_sockets().begin();
547 idle_socket != group->idle_sockets().end();
548 idle_socket++) {
549 int source_id = idle_socket->socket->NetLog().source().id;
550 idle_socket_list->Append(Value::CreateIntegerValue(source_id));
551 }
552 group_dict->Set("idle_sockets", idle_socket_list);
553
554 ListValue* connect_jobs_list = new ListValue();
[email protected]2c2bef152010-10-13 00:55:03555 std::set<ConnectJob*>::const_iterator job = group->jobs().begin();
[email protected]0496f9a32010-09-30 16:08:07556 for (job = group->jobs().begin(); job != group->jobs().end(); job++) {
557 int source_id = (*job)->net_log().source().id;
558 connect_jobs_list->Append(Value::CreateIntegerValue(source_id));
559 }
560 group_dict->Set("connect_jobs", connect_jobs_list);
[email protected]59d7a5a2010-08-30 16:44:27561
562 group_dict->SetBoolean("is_stalled",
563 group->IsStalled(max_sockets_per_group_));
[email protected]e4d9a9722011-05-12 00:16:00564 group_dict->SetBoolean("has_backup_job", group->HasBackupJob());
[email protected]59d7a5a2010-08-30 16:44:27565
566 all_groups_dict->SetWithoutPathExpansion(it->first, group_dict);
567 }
568 dict->Set("groups", all_groups_dict);
569 return dict;
570}
571
[email protected]d80a4322009-08-14 07:07:49572bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16573 base::TimeTicks now,
574 base::TimeDelta timeout) const {
575 bool timed_out = (now - start_time) >= timeout;
[email protected]0f873e82010-09-02 16:09:01576 if (timed_out)
577 return true;
578 if (socket->WasEverUsed())
579 return !socket->IsConnectedAndIdle();
580 return !socket->IsConnected();
[email protected]ff579d42009-06-24 15:47:02581}
582
[email protected]d80a4322009-08-14 07:07:49583void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02584 if (idle_socket_count_ == 0)
585 return;
586
587 // Current time value. Retrieving it once at the function start rather than
588 // inside the inner loop, since it shouldn't change by any meaningful amount.
589 base::TimeTicks now = base::TimeTicks::Now();
590
591 GroupMap::iterator i = group_map_.begin();
592 while (i != group_map_.end()) {
[email protected]aed99ef02010-08-26 14:04:32593 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02594
[email protected]e1b54dc2010-10-06 21:27:22595 std::list<IdleSocket>::iterator j = group->mutable_idle_sockets()->begin();
[email protected]aed99ef02010-08-26 14:04:32596 while (j != group->idle_sockets().end()) {
[email protected]9bf28db2009-08-29 01:35:16597 base::TimeDelta timeout =
[email protected]0f873e82010-09-02 16:09:01598 j->socket->WasEverUsed() ?
599 used_idle_socket_timeout_ : unused_idle_socket_timeout_;
[email protected]9bf28db2009-08-29 01:35:16600 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02601 delete j->socket;
[email protected]aed99ef02010-08-26 14:04:32602 j = group->mutable_idle_sockets()->erase(j);
[email protected]ff579d42009-06-24 15:47:02603 DecrementIdleCount();
604 } else {
605 ++j;
606 }
607 }
608
609 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32610 if (group->IsEmpty()) {
611 RemoveGroup(i++);
[email protected]ff579d42009-06-24 15:47:02612 } else {
613 ++i;
614 }
615 }
616}
617
[email protected]aed99ef02010-08-26 14:04:32618ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup(
619 const std::string& group_name) {
620 GroupMap::iterator it = group_map_.find(group_name);
621 if (it != group_map_.end())
622 return it->second;
623 Group* group = new Group;
624 group_map_[group_name] = group;
625 return group;
626}
627
628void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) {
629 GroupMap::iterator it = group_map_.find(group_name);
630 CHECK(it != group_map_.end());
631
632 RemoveGroup(it);
633}
634
635void ClientSocketPoolBaseHelper::RemoveGroup(GroupMap::iterator it) {
636 delete it->second;
637 group_map_.erase(it);
638}
639
[email protected]06d94042010-08-25 01:45:22640// static
[email protected]2d6728692011-03-12 01:39:55641bool ClientSocketPoolBaseHelper::connect_backup_jobs_enabled() {
642 return g_connect_backup_jobs_enabled;
643}
644
645// static
[email protected]636b8252011-04-08 19:56:54646bool ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(bool enabled) {
647 bool old_value = g_connect_backup_jobs_enabled;
[email protected]06d94042010-08-25 01:45:22648 g_connect_backup_jobs_enabled = enabled;
[email protected]636b8252011-04-08 19:56:54649 return old_value;
[email protected]06d94042010-08-25 01:45:22650}
651
652void ClientSocketPoolBaseHelper::EnableConnectBackupJobs() {
653 connect_backup_jobs_enabled_ = g_connect_backup_jobs_enabled;
654}
655
[email protected]d80a4322009-08-14 07:07:49656void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02657 if (++idle_socket_count_ == 1)
658 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49659 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02660}
661
[email protected]d80a4322009-08-14 07:07:49662void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02663 if (--idle_socket_count_ == 0)
664 timer_.Stop();
665}
666
[email protected]eb5a99382010-07-11 03:18:26667void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
[email protected]3268023f2011-05-05 00:08:10668 StreamSocket* socket,
[email protected]eb5a99382010-07-11 03:18:26669 int id) {
[email protected]ff579d42009-06-24 15:47:02670 GroupMap::iterator i = group_map_.find(group_name);
671 CHECK(i != group_map_.end());
672
[email protected]aed99ef02010-08-26 14:04:32673 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02674
[email protected]b1f031dd2010-03-02 23:19:33675 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53676 handed_out_socket_count_--;
677
[email protected]aed99ef02010-08-26 14:04:32678 CHECK_GT(group->active_socket_count(), 0);
679 group->DecrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02680
[email protected]a7e38572010-06-07 18:22:24681 const bool can_reuse = socket->IsConnectedAndIdle() &&
682 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02683 if (can_reuse) {
[email protected]eb5a99382010-07-11 03:18:26684 // Add it to the idle list.
[email protected]0f873e82010-09-02 16:09:01685 AddIdleSocket(socket, group);
[email protected]aed99ef02010-08-26 14:04:32686 OnAvailableSocketSlot(group_name, group);
[email protected]ff579d42009-06-24 15:47:02687 } else {
688 delete socket;
689 }
[email protected]05ea9ff2010-07-15 19:08:21690
[email protected]eb5a99382010-07-11 03:18:26691 CheckForStalledSocketGroups();
692}
[email protected]ff579d42009-06-24 15:47:02693
[email protected]eb5a99382010-07-11 03:18:26694void ClientSocketPoolBaseHelper::CheckForStalledSocketGroups() {
695 // If we have idle sockets, see if we can give one to the top-stalled group.
696 std::string top_group_name;
697 Group* top_group = NULL;
[email protected]05ea9ff2010-07-15 19:08:21698 if (!FindTopStalledGroup(&top_group, &top_group_name))
[email protected]eb5a99382010-07-11 03:18:26699 return;
[email protected]4f2abec2010-02-03 18:10:16700
[email protected]eb5a99382010-07-11 03:18:26701 if (ReachedMaxSocketsLimit()) {
702 if (idle_socket_count() > 0) {
703 CloseOneIdleSocket();
[email protected]d7027bb2010-05-10 18:58:54704 } else {
[email protected]eb5a99382010-07-11 03:18:26705 // We can't activate more sockets since we're already at our global
706 // limit.
[email protected]4f2abec2010-02-03 18:10:16707 return;
[email protected]d7027bb2010-05-10 18:58:54708 }
[email protected]4f2abec2010-02-03 18:10:16709 }
[email protected]eb5a99382010-07-11 03:18:26710
711 // Note: we don't loop on waking stalled groups. If the stalled group is at
712 // its limit, may be left with other stalled groups that could be
[email protected]05ea9ff2010-07-15 19:08:21713 // woken. This isn't optimal, but there is no starvation, so to avoid
[email protected]eb5a99382010-07-11 03:18:26714 // the looping we leave it at this.
[email protected]05ea9ff2010-07-15 19:08:21715 OnAvailableSocketSlot(top_group_name, top_group);
[email protected]ff579d42009-06-24 15:47:02716}
717
[email protected]211d2172009-07-22 15:48:53718// Search for the highest priority pending request, amongst the groups that
719// are not at the |max_sockets_per_group_| limit. Note: for requests with
720// the same priority, the winner is based on group hash ordering (and not
721// insertion order).
[email protected]05ea9ff2010-07-15 19:08:21722bool ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
723 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53724 Group* top_group = NULL;
725 const std::string* top_group_name = NULL;
[email protected]05ea9ff2010-07-15 19:08:21726 bool has_stalled_group = false;
[email protected]211d2172009-07-22 15:48:53727 for (GroupMap::iterator i = group_map_.begin();
728 i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32729 Group* curr_group = i->second;
730 const RequestQueue& queue = curr_group->pending_requests();
[email protected]211d2172009-07-22 15:48:53731 if (queue.empty())
732 continue;
[email protected]aed99ef02010-08-26 14:04:32733 if (curr_group->IsStalled(max_sockets_per_group_)) {
[email protected]05ea9ff2010-07-15 19:08:21734 has_stalled_group = true;
[email protected]6427fe22010-04-16 22:27:41735 bool has_higher_priority = !top_group ||
[email protected]aed99ef02010-08-26 14:04:32736 curr_group->TopPendingPriority() < top_group->TopPendingPriority();
[email protected]6427fe22010-04-16 22:27:41737 if (has_higher_priority) {
[email protected]aed99ef02010-08-26 14:04:32738 top_group = curr_group;
[email protected]6427fe22010-04-16 22:27:41739 top_group_name = &i->first;
740 }
[email protected]211d2172009-07-22 15:48:53741 }
742 }
[email protected]05ea9ff2010-07-15 19:08:21743
[email protected]211d2172009-07-22 15:48:53744 if (top_group) {
745 *group = top_group;
746 *group_name = *top_group_name;
747 }
[email protected]05ea9ff2010-07-15 19:08:21748 return has_stalled_group;
[email protected]211d2172009-07-22 15:48:53749}
750
[email protected]d80a4322009-08-14 07:07:49751void ClientSocketPoolBaseHelper::OnConnectJobComplete(
752 int result, ConnectJob* job) {
[email protected]2ab05b52009-07-01 23:57:58753 DCHECK_NE(ERR_IO_PENDING, result);
754 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02755 GroupMap::iterator group_it = group_map_.find(group_name);
756 CHECK(group_it != group_map_.end());
[email protected]aed99ef02010-08-26 14:04:32757 Group* group = group_it->second;
[email protected]ff579d42009-06-24 15:47:02758
[email protected]3268023f2011-05-05 00:08:10759 scoped_ptr<StreamSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02760
[email protected]9e743cd2010-03-16 07:03:53761 BoundNetLog job_log = job->net_log();
[email protected]5fc08e32009-07-15 17:09:57762
[email protected]4d3b05d2010-01-27 21:27:29763 if (result == OK) {
764 DCHECK(socket.get());
[email protected]aed99ef02010-08-26 14:04:32765 RemoveConnectJob(job, group);
766 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29767 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02768 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17769 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29770 HandOutSocket(
771 socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32772 base::TimeDelta(), group, r->net_log());
[email protected]06650c52010-06-03 00:49:17773 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21774 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]5fc08e32009-07-15 17:09:57775 } else {
[email protected]0f873e82010-09-02 16:09:01776 AddIdleSocket(socket.release(), group);
[email protected]aed99ef02010-08-26 14:04:32777 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21778 CheckForStalledSocketGroups();
[email protected]5fc08e32009-07-15 17:09:57779 }
[email protected]94c20472010-01-14 08:14:36780 } else {
[email protected]e772db3f2010-07-12 18:11:13781 // If we got a socket, it must contain error information so pass that
782 // up so that the caller can retrieve it.
783 bool handed_out_socket = false;
[email protected]aed99ef02010-08-26 14:04:32784 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29785 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02786 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17787 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]e60e47a2010-07-14 03:37:18788 job->GetAdditionalErrorState(r->handle());
[email protected]aed99ef02010-08-26 14:04:32789 RemoveConnectJob(job, group);
[email protected]e772db3f2010-07-12 18:11:13790 if (socket.get()) {
791 handed_out_socket = true;
792 HandOutSocket(socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32793 base::TimeDelta(), group, r->net_log());
[email protected]e772db3f2010-07-12 18:11:13794 }
[email protected]d7fd1782011-02-08 19:16:43795 r->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL,
796 result);
[email protected]05ea9ff2010-07-15 19:08:21797 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]e60e47a2010-07-14 03:37:18798 } else {
[email protected]aed99ef02010-08-26 14:04:32799 RemoveConnectJob(job, group);
[email protected]4d3b05d2010-01-27 21:27:29800 }
[email protected]05ea9ff2010-07-15 19:08:21801 if (!handed_out_socket) {
[email protected]aed99ef02010-08-26 14:04:32802 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21803 CheckForStalledSocketGroups();
804 }
[email protected]ff579d42009-06-24 15:47:02805 }
[email protected]ff579d42009-06-24 15:47:02806}
807
[email protected]66761b952010-06-25 21:30:38808void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
809 Flush();
810}
811
[email protected]a7e38572010-06-07 18:22:24812void ClientSocketPoolBaseHelper::Flush() {
813 pool_generation_number_++;
[email protected]06f92462010-08-31 19:24:14814 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52815 CloseIdleSockets();
[email protected]06f92462010-08-31 19:24:14816 AbortAllRequests();
[email protected]a554a8262010-05-20 00:13:52817}
818
[email protected]2c2bef152010-10-13 00:55:03819void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job,
[email protected]4d3b05d2010-01-27 21:27:29820 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33821 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53822 connecting_socket_count_--;
823
[email protected]25eea382010-07-10 23:55:26824 DCHECK(group);
[email protected]aed99ef02010-08-26 14:04:32825 DCHECK(ContainsKey(group->jobs(), job));
826 group->RemoveJob(job);
[email protected]25eea382010-07-10 23:55:26827
828 // If we've got no more jobs for this group, then we no longer need a
829 // backup job either.
[email protected]aed99ef02010-08-26 14:04:32830 if (group->jobs().empty())
[email protected]e4d9a9722011-05-12 00:16:00831 group->CleanupBackupJob();
[email protected]25eea382010-07-10 23:55:26832
[email protected]8ae03f42010-07-07 19:08:10833 DCHECK(job);
834 delete job;
[email protected]2ab05b52009-07-01 23:57:58835}
[email protected]ff579d42009-06-24 15:47:02836
[email protected]8ae03f42010-07-07 19:08:10837void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
[email protected]05ea9ff2010-07-15 19:08:21838 const std::string& group_name, Group* group) {
[email protected]2abfe90a2010-08-25 17:49:51839 DCHECK(ContainsKey(group_map_, group_name));
[email protected]05ea9ff2010-07-15 19:08:21840 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32841 RemoveGroup(group_name);
842 else if (!group->pending_requests().empty())
[email protected]2abfe90a2010-08-25 17:49:51843 ProcessPendingRequest(group_name, group);
[email protected]8ae03f42010-07-07 19:08:10844}
[email protected]06650c52010-06-03 00:49:17845
[email protected]8ae03f42010-07-07 19:08:10846void ClientSocketPoolBaseHelper::ProcessPendingRequest(
[email protected]05ea9ff2010-07-15 19:08:21847 const std::string& group_name, Group* group) {
848 int rv = RequestSocketInternal(group_name,
[email protected]aed99ef02010-08-26 14:04:32849 *group->pending_requests().begin());
[email protected]05ea9ff2010-07-15 19:08:21850 if (rv != ERR_IO_PENDING) {
851 scoped_ptr<const Request> request(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02852 group->mutable_pending_requests()->begin(), group));
[email protected]2abfe90a2010-08-25 17:49:51853 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32854 RemoveGroup(group_name);
[email protected]8ae03f42010-07-07 19:08:10855
[email protected]d7fd1782011-02-08 19:16:43856 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21857 InvokeUserCallbackLater(
858 request->handle(), request->callback(), rv);
[email protected]2ab05b52009-07-01 23:57:58859 }
860}
861
[email protected]d80a4322009-08-14 07:07:49862void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]3268023f2011-05-05 00:08:10863 StreamSocket* socket,
[email protected]2ab05b52009-07-01 23:57:58864 bool reused,
865 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29866 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15867 Group* group,
[email protected]9e743cd2010-03-16 07:03:53868 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58869 DCHECK(socket);
870 handle->set_socket(socket);
871 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29872 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24873 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53874
[email protected]d13f51b2010-04-27 23:20:45875 if (reused) {
[email protected]ec11be62010-04-28 19:28:09876 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45877 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57878 make_scoped_refptr(new NetLogIntegerParameter(
879 "idle_ms", static_cast<int>(idle_time.InMilliseconds()))));
[email protected]fd4fe0b2010-02-08 23:02:15880 }
[email protected]d13f51b2010-04-27 23:20:45881
[email protected]06650c52010-06-03 00:49:17882 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57883 make_scoped_refptr(new NetLogSourceParameter(
884 "source_dependency", socket->NetLog().source())));
[email protected]fd4fe0b2010-02-08 23:02:15885
[email protected]211d2172009-07-22 15:48:53886 handed_out_socket_count_++;
[email protected]aed99ef02010-08-26 14:04:32887 group->IncrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02888}
889
[email protected]d80a4322009-08-14 07:07:49890void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]3268023f2011-05-05 00:08:10891 StreamSocket* socket, Group* group) {
[email protected]5fc08e32009-07-15 17:09:57892 DCHECK(socket);
893 IdleSocket idle_socket;
894 idle_socket.socket = socket;
895 idle_socket.start_time = base::TimeTicks::Now();
[email protected]5fc08e32009-07-15 17:09:57896
[email protected]aed99ef02010-08-26 14:04:32897 group->mutable_idle_sockets()->push_back(idle_socket);
[email protected]5fc08e32009-07-15 17:09:57898 IncrementIdleCount();
899}
900
[email protected]d80a4322009-08-14 07:07:49901void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]74d75e0b2010-08-23 20:39:54902 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
[email protected]aed99ef02010-08-26 14:04:32903 Group* group = i->second;
904 connecting_socket_count_ -= group->jobs().size();
905 group->RemoveAllJobs();
[email protected]6b624c62010-03-14 08:37:32906
[email protected]5fc08e32009-07-15 17:09:57907 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32908 if (group->IsEmpty()) {
[email protected]06f92462010-08-31 19:24:14909 // RemoveGroup() will call .erase() which will invalidate the iterator,
910 // but i will already have been incremented to a valid iterator before
911 // RemoveGroup() is called.
912 RemoveGroup(i++);
913 } else {
914 ++i;
915 }
916 }
917 DCHECK_EQ(0, connecting_socket_count_);
918}
919
920void ClientSocketPoolBaseHelper::AbortAllRequests() {
921 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
922 Group* group = i->second;
923
924 RequestQueue pending_requests;
925 pending_requests.swap(*group->mutable_pending_requests());
926 for (RequestQueue::iterator it2 = pending_requests.begin();
927 it2 != pending_requests.end(); ++it2) {
[email protected]2c2bef152010-10-13 00:55:03928 scoped_ptr<const Request> request(*it2);
[email protected]06f92462010-08-31 19:24:14929 InvokeUserCallbackLater(
930 request->handle(), request->callback(), ERR_ABORTED);
931 }
932
933 // Delete group if no longer needed.
934 if (group->IsEmpty()) {
935 // RemoveGroup() will call .erase() which will invalidate the iterator,
936 // but i will already have been incremented to a valid iterator before
937 // RemoveGroup() is called.
[email protected]aed99ef02010-08-26 14:04:32938 RemoveGroup(i++);
[email protected]74d75e0b2010-08-23 20:39:54939 } else {
940 ++i;
[email protected]5fc08e32009-07-15 17:09:57941 }
942 }
943}
944
[email protected]d80a4322009-08-14 07:07:49945bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53946 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54947 int total = handed_out_socket_count_ + connecting_socket_count_ +
948 idle_socket_count();
[email protected]5acdce12011-03-30 13:00:20949 // There can be more sockets than the limit since some requests can ignore
950 // the limit
[email protected]c901f6d2010-04-27 17:48:28951 if (total < max_sockets_)
952 return false;
[email protected]c901f6d2010-04-27 17:48:28953 return true;
[email protected]211d2172009-07-22 15:48:53954}
955
[email protected]43a21b82010-06-10 21:30:54956void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
[email protected]dcbe168a2010-12-02 03:14:46957 CloseOneIdleSocketExceptInGroup(NULL);
958}
959
960bool ClientSocketPoolBaseHelper::CloseOneIdleSocketExceptInGroup(
961 const Group* exception_group) {
[email protected]43a21b82010-06-10 21:30:54962 CHECK_GT(idle_socket_count(), 0);
963
964 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32965 Group* group = i->second;
[email protected]dcbe168a2010-12-02 03:14:46966 if (exception_group == group)
967 continue;
[email protected]e1b54dc2010-10-06 21:27:22968 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
[email protected]43a21b82010-06-10 21:30:54969
[email protected]e1b54dc2010-10-06 21:27:22970 if (!idle_sockets->empty()) {
971 delete idle_sockets->front().socket;
972 idle_sockets->pop_front();
[email protected]43a21b82010-06-10 21:30:54973 DecrementIdleCount();
[email protected]aed99ef02010-08-26 14:04:32974 if (group->IsEmpty())
975 RemoveGroup(i);
[email protected]43a21b82010-06-10 21:30:54976
[email protected]dcbe168a2010-12-02 03:14:46977 return true;
[email protected]43a21b82010-06-10 21:30:54978 }
979 }
980
[email protected]dcbe168a2010-12-02 03:14:46981 if (!exception_group)
982 LOG(DFATAL) << "No idle socket found to close!.";
983
984 return false;
[email protected]43a21b82010-06-10 21:30:54985}
986
[email protected]05ea9ff2010-07-15 19:08:21987void ClientSocketPoolBaseHelper::InvokeUserCallbackLater(
988 ClientSocketHandle* handle, CompletionCallback* callback, int rv) {
989 CHECK(!ContainsKey(pending_callback_map_, handle));
990 pending_callback_map_[handle] = CallbackResultPair(callback, rv);
991 MessageLoop::current()->PostTask(
992 FROM_HERE,
[email protected]2431756e2010-09-29 20:26:13993 method_factory_.NewRunnableMethod(
[email protected]05ea9ff2010-07-15 19:08:21994 &ClientSocketPoolBaseHelper::InvokeUserCallback,
995 handle));
996}
997
998void ClientSocketPoolBaseHelper::InvokeUserCallback(
999 ClientSocketHandle* handle) {
1000 PendingCallbackMap::iterator it = pending_callback_map_.find(handle);
1001
1002 // Exit if the request has already been cancelled.
1003 if (it == pending_callback_map_.end())
1004 return;
1005
1006 CHECK(!handle->is_initialized());
1007 CompletionCallback* callback = it->second.callback;
1008 int result = it->second.result;
1009 pending_callback_map_.erase(it);
1010 callback->Run(result);
1011}
1012
[email protected]aed99ef02010-08-26 14:04:321013ClientSocketPoolBaseHelper::Group::Group()
1014 : active_socket_count_(0),
1015 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}
1016
[email protected]e4d9a9722011-05-12 00:16:001017ClientSocketPoolBaseHelper::Group::~Group() {
1018 CleanupBackupJob();
[email protected]aed99ef02010-08-26 14:04:321019}
1020
1021void ClientSocketPoolBaseHelper::Group::StartBackupSocketTimer(
1022 const std::string& group_name,
1023 ClientSocketPoolBaseHelper* pool) {
1024 // Only allow one timer pending to create a backup socket.
1025 if (!method_factory_.empty())
1026 return;
1027
1028 MessageLoop::current()->PostDelayedTask(
1029 FROM_HERE,
1030 method_factory_.NewRunnableMethod(
1031 &Group::OnBackupSocketTimerFired, group_name, pool),
1032 pool->ConnectRetryIntervalMs());
1033}
1034
[email protected]2c2bef152010-10-13 00:55:031035bool ClientSocketPoolBaseHelper::Group::TryToUsePreconnectConnectJob() {
1036 for (std::set<ConnectJob*>::iterator it = jobs_.begin();
1037 it != jobs_.end(); ++it) {
1038 ConnectJob* job = *it;
1039 if (job->is_unused_preconnect()) {
1040 job->UseForNormalRequest();
1041 return true;
1042 }
1043 }
1044 return false;
1045}
1046
[email protected]aed99ef02010-08-26 14:04:321047void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired(
1048 std::string group_name,
1049 ClientSocketPoolBaseHelper* pool) {
1050 // If there are no more jobs pending, there is no work to do.
1051 // If we've done our cleanups correctly, this should not happen.
1052 if (jobs_.empty()) {
1053 NOTREACHED();
1054 return;
1055 }
1056
1057 // If our backup job is waiting on DNS, or if we can't create any sockets
1058 // right now due to limits, just reset the timer.
1059 if (pool->ReachedMaxSocketsLimit() ||
1060 !HasAvailableSocketSlot(pool->max_sockets_per_group_) ||
1061 (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
1062 StartBackupSocketTimer(group_name, pool);
1063 return;
1064 }
1065
[email protected]a9fc8fc2011-05-10 02:41:071066 if (pending_requests_.empty())
[email protected]4baaf9d2010-08-31 15:15:441067 return;
[email protected]4baaf9d2010-08-31 15:15:441068
[email protected]aed99ef02010-08-26 14:04:321069 ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob(
1070 group_name, **pending_requests_.begin(), pool);
1071 backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED, NULL);
1072 SIMPLE_STATS_COUNTER("socket.backup_created");
1073 int rv = backup_job->Connect();
1074 pool->connecting_socket_count_++;
1075 AddJob(backup_job);
1076 if (rv != ERR_IO_PENDING)
1077 pool->OnConnectJobComplete(rv, backup_job);
1078}
1079
1080void ClientSocketPoolBaseHelper::Group::RemoveAllJobs() {
1081 // Delete active jobs.
1082 STLDeleteElements(&jobs_);
1083
1084 // Cancel pending backup job.
1085 method_factory_.RevokeAll();
1086}
1087
[email protected]d80a4322009-08-14 07:07:491088} // namespace internal
1089
[email protected]ff579d42009-06-24 15:47:021090} // namespace net