blob: 2a5f216c0c7049fa8c7008330cfc625e9473a160 [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),
[email protected]0d1f4c42011-05-05 15:27:5048 prefer_ipv4_(false),
[email protected]2c2bef152010-10-13 00:55:0349 preconnect_state_(NOT_PRECONNECT) {
[email protected]2ab05b52009-07-01 23:57:5850 DCHECK(!group_name.empty());
[email protected]2ab05b52009-07-01 23:57:5851 DCHECK(delegate);
[email protected]06650c52010-06-03 00:49:1752 net_log.BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]2ab05b52009-07-01 23:57:5853}
54
[email protected]fd7b7c92009-08-20 19:38:3055ConnectJob::~ConnectJob() {
[email protected]06650c52010-06-03 00:49:1756 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]fd7b7c92009-08-20 19:38:3057}
[email protected]2ab05b52009-07-01 23:57:5858
[email protected]2c2bef152010-10-13 00:55:0359void ConnectJob::Initialize(bool is_preconnect) {
60 if (is_preconnect)
61 preconnect_state_ = UNUSED_PRECONNECT;
62 else
63 preconnect_state_ = NOT_PRECONNECT;
64}
65
[email protected]974ebd62009-08-03 23:14:3466int ConnectJob::Connect() {
67 if (timeout_duration_ != base::TimeDelta())
68 timer_.Start(timeout_duration_, this, &ConnectJob::OnTimeout);
[email protected]fd7b7c92009-08-20 19:38:3069
[email protected]a2006ece2010-04-23 16:44:0270 idle_ = false;
[email protected]fd7b7c92009-08-20 19:38:3071
[email protected]06650c52010-06-03 00:49:1772 LogConnectStart();
73
[email protected]fd7b7c92009-08-20 19:38:3074 int rv = ConnectInternal();
75
76 if (rv != ERR_IO_PENDING) {
[email protected]06650c52010-06-03 00:49:1777 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:3078 delegate_ = NULL;
[email protected]fd7b7c92009-08-20 19:38:3079 }
80
81 return rv;
82}
83
[email protected]2c2bef152010-10-13 00:55:0384void ConnectJob::UseForNormalRequest() {
85 DCHECK_EQ(UNUSED_PRECONNECT, preconnect_state_);
86 preconnect_state_ = USED_PRECONNECT;
87}
88
[email protected]3268023f2011-05-05 00:08:1089void ConnectJob::set_socket(StreamSocket* socket) {
[email protected]06650c52010-06-03 00:49:1790 if (socket) {
[email protected]00cd9c42010-11-02 20:15:5791 net_log().AddEvent(NetLog::TYPE_CONNECT_JOB_SET_SOCKET, make_scoped_refptr(
92 new NetLogSourceParameter("source_dependency",
93 socket->NetLog().source())));
[email protected]06650c52010-06-03 00:49:1794 }
95 socket_.reset(socket);
96}
97
[email protected]fd7b7c92009-08-20 19:38:3098void ConnectJob::NotifyDelegateOfCompletion(int rv) {
99 // The delegate will delete |this|.
100 Delegate *delegate = delegate_;
101 delegate_ = NULL;
102
[email protected]06650c52010-06-03 00:49:17103 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:30104 delegate->OnConnectJobComplete(rv, this);
[email protected]974ebd62009-08-03 23:14:34105}
106
[email protected]a796bcec2010-03-22 17:17:26107void ConnectJob::ResetTimer(base::TimeDelta remaining_time) {
108 timer_.Stop();
109 timer_.Start(remaining_time, this, &ConnectJob::OnTimeout);
110}
111
[email protected]06650c52010-06-03 00:49:17112void ConnectJob::LogConnectStart() {
113 net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT,
[email protected]00cd9c42010-11-02 20:15:57114 make_scoped_refptr(new NetLogStringParameter("group_name", group_name_)));
[email protected]06650c52010-06-03 00:49:17115}
116
117void ConnectJob::LogConnectCompletion(int net_error) {
[email protected]d7fd1782011-02-08 19:16:43118 net_log().EndEventWithNetErrorCode(
119 NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT, net_error);
[email protected]06650c52010-06-03 00:49:17120}
121
[email protected]974ebd62009-08-03 23:14:34122void ConnectJob::OnTimeout() {
[email protected]6e713f02009-08-06 02:56:40123 // Make sure the socket is NULL before calling into |delegate|.
124 set_socket(NULL);
[email protected]fd7b7c92009-08-20 19:38:30125
[email protected]ec11be62010-04-28 19:28:09126 net_log_.AddEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_TIMED_OUT, NULL);
[email protected]fd7b7c92009-08-20 19:38:30127
128 NotifyDelegateOfCompletion(ERR_TIMED_OUT);
[email protected]974ebd62009-08-03 23:14:34129}
130
[email protected]d80a4322009-08-14 07:07:49131namespace internal {
132
[email protected]fd4fe0b2010-02-08 23:02:15133ClientSocketPoolBaseHelper::Request::Request(
134 ClientSocketHandle* handle,
135 CompletionCallback* callback,
136 RequestPriority priority,
[email protected]5acdce12011-03-30 13:00:20137 bool ignore_limits,
[email protected]2c2bef152010-10-13 00:55:03138 Flags flags,
[email protected]9e743cd2010-03-16 07:03:53139 const BoundNetLog& net_log)
[email protected]2431756e2010-09-29 20:26:13140 : handle_(handle),
141 callback_(callback),
142 priority_(priority),
[email protected]5acdce12011-03-30 13:00:20143 ignore_limits_(ignore_limits),
[email protected]2c2bef152010-10-13 00:55:03144 flags_(flags),
[email protected]9e743cd2010-03-16 07:03:53145 net_log_(net_log) {}
[email protected]fd4fe0b2010-02-08 23:02:15146
147ClientSocketPoolBaseHelper::Request::~Request() {}
148
[email protected]d80a4322009-08-14 07:07:49149ClientSocketPoolBaseHelper::ClientSocketPoolBaseHelper(
[email protected]211d2172009-07-22 15:48:53150 int max_sockets,
[email protected]ff579d42009-06-24 15:47:02151 int max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16152 base::TimeDelta unused_idle_socket_timeout,
153 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38154 ConnectJobFactory* connect_job_factory)
[email protected]ff579d42009-06-24 15:47:02155 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53156 connecting_socket_count_(0),
157 handed_out_socket_count_(0),
158 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02159 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16160 unused_idle_socket_timeout_(unused_idle_socket_timeout),
161 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]100d5fb92009-12-21 21:08:35162 connect_job_factory_(connect_job_factory),
[email protected]06d94042010-08-25 01:45:22163 connect_backup_jobs_enabled_(false),
[email protected]2431756e2010-09-29 20:26:13164 pool_generation_number_(0),
165 method_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
[email protected]211d2172009-07-22 15:48:53166 DCHECK_LE(0, max_sockets_per_group);
167 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52168
[email protected]232a5812011-03-04 22:42:08169 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]211d2172009-07-22 15:48:53170}
[email protected]ff579d42009-06-24 15:47:02171
[email protected]d80a4322009-08-14 07:07:49172ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]2431756e2010-09-29 20:26:13173 // Clean up any idle sockets and pending connect jobs. Assert that we have no
174 // remaining active sockets or pending requests. They should have all been
175 // cleaned up prior to |this| being destroyed.
176 Flush();
177 DCHECK(group_map_.empty());
[email protected]05ea9ff2010-07-15 19:08:21178 DCHECK(pending_callback_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29179 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52180
[email protected]232a5812011-03-04 22:42:08181 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]ff579d42009-06-24 15:47:02182}
183
184// InsertRequestIntoQueue inserts the request into the queue based on
185// priority. Highest priorities are closest to the front. Older requests are
186// prioritized over requests of equal priority.
187//
188// static
[email protected]d80a4322009-08-14 07:07:49189void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
190 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02191 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31192 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02193 ++it;
194 pending_requests->insert(it, r);
195}
196
[email protected]fd7b7c92009-08-20 19:38:30197// static
198const ClientSocketPoolBaseHelper::Request*
199ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
[email protected]417da102011-03-11 17:45:05200 const RequestQueue::iterator& it, Group* group) {
[email protected]fd7b7c92009-08-20 19:38:30201 const Request* req = *it;
[email protected]3f00be82010-09-27 19:50:02202 group->mutable_pending_requests()->erase(it);
203 // If there are no more requests, we kill the backup timer.
204 if (group->pending_requests().empty())
205 group->CleanupBackupJob();
[email protected]fd7b7c92009-08-20 19:38:30206 return req;
207}
208
[email protected]d80a4322009-08-14 07:07:49209int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02210 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49211 const Request* request) {
[email protected]2c2bef152010-10-13 00:55:03212 CHECK(request->callback());
213 CHECK(request->handle());
214
[email protected]ec11be62010-04-28 19:28:09215 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]aed99ef02010-08-26 14:04:32216 Group* group = GetOrCreateGroup(group_name);
[email protected]eb5a99382010-07-11 03:18:26217
[email protected]fd4fe0b2010-02-08 23:02:15218 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17219 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:43220 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21221 CHECK(!request->handle()->is_initialized());
[email protected]e7e99322010-05-04 23:30:17222 delete request;
223 } else {
[email protected]aed99ef02010-08-26 14:04:32224 InsertRequestIntoQueue(request, group->mutable_pending_requests());
[email protected]e7e99322010-05-04 23:30:17225 }
[email protected]fd4fe0b2010-02-08 23:02:15226 return rv;
227}
228
[email protected]2c2bef152010-10-13 00:55:03229void ClientSocketPoolBaseHelper::RequestSockets(
230 const std::string& group_name,
231 const Request& request,
232 int num_sockets) {
233 DCHECK(!request.callback());
234 DCHECK(!request.handle());
235
236 if (num_sockets > max_sockets_per_group_) {
[email protected]2c2bef152010-10-13 00:55:03237 num_sockets = max_sockets_per_group_;
238 }
239
240 request.net_log().BeginEvent(
241 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS,
[email protected]00cd9c42010-11-02 20:15:57242 make_scoped_refptr(new NetLogIntegerParameter(
243 "num_sockets", num_sockets)));
[email protected]2c2bef152010-10-13 00:55:03244
245 Group* group = GetOrCreateGroup(group_name);
246
[email protected]3c819f522010-12-02 02:03:12247 // RequestSocketsInternal() may delete the group.
248 bool deleted_group = false;
249
[email protected]d7fd1782011-02-08 19:16:43250 int rv = OK;
[email protected]2c2bef152010-10-13 00:55:03251 for (int num_iterations_left = num_sockets;
252 group->NumActiveSocketSlots() < num_sockets &&
253 num_iterations_left > 0 ; num_iterations_left--) {
[email protected]d7fd1782011-02-08 19:16:43254 rv = RequestSocketInternal(group_name, &request);
[email protected]2c2bef152010-10-13 00:55:03255 if (rv < 0 && rv != ERR_IO_PENDING) {
256 // We're encountering a synchronous error. Give up.
[email protected]3c819f522010-12-02 02:03:12257 if (!ContainsKey(group_map_, group_name))
258 deleted_group = true;
259 break;
260 }
261 if (!ContainsKey(group_map_, group_name)) {
262 // Unexpected. The group should only be getting deleted on synchronous
263 // error.
264 NOTREACHED();
265 deleted_group = true;
[email protected]2c2bef152010-10-13 00:55:03266 break;
267 }
268 }
269
[email protected]3c819f522010-12-02 02:03:12270 if (!deleted_group && group->IsEmpty())
[email protected]2c2bef152010-10-13 00:55:03271 RemoveGroup(group_name);
272
[email protected]d7fd1782011-02-08 19:16:43273 if (rv == ERR_IO_PENDING)
274 rv = OK;
275 request.net_log().EndEventWithNetErrorCode(
276 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS, rv);
[email protected]2c2bef152010-10-13 00:55:03277}
278
[email protected]fd4fe0b2010-02-08 23:02:15279int ClientSocketPoolBaseHelper::RequestSocketInternal(
280 const std::string& group_name,
281 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49282 DCHECK_GE(request->priority(), 0);
[email protected]d80a4322009-08-14 07:07:49283 ClientSocketHandle* const handle = request->handle();
[email protected]2c2bef152010-10-13 00:55:03284 const bool preconnecting = !handle;
[email protected]aed99ef02010-08-26 14:04:32285 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02286
[email protected]2c2bef152010-10-13 00:55:03287 if (!(request->flags() & NO_IDLE_SOCKETS)) {
288 // Try to reuse a socket.
289 if (AssignIdleSocketToGroup(request, group))
290 return OK;
291 }
292
293 if (!preconnecting && group->TryToUsePreconnectConnectJob())
294 return ERR_IO_PENDING;
[email protected]65552102010-04-09 22:58:10295
[email protected]43a21b82010-06-10 21:30:54296 // Can we make another active socket now?
[email protected]5acdce12011-03-30 13:00:20297 if (!group->HasAvailableSocketSlot(max_sockets_per_group_) &&
298 !request->ignore_limits()) {
[email protected]43a21b82010-06-10 21:30:54299 request->net_log().AddEvent(
300 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
301 return ERR_IO_PENDING;
302 }
303
[email protected]5acdce12011-03-30 13:00:20304 if (ReachedMaxSocketsLimit() && !request->ignore_limits()) {
[email protected]43a21b82010-06-10 21:30:54305 if (idle_socket_count() > 0) {
[email protected]dcbe168a2010-12-02 03:14:46306 bool closed = CloseOneIdleSocketExceptInGroup(group);
307 if (preconnecting && !closed)
308 return ERR_PRECONNECT_MAX_SOCKET_LIMIT;
[email protected]43a21b82010-06-10 21:30:54309 } else {
310 // We could check if we really have a stalled group here, but it requires
311 // a scan of all groups, so just flip a flag here, and do the check later.
[email protected]43a21b82010-06-10 21:30:54312 request->net_log().AddEvent(
313 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
314 return ERR_IO_PENDING;
315 }
316 }
317
[email protected]ff579d42009-06-24 15:47:02318 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58319 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17320 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02321
[email protected]2c2bef152010-10-13 00:55:03322 connect_job->Initialize(preconnecting);
[email protected]2ab05b52009-07-01 23:57:58323 int rv = connect_job->Connect();
324 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17325 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2c2bef152010-10-13 00:55:03326 if (!preconnecting) {
327 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
328 handle, base::TimeDelta(), group, request->net_log());
329 } else {
330 AddIdleSocket(connect_job->ReleaseSocket(), group);
331 }
[email protected]2ab05b52009-07-01 23:57:58332 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32333 // If we don't have any sockets in this group, set a timer for potentially
334 // creating a new one. If the SYN is lost, this backup socket may complete
335 // before the slow socket, improving end user latency.
[email protected]2c2bef152010-10-13 00:55:03336 if (connect_backup_jobs_enabled_ &&
337 group->IsEmpty() && !group->HasBackupJob() &&
338 handle) {
[email protected]aed99ef02010-08-26 14:04:32339 group->StartBackupSocketTimer(group_name, this);
[email protected]2c2bef152010-10-13 00:55:03340 }
[email protected]6b624c62010-03-14 08:37:32341
[email protected]211d2172009-07-22 15:48:53342 connecting_socket_count_++;
343
[email protected]aed99ef02010-08-26 14:04:32344 group->AddJob(connect_job.release());
[email protected]a2006ece2010-04-23 16:44:02345 } else {
[email protected]06650c52010-06-03 00:49:17346 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]3268023f2011-05-05 00:08:10347 StreamSocket* error_socket = NULL;
[email protected]fd2e53e2011-01-14 20:40:52348 if (!preconnecting) {
349 DCHECK(handle);
350 connect_job->GetAdditionalErrorState(handle);
351 error_socket = connect_job->ReleaseSocket();
352 }
[email protected]e772db3f2010-07-12 18:11:13353 if (error_socket) {
354 HandOutSocket(error_socket, false /* not reused */, handle,
[email protected]aed99ef02010-08-26 14:04:32355 base::TimeDelta(), group, request->net_log());
356 } else if (group->IsEmpty()) {
357 RemoveGroup(group_name);
[email protected]05ea9ff2010-07-15 19:08:21358 }
[email protected]2ab05b52009-07-01 23:57:58359 }
[email protected]ff579d42009-06-24 15:47:02360
[email protected]2ab05b52009-07-01 23:57:58361 return rv;
[email protected]ff579d42009-06-24 15:47:02362}
363
[email protected]05ea9ff2010-07-15 19:08:21364bool ClientSocketPoolBaseHelper::AssignIdleSocketToGroup(
[email protected]aed99ef02010-08-26 14:04:32365 const Request* request, Group* group) {
[email protected]e1b54dc2010-10-06 21:27:22366 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
367 std::list<IdleSocket>::iterator idle_socket_it = idle_sockets->end();
368
369 // Iterate through the idle sockets forwards (oldest to newest)
370 // * Delete any disconnected ones.
371 // * If we find a used idle socket, assign to |idle_socket|. At the end,
372 // the |idle_socket_it| will be set to the newest used idle socket.
373 for (std::list<IdleSocket>::iterator it = idle_sockets->begin();
374 it != idle_sockets->end();) {
375 if (!it->socket->IsConnectedAndIdle()) {
376 DecrementIdleCount();
377 delete it->socket;
378 it = idle_sockets->erase(it);
379 continue;
[email protected]eb5a99382010-07-11 03:18:26380 }
[email protected]e1b54dc2010-10-06 21:27:22381
382 if (it->socket->WasEverUsed()) {
383 // We found one we can reuse!
384 idle_socket_it = it;
385 }
386
387 ++it;
[email protected]eb5a99382010-07-11 03:18:26388 }
[email protected]e1b54dc2010-10-06 21:27:22389
390 // If we haven't found an idle socket, that means there are no used idle
391 // sockets. Pick the oldest (first) idle socket (FIFO).
392
393 if (idle_socket_it == idle_sockets->end() && !idle_sockets->empty())
394 idle_socket_it = idle_sockets->begin();
395
396 if (idle_socket_it != idle_sockets->end()) {
397 DecrementIdleCount();
398 base::TimeDelta idle_time =
399 base::TimeTicks::Now() - idle_socket_it->start_time;
400 IdleSocket idle_socket = *idle_socket_it;
401 idle_sockets->erase(idle_socket_it);
402 HandOutSocket(
403 idle_socket.socket,
404 idle_socket.socket->WasEverUsed(),
405 request->handle(),
406 idle_time,
407 group,
408 request->net_log());
409 return true;
410 }
411
[email protected]eb5a99382010-07-11 03:18:26412 return false;
413}
414
[email protected]06650c52010-06-03 00:49:17415// static
416void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
417 const NetLog::Source& connect_job_source, const Request* request) {
418 request->net_log().AddEvent(
419 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
[email protected]00cd9c42010-11-02 20:15:57420 make_scoped_refptr(new NetLogSourceParameter(
421 "source_dependency", connect_job_source)));
[email protected]06650c52010-06-03 00:49:17422}
423
[email protected]d80a4322009-08-14 07:07:49424void ClientSocketPoolBaseHelper::CancelRequest(
[email protected]05ea9ff2010-07-15 19:08:21425 const std::string& group_name, ClientSocketHandle* handle) {
426 PendingCallbackMap::iterator callback_it = pending_callback_map_.find(handle);
427 if (callback_it != pending_callback_map_.end()) {
428 int result = callback_it->second.result;
429 pending_callback_map_.erase(callback_it);
[email protected]3268023f2011-05-05 00:08:10430 StreamSocket* socket = handle->release_socket();
[email protected]05ea9ff2010-07-15 19:08:21431 if (socket) {
432 if (result != OK)
433 socket->Disconnect();
434 ReleaseSocket(handle->group_name(), socket, handle->id());
435 }
436 return;
437 }
[email protected]b6501d3d2010-06-03 23:53:34438
[email protected]ff579d42009-06-24 15:47:02439 CHECK(ContainsKey(group_map_, group_name));
440
[email protected]aed99ef02010-08-26 14:04:32441 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02442
[email protected]ff579d42009-06-24 15:47:02443 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32444 RequestQueue::iterator it = group->mutable_pending_requests()->begin();
445 for (; it != group->pending_requests().end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49446 if ((*it)->handle() == handle) {
[email protected]2c2bef152010-10-13 00:55:03447 scoped_ptr<const Request> req(RemoveRequestFromQueue(it, group));
[email protected]ec11be62010-04-28 19:28:09448 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
449 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]eb5a99382010-07-11 03:18:26450
451 // We let the job run, unless we're at the socket limit.
[email protected]aed99ef02010-08-26 14:04:32452 if (group->jobs().size() && ReachedMaxSocketsLimit()) {
453 RemoveConnectJob(*group->jobs().begin(), group);
[email protected]eb5a99382010-07-11 03:18:26454 CheckForStalledSocketGroups();
[email protected]974ebd62009-08-03 23:14:34455 }
[email protected]eb5a99382010-07-11 03:18:26456 break;
[email protected]ff579d42009-06-24 15:47:02457 }
458 }
[email protected]ff579d42009-06-24 15:47:02459}
460
[email protected]2abfe90a2010-08-25 17:49:51461bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const {
462 return ContainsKey(group_map_, group_name);
463}
464
[email protected]d80a4322009-08-14 07:07:49465void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02466 CleanupIdleSockets(true);
[email protected]06f92462010-08-31 19:24:14467 DCHECK_EQ(0, idle_socket_count_);
[email protected]ff579d42009-06-24 15:47:02468}
469
[email protected]d80a4322009-08-14 07:07:49470int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02471 const std::string& group_name) const {
472 GroupMap::const_iterator i = group_map_.find(group_name);
473 CHECK(i != group_map_.end());
474
[email protected]aed99ef02010-08-26 14:04:32475 return i->second->idle_sockets().size();
[email protected]ff579d42009-06-24 15:47:02476}
477
[email protected]d80a4322009-08-14 07:07:49478LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02479 const std::string& group_name,
480 const ClientSocketHandle* handle) const {
[email protected]05ea9ff2010-07-15 19:08:21481 if (ContainsKey(pending_callback_map_, handle))
482 return LOAD_STATE_CONNECTING;
483
[email protected]ff579d42009-06-24 15:47:02484 if (!ContainsKey(group_map_, group_name)) {
485 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
486 << " for handle: " << handle;
487 return LOAD_STATE_IDLE;
488 }
489
490 // Can't use operator[] since it is non-const.
[email protected]aed99ef02010-08-26 14:04:32491 const Group& group = *group_map_.find(group_name)->second;
[email protected]ff579d42009-06-24 15:47:02492
[email protected]ff579d42009-06-24 15:47:02493 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32494 RequestQueue::const_iterator it = group.pending_requests().begin();
495 for (size_t i = 0; it != group.pending_requests().end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49496 if ((*it)->handle() == handle) {
[email protected]aed99ef02010-08-26 14:04:32497 if (i < group.jobs().size()) {
[email protected]5fc08e32009-07-15 17:09:57498 LoadState max_state = LOAD_STATE_IDLE;
[email protected]aed99ef02010-08-26 14:04:32499 for (ConnectJobSet::const_iterator job_it = group.jobs().begin();
500 job_it != group.jobs().end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21501 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57502 }
503 return max_state;
504 } else {
505 // TODO(wtc): Add a state for being on the wait list.
506 // See http://www.crbug.com/5077.
507 return LOAD_STATE_IDLE;
508 }
[email protected]ff579d42009-06-24 15:47:02509 }
510 }
511
512 NOTREACHED();
513 return LOAD_STATE_IDLE;
514}
515
[email protected]ba00b492010-09-08 14:53:38516DictionaryValue* ClientSocketPoolBaseHelper::GetInfoAsValue(
[email protected]59d7a5a2010-08-30 16:44:27517 const std::string& name, const std::string& type) const {
518 DictionaryValue* dict = new DictionaryValue();
519 dict->SetString("name", name);
520 dict->SetString("type", type);
521 dict->SetInteger("handed_out_socket_count", handed_out_socket_count_);
522 dict->SetInteger("connecting_socket_count", connecting_socket_count_);
523 dict->SetInteger("idle_socket_count", idle_socket_count_);
524 dict->SetInteger("max_socket_count", max_sockets_);
525 dict->SetInteger("max_sockets_per_group", max_sockets_per_group_);
526 dict->SetInteger("pool_generation_number", pool_generation_number_);
527
528 if (group_map_.empty())
529 return dict;
530
531 DictionaryValue* all_groups_dict = new DictionaryValue();
532 for (GroupMap::const_iterator it = group_map_.begin();
533 it != group_map_.end(); it++) {
534 const Group* group = it->second;
535 DictionaryValue* group_dict = new DictionaryValue();
536
537 group_dict->SetInteger("pending_request_count",
538 group->pending_requests().size());
539 if (!group->pending_requests().empty()) {
540 group_dict->SetInteger("top_pending_priority",
541 group->TopPendingPriority());
542 }
543
544 group_dict->SetInteger("active_socket_count", group->active_socket_count());
[email protected]0496f9a32010-09-30 16:08:07545
546 ListValue* idle_socket_list = new ListValue();
[email protected]e1b54dc2010-10-06 21:27:22547 std::list<IdleSocket>::const_iterator idle_socket;
[email protected]0496f9a32010-09-30 16:08:07548 for (idle_socket = group->idle_sockets().begin();
549 idle_socket != group->idle_sockets().end();
550 idle_socket++) {
551 int source_id = idle_socket->socket->NetLog().source().id;
552 idle_socket_list->Append(Value::CreateIntegerValue(source_id));
553 }
554 group_dict->Set("idle_sockets", idle_socket_list);
555
556 ListValue* connect_jobs_list = new ListValue();
[email protected]2c2bef152010-10-13 00:55:03557 std::set<ConnectJob*>::const_iterator job = group->jobs().begin();
[email protected]0496f9a32010-09-30 16:08:07558 for (job = group->jobs().begin(); job != group->jobs().end(); job++) {
559 int source_id = (*job)->net_log().source().id;
560 connect_jobs_list->Append(Value::CreateIntegerValue(source_id));
561 }
562 group_dict->Set("connect_jobs", connect_jobs_list);
[email protected]59d7a5a2010-08-30 16:44:27563
564 group_dict->SetBoolean("is_stalled",
565 group->IsStalled(max_sockets_per_group_));
566 group_dict->SetBoolean("has_backup_job", group->HasBackupJob());
567
568 all_groups_dict->SetWithoutPathExpansion(it->first, group_dict);
569 }
570 dict->Set("groups", all_groups_dict);
571 return dict;
572}
573
[email protected]d80a4322009-08-14 07:07:49574bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16575 base::TimeTicks now,
576 base::TimeDelta timeout) const {
577 bool timed_out = (now - start_time) >= timeout;
[email protected]0f873e82010-09-02 16:09:01578 if (timed_out)
579 return true;
580 if (socket->WasEverUsed())
581 return !socket->IsConnectedAndIdle();
582 return !socket->IsConnected();
[email protected]ff579d42009-06-24 15:47:02583}
584
[email protected]d80a4322009-08-14 07:07:49585void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02586 if (idle_socket_count_ == 0)
587 return;
588
589 // Current time value. Retrieving it once at the function start rather than
590 // inside the inner loop, since it shouldn't change by any meaningful amount.
591 base::TimeTicks now = base::TimeTicks::Now();
592
593 GroupMap::iterator i = group_map_.begin();
594 while (i != group_map_.end()) {
[email protected]aed99ef02010-08-26 14:04:32595 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02596
[email protected]e1b54dc2010-10-06 21:27:22597 std::list<IdleSocket>::iterator j = group->mutable_idle_sockets()->begin();
[email protected]aed99ef02010-08-26 14:04:32598 while (j != group->idle_sockets().end()) {
[email protected]9bf28db2009-08-29 01:35:16599 base::TimeDelta timeout =
[email protected]0f873e82010-09-02 16:09:01600 j->socket->WasEverUsed() ?
601 used_idle_socket_timeout_ : unused_idle_socket_timeout_;
[email protected]9bf28db2009-08-29 01:35:16602 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02603 delete j->socket;
[email protected]aed99ef02010-08-26 14:04:32604 j = group->mutable_idle_sockets()->erase(j);
[email protected]ff579d42009-06-24 15:47:02605 DecrementIdleCount();
606 } else {
607 ++j;
608 }
609 }
610
611 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32612 if (group->IsEmpty()) {
613 RemoveGroup(i++);
[email protected]ff579d42009-06-24 15:47:02614 } else {
615 ++i;
616 }
617 }
618}
619
[email protected]aed99ef02010-08-26 14:04:32620ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup(
621 const std::string& group_name) {
622 GroupMap::iterator it = group_map_.find(group_name);
623 if (it != group_map_.end())
624 return it->second;
625 Group* group = new Group;
626 group_map_[group_name] = group;
627 return group;
628}
629
630void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) {
631 GroupMap::iterator it = group_map_.find(group_name);
632 CHECK(it != group_map_.end());
633
634 RemoveGroup(it);
635}
636
637void ClientSocketPoolBaseHelper::RemoveGroup(GroupMap::iterator it) {
638 delete it->second;
639 group_map_.erase(it);
640}
641
[email protected]06d94042010-08-25 01:45:22642// static
[email protected]2d6728692011-03-12 01:39:55643bool ClientSocketPoolBaseHelper::connect_backup_jobs_enabled() {
644 return g_connect_backup_jobs_enabled;
645}
646
647// static
[email protected]636b8252011-04-08 19:56:54648bool ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(bool enabled) {
649 bool old_value = g_connect_backup_jobs_enabled;
[email protected]06d94042010-08-25 01:45:22650 g_connect_backup_jobs_enabled = enabled;
[email protected]636b8252011-04-08 19:56:54651 return old_value;
[email protected]06d94042010-08-25 01:45:22652}
653
654void ClientSocketPoolBaseHelper::EnableConnectBackupJobs() {
655 connect_backup_jobs_enabled_ = g_connect_backup_jobs_enabled;
656}
657
[email protected]d80a4322009-08-14 07:07:49658void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02659 if (++idle_socket_count_ == 1)
660 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49661 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02662}
663
[email protected]d80a4322009-08-14 07:07:49664void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02665 if (--idle_socket_count_ == 0)
666 timer_.Stop();
667}
668
[email protected]eb5a99382010-07-11 03:18:26669void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
[email protected]3268023f2011-05-05 00:08:10670 StreamSocket* socket,
[email protected]eb5a99382010-07-11 03:18:26671 int id) {
[email protected]ff579d42009-06-24 15:47:02672 GroupMap::iterator i = group_map_.find(group_name);
673 CHECK(i != group_map_.end());
674
[email protected]aed99ef02010-08-26 14:04:32675 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02676
[email protected]b1f031dd2010-03-02 23:19:33677 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53678 handed_out_socket_count_--;
679
[email protected]aed99ef02010-08-26 14:04:32680 CHECK_GT(group->active_socket_count(), 0);
681 group->DecrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02682
[email protected]a7e38572010-06-07 18:22:24683 const bool can_reuse = socket->IsConnectedAndIdle() &&
684 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02685 if (can_reuse) {
[email protected]eb5a99382010-07-11 03:18:26686 // Add it to the idle list.
[email protected]0f873e82010-09-02 16:09:01687 AddIdleSocket(socket, group);
[email protected]aed99ef02010-08-26 14:04:32688 OnAvailableSocketSlot(group_name, group);
[email protected]ff579d42009-06-24 15:47:02689 } else {
690 delete socket;
691 }
[email protected]05ea9ff2010-07-15 19:08:21692
[email protected]eb5a99382010-07-11 03:18:26693 CheckForStalledSocketGroups();
694}
[email protected]ff579d42009-06-24 15:47:02695
[email protected]eb5a99382010-07-11 03:18:26696void ClientSocketPoolBaseHelper::CheckForStalledSocketGroups() {
697 // If we have idle sockets, see if we can give one to the top-stalled group.
698 std::string top_group_name;
699 Group* top_group = NULL;
[email protected]05ea9ff2010-07-15 19:08:21700 if (!FindTopStalledGroup(&top_group, &top_group_name))
[email protected]eb5a99382010-07-11 03:18:26701 return;
[email protected]4f2abec2010-02-03 18:10:16702
[email protected]eb5a99382010-07-11 03:18:26703 if (ReachedMaxSocketsLimit()) {
704 if (idle_socket_count() > 0) {
705 CloseOneIdleSocket();
[email protected]d7027bb2010-05-10 18:58:54706 } else {
[email protected]eb5a99382010-07-11 03:18:26707 // We can't activate more sockets since we're already at our global
708 // limit.
[email protected]4f2abec2010-02-03 18:10:16709 return;
[email protected]d7027bb2010-05-10 18:58:54710 }
[email protected]4f2abec2010-02-03 18:10:16711 }
[email protected]eb5a99382010-07-11 03:18:26712
713 // Note: we don't loop on waking stalled groups. If the stalled group is at
714 // its limit, may be left with other stalled groups that could be
[email protected]05ea9ff2010-07-15 19:08:21715 // woken. This isn't optimal, but there is no starvation, so to avoid
[email protected]eb5a99382010-07-11 03:18:26716 // the looping we leave it at this.
[email protected]05ea9ff2010-07-15 19:08:21717 OnAvailableSocketSlot(top_group_name, top_group);
[email protected]ff579d42009-06-24 15:47:02718}
719
[email protected]211d2172009-07-22 15:48:53720// Search for the highest priority pending request, amongst the groups that
721// are not at the |max_sockets_per_group_| limit. Note: for requests with
722// the same priority, the winner is based on group hash ordering (and not
723// insertion order).
[email protected]05ea9ff2010-07-15 19:08:21724bool ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
725 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53726 Group* top_group = NULL;
727 const std::string* top_group_name = NULL;
[email protected]05ea9ff2010-07-15 19:08:21728 bool has_stalled_group = false;
[email protected]211d2172009-07-22 15:48:53729 for (GroupMap::iterator i = group_map_.begin();
730 i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32731 Group* curr_group = i->second;
732 const RequestQueue& queue = curr_group->pending_requests();
[email protected]211d2172009-07-22 15:48:53733 if (queue.empty())
734 continue;
[email protected]aed99ef02010-08-26 14:04:32735 if (curr_group->IsStalled(max_sockets_per_group_)) {
[email protected]05ea9ff2010-07-15 19:08:21736 has_stalled_group = true;
[email protected]6427fe22010-04-16 22:27:41737 bool has_higher_priority = !top_group ||
[email protected]aed99ef02010-08-26 14:04:32738 curr_group->TopPendingPriority() < top_group->TopPendingPriority();
[email protected]6427fe22010-04-16 22:27:41739 if (has_higher_priority) {
[email protected]aed99ef02010-08-26 14:04:32740 top_group = curr_group;
[email protected]6427fe22010-04-16 22:27:41741 top_group_name = &i->first;
742 }
[email protected]211d2172009-07-22 15:48:53743 }
744 }
[email protected]05ea9ff2010-07-15 19:08:21745
[email protected]211d2172009-07-22 15:48:53746 if (top_group) {
747 *group = top_group;
748 *group_name = *top_group_name;
749 }
[email protected]05ea9ff2010-07-15 19:08:21750 return has_stalled_group;
[email protected]211d2172009-07-22 15:48:53751}
752
[email protected]d80a4322009-08-14 07:07:49753void ClientSocketPoolBaseHelper::OnConnectJobComplete(
754 int result, ConnectJob* job) {
[email protected]2ab05b52009-07-01 23:57:58755 DCHECK_NE(ERR_IO_PENDING, result);
756 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02757 GroupMap::iterator group_it = group_map_.find(group_name);
758 CHECK(group_it != group_map_.end());
[email protected]aed99ef02010-08-26 14:04:32759 Group* group = group_it->second;
[email protected]ff579d42009-06-24 15:47:02760
[email protected]3268023f2011-05-05 00:08:10761 scoped_ptr<StreamSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02762
[email protected]9e743cd2010-03-16 07:03:53763 BoundNetLog job_log = job->net_log();
[email protected]5fc08e32009-07-15 17:09:57764
[email protected]4d3b05d2010-01-27 21:27:29765 if (result == OK) {
766 DCHECK(socket.get());
[email protected]aed99ef02010-08-26 14:04:32767 RemoveConnectJob(job, group);
768 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29769 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02770 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17771 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29772 HandOutSocket(
773 socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32774 base::TimeDelta(), group, r->net_log());
[email protected]06650c52010-06-03 00:49:17775 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21776 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]5fc08e32009-07-15 17:09:57777 } else {
[email protected]0f873e82010-09-02 16:09:01778 AddIdleSocket(socket.release(), group);
[email protected]aed99ef02010-08-26 14:04:32779 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21780 CheckForStalledSocketGroups();
[email protected]5fc08e32009-07-15 17:09:57781 }
[email protected]94c20472010-01-14 08:14:36782 } else {
[email protected]e772db3f2010-07-12 18:11:13783 // If we got a socket, it must contain error information so pass that
784 // up so that the caller can retrieve it.
785 bool handed_out_socket = false;
[email protected]aed99ef02010-08-26 14:04:32786 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29787 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02788 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17789 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]e60e47a2010-07-14 03:37:18790 job->GetAdditionalErrorState(r->handle());
[email protected]aed99ef02010-08-26 14:04:32791 RemoveConnectJob(job, group);
[email protected]e772db3f2010-07-12 18:11:13792 if (socket.get()) {
793 handed_out_socket = true;
794 HandOutSocket(socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32795 base::TimeDelta(), group, r->net_log());
[email protected]e772db3f2010-07-12 18:11:13796 }
[email protected]d7fd1782011-02-08 19:16:43797 r->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL,
798 result);
[email protected]05ea9ff2010-07-15 19:08:21799 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]e60e47a2010-07-14 03:37:18800 } else {
[email protected]aed99ef02010-08-26 14:04:32801 RemoveConnectJob(job, group);
[email protected]4d3b05d2010-01-27 21:27:29802 }
[email protected]05ea9ff2010-07-15 19:08:21803 if (!handed_out_socket) {
[email protected]aed99ef02010-08-26 14:04:32804 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21805 CheckForStalledSocketGroups();
806 }
[email protected]ff579d42009-06-24 15:47:02807 }
[email protected]ff579d42009-06-24 15:47:02808}
809
[email protected]66761b952010-06-25 21:30:38810void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
811 Flush();
812}
813
[email protected]a7e38572010-06-07 18:22:24814void ClientSocketPoolBaseHelper::Flush() {
815 pool_generation_number_++;
[email protected]06f92462010-08-31 19:24:14816 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52817 CloseIdleSockets();
[email protected]06f92462010-08-31 19:24:14818 AbortAllRequests();
[email protected]a554a8262010-05-20 00:13:52819}
820
[email protected]2c2bef152010-10-13 00:55:03821void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job,
[email protected]4d3b05d2010-01-27 21:27:29822 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33823 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53824 connecting_socket_count_--;
825
[email protected]25eea382010-07-10 23:55:26826 DCHECK(group);
[email protected]aed99ef02010-08-26 14:04:32827 DCHECK(ContainsKey(group->jobs(), job));
828 group->RemoveJob(job);
[email protected]25eea382010-07-10 23:55:26829
830 // If we've got no more jobs for this group, then we no longer need a
831 // backup job either.
[email protected]aed99ef02010-08-26 14:04:32832 if (group->jobs().empty())
[email protected]25eea382010-07-10 23:55:26833 group->CleanupBackupJob();
834
[email protected]8ae03f42010-07-07 19:08:10835 DCHECK(job);
836 delete job;
[email protected]2ab05b52009-07-01 23:57:58837}
[email protected]ff579d42009-06-24 15:47:02838
[email protected]8ae03f42010-07-07 19:08:10839void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
[email protected]05ea9ff2010-07-15 19:08:21840 const std::string& group_name, Group* group) {
[email protected]2abfe90a2010-08-25 17:49:51841 DCHECK(ContainsKey(group_map_, group_name));
[email protected]05ea9ff2010-07-15 19:08:21842 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32843 RemoveGroup(group_name);
844 else if (!group->pending_requests().empty())
[email protected]2abfe90a2010-08-25 17:49:51845 ProcessPendingRequest(group_name, group);
[email protected]8ae03f42010-07-07 19:08:10846}
[email protected]06650c52010-06-03 00:49:17847
[email protected]8ae03f42010-07-07 19:08:10848void ClientSocketPoolBaseHelper::ProcessPendingRequest(
[email protected]05ea9ff2010-07-15 19:08:21849 const std::string& group_name, Group* group) {
850 int rv = RequestSocketInternal(group_name,
[email protected]aed99ef02010-08-26 14:04:32851 *group->pending_requests().begin());
[email protected]05ea9ff2010-07-15 19:08:21852 if (rv != ERR_IO_PENDING) {
853 scoped_ptr<const Request> request(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02854 group->mutable_pending_requests()->begin(), group));
[email protected]2abfe90a2010-08-25 17:49:51855 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32856 RemoveGroup(group_name);
[email protected]8ae03f42010-07-07 19:08:10857
[email protected]d7fd1782011-02-08 19:16:43858 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21859 InvokeUserCallbackLater(
860 request->handle(), request->callback(), rv);
[email protected]2ab05b52009-07-01 23:57:58861 }
862}
863
[email protected]d80a4322009-08-14 07:07:49864void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]3268023f2011-05-05 00:08:10865 StreamSocket* socket,
[email protected]2ab05b52009-07-01 23:57:58866 bool reused,
867 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29868 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15869 Group* group,
[email protected]9e743cd2010-03-16 07:03:53870 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58871 DCHECK(socket);
872 handle->set_socket(socket);
873 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29874 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24875 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53876
[email protected]d13f51b2010-04-27 23:20:45877 if (reused) {
[email protected]ec11be62010-04-28 19:28:09878 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45879 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57880 make_scoped_refptr(new NetLogIntegerParameter(
881 "idle_ms", static_cast<int>(idle_time.InMilliseconds()))));
[email protected]fd4fe0b2010-02-08 23:02:15882 }
[email protected]d13f51b2010-04-27 23:20:45883
[email protected]06650c52010-06-03 00:49:17884 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57885 make_scoped_refptr(new NetLogSourceParameter(
886 "source_dependency", socket->NetLog().source())));
[email protected]fd4fe0b2010-02-08 23:02:15887
[email protected]211d2172009-07-22 15:48:53888 handed_out_socket_count_++;
[email protected]aed99ef02010-08-26 14:04:32889 group->IncrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02890}
891
[email protected]d80a4322009-08-14 07:07:49892void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]3268023f2011-05-05 00:08:10893 StreamSocket* socket, Group* group) {
[email protected]5fc08e32009-07-15 17:09:57894 DCHECK(socket);
895 IdleSocket idle_socket;
896 idle_socket.socket = socket;
897 idle_socket.start_time = base::TimeTicks::Now();
[email protected]5fc08e32009-07-15 17:09:57898
[email protected]aed99ef02010-08-26 14:04:32899 group->mutable_idle_sockets()->push_back(idle_socket);
[email protected]5fc08e32009-07-15 17:09:57900 IncrementIdleCount();
901}
902
[email protected]d80a4322009-08-14 07:07:49903void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]74d75e0b2010-08-23 20:39:54904 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
[email protected]aed99ef02010-08-26 14:04:32905 Group* group = i->second;
906 connecting_socket_count_ -= group->jobs().size();
907 group->RemoveAllJobs();
[email protected]6b624c62010-03-14 08:37:32908
[email protected]5fc08e32009-07-15 17:09:57909 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32910 if (group->IsEmpty()) {
[email protected]06f92462010-08-31 19:24:14911 // RemoveGroup() will call .erase() which will invalidate the iterator,
912 // but i will already have been incremented to a valid iterator before
913 // RemoveGroup() is called.
914 RemoveGroup(i++);
915 } else {
916 ++i;
917 }
918 }
919 DCHECK_EQ(0, connecting_socket_count_);
920}
921
922void ClientSocketPoolBaseHelper::AbortAllRequests() {
923 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
924 Group* group = i->second;
925
926 RequestQueue pending_requests;
927 pending_requests.swap(*group->mutable_pending_requests());
928 for (RequestQueue::iterator it2 = pending_requests.begin();
929 it2 != pending_requests.end(); ++it2) {
[email protected]2c2bef152010-10-13 00:55:03930 scoped_ptr<const Request> request(*it2);
[email protected]06f92462010-08-31 19:24:14931 InvokeUserCallbackLater(
932 request->handle(), request->callback(), ERR_ABORTED);
933 }
934
935 // Delete group if no longer needed.
936 if (group->IsEmpty()) {
937 // RemoveGroup() will call .erase() which will invalidate the iterator,
938 // but i will already have been incremented to a valid iterator before
939 // RemoveGroup() is called.
[email protected]aed99ef02010-08-26 14:04:32940 RemoveGroup(i++);
[email protected]74d75e0b2010-08-23 20:39:54941 } else {
942 ++i;
[email protected]5fc08e32009-07-15 17:09:57943 }
944 }
945}
946
[email protected]d80a4322009-08-14 07:07:49947bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53948 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54949 int total = handed_out_socket_count_ + connecting_socket_count_ +
950 idle_socket_count();
[email protected]5acdce12011-03-30 13:00:20951 // There can be more sockets than the limit since some requests can ignore
952 // the limit
[email protected]c901f6d2010-04-27 17:48:28953 if (total < max_sockets_)
954 return false;
[email protected]c901f6d2010-04-27 17:48:28955 return true;
[email protected]211d2172009-07-22 15:48:53956}
957
[email protected]43a21b82010-06-10 21:30:54958void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
[email protected]dcbe168a2010-12-02 03:14:46959 CloseOneIdleSocketExceptInGroup(NULL);
960}
961
962bool ClientSocketPoolBaseHelper::CloseOneIdleSocketExceptInGroup(
963 const Group* exception_group) {
[email protected]43a21b82010-06-10 21:30:54964 CHECK_GT(idle_socket_count(), 0);
965
966 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32967 Group* group = i->second;
[email protected]dcbe168a2010-12-02 03:14:46968 if (exception_group == group)
969 continue;
[email protected]e1b54dc2010-10-06 21:27:22970 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
[email protected]43a21b82010-06-10 21:30:54971
[email protected]e1b54dc2010-10-06 21:27:22972 if (!idle_sockets->empty()) {
973 delete idle_sockets->front().socket;
974 idle_sockets->pop_front();
[email protected]43a21b82010-06-10 21:30:54975 DecrementIdleCount();
[email protected]aed99ef02010-08-26 14:04:32976 if (group->IsEmpty())
977 RemoveGroup(i);
[email protected]43a21b82010-06-10 21:30:54978
[email protected]dcbe168a2010-12-02 03:14:46979 return true;
[email protected]43a21b82010-06-10 21:30:54980 }
981 }
982
[email protected]dcbe168a2010-12-02 03:14:46983 if (!exception_group)
984 LOG(DFATAL) << "No idle socket found to close!.";
985
986 return false;
[email protected]43a21b82010-06-10 21:30:54987}
988
[email protected]05ea9ff2010-07-15 19:08:21989void ClientSocketPoolBaseHelper::InvokeUserCallbackLater(
990 ClientSocketHandle* handle, CompletionCallback* callback, int rv) {
991 CHECK(!ContainsKey(pending_callback_map_, handle));
992 pending_callback_map_[handle] = CallbackResultPair(callback, rv);
993 MessageLoop::current()->PostTask(
994 FROM_HERE,
[email protected]2431756e2010-09-29 20:26:13995 method_factory_.NewRunnableMethod(
[email protected]05ea9ff2010-07-15 19:08:21996 &ClientSocketPoolBaseHelper::InvokeUserCallback,
997 handle));
998}
999
1000void ClientSocketPoolBaseHelper::InvokeUserCallback(
1001 ClientSocketHandle* handle) {
1002 PendingCallbackMap::iterator it = pending_callback_map_.find(handle);
1003
1004 // Exit if the request has already been cancelled.
1005 if (it == pending_callback_map_.end())
1006 return;
1007
1008 CHECK(!handle->is_initialized());
1009 CompletionCallback* callback = it->second.callback;
1010 int result = it->second.result;
1011 pending_callback_map_.erase(it);
1012 callback->Run(result);
1013}
1014
[email protected]aed99ef02010-08-26 14:04:321015ClientSocketPoolBaseHelper::Group::Group()
1016 : active_socket_count_(0),
1017 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}
1018
1019ClientSocketPoolBaseHelper::Group::~Group() {
1020 CleanupBackupJob();
1021}
1022
1023void ClientSocketPoolBaseHelper::Group::StartBackupSocketTimer(
1024 const std::string& group_name,
1025 ClientSocketPoolBaseHelper* pool) {
1026 // Only allow one timer pending to create a backup socket.
1027 if (!method_factory_.empty())
1028 return;
1029
1030 MessageLoop::current()->PostDelayedTask(
1031 FROM_HERE,
1032 method_factory_.NewRunnableMethod(
1033 &Group::OnBackupSocketTimerFired, group_name, pool),
1034 pool->ConnectRetryIntervalMs());
1035}
1036
[email protected]2c2bef152010-10-13 00:55:031037bool ClientSocketPoolBaseHelper::Group::TryToUsePreconnectConnectJob() {
1038 for (std::set<ConnectJob*>::iterator it = jobs_.begin();
1039 it != jobs_.end(); ++it) {
1040 ConnectJob* job = *it;
1041 if (job->is_unused_preconnect()) {
1042 job->UseForNormalRequest();
1043 return true;
1044 }
1045 }
1046 return false;
1047}
1048
[email protected]aed99ef02010-08-26 14:04:321049void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired(
1050 std::string group_name,
1051 ClientSocketPoolBaseHelper* pool) {
1052 // If there are no more jobs pending, there is no work to do.
1053 // If we've done our cleanups correctly, this should not happen.
1054 if (jobs_.empty()) {
1055 NOTREACHED();
1056 return;
1057 }
1058
1059 // If our backup job is waiting on DNS, or if we can't create any sockets
1060 // right now due to limits, just reset the timer.
1061 if (pool->ReachedMaxSocketsLimit() ||
1062 !HasAvailableSocketSlot(pool->max_sockets_per_group_) ||
1063 (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
1064 StartBackupSocketTimer(group_name, pool);
1065 return;
1066 }
1067
[email protected]4baaf9d2010-08-31 15:15:441068 if (pending_requests_.empty()) {
1069 LOG(DFATAL) << "No pending request for backup job.";
1070 return;
1071 }
1072
[email protected]aed99ef02010-08-26 14:04:321073 ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob(
1074 group_name, **pending_requests_.begin(), pool);
1075 backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED, NULL);
1076 SIMPLE_STATS_COUNTER("socket.backup_created");
[email protected]0d1f4c42011-05-05 15:27:501077 // The purpose of the backup job is to initiate a new connect job when the
1078 // first connect job takes too long. We call set_prefer_ipv4 here to use
1079 // the backup job for a second purpose: if the first connect job is IPv6,
1080 // try an IPv4 connect job in parallel. This hides the long timeout error
1081 // on some networks with broken IPv6 support.
1082 // TODO(wtc): remove the set_prefer_ipv4 call when broken IPv6 networks are
1083 // gone.
1084 backup_job->set_prefer_ipv4();
[email protected]aed99ef02010-08-26 14:04:321085 int rv = backup_job->Connect();
1086 pool->connecting_socket_count_++;
1087 AddJob(backup_job);
1088 if (rv != ERR_IO_PENDING)
1089 pool->OnConnectJobComplete(rv, backup_job);
1090}
1091
1092void ClientSocketPoolBaseHelper::Group::RemoveAllJobs() {
1093 // Delete active jobs.
1094 STLDeleteElements(&jobs_);
1095
1096 // Cancel pending backup job.
1097 method_factory_.RevokeAll();
1098}
1099
[email protected]d80a4322009-08-14 07:07:491100} // namespace internal
1101
[email protected]ff579d42009-06-24 15:47:021102} // namespace net