blob: 09725345b8b01bcce22e8b10a4cba2f0099308d2 [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_ &&
[email protected]a9fc8fc2011-05-10 02:41:07337 group->IsEmpty() && !group->HasBackupJob()) {
[email protected]aed99ef02010-08-26 14:04:32338 group->StartBackupSocketTimer(group_name, this);
[email protected]2c2bef152010-10-13 00:55:03339 }
[email protected]6b624c62010-03-14 08:37:32340
[email protected]211d2172009-07-22 15:48:53341 connecting_socket_count_++;
342
[email protected]aed99ef02010-08-26 14:04:32343 group->AddJob(connect_job.release());
[email protected]a2006ece2010-04-23 16:44:02344 } else {
[email protected]06650c52010-06-03 00:49:17345 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]3268023f2011-05-05 00:08:10346 StreamSocket* error_socket = NULL;
[email protected]fd2e53e2011-01-14 20:40:52347 if (!preconnecting) {
348 DCHECK(handle);
349 connect_job->GetAdditionalErrorState(handle);
350 error_socket = connect_job->ReleaseSocket();
351 }
[email protected]e772db3f2010-07-12 18:11:13352 if (error_socket) {
353 HandOutSocket(error_socket, false /* not reused */, handle,
[email protected]aed99ef02010-08-26 14:04:32354 base::TimeDelta(), group, request->net_log());
355 } else if (group->IsEmpty()) {
356 RemoveGroup(group_name);
[email protected]05ea9ff2010-07-15 19:08:21357 }
[email protected]2ab05b52009-07-01 23:57:58358 }
[email protected]ff579d42009-06-24 15:47:02359
[email protected]2ab05b52009-07-01 23:57:58360 return rv;
[email protected]ff579d42009-06-24 15:47:02361}
362
[email protected]05ea9ff2010-07-15 19:08:21363bool ClientSocketPoolBaseHelper::AssignIdleSocketToGroup(
[email protected]aed99ef02010-08-26 14:04:32364 const Request* request, Group* group) {
[email protected]e1b54dc2010-10-06 21:27:22365 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
366 std::list<IdleSocket>::iterator idle_socket_it = idle_sockets->end();
367
368 // Iterate through the idle sockets forwards (oldest to newest)
369 // * Delete any disconnected ones.
370 // * If we find a used idle socket, assign to |idle_socket|. At the end,
371 // the |idle_socket_it| will be set to the newest used idle socket.
372 for (std::list<IdleSocket>::iterator it = idle_sockets->begin();
373 it != idle_sockets->end();) {
374 if (!it->socket->IsConnectedAndIdle()) {
375 DecrementIdleCount();
376 delete it->socket;
377 it = idle_sockets->erase(it);
378 continue;
[email protected]eb5a99382010-07-11 03:18:26379 }
[email protected]e1b54dc2010-10-06 21:27:22380
381 if (it->socket->WasEverUsed()) {
382 // We found one we can reuse!
383 idle_socket_it = it;
384 }
385
386 ++it;
[email protected]eb5a99382010-07-11 03:18:26387 }
[email protected]e1b54dc2010-10-06 21:27:22388
389 // If we haven't found an idle socket, that means there are no used idle
390 // sockets. Pick the oldest (first) idle socket (FIFO).
391
392 if (idle_socket_it == idle_sockets->end() && !idle_sockets->empty())
393 idle_socket_it = idle_sockets->begin();
394
395 if (idle_socket_it != idle_sockets->end()) {
396 DecrementIdleCount();
397 base::TimeDelta idle_time =
398 base::TimeTicks::Now() - idle_socket_it->start_time;
399 IdleSocket idle_socket = *idle_socket_it;
400 idle_sockets->erase(idle_socket_it);
401 HandOutSocket(
402 idle_socket.socket,
403 idle_socket.socket->WasEverUsed(),
404 request->handle(),
405 idle_time,
406 group,
407 request->net_log());
408 return true;
409 }
410
[email protected]eb5a99382010-07-11 03:18:26411 return false;
412}
413
[email protected]06650c52010-06-03 00:49:17414// static
415void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
416 const NetLog::Source& connect_job_source, const Request* request) {
417 request->net_log().AddEvent(
418 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
[email protected]00cd9c42010-11-02 20:15:57419 make_scoped_refptr(new NetLogSourceParameter(
420 "source_dependency", connect_job_source)));
[email protected]06650c52010-06-03 00:49:17421}
422
[email protected]d80a4322009-08-14 07:07:49423void ClientSocketPoolBaseHelper::CancelRequest(
[email protected]05ea9ff2010-07-15 19:08:21424 const std::string& group_name, ClientSocketHandle* handle) {
425 PendingCallbackMap::iterator callback_it = pending_callback_map_.find(handle);
426 if (callback_it != pending_callback_map_.end()) {
427 int result = callback_it->second.result;
428 pending_callback_map_.erase(callback_it);
[email protected]3268023f2011-05-05 00:08:10429 StreamSocket* socket = handle->release_socket();
[email protected]05ea9ff2010-07-15 19:08:21430 if (socket) {
431 if (result != OK)
432 socket->Disconnect();
433 ReleaseSocket(handle->group_name(), socket, handle->id());
434 }
435 return;
436 }
[email protected]b6501d3d2010-06-03 23:53:34437
[email protected]ff579d42009-06-24 15:47:02438 CHECK(ContainsKey(group_map_, group_name));
439
[email protected]aed99ef02010-08-26 14:04:32440 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02441
[email protected]ff579d42009-06-24 15:47:02442 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32443 RequestQueue::iterator it = group->mutable_pending_requests()->begin();
444 for (; it != group->pending_requests().end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49445 if ((*it)->handle() == handle) {
[email protected]2c2bef152010-10-13 00:55:03446 scoped_ptr<const Request> req(RemoveRequestFromQueue(it, group));
[email protected]ec11be62010-04-28 19:28:09447 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
448 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]eb5a99382010-07-11 03:18:26449
450 // We let the job run, unless we're at the socket limit.
[email protected]aed99ef02010-08-26 14:04:32451 if (group->jobs().size() && ReachedMaxSocketsLimit()) {
452 RemoveConnectJob(*group->jobs().begin(), group);
[email protected]eb5a99382010-07-11 03:18:26453 CheckForStalledSocketGroups();
[email protected]974ebd62009-08-03 23:14:34454 }
[email protected]eb5a99382010-07-11 03:18:26455 break;
[email protected]ff579d42009-06-24 15:47:02456 }
457 }
[email protected]ff579d42009-06-24 15:47:02458}
459
[email protected]2abfe90a2010-08-25 17:49:51460bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const {
461 return ContainsKey(group_map_, group_name);
462}
463
[email protected]d80a4322009-08-14 07:07:49464void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02465 CleanupIdleSockets(true);
[email protected]06f92462010-08-31 19:24:14466 DCHECK_EQ(0, idle_socket_count_);
[email protected]ff579d42009-06-24 15:47:02467}
468
[email protected]d80a4322009-08-14 07:07:49469int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02470 const std::string& group_name) const {
471 GroupMap::const_iterator i = group_map_.find(group_name);
472 CHECK(i != group_map_.end());
473
[email protected]aed99ef02010-08-26 14:04:32474 return i->second->idle_sockets().size();
[email protected]ff579d42009-06-24 15:47:02475}
476
[email protected]d80a4322009-08-14 07:07:49477LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02478 const std::string& group_name,
479 const ClientSocketHandle* handle) const {
[email protected]05ea9ff2010-07-15 19:08:21480 if (ContainsKey(pending_callback_map_, handle))
481 return LOAD_STATE_CONNECTING;
482
[email protected]ff579d42009-06-24 15:47:02483 if (!ContainsKey(group_map_, group_name)) {
484 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
485 << " for handle: " << handle;
486 return LOAD_STATE_IDLE;
487 }
488
489 // Can't use operator[] since it is non-const.
[email protected]aed99ef02010-08-26 14:04:32490 const Group& group = *group_map_.find(group_name)->second;
[email protected]ff579d42009-06-24 15:47:02491
[email protected]ff579d42009-06-24 15:47:02492 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32493 RequestQueue::const_iterator it = group.pending_requests().begin();
494 for (size_t i = 0; it != group.pending_requests().end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49495 if ((*it)->handle() == handle) {
[email protected]aed99ef02010-08-26 14:04:32496 if (i < group.jobs().size()) {
[email protected]5fc08e32009-07-15 17:09:57497 LoadState max_state = LOAD_STATE_IDLE;
[email protected]aed99ef02010-08-26 14:04:32498 for (ConnectJobSet::const_iterator job_it = group.jobs().begin();
499 job_it != group.jobs().end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21500 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57501 }
502 return max_state;
503 } else {
504 // TODO(wtc): Add a state for being on the wait list.
505 // See http://www.crbug.com/5077.
506 return LOAD_STATE_IDLE;
507 }
[email protected]ff579d42009-06-24 15:47:02508 }
509 }
510
511 NOTREACHED();
512 return LOAD_STATE_IDLE;
513}
514
[email protected]ba00b492010-09-08 14:53:38515DictionaryValue* ClientSocketPoolBaseHelper::GetInfoAsValue(
[email protected]59d7a5a2010-08-30 16:44:27516 const std::string& name, const std::string& type) const {
517 DictionaryValue* dict = new DictionaryValue();
518 dict->SetString("name", name);
519 dict->SetString("type", type);
520 dict->SetInteger("handed_out_socket_count", handed_out_socket_count_);
521 dict->SetInteger("connecting_socket_count", connecting_socket_count_);
522 dict->SetInteger("idle_socket_count", idle_socket_count_);
523 dict->SetInteger("max_socket_count", max_sockets_);
524 dict->SetInteger("max_sockets_per_group", max_sockets_per_group_);
525 dict->SetInteger("pool_generation_number", pool_generation_number_);
526
527 if (group_map_.empty())
528 return dict;
529
530 DictionaryValue* all_groups_dict = new DictionaryValue();
531 for (GroupMap::const_iterator it = group_map_.begin();
532 it != group_map_.end(); it++) {
533 const Group* group = it->second;
534 DictionaryValue* group_dict = new DictionaryValue();
535
536 group_dict->SetInteger("pending_request_count",
537 group->pending_requests().size());
538 if (!group->pending_requests().empty()) {
539 group_dict->SetInteger("top_pending_priority",
540 group->TopPendingPriority());
541 }
542
543 group_dict->SetInteger("active_socket_count", group->active_socket_count());
[email protected]0496f9a32010-09-30 16:08:07544
545 ListValue* idle_socket_list = new ListValue();
[email protected]e1b54dc2010-10-06 21:27:22546 std::list<IdleSocket>::const_iterator idle_socket;
[email protected]0496f9a32010-09-30 16:08:07547 for (idle_socket = group->idle_sockets().begin();
548 idle_socket != group->idle_sockets().end();
549 idle_socket++) {
550 int source_id = idle_socket->socket->NetLog().source().id;
551 idle_socket_list->Append(Value::CreateIntegerValue(source_id));
552 }
553 group_dict->Set("idle_sockets", idle_socket_list);
554
555 ListValue* connect_jobs_list = new ListValue();
[email protected]2c2bef152010-10-13 00:55:03556 std::set<ConnectJob*>::const_iterator job = group->jobs().begin();
[email protected]0496f9a32010-09-30 16:08:07557 for (job = group->jobs().begin(); job != group->jobs().end(); job++) {
558 int source_id = (*job)->net_log().source().id;
559 connect_jobs_list->Append(Value::CreateIntegerValue(source_id));
560 }
561 group_dict->Set("connect_jobs", connect_jobs_list);
[email protected]59d7a5a2010-08-30 16:44:27562
563 group_dict->SetBoolean("is_stalled",
564 group->IsStalled(max_sockets_per_group_));
565 group_dict->SetBoolean("has_backup_job", group->HasBackupJob());
566
567 all_groups_dict->SetWithoutPathExpansion(it->first, group_dict);
568 }
569 dict->Set("groups", all_groups_dict);
570 return dict;
571}
572
[email protected]d80a4322009-08-14 07:07:49573bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16574 base::TimeTicks now,
575 base::TimeDelta timeout) const {
576 bool timed_out = (now - start_time) >= timeout;
[email protected]0f873e82010-09-02 16:09:01577 if (timed_out)
578 return true;
579 if (socket->WasEverUsed())
580 return !socket->IsConnectedAndIdle();
581 return !socket->IsConnected();
[email protected]ff579d42009-06-24 15:47:02582}
583
[email protected]d80a4322009-08-14 07:07:49584void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02585 if (idle_socket_count_ == 0)
586 return;
587
588 // Current time value. Retrieving it once at the function start rather than
589 // inside the inner loop, since it shouldn't change by any meaningful amount.
590 base::TimeTicks now = base::TimeTicks::Now();
591
592 GroupMap::iterator i = group_map_.begin();
593 while (i != group_map_.end()) {
[email protected]aed99ef02010-08-26 14:04:32594 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02595
[email protected]e1b54dc2010-10-06 21:27:22596 std::list<IdleSocket>::iterator j = group->mutable_idle_sockets()->begin();
[email protected]aed99ef02010-08-26 14:04:32597 while (j != group->idle_sockets().end()) {
[email protected]9bf28db2009-08-29 01:35:16598 base::TimeDelta timeout =
[email protected]0f873e82010-09-02 16:09:01599 j->socket->WasEverUsed() ?
600 used_idle_socket_timeout_ : unused_idle_socket_timeout_;
[email protected]9bf28db2009-08-29 01:35:16601 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02602 delete j->socket;
[email protected]aed99ef02010-08-26 14:04:32603 j = group->mutable_idle_sockets()->erase(j);
[email protected]ff579d42009-06-24 15:47:02604 DecrementIdleCount();
605 } else {
606 ++j;
607 }
608 }
609
610 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32611 if (group->IsEmpty()) {
612 RemoveGroup(i++);
[email protected]ff579d42009-06-24 15:47:02613 } else {
614 ++i;
615 }
616 }
617}
618
[email protected]aed99ef02010-08-26 14:04:32619ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup(
620 const std::string& group_name) {
621 GroupMap::iterator it = group_map_.find(group_name);
622 if (it != group_map_.end())
623 return it->second;
624 Group* group = new Group;
625 group_map_[group_name] = group;
626 return group;
627}
628
629void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) {
630 GroupMap::iterator it = group_map_.find(group_name);
631 CHECK(it != group_map_.end());
632
633 RemoveGroup(it);
634}
635
636void ClientSocketPoolBaseHelper::RemoveGroup(GroupMap::iterator it) {
637 delete it->second;
638 group_map_.erase(it);
639}
640
[email protected]06d94042010-08-25 01:45:22641// static
[email protected]2d6728692011-03-12 01:39:55642bool ClientSocketPoolBaseHelper::connect_backup_jobs_enabled() {
643 return g_connect_backup_jobs_enabled;
644}
645
646// static
[email protected]636b8252011-04-08 19:56:54647bool ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(bool enabled) {
648 bool old_value = g_connect_backup_jobs_enabled;
[email protected]06d94042010-08-25 01:45:22649 g_connect_backup_jobs_enabled = enabled;
[email protected]636b8252011-04-08 19:56:54650 return old_value;
[email protected]06d94042010-08-25 01:45:22651}
652
653void ClientSocketPoolBaseHelper::EnableConnectBackupJobs() {
654 connect_backup_jobs_enabled_ = g_connect_backup_jobs_enabled;
655}
656
[email protected]d80a4322009-08-14 07:07:49657void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02658 if (++idle_socket_count_ == 1)
659 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49660 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02661}
662
[email protected]d80a4322009-08-14 07:07:49663void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02664 if (--idle_socket_count_ == 0)
665 timer_.Stop();
666}
667
[email protected]eb5a99382010-07-11 03:18:26668void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
[email protected]3268023f2011-05-05 00:08:10669 StreamSocket* socket,
[email protected]eb5a99382010-07-11 03:18:26670 int id) {
[email protected]ff579d42009-06-24 15:47:02671 GroupMap::iterator i = group_map_.find(group_name);
672 CHECK(i != group_map_.end());
673
[email protected]aed99ef02010-08-26 14:04:32674 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02675
[email protected]b1f031dd2010-03-02 23:19:33676 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53677 handed_out_socket_count_--;
678
[email protected]aed99ef02010-08-26 14:04:32679 CHECK_GT(group->active_socket_count(), 0);
680 group->DecrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02681
[email protected]a7e38572010-06-07 18:22:24682 const bool can_reuse = socket->IsConnectedAndIdle() &&
683 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02684 if (can_reuse) {
[email protected]eb5a99382010-07-11 03:18:26685 // Add it to the idle list.
[email protected]0f873e82010-09-02 16:09:01686 AddIdleSocket(socket, group);
[email protected]aed99ef02010-08-26 14:04:32687 OnAvailableSocketSlot(group_name, group);
[email protected]ff579d42009-06-24 15:47:02688 } else {
689 delete socket;
690 }
[email protected]05ea9ff2010-07-15 19:08:21691
[email protected]eb5a99382010-07-11 03:18:26692 CheckForStalledSocketGroups();
693}
[email protected]ff579d42009-06-24 15:47:02694
[email protected]eb5a99382010-07-11 03:18:26695void ClientSocketPoolBaseHelper::CheckForStalledSocketGroups() {
696 // If we have idle sockets, see if we can give one to the top-stalled group.
697 std::string top_group_name;
698 Group* top_group = NULL;
[email protected]05ea9ff2010-07-15 19:08:21699 if (!FindTopStalledGroup(&top_group, &top_group_name))
[email protected]eb5a99382010-07-11 03:18:26700 return;
[email protected]4f2abec2010-02-03 18:10:16701
[email protected]eb5a99382010-07-11 03:18:26702 if (ReachedMaxSocketsLimit()) {
703 if (idle_socket_count() > 0) {
704 CloseOneIdleSocket();
[email protected]d7027bb2010-05-10 18:58:54705 } else {
[email protected]eb5a99382010-07-11 03:18:26706 // We can't activate more sockets since we're already at our global
707 // limit.
[email protected]4f2abec2010-02-03 18:10:16708 return;
[email protected]d7027bb2010-05-10 18:58:54709 }
[email protected]4f2abec2010-02-03 18:10:16710 }
[email protected]eb5a99382010-07-11 03:18:26711
712 // Note: we don't loop on waking stalled groups. If the stalled group is at
713 // its limit, may be left with other stalled groups that could be
[email protected]05ea9ff2010-07-15 19:08:21714 // woken. This isn't optimal, but there is no starvation, so to avoid
[email protected]eb5a99382010-07-11 03:18:26715 // the looping we leave it at this.
[email protected]05ea9ff2010-07-15 19:08:21716 OnAvailableSocketSlot(top_group_name, top_group);
[email protected]ff579d42009-06-24 15:47:02717}
718
[email protected]211d2172009-07-22 15:48:53719// Search for the highest priority pending request, amongst the groups that
720// are not at the |max_sockets_per_group_| limit. Note: for requests with
721// the same priority, the winner is based on group hash ordering (and not
722// insertion order).
[email protected]05ea9ff2010-07-15 19:08:21723bool ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
724 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53725 Group* top_group = NULL;
726 const std::string* top_group_name = NULL;
[email protected]05ea9ff2010-07-15 19:08:21727 bool has_stalled_group = false;
[email protected]211d2172009-07-22 15:48:53728 for (GroupMap::iterator i = group_map_.begin();
729 i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32730 Group* curr_group = i->second;
731 const RequestQueue& queue = curr_group->pending_requests();
[email protected]211d2172009-07-22 15:48:53732 if (queue.empty())
733 continue;
[email protected]aed99ef02010-08-26 14:04:32734 if (curr_group->IsStalled(max_sockets_per_group_)) {
[email protected]05ea9ff2010-07-15 19:08:21735 has_stalled_group = true;
[email protected]6427fe22010-04-16 22:27:41736 bool has_higher_priority = !top_group ||
[email protected]aed99ef02010-08-26 14:04:32737 curr_group->TopPendingPriority() < top_group->TopPendingPriority();
[email protected]6427fe22010-04-16 22:27:41738 if (has_higher_priority) {
[email protected]aed99ef02010-08-26 14:04:32739 top_group = curr_group;
[email protected]6427fe22010-04-16 22:27:41740 top_group_name = &i->first;
741 }
[email protected]211d2172009-07-22 15:48:53742 }
743 }
[email protected]05ea9ff2010-07-15 19:08:21744
[email protected]211d2172009-07-22 15:48:53745 if (top_group) {
746 *group = top_group;
747 *group_name = *top_group_name;
748 }
[email protected]05ea9ff2010-07-15 19:08:21749 return has_stalled_group;
[email protected]211d2172009-07-22 15:48:53750}
751
[email protected]d80a4322009-08-14 07:07:49752void ClientSocketPoolBaseHelper::OnConnectJobComplete(
753 int result, ConnectJob* job) {
[email protected]2ab05b52009-07-01 23:57:58754 DCHECK_NE(ERR_IO_PENDING, result);
755 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02756 GroupMap::iterator group_it = group_map_.find(group_name);
757 CHECK(group_it != group_map_.end());
[email protected]aed99ef02010-08-26 14:04:32758 Group* group = group_it->second;
[email protected]ff579d42009-06-24 15:47:02759
[email protected]3268023f2011-05-05 00:08:10760 scoped_ptr<StreamSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02761
[email protected]9e743cd2010-03-16 07:03:53762 BoundNetLog job_log = job->net_log();
[email protected]5fc08e32009-07-15 17:09:57763
[email protected]4d3b05d2010-01-27 21:27:29764 if (result == OK) {
765 DCHECK(socket.get());
[email protected]aed99ef02010-08-26 14:04:32766 RemoveConnectJob(job, group);
767 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29768 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02769 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17770 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29771 HandOutSocket(
772 socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32773 base::TimeDelta(), group, r->net_log());
[email protected]06650c52010-06-03 00:49:17774 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21775 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]5fc08e32009-07-15 17:09:57776 } else {
[email protected]0f873e82010-09-02 16:09:01777 AddIdleSocket(socket.release(), group);
[email protected]aed99ef02010-08-26 14:04:32778 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21779 CheckForStalledSocketGroups();
[email protected]5fc08e32009-07-15 17:09:57780 }
[email protected]94c20472010-01-14 08:14:36781 } else {
[email protected]e772db3f2010-07-12 18:11:13782 // If we got a socket, it must contain error information so pass that
783 // up so that the caller can retrieve it.
784 bool handed_out_socket = false;
[email protected]aed99ef02010-08-26 14:04:32785 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29786 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02787 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17788 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]e60e47a2010-07-14 03:37:18789 job->GetAdditionalErrorState(r->handle());
[email protected]aed99ef02010-08-26 14:04:32790 RemoveConnectJob(job, group);
[email protected]e772db3f2010-07-12 18:11:13791 if (socket.get()) {
792 handed_out_socket = true;
793 HandOutSocket(socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32794 base::TimeDelta(), group, r->net_log());
[email protected]e772db3f2010-07-12 18:11:13795 }
[email protected]d7fd1782011-02-08 19:16:43796 r->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL,
797 result);
[email protected]05ea9ff2010-07-15 19:08:21798 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]e60e47a2010-07-14 03:37:18799 } else {
[email protected]aed99ef02010-08-26 14:04:32800 RemoveConnectJob(job, group);
[email protected]4d3b05d2010-01-27 21:27:29801 }
[email protected]05ea9ff2010-07-15 19:08:21802 if (!handed_out_socket) {
[email protected]aed99ef02010-08-26 14:04:32803 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21804 CheckForStalledSocketGroups();
805 }
[email protected]ff579d42009-06-24 15:47:02806 }
[email protected]ff579d42009-06-24 15:47:02807}
808
[email protected]66761b952010-06-25 21:30:38809void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
810 Flush();
811}
812
[email protected]a7e38572010-06-07 18:22:24813void ClientSocketPoolBaseHelper::Flush() {
814 pool_generation_number_++;
[email protected]06f92462010-08-31 19:24:14815 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52816 CloseIdleSockets();
[email protected]06f92462010-08-31 19:24:14817 AbortAllRequests();
[email protected]a554a8262010-05-20 00:13:52818}
819
[email protected]2c2bef152010-10-13 00:55:03820void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job,
[email protected]4d3b05d2010-01-27 21:27:29821 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33822 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53823 connecting_socket_count_--;
824
[email protected]25eea382010-07-10 23:55:26825 DCHECK(group);
[email protected]aed99ef02010-08-26 14:04:32826 DCHECK(ContainsKey(group->jobs(), job));
827 group->RemoveJob(job);
[email protected]25eea382010-07-10 23:55:26828
829 // If we've got no more jobs for this group, then we no longer need a
830 // backup job either.
[email protected]aed99ef02010-08-26 14:04:32831 if (group->jobs().empty())
[email protected]25eea382010-07-10 23:55:26832 group->CleanupBackupJob();
833
[email protected]8ae03f42010-07-07 19:08:10834 DCHECK(job);
835 delete job;
[email protected]2ab05b52009-07-01 23:57:58836}
[email protected]ff579d42009-06-24 15:47:02837
[email protected]8ae03f42010-07-07 19:08:10838void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
[email protected]05ea9ff2010-07-15 19:08:21839 const std::string& group_name, Group* group) {
[email protected]2abfe90a2010-08-25 17:49:51840 DCHECK(ContainsKey(group_map_, group_name));
[email protected]05ea9ff2010-07-15 19:08:21841 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32842 RemoveGroup(group_name);
843 else if (!group->pending_requests().empty())
[email protected]2abfe90a2010-08-25 17:49:51844 ProcessPendingRequest(group_name, group);
[email protected]8ae03f42010-07-07 19:08:10845}
[email protected]06650c52010-06-03 00:49:17846
[email protected]8ae03f42010-07-07 19:08:10847void ClientSocketPoolBaseHelper::ProcessPendingRequest(
[email protected]05ea9ff2010-07-15 19:08:21848 const std::string& group_name, Group* group) {
849 int rv = RequestSocketInternal(group_name,
[email protected]aed99ef02010-08-26 14:04:32850 *group->pending_requests().begin());
[email protected]05ea9ff2010-07-15 19:08:21851 if (rv != ERR_IO_PENDING) {
852 scoped_ptr<const Request> request(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02853 group->mutable_pending_requests()->begin(), group));
[email protected]2abfe90a2010-08-25 17:49:51854 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32855 RemoveGroup(group_name);
[email protected]8ae03f42010-07-07 19:08:10856
[email protected]d7fd1782011-02-08 19:16:43857 request->net_log().EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
[email protected]05ea9ff2010-07-15 19:08:21858 InvokeUserCallbackLater(
859 request->handle(), request->callback(), rv);
[email protected]2ab05b52009-07-01 23:57:58860 }
861}
862
[email protected]d80a4322009-08-14 07:07:49863void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]3268023f2011-05-05 00:08:10864 StreamSocket* socket,
[email protected]2ab05b52009-07-01 23:57:58865 bool reused,
866 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29867 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15868 Group* group,
[email protected]9e743cd2010-03-16 07:03:53869 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58870 DCHECK(socket);
871 handle->set_socket(socket);
872 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29873 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24874 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53875
[email protected]d13f51b2010-04-27 23:20:45876 if (reused) {
[email protected]ec11be62010-04-28 19:28:09877 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45878 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57879 make_scoped_refptr(new NetLogIntegerParameter(
880 "idle_ms", static_cast<int>(idle_time.InMilliseconds()))));
[email protected]fd4fe0b2010-02-08 23:02:15881 }
[email protected]d13f51b2010-04-27 23:20:45882
[email protected]06650c52010-06-03 00:49:17883 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57884 make_scoped_refptr(new NetLogSourceParameter(
885 "source_dependency", socket->NetLog().source())));
[email protected]fd4fe0b2010-02-08 23:02:15886
[email protected]211d2172009-07-22 15:48:53887 handed_out_socket_count_++;
[email protected]aed99ef02010-08-26 14:04:32888 group->IncrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02889}
890
[email protected]d80a4322009-08-14 07:07:49891void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]3268023f2011-05-05 00:08:10892 StreamSocket* socket, Group* group) {
[email protected]5fc08e32009-07-15 17:09:57893 DCHECK(socket);
894 IdleSocket idle_socket;
895 idle_socket.socket = socket;
896 idle_socket.start_time = base::TimeTicks::Now();
[email protected]5fc08e32009-07-15 17:09:57897
[email protected]aed99ef02010-08-26 14:04:32898 group->mutable_idle_sockets()->push_back(idle_socket);
[email protected]5fc08e32009-07-15 17:09:57899 IncrementIdleCount();
900}
901
[email protected]d80a4322009-08-14 07:07:49902void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]74d75e0b2010-08-23 20:39:54903 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
[email protected]aed99ef02010-08-26 14:04:32904 Group* group = i->second;
905 connecting_socket_count_ -= group->jobs().size();
906 group->RemoveAllJobs();
[email protected]6b624c62010-03-14 08:37:32907
[email protected]5fc08e32009-07-15 17:09:57908 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32909 if (group->IsEmpty()) {
[email protected]06f92462010-08-31 19:24:14910 // RemoveGroup() will call .erase() which will invalidate the iterator,
911 // but i will already have been incremented to a valid iterator before
912 // RemoveGroup() is called.
913 RemoveGroup(i++);
914 } else {
915 ++i;
916 }
917 }
918 DCHECK_EQ(0, connecting_socket_count_);
919}
920
921void ClientSocketPoolBaseHelper::AbortAllRequests() {
922 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
923 Group* group = i->second;
924
925 RequestQueue pending_requests;
926 pending_requests.swap(*group->mutable_pending_requests());
927 for (RequestQueue::iterator it2 = pending_requests.begin();
928 it2 != pending_requests.end(); ++it2) {
[email protected]2c2bef152010-10-13 00:55:03929 scoped_ptr<const Request> request(*it2);
[email protected]06f92462010-08-31 19:24:14930 InvokeUserCallbackLater(
931 request->handle(), request->callback(), ERR_ABORTED);
932 }
933
934 // Delete group if no longer needed.
935 if (group->IsEmpty()) {
936 // RemoveGroup() will call .erase() which will invalidate the iterator,
937 // but i will already have been incremented to a valid iterator before
938 // RemoveGroup() is called.
[email protected]aed99ef02010-08-26 14:04:32939 RemoveGroup(i++);
[email protected]74d75e0b2010-08-23 20:39:54940 } else {
941 ++i;
[email protected]5fc08e32009-07-15 17:09:57942 }
943 }
944}
945
[email protected]d80a4322009-08-14 07:07:49946bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53947 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54948 int total = handed_out_socket_count_ + connecting_socket_count_ +
949 idle_socket_count();
[email protected]5acdce12011-03-30 13:00:20950 // There can be more sockets than the limit since some requests can ignore
951 // the limit
[email protected]c901f6d2010-04-27 17:48:28952 if (total < max_sockets_)
953 return false;
[email protected]c901f6d2010-04-27 17:48:28954 return true;
[email protected]211d2172009-07-22 15:48:53955}
956
[email protected]43a21b82010-06-10 21:30:54957void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
[email protected]dcbe168a2010-12-02 03:14:46958 CloseOneIdleSocketExceptInGroup(NULL);
959}
960
961bool ClientSocketPoolBaseHelper::CloseOneIdleSocketExceptInGroup(
962 const Group* exception_group) {
[email protected]43a21b82010-06-10 21:30:54963 CHECK_GT(idle_socket_count(), 0);
964
965 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32966 Group* group = i->second;
[email protected]dcbe168a2010-12-02 03:14:46967 if (exception_group == group)
968 continue;
[email protected]e1b54dc2010-10-06 21:27:22969 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
[email protected]43a21b82010-06-10 21:30:54970
[email protected]e1b54dc2010-10-06 21:27:22971 if (!idle_sockets->empty()) {
972 delete idle_sockets->front().socket;
973 idle_sockets->pop_front();
[email protected]43a21b82010-06-10 21:30:54974 DecrementIdleCount();
[email protected]aed99ef02010-08-26 14:04:32975 if (group->IsEmpty())
976 RemoveGroup(i);
[email protected]43a21b82010-06-10 21:30:54977
[email protected]dcbe168a2010-12-02 03:14:46978 return true;
[email protected]43a21b82010-06-10 21:30:54979 }
980 }
981
[email protected]dcbe168a2010-12-02 03:14:46982 if (!exception_group)
983 LOG(DFATAL) << "No idle socket found to close!.";
984
985 return false;
[email protected]43a21b82010-06-10 21:30:54986}
987
[email protected]05ea9ff2010-07-15 19:08:21988void ClientSocketPoolBaseHelper::InvokeUserCallbackLater(
989 ClientSocketHandle* handle, CompletionCallback* callback, int rv) {
990 CHECK(!ContainsKey(pending_callback_map_, handle));
991 pending_callback_map_[handle] = CallbackResultPair(callback, rv);
992 MessageLoop::current()->PostTask(
993 FROM_HERE,
[email protected]2431756e2010-09-29 20:26:13994 method_factory_.NewRunnableMethod(
[email protected]05ea9ff2010-07-15 19:08:21995 &ClientSocketPoolBaseHelper::InvokeUserCallback,
996 handle));
997}
998
999void ClientSocketPoolBaseHelper::InvokeUserCallback(
1000 ClientSocketHandle* handle) {
1001 PendingCallbackMap::iterator it = pending_callback_map_.find(handle);
1002
1003 // Exit if the request has already been cancelled.
1004 if (it == pending_callback_map_.end())
1005 return;
1006
1007 CHECK(!handle->is_initialized());
1008 CompletionCallback* callback = it->second.callback;
1009 int result = it->second.result;
1010 pending_callback_map_.erase(it);
1011 callback->Run(result);
1012}
1013
[email protected]aed99ef02010-08-26 14:04:321014ClientSocketPoolBaseHelper::Group::Group()
1015 : active_socket_count_(0),
1016 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}
1017
1018ClientSocketPoolBaseHelper::Group::~Group() {
1019 CleanupBackupJob();
1020}
1021
1022void ClientSocketPoolBaseHelper::Group::StartBackupSocketTimer(
1023 const std::string& group_name,
1024 ClientSocketPoolBaseHelper* pool) {
1025 // Only allow one timer pending to create a backup socket.
1026 if (!method_factory_.empty())
1027 return;
1028
1029 MessageLoop::current()->PostDelayedTask(
1030 FROM_HERE,
1031 method_factory_.NewRunnableMethod(
1032 &Group::OnBackupSocketTimerFired, group_name, pool),
1033 pool->ConnectRetryIntervalMs());
1034}
1035
[email protected]2c2bef152010-10-13 00:55:031036bool ClientSocketPoolBaseHelper::Group::TryToUsePreconnectConnectJob() {
1037 for (std::set<ConnectJob*>::iterator it = jobs_.begin();
1038 it != jobs_.end(); ++it) {
1039 ConnectJob* job = *it;
1040 if (job->is_unused_preconnect()) {
1041 job->UseForNormalRequest();
1042 return true;
1043 }
1044 }
1045 return false;
1046}
1047
[email protected]aed99ef02010-08-26 14:04:321048void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired(
1049 std::string group_name,
1050 ClientSocketPoolBaseHelper* pool) {
1051 // If there are no more jobs pending, there is no work to do.
1052 // If we've done our cleanups correctly, this should not happen.
1053 if (jobs_.empty()) {
1054 NOTREACHED();
1055 return;
1056 }
1057
1058 // If our backup job is waiting on DNS, or if we can't create any sockets
1059 // right now due to limits, just reset the timer.
1060 if (pool->ReachedMaxSocketsLimit() ||
1061 !HasAvailableSocketSlot(pool->max_sockets_per_group_) ||
1062 (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
1063 StartBackupSocketTimer(group_name, pool);
1064 return;
1065 }
1066
[email protected]a9fc8fc2011-05-10 02:41:071067 if (pending_requests_.empty())
[email protected]4baaf9d2010-08-31 15:15:441068 return;
[email protected]4baaf9d2010-08-31 15:15:441069
[email protected]aed99ef02010-08-26 14:04:321070 ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob(
1071 group_name, **pending_requests_.begin(), pool);
1072 backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED, NULL);
1073 SIMPLE_STATS_COUNTER("socket.backup_created");
[email protected]0d1f4c42011-05-05 15:27:501074 // The purpose of the backup job is to initiate a new connect job when the
1075 // first connect job takes too long. We call set_prefer_ipv4 here to use
1076 // the backup job for a second purpose: if the first connect job is IPv6,
1077 // try an IPv4 connect job in parallel. This hides the long timeout error
1078 // on some networks with broken IPv6 support.
1079 // TODO(wtc): remove the set_prefer_ipv4 call when broken IPv6 networks are
1080 // gone.
1081 backup_job->set_prefer_ipv4();
[email protected]aed99ef02010-08-26 14:04:321082 int rv = backup_job->Connect();
1083 pool->connecting_socket_count_++;
1084 AddJob(backup_job);
1085 if (rv != ERR_IO_PENDING)
1086 pool->OnConnectJobComplete(rv, backup_job);
1087}
1088
1089void ClientSocketPoolBaseHelper::Group::RemoveAllJobs() {
1090 // Delete active jobs.
1091 STLDeleteElements(&jobs_);
1092
1093 // Cancel pending backup job.
1094 method_factory_.RevokeAll();
1095}
1096
[email protected]d80a4322009-08-14 07:07:491097} // namespace internal
1098
[email protected]ff579d42009-06-24 15:47:021099} // namespace net