blob: 8aaf1b5b9341e477d3a561fd384ef438c11019ba [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]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]06d94042010-08-25 01:45:2231// Indicate whether or not we should establish a new TCP connection after a
32// certain timeout has passed without receiving an ACK.
33bool 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]06650c52010-06-03 00:49:1788void ConnectJob::set_socket(ClientSocket* socket) {
89 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]2c2bef152010-10-13 00:55:03136 Flags flags,
[email protected]9e743cd2010-03-16 07:03:53137 const BoundNetLog& net_log)
[email protected]2431756e2010-09-29 20:26:13138 : handle_(handle),
139 callback_(callback),
140 priority_(priority),
[email protected]2c2bef152010-10-13 00:55:03141 flags_(flags),
[email protected]9e743cd2010-03-16 07:03:53142 net_log_(net_log) {}
[email protected]fd4fe0b2010-02-08 23:02:15143
144ClientSocketPoolBaseHelper::Request::~Request() {}
145
[email protected]d80a4322009-08-14 07:07:49146ClientSocketPoolBaseHelper::ClientSocketPoolBaseHelper(
[email protected]211d2172009-07-22 15:48:53147 int max_sockets,
[email protected]ff579d42009-06-24 15:47:02148 int max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16149 base::TimeDelta unused_idle_socket_timeout,
150 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38151 ConnectJobFactory* connect_job_factory)
[email protected]ff579d42009-06-24 15:47:02152 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53153 connecting_socket_count_(0),
154 handed_out_socket_count_(0),
155 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02156 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16157 unused_idle_socket_timeout_(unused_idle_socket_timeout),
158 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]100d5fb92009-12-21 21:08:35159 connect_job_factory_(connect_job_factory),
[email protected]06d94042010-08-25 01:45:22160 connect_backup_jobs_enabled_(false),
[email protected]2431756e2010-09-29 20:26:13161 pool_generation_number_(0),
162 method_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
[email protected]211d2172009-07-22 15:48:53163 DCHECK_LE(0, max_sockets_per_group);
164 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52165
[email protected]232a5812011-03-04 22:42:08166 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]211d2172009-07-22 15:48:53167}
[email protected]ff579d42009-06-24 15:47:02168
[email protected]d80a4322009-08-14 07:07:49169ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]2431756e2010-09-29 20:26:13170 // Clean up any idle sockets and pending connect jobs. Assert that we have no
171 // remaining active sockets or pending requests. They should have all been
172 // cleaned up prior to |this| being destroyed.
173 Flush();
174 DCHECK(group_map_.empty());
[email protected]05ea9ff2010-07-15 19:08:21175 DCHECK(pending_callback_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29176 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52177
[email protected]232a5812011-03-04 22:42:08178 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]ff579d42009-06-24 15:47:02179}
180
181// InsertRequestIntoQueue inserts the request into the queue based on
182// priority. Highest priorities are closest to the front. Older requests are
183// prioritized over requests of equal priority.
184//
185// static
[email protected]d80a4322009-08-14 07:07:49186void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
187 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02188 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31189 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02190 ++it;
191 pending_requests->insert(it, r);
192}
193
[email protected]fd7b7c92009-08-20 19:38:30194// static
195const ClientSocketPoolBaseHelper::Request*
196ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02197 RequestQueue::iterator it, Group* group) {
[email protected]fd7b7c92009-08-20 19:38:30198 const Request* req = *it;
[email protected]3f00be82010-09-27 19:50:02199 group->mutable_pending_requests()->erase(it);
200 // If there are no more requests, we kill the backup timer.
201 if (group->pending_requests().empty())
202 group->CleanupBackupJob();
[email protected]fd7b7c92009-08-20 19:38:30203 return req;
204}
205
[email protected]d80a4322009-08-14 07:07:49206int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02207 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49208 const Request* request) {
[email protected]2c2bef152010-10-13 00:55:03209 CHECK(request->callback());
210 CHECK(request->handle());
211
[email protected]ec11be62010-04-28 19:28:09212 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]aed99ef02010-08-26 14:04:32213 Group* group = GetOrCreateGroup(group_name);
[email protected]eb5a99382010-07-11 03:18:26214
[email protected]fd4fe0b2010-02-08 23:02:15215 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17216 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:43217 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21218 CHECK(!request->handle()->is_initialized());
[email protected]e7e99322010-05-04 23:30:17219 delete request;
220 } else {
[email protected]aed99ef02010-08-26 14:04:32221 InsertRequestIntoQueue(request, group->mutable_pending_requests());
[email protected]e7e99322010-05-04 23:30:17222 }
[email protected]fd4fe0b2010-02-08 23:02:15223 return rv;
224}
225
[email protected]2c2bef152010-10-13 00:55:03226void ClientSocketPoolBaseHelper::RequestSockets(
227 const std::string& group_name,
228 const Request& request,
229 int num_sockets) {
230 DCHECK(!request.callback());
231 DCHECK(!request.handle());
232
233 if (num_sockets > max_sockets_per_group_) {
[email protected]2c2bef152010-10-13 00:55:03234 num_sockets = max_sockets_per_group_;
235 }
236
237 request.net_log().BeginEvent(
238 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS,
[email protected]00cd9c42010-11-02 20:15:57239 make_scoped_refptr(new NetLogIntegerParameter(
240 "num_sockets", num_sockets)));
[email protected]2c2bef152010-10-13 00:55:03241
242 Group* group = GetOrCreateGroup(group_name);
243
[email protected]3c819f522010-12-02 02:03:12244 // RequestSocketsInternal() may delete the group.
245 bool deleted_group = false;
246
[email protected]d7fd1782011-02-08 19:16:43247 int rv = OK;
[email protected]2c2bef152010-10-13 00:55:03248 for (int num_iterations_left = num_sockets;
249 group->NumActiveSocketSlots() < num_sockets &&
250 num_iterations_left > 0 ; num_iterations_left--) {
[email protected]d7fd1782011-02-08 19:16:43251 rv = RequestSocketInternal(group_name, &request);
[email protected]2c2bef152010-10-13 00:55:03252 if (rv < 0 && rv != ERR_IO_PENDING) {
253 // We're encountering a synchronous error. Give up.
[email protected]3c819f522010-12-02 02:03:12254 if (!ContainsKey(group_map_, group_name))
255 deleted_group = true;
256 break;
257 }
258 if (!ContainsKey(group_map_, group_name)) {
259 // Unexpected. The group should only be getting deleted on synchronous
260 // error.
261 NOTREACHED();
262 deleted_group = true;
[email protected]2c2bef152010-10-13 00:55:03263 break;
264 }
265 }
266
[email protected]3c819f522010-12-02 02:03:12267 if (!deleted_group && group->IsEmpty())
[email protected]2c2bef152010-10-13 00:55:03268 RemoveGroup(group_name);
269
[email protected]d7fd1782011-02-08 19:16:43270 if (rv == ERR_IO_PENDING)
271 rv = OK;
272 request.net_log().EndEventWithNetErrorCode(
273 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS, rv);
[email protected]2c2bef152010-10-13 00:55:03274}
275
[email protected]fd4fe0b2010-02-08 23:02:15276int ClientSocketPoolBaseHelper::RequestSocketInternal(
277 const std::string& group_name,
278 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49279 DCHECK_GE(request->priority(), 0);
[email protected]d80a4322009-08-14 07:07:49280 ClientSocketHandle* const handle = request->handle();
[email protected]2c2bef152010-10-13 00:55:03281 const bool preconnecting = !handle;
[email protected]aed99ef02010-08-26 14:04:32282 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02283
[email protected]2c2bef152010-10-13 00:55:03284 if (!(request->flags() & NO_IDLE_SOCKETS)) {
285 // Try to reuse a socket.
286 if (AssignIdleSocketToGroup(request, group))
287 return OK;
288 }
289
290 if (!preconnecting && group->TryToUsePreconnectConnectJob())
291 return ERR_IO_PENDING;
[email protected]65552102010-04-09 22:58:10292
[email protected]43a21b82010-06-10 21:30:54293 // Can we make another active socket now?
[email protected]aed99ef02010-08-26 14:04:32294 if (!group->HasAvailableSocketSlot(max_sockets_per_group_)) {
[email protected]43a21b82010-06-10 21:30:54295 request->net_log().AddEvent(
296 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
297 return ERR_IO_PENDING;
298 }
299
300 if (ReachedMaxSocketsLimit()) {
301 if (idle_socket_count() > 0) {
[email protected]dcbe168a2010-12-02 03:14:46302 bool closed = CloseOneIdleSocketExceptInGroup(group);
303 if (preconnecting && !closed)
304 return ERR_PRECONNECT_MAX_SOCKET_LIMIT;
[email protected]43a21b82010-06-10 21:30:54305 } else {
306 // We could check if we really have a stalled group here, but it requires
307 // a scan of all groups, so just flip a flag here, and do the check later.
[email protected]43a21b82010-06-10 21:30:54308 request->net_log().AddEvent(
309 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
310 return ERR_IO_PENDING;
311 }
312 }
313
[email protected]ff579d42009-06-24 15:47:02314 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58315 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17316 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02317
[email protected]2c2bef152010-10-13 00:55:03318 connect_job->Initialize(preconnecting);
[email protected]2ab05b52009-07-01 23:57:58319 int rv = connect_job->Connect();
320 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17321 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2c2bef152010-10-13 00:55:03322 if (!preconnecting) {
323 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
324 handle, base::TimeDelta(), group, request->net_log());
325 } else {
326 AddIdleSocket(connect_job->ReleaseSocket(), group);
327 }
[email protected]2ab05b52009-07-01 23:57:58328 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32329 // If we don't have any sockets in this group, set a timer for potentially
330 // creating a new one. If the SYN is lost, this backup socket may complete
331 // before the slow socket, improving end user latency.
[email protected]2c2bef152010-10-13 00:55:03332 if (connect_backup_jobs_enabled_ &&
333 group->IsEmpty() && !group->HasBackupJob() &&
334 handle) {
[email protected]aed99ef02010-08-26 14:04:32335 group->StartBackupSocketTimer(group_name, this);
[email protected]2c2bef152010-10-13 00:55:03336 }
[email protected]6b624c62010-03-14 08:37:32337
[email protected]211d2172009-07-22 15:48:53338 connecting_socket_count_++;
339
[email protected]aed99ef02010-08-26 14:04:32340 group->AddJob(connect_job.release());
[email protected]a2006ece2010-04-23 16:44:02341 } else {
[email protected]06650c52010-06-03 00:49:17342 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]fd2e53e2011-01-14 20:40:52343 ClientSocket* error_socket = NULL;
344 if (!preconnecting) {
345 DCHECK(handle);
346 connect_job->GetAdditionalErrorState(handle);
347 error_socket = connect_job->ReleaseSocket();
348 }
[email protected]e772db3f2010-07-12 18:11:13349 if (error_socket) {
350 HandOutSocket(error_socket, false /* not reused */, handle,
[email protected]aed99ef02010-08-26 14:04:32351 base::TimeDelta(), group, request->net_log());
352 } else if (group->IsEmpty()) {
353 RemoveGroup(group_name);
[email protected]05ea9ff2010-07-15 19:08:21354 }
[email protected]2ab05b52009-07-01 23:57:58355 }
[email protected]ff579d42009-06-24 15:47:02356
[email protected]2ab05b52009-07-01 23:57:58357 return rv;
[email protected]ff579d42009-06-24 15:47:02358}
359
[email protected]05ea9ff2010-07-15 19:08:21360bool ClientSocketPoolBaseHelper::AssignIdleSocketToGroup(
[email protected]aed99ef02010-08-26 14:04:32361 const Request* request, Group* group) {
[email protected]e1b54dc2010-10-06 21:27:22362 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
363 std::list<IdleSocket>::iterator idle_socket_it = idle_sockets->end();
364
365 // Iterate through the idle sockets forwards (oldest to newest)
366 // * Delete any disconnected ones.
367 // * If we find a used idle socket, assign to |idle_socket|. At the end,
368 // the |idle_socket_it| will be set to the newest used idle socket.
369 for (std::list<IdleSocket>::iterator it = idle_sockets->begin();
370 it != idle_sockets->end();) {
371 if (!it->socket->IsConnectedAndIdle()) {
372 DecrementIdleCount();
373 delete it->socket;
374 it = idle_sockets->erase(it);
375 continue;
[email protected]eb5a99382010-07-11 03:18:26376 }
[email protected]e1b54dc2010-10-06 21:27:22377
378 if (it->socket->WasEverUsed()) {
379 // We found one we can reuse!
380 idle_socket_it = it;
381 }
382
383 ++it;
[email protected]eb5a99382010-07-11 03:18:26384 }
[email protected]e1b54dc2010-10-06 21:27:22385
386 // If we haven't found an idle socket, that means there are no used idle
387 // sockets. Pick the oldest (first) idle socket (FIFO).
388
389 if (idle_socket_it == idle_sockets->end() && !idle_sockets->empty())
390 idle_socket_it = idle_sockets->begin();
391
392 if (idle_socket_it != idle_sockets->end()) {
393 DecrementIdleCount();
394 base::TimeDelta idle_time =
395 base::TimeTicks::Now() - idle_socket_it->start_time;
396 IdleSocket idle_socket = *idle_socket_it;
397 idle_sockets->erase(idle_socket_it);
398 HandOutSocket(
399 idle_socket.socket,
400 idle_socket.socket->WasEverUsed(),
401 request->handle(),
402 idle_time,
403 group,
404 request->net_log());
405 return true;
406 }
407
[email protected]eb5a99382010-07-11 03:18:26408 return false;
409}
410
[email protected]06650c52010-06-03 00:49:17411// static
412void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
413 const NetLog::Source& connect_job_source, const Request* request) {
414 request->net_log().AddEvent(
415 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
[email protected]00cd9c42010-11-02 20:15:57416 make_scoped_refptr(new NetLogSourceParameter(
417 "source_dependency", connect_job_source)));
[email protected]06650c52010-06-03 00:49:17418}
419
[email protected]d80a4322009-08-14 07:07:49420void ClientSocketPoolBaseHelper::CancelRequest(
[email protected]05ea9ff2010-07-15 19:08:21421 const std::string& group_name, ClientSocketHandle* handle) {
422 PendingCallbackMap::iterator callback_it = pending_callback_map_.find(handle);
423 if (callback_it != pending_callback_map_.end()) {
424 int result = callback_it->second.result;
425 pending_callback_map_.erase(callback_it);
426 ClientSocket* socket = handle->release_socket();
427 if (socket) {
428 if (result != OK)
429 socket->Disconnect();
430 ReleaseSocket(handle->group_name(), socket, handle->id());
431 }
432 return;
433 }
[email protected]b6501d3d2010-06-03 23:53:34434
[email protected]ff579d42009-06-24 15:47:02435 CHECK(ContainsKey(group_map_, group_name));
436
[email protected]aed99ef02010-08-26 14:04:32437 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02438
[email protected]ff579d42009-06-24 15:47:02439 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32440 RequestQueue::iterator it = group->mutable_pending_requests()->begin();
441 for (; it != group->pending_requests().end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49442 if ((*it)->handle() == handle) {
[email protected]2c2bef152010-10-13 00:55:03443 scoped_ptr<const Request> req(RemoveRequestFromQueue(it, group));
[email protected]ec11be62010-04-28 19:28:09444 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
445 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]eb5a99382010-07-11 03:18:26446
447 // We let the job run, unless we're at the socket limit.
[email protected]aed99ef02010-08-26 14:04:32448 if (group->jobs().size() && ReachedMaxSocketsLimit()) {
449 RemoveConnectJob(*group->jobs().begin(), group);
[email protected]eb5a99382010-07-11 03:18:26450 CheckForStalledSocketGroups();
[email protected]974ebd62009-08-03 23:14:34451 }
[email protected]eb5a99382010-07-11 03:18:26452 break;
[email protected]ff579d42009-06-24 15:47:02453 }
454 }
[email protected]ff579d42009-06-24 15:47:02455}
456
[email protected]2abfe90a2010-08-25 17:49:51457bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const {
458 return ContainsKey(group_map_, group_name);
459}
460
[email protected]d80a4322009-08-14 07:07:49461void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02462 CleanupIdleSockets(true);
[email protected]06f92462010-08-31 19:24:14463 DCHECK_EQ(0, idle_socket_count_);
[email protected]ff579d42009-06-24 15:47:02464}
465
[email protected]d80a4322009-08-14 07:07:49466int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02467 const std::string& group_name) const {
468 GroupMap::const_iterator i = group_map_.find(group_name);
469 CHECK(i != group_map_.end());
470
[email protected]aed99ef02010-08-26 14:04:32471 return i->second->idle_sockets().size();
[email protected]ff579d42009-06-24 15:47:02472}
473
[email protected]d80a4322009-08-14 07:07:49474LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02475 const std::string& group_name,
476 const ClientSocketHandle* handle) const {
[email protected]05ea9ff2010-07-15 19:08:21477 if (ContainsKey(pending_callback_map_, handle))
478 return LOAD_STATE_CONNECTING;
479
[email protected]ff579d42009-06-24 15:47:02480 if (!ContainsKey(group_map_, group_name)) {
481 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
482 << " for handle: " << handle;
483 return LOAD_STATE_IDLE;
484 }
485
486 // Can't use operator[] since it is non-const.
[email protected]aed99ef02010-08-26 14:04:32487 const Group& group = *group_map_.find(group_name)->second;
[email protected]ff579d42009-06-24 15:47:02488
[email protected]ff579d42009-06-24 15:47:02489 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32490 RequestQueue::const_iterator it = group.pending_requests().begin();
491 for (size_t i = 0; it != group.pending_requests().end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49492 if ((*it)->handle() == handle) {
[email protected]aed99ef02010-08-26 14:04:32493 if (i < group.jobs().size()) {
[email protected]5fc08e32009-07-15 17:09:57494 LoadState max_state = LOAD_STATE_IDLE;
[email protected]aed99ef02010-08-26 14:04:32495 for (ConnectJobSet::const_iterator job_it = group.jobs().begin();
496 job_it != group.jobs().end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21497 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57498 }
499 return max_state;
500 } else {
501 // TODO(wtc): Add a state for being on the wait list.
502 // See http://www.crbug.com/5077.
503 return LOAD_STATE_IDLE;
504 }
[email protected]ff579d42009-06-24 15:47:02505 }
506 }
507
508 NOTREACHED();
509 return LOAD_STATE_IDLE;
510}
511
[email protected]ba00b492010-09-08 14:53:38512DictionaryValue* ClientSocketPoolBaseHelper::GetInfoAsValue(
[email protected]59d7a5a2010-08-30 16:44:27513 const std::string& name, const std::string& type) const {
514 DictionaryValue* dict = new DictionaryValue();
515 dict->SetString("name", name);
516 dict->SetString("type", type);
517 dict->SetInteger("handed_out_socket_count", handed_out_socket_count_);
518 dict->SetInteger("connecting_socket_count", connecting_socket_count_);
519 dict->SetInteger("idle_socket_count", idle_socket_count_);
520 dict->SetInteger("max_socket_count", max_sockets_);
521 dict->SetInteger("max_sockets_per_group", max_sockets_per_group_);
522 dict->SetInteger("pool_generation_number", pool_generation_number_);
523
524 if (group_map_.empty())
525 return dict;
526
527 DictionaryValue* all_groups_dict = new DictionaryValue();
528 for (GroupMap::const_iterator it = group_map_.begin();
529 it != group_map_.end(); it++) {
530 const Group* group = it->second;
531 DictionaryValue* group_dict = new DictionaryValue();
532
533 group_dict->SetInteger("pending_request_count",
534 group->pending_requests().size());
535 if (!group->pending_requests().empty()) {
536 group_dict->SetInteger("top_pending_priority",
537 group->TopPendingPriority());
538 }
539
540 group_dict->SetInteger("active_socket_count", group->active_socket_count());
[email protected]0496f9a32010-09-30 16:08:07541
542 ListValue* idle_socket_list = new ListValue();
[email protected]e1b54dc2010-10-06 21:27:22543 std::list<IdleSocket>::const_iterator idle_socket;
[email protected]0496f9a32010-09-30 16:08:07544 for (idle_socket = group->idle_sockets().begin();
545 idle_socket != group->idle_sockets().end();
546 idle_socket++) {
547 int source_id = idle_socket->socket->NetLog().source().id;
548 idle_socket_list->Append(Value::CreateIntegerValue(source_id));
549 }
550 group_dict->Set("idle_sockets", idle_socket_list);
551
552 ListValue* connect_jobs_list = new ListValue();
[email protected]2c2bef152010-10-13 00:55:03553 std::set<ConnectJob*>::const_iterator job = group->jobs().begin();
[email protected]0496f9a32010-09-30 16:08:07554 for (job = group->jobs().begin(); job != group->jobs().end(); job++) {
555 int source_id = (*job)->net_log().source().id;
556 connect_jobs_list->Append(Value::CreateIntegerValue(source_id));
557 }
558 group_dict->Set("connect_jobs", connect_jobs_list);
[email protected]59d7a5a2010-08-30 16:44:27559
560 group_dict->SetBoolean("is_stalled",
561 group->IsStalled(max_sockets_per_group_));
562 group_dict->SetBoolean("has_backup_job", group->HasBackupJob());
563
564 all_groups_dict->SetWithoutPathExpansion(it->first, group_dict);
565 }
566 dict->Set("groups", all_groups_dict);
567 return dict;
568}
569
[email protected]d80a4322009-08-14 07:07:49570bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16571 base::TimeTicks now,
572 base::TimeDelta timeout) const {
573 bool timed_out = (now - start_time) >= timeout;
[email protected]0f873e82010-09-02 16:09:01574 if (timed_out)
575 return true;
576 if (socket->WasEverUsed())
577 return !socket->IsConnectedAndIdle();
578 return !socket->IsConnected();
[email protected]ff579d42009-06-24 15:47:02579}
580
[email protected]d80a4322009-08-14 07:07:49581void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02582 if (idle_socket_count_ == 0)
583 return;
584
585 // Current time value. Retrieving it once at the function start rather than
586 // inside the inner loop, since it shouldn't change by any meaningful amount.
587 base::TimeTicks now = base::TimeTicks::Now();
588
589 GroupMap::iterator i = group_map_.begin();
590 while (i != group_map_.end()) {
[email protected]aed99ef02010-08-26 14:04:32591 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02592
[email protected]e1b54dc2010-10-06 21:27:22593 std::list<IdleSocket>::iterator j = group->mutable_idle_sockets()->begin();
[email protected]aed99ef02010-08-26 14:04:32594 while (j != group->idle_sockets().end()) {
[email protected]9bf28db2009-08-29 01:35:16595 base::TimeDelta timeout =
[email protected]0f873e82010-09-02 16:09:01596 j->socket->WasEverUsed() ?
597 used_idle_socket_timeout_ : unused_idle_socket_timeout_;
[email protected]9bf28db2009-08-29 01:35:16598 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02599 delete j->socket;
[email protected]aed99ef02010-08-26 14:04:32600 j = group->mutable_idle_sockets()->erase(j);
[email protected]ff579d42009-06-24 15:47:02601 DecrementIdleCount();
602 } else {
603 ++j;
604 }
605 }
606
607 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32608 if (group->IsEmpty()) {
609 RemoveGroup(i++);
[email protected]ff579d42009-06-24 15:47:02610 } else {
611 ++i;
612 }
613 }
614}
615
[email protected]aed99ef02010-08-26 14:04:32616ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup(
617 const std::string& group_name) {
618 GroupMap::iterator it = group_map_.find(group_name);
619 if (it != group_map_.end())
620 return it->second;
621 Group* group = new Group;
622 group_map_[group_name] = group;
623 return group;
624}
625
626void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) {
627 GroupMap::iterator it = group_map_.find(group_name);
628 CHECK(it != group_map_.end());
629
630 RemoveGroup(it);
631}
632
633void ClientSocketPoolBaseHelper::RemoveGroup(GroupMap::iterator it) {
634 delete it->second;
635 group_map_.erase(it);
636}
637
[email protected]06d94042010-08-25 01:45:22638// static
639void ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(bool enabled) {
640 g_connect_backup_jobs_enabled = enabled;
641}
642
643void ClientSocketPoolBaseHelper::EnableConnectBackupJobs() {
644 connect_backup_jobs_enabled_ = g_connect_backup_jobs_enabled;
645}
646
[email protected]d80a4322009-08-14 07:07:49647void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02648 if (++idle_socket_count_ == 1)
649 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49650 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02651}
652
[email protected]d80a4322009-08-14 07:07:49653void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02654 if (--idle_socket_count_ == 0)
655 timer_.Stop();
656}
657
[email protected]eb5a99382010-07-11 03:18:26658void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
659 ClientSocket* socket,
660 int id) {
[email protected]ff579d42009-06-24 15:47:02661 GroupMap::iterator i = group_map_.find(group_name);
662 CHECK(i != group_map_.end());
663
[email protected]aed99ef02010-08-26 14:04:32664 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02665
[email protected]b1f031dd2010-03-02 23:19:33666 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53667 handed_out_socket_count_--;
668
[email protected]aed99ef02010-08-26 14:04:32669 CHECK_GT(group->active_socket_count(), 0);
670 group->DecrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02671
[email protected]a7e38572010-06-07 18:22:24672 const bool can_reuse = socket->IsConnectedAndIdle() &&
673 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02674 if (can_reuse) {
[email protected]eb5a99382010-07-11 03:18:26675 // Add it to the idle list.
[email protected]0f873e82010-09-02 16:09:01676 AddIdleSocket(socket, group);
[email protected]aed99ef02010-08-26 14:04:32677 OnAvailableSocketSlot(group_name, group);
[email protected]ff579d42009-06-24 15:47:02678 } else {
679 delete socket;
680 }
[email protected]05ea9ff2010-07-15 19:08:21681
[email protected]eb5a99382010-07-11 03:18:26682 CheckForStalledSocketGroups();
683}
[email protected]ff579d42009-06-24 15:47:02684
[email protected]eb5a99382010-07-11 03:18:26685void ClientSocketPoolBaseHelper::CheckForStalledSocketGroups() {
686 // If we have idle sockets, see if we can give one to the top-stalled group.
687 std::string top_group_name;
688 Group* top_group = NULL;
[email protected]05ea9ff2010-07-15 19:08:21689 if (!FindTopStalledGroup(&top_group, &top_group_name))
[email protected]eb5a99382010-07-11 03:18:26690 return;
[email protected]4f2abec2010-02-03 18:10:16691
[email protected]eb5a99382010-07-11 03:18:26692 if (ReachedMaxSocketsLimit()) {
693 if (idle_socket_count() > 0) {
694 CloseOneIdleSocket();
[email protected]d7027bb2010-05-10 18:58:54695 } else {
[email protected]eb5a99382010-07-11 03:18:26696 // We can't activate more sockets since we're already at our global
697 // limit.
[email protected]4f2abec2010-02-03 18:10:16698 return;
[email protected]d7027bb2010-05-10 18:58:54699 }
[email protected]4f2abec2010-02-03 18:10:16700 }
[email protected]eb5a99382010-07-11 03:18:26701
702 // Note: we don't loop on waking stalled groups. If the stalled group is at
703 // its limit, may be left with other stalled groups that could be
[email protected]05ea9ff2010-07-15 19:08:21704 // woken. This isn't optimal, but there is no starvation, so to avoid
[email protected]eb5a99382010-07-11 03:18:26705 // the looping we leave it at this.
[email protected]05ea9ff2010-07-15 19:08:21706 OnAvailableSocketSlot(top_group_name, top_group);
[email protected]ff579d42009-06-24 15:47:02707}
708
[email protected]211d2172009-07-22 15:48:53709// Search for the highest priority pending request, amongst the groups that
710// are not at the |max_sockets_per_group_| limit. Note: for requests with
711// the same priority, the winner is based on group hash ordering (and not
712// insertion order).
[email protected]05ea9ff2010-07-15 19:08:21713bool ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
714 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53715 Group* top_group = NULL;
716 const std::string* top_group_name = NULL;
[email protected]05ea9ff2010-07-15 19:08:21717 bool has_stalled_group = false;
[email protected]211d2172009-07-22 15:48:53718 for (GroupMap::iterator i = group_map_.begin();
719 i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32720 Group* curr_group = i->second;
721 const RequestQueue& queue = curr_group->pending_requests();
[email protected]211d2172009-07-22 15:48:53722 if (queue.empty())
723 continue;
[email protected]aed99ef02010-08-26 14:04:32724 if (curr_group->IsStalled(max_sockets_per_group_)) {
[email protected]05ea9ff2010-07-15 19:08:21725 has_stalled_group = true;
[email protected]6427fe22010-04-16 22:27:41726 bool has_higher_priority = !top_group ||
[email protected]aed99ef02010-08-26 14:04:32727 curr_group->TopPendingPriority() < top_group->TopPendingPriority();
[email protected]6427fe22010-04-16 22:27:41728 if (has_higher_priority) {
[email protected]aed99ef02010-08-26 14:04:32729 top_group = curr_group;
[email protected]6427fe22010-04-16 22:27:41730 top_group_name = &i->first;
731 }
[email protected]211d2172009-07-22 15:48:53732 }
733 }
[email protected]05ea9ff2010-07-15 19:08:21734
[email protected]211d2172009-07-22 15:48:53735 if (top_group) {
736 *group = top_group;
737 *group_name = *top_group_name;
738 }
[email protected]05ea9ff2010-07-15 19:08:21739 return has_stalled_group;
[email protected]211d2172009-07-22 15:48:53740}
741
[email protected]d80a4322009-08-14 07:07:49742void ClientSocketPoolBaseHelper::OnConnectJobComplete(
743 int result, ConnectJob* job) {
[email protected]2ab05b52009-07-01 23:57:58744 DCHECK_NE(ERR_IO_PENDING, result);
745 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02746 GroupMap::iterator group_it = group_map_.find(group_name);
747 CHECK(group_it != group_map_.end());
[email protected]aed99ef02010-08-26 14:04:32748 Group* group = group_it->second;
[email protected]ff579d42009-06-24 15:47:02749
[email protected]5fc08e32009-07-15 17:09:57750 scoped_ptr<ClientSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02751
[email protected]9e743cd2010-03-16 07:03:53752 BoundNetLog job_log = job->net_log();
[email protected]5fc08e32009-07-15 17:09:57753
[email protected]4d3b05d2010-01-27 21:27:29754 if (result == OK) {
755 DCHECK(socket.get());
[email protected]aed99ef02010-08-26 14:04:32756 RemoveConnectJob(job, group);
757 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29758 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02759 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17760 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29761 HandOutSocket(
762 socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32763 base::TimeDelta(), group, r->net_log());
[email protected]06650c52010-06-03 00:49:17764 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21765 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]5fc08e32009-07-15 17:09:57766 } else {
[email protected]0f873e82010-09-02 16:09:01767 AddIdleSocket(socket.release(), group);
[email protected]aed99ef02010-08-26 14:04:32768 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21769 CheckForStalledSocketGroups();
[email protected]5fc08e32009-07-15 17:09:57770 }
[email protected]94c20472010-01-14 08:14:36771 } else {
[email protected]e772db3f2010-07-12 18:11:13772 // If we got a socket, it must contain error information so pass that
773 // up so that the caller can retrieve it.
774 bool handed_out_socket = false;
[email protected]aed99ef02010-08-26 14:04:32775 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29776 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02777 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17778 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]e60e47a2010-07-14 03:37:18779 job->GetAdditionalErrorState(r->handle());
[email protected]aed99ef02010-08-26 14:04:32780 RemoveConnectJob(job, group);
[email protected]e772db3f2010-07-12 18:11:13781 if (socket.get()) {
782 handed_out_socket = true;
783 HandOutSocket(socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32784 base::TimeDelta(), group, r->net_log());
[email protected]e772db3f2010-07-12 18:11:13785 }
[email protected]d7fd1782011-02-08 19:16:43786 r->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL,
787 result);
[email protected]05ea9ff2010-07-15 19:08:21788 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]e60e47a2010-07-14 03:37:18789 } else {
[email protected]aed99ef02010-08-26 14:04:32790 RemoveConnectJob(job, group);
[email protected]4d3b05d2010-01-27 21:27:29791 }
[email protected]05ea9ff2010-07-15 19:08:21792 if (!handed_out_socket) {
[email protected]aed99ef02010-08-26 14:04:32793 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21794 CheckForStalledSocketGroups();
795 }
[email protected]ff579d42009-06-24 15:47:02796 }
[email protected]ff579d42009-06-24 15:47:02797}
798
[email protected]66761b952010-06-25 21:30:38799void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
800 Flush();
801}
802
[email protected]a7e38572010-06-07 18:22:24803void ClientSocketPoolBaseHelper::Flush() {
804 pool_generation_number_++;
[email protected]06f92462010-08-31 19:24:14805 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52806 CloseIdleSockets();
[email protected]06f92462010-08-31 19:24:14807 AbortAllRequests();
[email protected]a554a8262010-05-20 00:13:52808}
809
[email protected]2c2bef152010-10-13 00:55:03810void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job,
[email protected]4d3b05d2010-01-27 21:27:29811 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33812 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53813 connecting_socket_count_--;
814
[email protected]25eea382010-07-10 23:55:26815 DCHECK(group);
[email protected]aed99ef02010-08-26 14:04:32816 DCHECK(ContainsKey(group->jobs(), job));
817 group->RemoveJob(job);
[email protected]25eea382010-07-10 23:55:26818
819 // If we've got no more jobs for this group, then we no longer need a
820 // backup job either.
[email protected]aed99ef02010-08-26 14:04:32821 if (group->jobs().empty())
[email protected]25eea382010-07-10 23:55:26822 group->CleanupBackupJob();
823
[email protected]8ae03f42010-07-07 19:08:10824 DCHECK(job);
825 delete job;
[email protected]2ab05b52009-07-01 23:57:58826}
[email protected]ff579d42009-06-24 15:47:02827
[email protected]8ae03f42010-07-07 19:08:10828void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
[email protected]05ea9ff2010-07-15 19:08:21829 const std::string& group_name, Group* group) {
[email protected]2abfe90a2010-08-25 17:49:51830 DCHECK(ContainsKey(group_map_, group_name));
[email protected]05ea9ff2010-07-15 19:08:21831 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32832 RemoveGroup(group_name);
833 else if (!group->pending_requests().empty())
[email protected]2abfe90a2010-08-25 17:49:51834 ProcessPendingRequest(group_name, group);
[email protected]8ae03f42010-07-07 19:08:10835}
[email protected]06650c52010-06-03 00:49:17836
[email protected]8ae03f42010-07-07 19:08:10837void ClientSocketPoolBaseHelper::ProcessPendingRequest(
[email protected]05ea9ff2010-07-15 19:08:21838 const std::string& group_name, Group* group) {
839 int rv = RequestSocketInternal(group_name,
[email protected]aed99ef02010-08-26 14:04:32840 *group->pending_requests().begin());
[email protected]05ea9ff2010-07-15 19:08:21841 if (rv != ERR_IO_PENDING) {
842 scoped_ptr<const Request> request(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02843 group->mutable_pending_requests()->begin(), group));
[email protected]2abfe90a2010-08-25 17:49:51844 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32845 RemoveGroup(group_name);
[email protected]8ae03f42010-07-07 19:08:10846
[email protected]d7fd1782011-02-08 19:16:43847 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21848 InvokeUserCallbackLater(
849 request->handle(), request->callback(), rv);
[email protected]2ab05b52009-07-01 23:57:58850 }
851}
852
[email protected]d80a4322009-08-14 07:07:49853void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]2ab05b52009-07-01 23:57:58854 ClientSocket* socket,
855 bool reused,
856 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29857 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15858 Group* group,
[email protected]9e743cd2010-03-16 07:03:53859 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58860 DCHECK(socket);
861 handle->set_socket(socket);
862 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29863 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24864 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53865
[email protected]d13f51b2010-04-27 23:20:45866 if (reused) {
[email protected]ec11be62010-04-28 19:28:09867 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45868 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57869 make_scoped_refptr(new NetLogIntegerParameter(
870 "idle_ms", static_cast<int>(idle_time.InMilliseconds()))));
[email protected]fd4fe0b2010-02-08 23:02:15871 }
[email protected]d13f51b2010-04-27 23:20:45872
[email protected]06650c52010-06-03 00:49:17873 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57874 make_scoped_refptr(new NetLogSourceParameter(
875 "source_dependency", socket->NetLog().source())));
[email protected]fd4fe0b2010-02-08 23:02:15876
[email protected]211d2172009-07-22 15:48:53877 handed_out_socket_count_++;
[email protected]aed99ef02010-08-26 14:04:32878 group->IncrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02879}
880
[email protected]d80a4322009-08-14 07:07:49881void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]0f873e82010-09-02 16:09:01882 ClientSocket* socket, Group* group) {
[email protected]5fc08e32009-07-15 17:09:57883 DCHECK(socket);
884 IdleSocket idle_socket;
885 idle_socket.socket = socket;
886 idle_socket.start_time = base::TimeTicks::Now();
[email protected]5fc08e32009-07-15 17:09:57887
[email protected]aed99ef02010-08-26 14:04:32888 group->mutable_idle_sockets()->push_back(idle_socket);
[email protected]5fc08e32009-07-15 17:09:57889 IncrementIdleCount();
890}
891
[email protected]d80a4322009-08-14 07:07:49892void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]74d75e0b2010-08-23 20:39:54893 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
[email protected]aed99ef02010-08-26 14:04:32894 Group* group = i->second;
895 connecting_socket_count_ -= group->jobs().size();
896 group->RemoveAllJobs();
[email protected]6b624c62010-03-14 08:37:32897
[email protected]5fc08e32009-07-15 17:09:57898 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32899 if (group->IsEmpty()) {
[email protected]06f92462010-08-31 19:24:14900 // RemoveGroup() will call .erase() which will invalidate the iterator,
901 // but i will already have been incremented to a valid iterator before
902 // RemoveGroup() is called.
903 RemoveGroup(i++);
904 } else {
905 ++i;
906 }
907 }
908 DCHECK_EQ(0, connecting_socket_count_);
909}
910
911void ClientSocketPoolBaseHelper::AbortAllRequests() {
912 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
913 Group* group = i->second;
914
915 RequestQueue pending_requests;
916 pending_requests.swap(*group->mutable_pending_requests());
917 for (RequestQueue::iterator it2 = pending_requests.begin();
918 it2 != pending_requests.end(); ++it2) {
[email protected]2c2bef152010-10-13 00:55:03919 scoped_ptr<const Request> request(*it2);
[email protected]06f92462010-08-31 19:24:14920 InvokeUserCallbackLater(
921 request->handle(), request->callback(), ERR_ABORTED);
922 }
923
924 // Delete group if no longer needed.
925 if (group->IsEmpty()) {
926 // RemoveGroup() will call .erase() which will invalidate the iterator,
927 // but i will already have been incremented to a valid iterator before
928 // RemoveGroup() is called.
[email protected]aed99ef02010-08-26 14:04:32929 RemoveGroup(i++);
[email protected]74d75e0b2010-08-23 20:39:54930 } else {
931 ++i;
[email protected]5fc08e32009-07-15 17:09:57932 }
933 }
934}
935
[email protected]d80a4322009-08-14 07:07:49936bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53937 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54938 int total = handed_out_socket_count_ + connecting_socket_count_ +
939 idle_socket_count();
[email protected]211d2172009-07-22 15:48:53940 DCHECK_LE(total, max_sockets_);
[email protected]c901f6d2010-04-27 17:48:28941 if (total < max_sockets_)
942 return false;
[email protected]c901f6d2010-04-27 17:48:28943 return true;
[email protected]211d2172009-07-22 15:48:53944}
945
[email protected]43a21b82010-06-10 21:30:54946void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
[email protected]dcbe168a2010-12-02 03:14:46947 CloseOneIdleSocketExceptInGroup(NULL);
948}
949
950bool ClientSocketPoolBaseHelper::CloseOneIdleSocketExceptInGroup(
951 const Group* exception_group) {
[email protected]43a21b82010-06-10 21:30:54952 CHECK_GT(idle_socket_count(), 0);
953
954 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32955 Group* group = i->second;
[email protected]dcbe168a2010-12-02 03:14:46956 if (exception_group == group)
957 continue;
[email protected]e1b54dc2010-10-06 21:27:22958 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
[email protected]43a21b82010-06-10 21:30:54959
[email protected]e1b54dc2010-10-06 21:27:22960 if (!idle_sockets->empty()) {
961 delete idle_sockets->front().socket;
962 idle_sockets->pop_front();
[email protected]43a21b82010-06-10 21:30:54963 DecrementIdleCount();
[email protected]aed99ef02010-08-26 14:04:32964 if (group->IsEmpty())
965 RemoveGroup(i);
[email protected]43a21b82010-06-10 21:30:54966
[email protected]dcbe168a2010-12-02 03:14:46967 return true;
[email protected]43a21b82010-06-10 21:30:54968 }
969 }
970
[email protected]dcbe168a2010-12-02 03:14:46971 if (!exception_group)
972 LOG(DFATAL) << "No idle socket found to close!.";
973
974 return false;
[email protected]43a21b82010-06-10 21:30:54975}
976
[email protected]05ea9ff2010-07-15 19:08:21977void ClientSocketPoolBaseHelper::InvokeUserCallbackLater(
978 ClientSocketHandle* handle, CompletionCallback* callback, int rv) {
979 CHECK(!ContainsKey(pending_callback_map_, handle));
980 pending_callback_map_[handle] = CallbackResultPair(callback, rv);
981 MessageLoop::current()->PostTask(
982 FROM_HERE,
[email protected]2431756e2010-09-29 20:26:13983 method_factory_.NewRunnableMethod(
[email protected]05ea9ff2010-07-15 19:08:21984 &ClientSocketPoolBaseHelper::InvokeUserCallback,
985 handle));
986}
987
988void ClientSocketPoolBaseHelper::InvokeUserCallback(
989 ClientSocketHandle* handle) {
990 PendingCallbackMap::iterator it = pending_callback_map_.find(handle);
991
992 // Exit if the request has already been cancelled.
993 if (it == pending_callback_map_.end())
994 return;
995
996 CHECK(!handle->is_initialized());
997 CompletionCallback* callback = it->second.callback;
998 int result = it->second.result;
999 pending_callback_map_.erase(it);
1000 callback->Run(result);
1001}
1002
[email protected]aed99ef02010-08-26 14:04:321003ClientSocketPoolBaseHelper::Group::Group()
1004 : active_socket_count_(0),
1005 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}
1006
1007ClientSocketPoolBaseHelper::Group::~Group() {
1008 CleanupBackupJob();
1009}
1010
1011void ClientSocketPoolBaseHelper::Group::StartBackupSocketTimer(
1012 const std::string& group_name,
1013 ClientSocketPoolBaseHelper* pool) {
1014 // Only allow one timer pending to create a backup socket.
1015 if (!method_factory_.empty())
1016 return;
1017
1018 MessageLoop::current()->PostDelayedTask(
1019 FROM_HERE,
1020 method_factory_.NewRunnableMethod(
1021 &Group::OnBackupSocketTimerFired, group_name, pool),
1022 pool->ConnectRetryIntervalMs());
1023}
1024
[email protected]2c2bef152010-10-13 00:55:031025bool ClientSocketPoolBaseHelper::Group::TryToUsePreconnectConnectJob() {
1026 for (std::set<ConnectJob*>::iterator it = jobs_.begin();
1027 it != jobs_.end(); ++it) {
1028 ConnectJob* job = *it;
1029 if (job->is_unused_preconnect()) {
1030 job->UseForNormalRequest();
1031 return true;
1032 }
1033 }
1034 return false;
1035}
1036
[email protected]aed99ef02010-08-26 14:04:321037void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired(
1038 std::string group_name,
1039 ClientSocketPoolBaseHelper* pool) {
1040 // If there are no more jobs pending, there is no work to do.
1041 // If we've done our cleanups correctly, this should not happen.
1042 if (jobs_.empty()) {
1043 NOTREACHED();
1044 return;
1045 }
1046
1047 // If our backup job is waiting on DNS, or if we can't create any sockets
1048 // right now due to limits, just reset the timer.
1049 if (pool->ReachedMaxSocketsLimit() ||
1050 !HasAvailableSocketSlot(pool->max_sockets_per_group_) ||
1051 (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
1052 StartBackupSocketTimer(group_name, pool);
1053 return;
1054 }
1055
[email protected]4baaf9d2010-08-31 15:15:441056 if (pending_requests_.empty()) {
1057 LOG(DFATAL) << "No pending request for backup job.";
1058 return;
1059 }
1060
[email protected]aed99ef02010-08-26 14:04:321061 ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob(
1062 group_name, **pending_requests_.begin(), pool);
1063 backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED, NULL);
1064 SIMPLE_STATS_COUNTER("socket.backup_created");
1065 int rv = backup_job->Connect();
1066 pool->connecting_socket_count_++;
1067 AddJob(backup_job);
1068 if (rv != ERR_IO_PENDING)
1069 pool->OnConnectJobComplete(rv, backup_job);
1070}
1071
1072void ClientSocketPoolBaseHelper::Group::RemoveAllJobs() {
1073 // Delete active jobs.
1074 STLDeleteElements(&jobs_);
1075
1076 // Cancel pending backup job.
1077 method_factory_.RevokeAll();
1078}
1079
[email protected]d80a4322009-08-14 07:07:491080} // namespace internal
1081
[email protected]ff579d42009-06-24 15:47:021082} // namespace net