blob: 816ecc97c456500f8a9543306c9ab6e9e43bc333 [file] [log] [blame]
[email protected]a796bcec2010-03-22 17:17:261// Copyright (c) 2010 The Chromium Authors. All rights reserved.
[email protected]ff579d42009-06-24 15:47:022// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/socket/client_socket_pool_base.h"
6
7#include "base/compiler_specific.h"
[email protected]fd4fe0b2010-02-08 23:02:158#include "base/format_macros.h"
[email protected]ff579d42009-06-24 15:47:029#include "base/message_loop.h"
[email protected]835d7c82010-10-14 04:38:3810#include "base/metrics/stats_counters.h"
[email protected]ff579d42009-06-24 15:47:0211#include "base/stl_util-inl.h"
[email protected]fd4fe0b2010-02-08 23:02:1512#include "base/string_util.h"
[email protected]ff579d42009-06-24 15:47:0213#include "base/time.h"
[email protected]9349cfb2010-08-31 18:00:5314#include "base/values.h"
[email protected]9e743cd2010-03-16 07:03:5315#include "net/base/net_log.h"
[email protected]ff579d42009-06-24 15:47:0216#include "net/base/net_errors.h"
17#include "net/socket/client_socket_handle.h"
18
19using base::TimeDelta;
20
21namespace {
22
23// The timeout value, in seconds, used to clean up idle sockets that can't be
24// reused.
25//
26// Note: It's important to close idle sockets that have received data as soon
27// as possible because the received data may cause BSOD on Windows XP under
28// some conditions. See http://crbug.com/4606.
29const int kCleanupInterval = 10; // DO NOT INCREASE THIS TIMEOUT.
30
[email protected]06d94042010-08-25 01:45:2231// Indicate whether or not we should establish a new TCP connection after a
32// certain timeout has passed without receiving an ACK.
33bool g_connect_backup_jobs_enabled = true;
34
[email protected]ff579d42009-06-24 15:47:0235} // namespace
36
37namespace net {
38
[email protected]2ab05b52009-07-01 23:57:5839ConnectJob::ConnectJob(const std::string& group_name,
[email protected]974ebd62009-08-03 23:14:3440 base::TimeDelta timeout_duration,
[email protected]fd7b7c92009-08-20 19:38:3041 Delegate* delegate,
[email protected]9e743cd2010-03-16 07:03:5342 const BoundNetLog& net_log)
[email protected]2ab05b52009-07-01 23:57:5843 : group_name_(group_name),
[email protected]974ebd62009-08-03 23:14:3444 timeout_duration_(timeout_duration),
[email protected]2ab05b52009-07-01 23:57:5845 delegate_(delegate),
[email protected]a2006ece2010-04-23 16:44:0246 net_log_(net_log),
[email protected]2c2bef152010-10-13 00:55:0347 idle_(true),
48 preconnect_state_(NOT_PRECONNECT) {
[email protected]2ab05b52009-07-01 23:57:5849 DCHECK(!group_name.empty());
[email protected]2ab05b52009-07-01 23:57:5850 DCHECK(delegate);
[email protected]06650c52010-06-03 00:49:1751 net_log.BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]2ab05b52009-07-01 23:57:5852}
53
[email protected]fd7b7c92009-08-20 19:38:3054ConnectJob::~ConnectJob() {
[email protected]06650c52010-06-03 00:49:1755 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
[email protected]fd7b7c92009-08-20 19:38:3056}
[email protected]2ab05b52009-07-01 23:57:5857
[email protected]2c2bef152010-10-13 00:55:0358void ConnectJob::Initialize(bool is_preconnect) {
59 if (is_preconnect)
60 preconnect_state_ = UNUSED_PRECONNECT;
61 else
62 preconnect_state_ = NOT_PRECONNECT;
63}
64
[email protected]974ebd62009-08-03 23:14:3465int ConnectJob::Connect() {
66 if (timeout_duration_ != base::TimeDelta())
67 timer_.Start(timeout_duration_, this, &ConnectJob::OnTimeout);
[email protected]fd7b7c92009-08-20 19:38:3068
[email protected]a2006ece2010-04-23 16:44:0269 idle_ = false;
[email protected]fd7b7c92009-08-20 19:38:3070
[email protected]06650c52010-06-03 00:49:1771 LogConnectStart();
72
[email protected]fd7b7c92009-08-20 19:38:3073 int rv = ConnectInternal();
74
75 if (rv != ERR_IO_PENDING) {
[email protected]06650c52010-06-03 00:49:1776 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:3077 delegate_ = NULL;
[email protected]fd7b7c92009-08-20 19:38:3078 }
79
80 return rv;
81}
82
[email protected]2c2bef152010-10-13 00:55:0383void ConnectJob::UseForNormalRequest() {
84 DCHECK_EQ(UNUSED_PRECONNECT, preconnect_state_);
85 preconnect_state_ = USED_PRECONNECT;
86}
87
[email protected]06650c52010-06-03 00:49:1788void ConnectJob::set_socket(ClientSocket* socket) {
89 if (socket) {
[email protected]00cd9c42010-11-02 20:15:5790 net_log().AddEvent(NetLog::TYPE_CONNECT_JOB_SET_SOCKET, make_scoped_refptr(
91 new NetLogSourceParameter("source_dependency",
92 socket->NetLog().source())));
[email protected]06650c52010-06-03 00:49:1793 }
94 socket_.reset(socket);
95}
96
[email protected]fd7b7c92009-08-20 19:38:3097void ConnectJob::NotifyDelegateOfCompletion(int rv) {
98 // The delegate will delete |this|.
99 Delegate *delegate = delegate_;
100 delegate_ = NULL;
101
[email protected]06650c52010-06-03 00:49:17102 LogConnectCompletion(rv);
[email protected]fd7b7c92009-08-20 19:38:30103 delegate->OnConnectJobComplete(rv, this);
[email protected]974ebd62009-08-03 23:14:34104}
105
[email protected]a796bcec2010-03-22 17:17:26106void ConnectJob::ResetTimer(base::TimeDelta remaining_time) {
107 timer_.Stop();
108 timer_.Start(remaining_time, this, &ConnectJob::OnTimeout);
109}
110
[email protected]06650c52010-06-03 00:49:17111void ConnectJob::LogConnectStart() {
112 net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT,
[email protected]00cd9c42010-11-02 20:15:57113 make_scoped_refptr(new NetLogStringParameter("group_name", group_name_)));
[email protected]06650c52010-06-03 00:49:17114}
115
116void ConnectJob::LogConnectCompletion(int net_error) {
117 scoped_refptr<NetLog::EventParameters> params;
118 if (net_error != OK)
119 params = new NetLogIntegerParameter("net_error", net_error);
120 net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_CONNECT, params);
121}
122
[email protected]974ebd62009-08-03 23:14:34123void ConnectJob::OnTimeout() {
[email protected]6e713f02009-08-06 02:56:40124 // Make sure the socket is NULL before calling into |delegate|.
125 set_socket(NULL);
[email protected]fd7b7c92009-08-20 19:38:30126
[email protected]ec11be62010-04-28 19:28:09127 net_log_.AddEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_TIMED_OUT, NULL);
[email protected]fd7b7c92009-08-20 19:38:30128
129 NotifyDelegateOfCompletion(ERR_TIMED_OUT);
[email protected]974ebd62009-08-03 23:14:34130}
131
[email protected]d80a4322009-08-14 07:07:49132namespace internal {
133
[email protected]fd4fe0b2010-02-08 23:02:15134ClientSocketPoolBaseHelper::Request::Request(
135 ClientSocketHandle* handle,
136 CompletionCallback* callback,
137 RequestPriority priority,
[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]2c2bef152010-10-13 00:55:03143 flags_(flags),
[email protected]9e743cd2010-03-16 07:03:53144 net_log_(net_log) {}
[email protected]fd4fe0b2010-02-08 23:02:15145
146ClientSocketPoolBaseHelper::Request::~Request() {}
147
[email protected]d80a4322009-08-14 07:07:49148ClientSocketPoolBaseHelper::ClientSocketPoolBaseHelper(
[email protected]211d2172009-07-22 15:48:53149 int max_sockets,
[email protected]ff579d42009-06-24 15:47:02150 int max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16151 base::TimeDelta unused_idle_socket_timeout,
152 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38153 ConnectJobFactory* connect_job_factory)
[email protected]ff579d42009-06-24 15:47:02154 : idle_socket_count_(0),
[email protected]211d2172009-07-22 15:48:53155 connecting_socket_count_(0),
156 handed_out_socket_count_(0),
157 max_sockets_(max_sockets),
[email protected]ff579d42009-06-24 15:47:02158 max_sockets_per_group_(max_sockets_per_group),
[email protected]9bf28db2009-08-29 01:35:16159 unused_idle_socket_timeout_(unused_idle_socket_timeout),
160 used_idle_socket_timeout_(used_idle_socket_timeout),
[email protected]100d5fb92009-12-21 21:08:35161 connect_job_factory_(connect_job_factory),
[email protected]06d94042010-08-25 01:45:22162 connect_backup_jobs_enabled_(false),
[email protected]2431756e2010-09-29 20:26:13163 pool_generation_number_(0),
164 method_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
[email protected]211d2172009-07-22 15:48:53165 DCHECK_LE(0, max_sockets_per_group);
166 DCHECK_LE(max_sockets_per_group, max_sockets);
[email protected]a554a8262010-05-20 00:13:52167
[email protected]66761b952010-06-25 21:30:38168 NetworkChangeNotifier::AddObserver(this);
[email protected]211d2172009-07-22 15:48:53169}
[email protected]ff579d42009-06-24 15:47:02170
[email protected]d80a4322009-08-14 07:07:49171ClientSocketPoolBaseHelper::~ClientSocketPoolBaseHelper() {
[email protected]2431756e2010-09-29 20:26:13172 // Clean up any idle sockets and pending connect jobs. Assert that we have no
173 // remaining active sockets or pending requests. They should have all been
174 // cleaned up prior to |this| being destroyed.
175 Flush();
176 DCHECK(group_map_.empty());
[email protected]05ea9ff2010-07-15 19:08:21177 DCHECK(pending_callback_map_.empty());
[email protected]4d3b05d2010-01-27 21:27:29178 DCHECK_EQ(0, connecting_socket_count_);
[email protected]a554a8262010-05-20 00:13:52179
[email protected]66761b952010-06-25 21:30:38180 NetworkChangeNotifier::RemoveObserver(this);
[email protected]ff579d42009-06-24 15:47:02181}
182
183// InsertRequestIntoQueue inserts the request into the queue based on
184// priority. Highest priorities are closest to the front. Older requests are
185// prioritized over requests of equal priority.
186//
187// static
[email protected]d80a4322009-08-14 07:07:49188void ClientSocketPoolBaseHelper::InsertRequestIntoQueue(
189 const Request* r, RequestQueue* pending_requests) {
[email protected]ff579d42009-06-24 15:47:02190 RequestQueue::iterator it = pending_requests->begin();
[email protected]ac790b42009-12-02 04:31:31191 while (it != pending_requests->end() && r->priority() >= (*it)->priority())
[email protected]ff579d42009-06-24 15:47:02192 ++it;
193 pending_requests->insert(it, r);
194}
195
[email protected]fd7b7c92009-08-20 19:38:30196// static
197const ClientSocketPoolBaseHelper::Request*
198ClientSocketPoolBaseHelper::RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02199 RequestQueue::iterator it, Group* group) {
[email protected]fd7b7c92009-08-20 19:38:30200 const Request* req = *it;
[email protected]3f00be82010-09-27 19:50:02201 group->mutable_pending_requests()->erase(it);
202 // If there are no more requests, we kill the backup timer.
203 if (group->pending_requests().empty())
204 group->CleanupBackupJob();
[email protected]fd7b7c92009-08-20 19:38:30205 return req;
206}
207
[email protected]d80a4322009-08-14 07:07:49208int ClientSocketPoolBaseHelper::RequestSocket(
[email protected]ff579d42009-06-24 15:47:02209 const std::string& group_name,
[email protected]d80a4322009-08-14 07:07:49210 const Request* request) {
[email protected]2c2bef152010-10-13 00:55:03211 CHECK(request->callback());
212 CHECK(request->handle());
213
[email protected]ec11be62010-04-28 19:28:09214 request->net_log().BeginEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]aed99ef02010-08-26 14:04:32215 Group* group = GetOrCreateGroup(group_name);
[email protected]eb5a99382010-07-11 03:18:26216
[email protected]fd4fe0b2010-02-08 23:02:15217 int rv = RequestSocketInternal(group_name, request);
[email protected]e7e99322010-05-04 23:30:17218 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09219 request->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21220 CHECK(!request->handle()->is_initialized());
[email protected]e7e99322010-05-04 23:30:17221 delete request;
222 } else {
[email protected]aed99ef02010-08-26 14:04:32223 InsertRequestIntoQueue(request, group->mutable_pending_requests());
[email protected]e7e99322010-05-04 23:30:17224 }
[email protected]fd4fe0b2010-02-08 23:02:15225 return rv;
226}
227
[email protected]2c2bef152010-10-13 00:55:03228void ClientSocketPoolBaseHelper::RequestSockets(
229 const std::string& group_name,
230 const Request& request,
231 int num_sockets) {
232 DCHECK(!request.callback());
233 DCHECK(!request.handle());
234
235 if (num_sockets > max_sockets_per_group_) {
[email protected]2c2bef152010-10-13 00:55:03236 num_sockets = max_sockets_per_group_;
237 }
238
239 request.net_log().BeginEvent(
240 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS,
[email protected]00cd9c42010-11-02 20:15:57241 make_scoped_refptr(new NetLogIntegerParameter(
242 "num_sockets", num_sockets)));
[email protected]2c2bef152010-10-13 00:55:03243
244 Group* group = GetOrCreateGroup(group_name);
245
[email protected]3c819f522010-12-02 02:03:12246 // RequestSocketsInternal() may delete the group.
247 bool deleted_group = false;
248
[email protected]2c2bef152010-10-13 00:55:03249 for (int num_iterations_left = num_sockets;
250 group->NumActiveSocketSlots() < num_sockets &&
251 num_iterations_left > 0 ; num_iterations_left--) {
252 int rv = RequestSocketInternal(group_name, &request);
[email protected]dcbe168a2010-12-02 03:14:46253 // TODO(willchan): Possibly check for ERR_PRECONNECT_MAX_SOCKET_LIMIT so we
254 // can log it into the NetLog.
[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
273 request.net_log().EndEvent(
274 NetLog::TYPE_SOCKET_POOL_CONNECTING_N_SOCKETS, NULL);
275}
276
[email protected]fd4fe0b2010-02-08 23:02:15277int ClientSocketPoolBaseHelper::RequestSocketInternal(
278 const std::string& group_name,
279 const Request* request) {
[email protected]d80a4322009-08-14 07:07:49280 DCHECK_GE(request->priority(), 0);
[email protected]d80a4322009-08-14 07:07:49281 ClientSocketHandle* const handle = request->handle();
[email protected]2c2bef152010-10-13 00:55:03282 const bool preconnecting = !handle;
[email protected]aed99ef02010-08-26 14:04:32283 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02284
[email protected]2c2bef152010-10-13 00:55:03285 if (!(request->flags() & NO_IDLE_SOCKETS)) {
286 // Try to reuse a socket.
287 if (AssignIdleSocketToGroup(request, group))
288 return OK;
289 }
290
291 if (!preconnecting && group->TryToUsePreconnectConnectJob())
292 return ERR_IO_PENDING;
[email protected]65552102010-04-09 22:58:10293
[email protected]43a21b82010-06-10 21:30:54294 // Can we make another active socket now?
[email protected]aed99ef02010-08-26 14:04:32295 if (!group->HasAvailableSocketSlot(max_sockets_per_group_)) {
[email protected]43a21b82010-06-10 21:30:54296 request->net_log().AddEvent(
297 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS_PER_GROUP, NULL);
298 return ERR_IO_PENDING;
299 }
300
301 if (ReachedMaxSocketsLimit()) {
302 if (idle_socket_count() > 0) {
[email protected]dcbe168a2010-12-02 03:14:46303 bool closed = CloseOneIdleSocketExceptInGroup(group);
304 if (preconnecting && !closed)
305 return ERR_PRECONNECT_MAX_SOCKET_LIMIT;
[email protected]43a21b82010-06-10 21:30:54306 } else {
307 // We could check if we really have a stalled group here, but it requires
308 // a scan of all groups, so just flip a flag here, and do the check later.
[email protected]43a21b82010-06-10 21:30:54309 request->net_log().AddEvent(
310 NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS, NULL);
311 return ERR_IO_PENDING;
312 }
313 }
314
[email protected]ff579d42009-06-24 15:47:02315 // We couldn't find a socket to reuse, so allocate and connect a new one.
[email protected]2ab05b52009-07-01 23:57:58316 scoped_ptr<ConnectJob> connect_job(
[email protected]06650c52010-06-03 00:49:17317 connect_job_factory_->NewConnectJob(group_name, *request, this));
[email protected]ff579d42009-06-24 15:47:02318
[email protected]2c2bef152010-10-13 00:55:03319 connect_job->Initialize(preconnecting);
[email protected]2ab05b52009-07-01 23:57:58320 int rv = connect_job->Connect();
321 if (rv == OK) {
[email protected]06650c52010-06-03 00:49:17322 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]2c2bef152010-10-13 00:55:03323 if (!preconnecting) {
324 HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */,
325 handle, base::TimeDelta(), group, request->net_log());
326 } else {
327 AddIdleSocket(connect_job->ReleaseSocket(), group);
328 }
[email protected]2ab05b52009-07-01 23:57:58329 } else if (rv == ERR_IO_PENDING) {
[email protected]6b624c62010-03-14 08:37:32330 // If we don't have any sockets in this group, set a timer for potentially
331 // creating a new one. If the SYN is lost, this backup socket may complete
332 // before the slow socket, improving end user latency.
[email protected]2c2bef152010-10-13 00:55:03333 if (connect_backup_jobs_enabled_ &&
334 group->IsEmpty() && !group->HasBackupJob() &&
335 handle) {
[email protected]aed99ef02010-08-26 14:04:32336 group->StartBackupSocketTimer(group_name, this);
[email protected]2c2bef152010-10-13 00:55:03337 }
[email protected]6b624c62010-03-14 08:37:32338
[email protected]211d2172009-07-22 15:48:53339 connecting_socket_count_++;
340
[email protected]aed99ef02010-08-26 14:04:32341 group->AddJob(connect_job.release());
[email protected]a2006ece2010-04-23 16:44:02342 } else {
[email protected]06650c52010-06-03 00:49:17343 LogBoundConnectJobToRequest(connect_job->net_log().source(), request);
[email protected]fd2e53e2011-01-14 20:40:52344 ClientSocket* error_socket = NULL;
345 if (!preconnecting) {
346 DCHECK(handle);
347 connect_job->GetAdditionalErrorState(handle);
348 error_socket = connect_job->ReleaseSocket();
349 }
[email protected]e772db3f2010-07-12 18:11:13350 if (error_socket) {
351 HandOutSocket(error_socket, false /* not reused */, handle,
[email protected]aed99ef02010-08-26 14:04:32352 base::TimeDelta(), group, request->net_log());
353 } else if (group->IsEmpty()) {
354 RemoveGroup(group_name);
[email protected]05ea9ff2010-07-15 19:08:21355 }
[email protected]2ab05b52009-07-01 23:57:58356 }
[email protected]ff579d42009-06-24 15:47:02357
[email protected]2ab05b52009-07-01 23:57:58358 return rv;
[email protected]ff579d42009-06-24 15:47:02359}
360
[email protected]05ea9ff2010-07-15 19:08:21361bool ClientSocketPoolBaseHelper::AssignIdleSocketToGroup(
[email protected]aed99ef02010-08-26 14:04:32362 const Request* request, Group* group) {
[email protected]e1b54dc2010-10-06 21:27:22363 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
364 std::list<IdleSocket>::iterator idle_socket_it = idle_sockets->end();
365
366 // Iterate through the idle sockets forwards (oldest to newest)
367 // * Delete any disconnected ones.
368 // * If we find a used idle socket, assign to |idle_socket|. At the end,
369 // the |idle_socket_it| will be set to the newest used idle socket.
370 for (std::list<IdleSocket>::iterator it = idle_sockets->begin();
371 it != idle_sockets->end();) {
372 if (!it->socket->IsConnectedAndIdle()) {
373 DecrementIdleCount();
374 delete it->socket;
375 it = idle_sockets->erase(it);
376 continue;
[email protected]eb5a99382010-07-11 03:18:26377 }
[email protected]e1b54dc2010-10-06 21:27:22378
379 if (it->socket->WasEverUsed()) {
380 // We found one we can reuse!
381 idle_socket_it = it;
382 }
383
384 ++it;
[email protected]eb5a99382010-07-11 03:18:26385 }
[email protected]e1b54dc2010-10-06 21:27:22386
387 // If we haven't found an idle socket, that means there are no used idle
388 // sockets. Pick the oldest (first) idle socket (FIFO).
389
390 if (idle_socket_it == idle_sockets->end() && !idle_sockets->empty())
391 idle_socket_it = idle_sockets->begin();
392
393 if (idle_socket_it != idle_sockets->end()) {
394 DecrementIdleCount();
395 base::TimeDelta idle_time =
396 base::TimeTicks::Now() - idle_socket_it->start_time;
397 IdleSocket idle_socket = *idle_socket_it;
398 idle_sockets->erase(idle_socket_it);
399 HandOutSocket(
400 idle_socket.socket,
401 idle_socket.socket->WasEverUsed(),
402 request->handle(),
403 idle_time,
404 group,
405 request->net_log());
406 return true;
407 }
408
[email protected]eb5a99382010-07-11 03:18:26409 return false;
410}
411
[email protected]06650c52010-06-03 00:49:17412// static
413void ClientSocketPoolBaseHelper::LogBoundConnectJobToRequest(
414 const NetLog::Source& connect_job_source, const Request* request) {
415 request->net_log().AddEvent(
416 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
[email protected]00cd9c42010-11-02 20:15:57417 make_scoped_refptr(new NetLogSourceParameter(
418 "source_dependency", connect_job_source)));
[email protected]06650c52010-06-03 00:49:17419}
420
[email protected]d80a4322009-08-14 07:07:49421void ClientSocketPoolBaseHelper::CancelRequest(
[email protected]05ea9ff2010-07-15 19:08:21422 const std::string& group_name, ClientSocketHandle* handle) {
423 PendingCallbackMap::iterator callback_it = pending_callback_map_.find(handle);
424 if (callback_it != pending_callback_map_.end()) {
425 int result = callback_it->second.result;
426 pending_callback_map_.erase(callback_it);
427 ClientSocket* socket = handle->release_socket();
428 if (socket) {
429 if (result != OK)
430 socket->Disconnect();
431 ReleaseSocket(handle->group_name(), socket, handle->id());
432 }
433 return;
434 }
[email protected]b6501d3d2010-06-03 23:53:34435
[email protected]ff579d42009-06-24 15:47:02436 CHECK(ContainsKey(group_map_, group_name));
437
[email protected]aed99ef02010-08-26 14:04:32438 Group* group = GetOrCreateGroup(group_name);
[email protected]ff579d42009-06-24 15:47:02439
[email protected]ff579d42009-06-24 15:47:02440 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32441 RequestQueue::iterator it = group->mutable_pending_requests()->begin();
442 for (; it != group->pending_requests().end(); ++it) {
[email protected]d80a4322009-08-14 07:07:49443 if ((*it)->handle() == handle) {
[email protected]2c2bef152010-10-13 00:55:03444 scoped_ptr<const Request> req(RemoveRequestFromQueue(it, group));
[email protected]ec11be62010-04-28 19:28:09445 req->net_log().AddEvent(NetLog::TYPE_CANCELLED, NULL);
446 req->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]eb5a99382010-07-11 03:18:26447
448 // We let the job run, unless we're at the socket limit.
[email protected]aed99ef02010-08-26 14:04:32449 if (group->jobs().size() && ReachedMaxSocketsLimit()) {
450 RemoveConnectJob(*group->jobs().begin(), group);
[email protected]eb5a99382010-07-11 03:18:26451 CheckForStalledSocketGroups();
[email protected]974ebd62009-08-03 23:14:34452 }
[email protected]eb5a99382010-07-11 03:18:26453 break;
[email protected]ff579d42009-06-24 15:47:02454 }
455 }
[email protected]ff579d42009-06-24 15:47:02456}
457
[email protected]2abfe90a2010-08-25 17:49:51458bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const {
459 return ContainsKey(group_map_, group_name);
460}
461
[email protected]d80a4322009-08-14 07:07:49462void ClientSocketPoolBaseHelper::CloseIdleSockets() {
[email protected]ff579d42009-06-24 15:47:02463 CleanupIdleSockets(true);
[email protected]06f92462010-08-31 19:24:14464 DCHECK_EQ(0, idle_socket_count_);
[email protected]ff579d42009-06-24 15:47:02465}
466
[email protected]d80a4322009-08-14 07:07:49467int ClientSocketPoolBaseHelper::IdleSocketCountInGroup(
[email protected]ff579d42009-06-24 15:47:02468 const std::string& group_name) const {
469 GroupMap::const_iterator i = group_map_.find(group_name);
470 CHECK(i != group_map_.end());
471
[email protected]aed99ef02010-08-26 14:04:32472 return i->second->idle_sockets().size();
[email protected]ff579d42009-06-24 15:47:02473}
474
[email protected]d80a4322009-08-14 07:07:49475LoadState ClientSocketPoolBaseHelper::GetLoadState(
[email protected]ff579d42009-06-24 15:47:02476 const std::string& group_name,
477 const ClientSocketHandle* handle) const {
[email protected]05ea9ff2010-07-15 19:08:21478 if (ContainsKey(pending_callback_map_, handle))
479 return LOAD_STATE_CONNECTING;
480
[email protected]ff579d42009-06-24 15:47:02481 if (!ContainsKey(group_map_, group_name)) {
482 NOTREACHED() << "ClientSocketPool does not contain group: " << group_name
483 << " for handle: " << handle;
484 return LOAD_STATE_IDLE;
485 }
486
487 // Can't use operator[] since it is non-const.
[email protected]aed99ef02010-08-26 14:04:32488 const Group& group = *group_map_.find(group_name)->second;
[email protected]ff579d42009-06-24 15:47:02489
[email protected]ff579d42009-06-24 15:47:02490 // Search pending_requests for matching handle.
[email protected]aed99ef02010-08-26 14:04:32491 RequestQueue::const_iterator it = group.pending_requests().begin();
492 for (size_t i = 0; it != group.pending_requests().end(); ++it, ++i) {
[email protected]d80a4322009-08-14 07:07:49493 if ((*it)->handle() == handle) {
[email protected]aed99ef02010-08-26 14:04:32494 if (i < group.jobs().size()) {
[email protected]5fc08e32009-07-15 17:09:57495 LoadState max_state = LOAD_STATE_IDLE;
[email protected]aed99ef02010-08-26 14:04:32496 for (ConnectJobSet::const_iterator job_it = group.jobs().begin();
497 job_it != group.jobs().end(); ++job_it) {
[email protected]46451352009-09-01 14:54:21498 max_state = std::max(max_state, (*job_it)->GetLoadState());
[email protected]5fc08e32009-07-15 17:09:57499 }
500 return max_state;
501 } else {
502 // TODO(wtc): Add a state for being on the wait list.
503 // See http://www.crbug.com/5077.
504 return LOAD_STATE_IDLE;
505 }
[email protected]ff579d42009-06-24 15:47:02506 }
507 }
508
509 NOTREACHED();
510 return LOAD_STATE_IDLE;
511}
512
[email protected]ba00b492010-09-08 14:53:38513DictionaryValue* ClientSocketPoolBaseHelper::GetInfoAsValue(
[email protected]59d7a5a2010-08-30 16:44:27514 const std::string& name, const std::string& type) const {
515 DictionaryValue* dict = new DictionaryValue();
516 dict->SetString("name", name);
517 dict->SetString("type", type);
518 dict->SetInteger("handed_out_socket_count", handed_out_socket_count_);
519 dict->SetInteger("connecting_socket_count", connecting_socket_count_);
520 dict->SetInteger("idle_socket_count", idle_socket_count_);
521 dict->SetInteger("max_socket_count", max_sockets_);
522 dict->SetInteger("max_sockets_per_group", max_sockets_per_group_);
523 dict->SetInteger("pool_generation_number", pool_generation_number_);
524
525 if (group_map_.empty())
526 return dict;
527
528 DictionaryValue* all_groups_dict = new DictionaryValue();
529 for (GroupMap::const_iterator it = group_map_.begin();
530 it != group_map_.end(); it++) {
531 const Group* group = it->second;
532 DictionaryValue* group_dict = new DictionaryValue();
533
534 group_dict->SetInteger("pending_request_count",
535 group->pending_requests().size());
536 if (!group->pending_requests().empty()) {
537 group_dict->SetInteger("top_pending_priority",
538 group->TopPendingPriority());
539 }
540
541 group_dict->SetInteger("active_socket_count", group->active_socket_count());
[email protected]0496f9a32010-09-30 16:08:07542
543 ListValue* idle_socket_list = new ListValue();
[email protected]e1b54dc2010-10-06 21:27:22544 std::list<IdleSocket>::const_iterator idle_socket;
[email protected]0496f9a32010-09-30 16:08:07545 for (idle_socket = group->idle_sockets().begin();
546 idle_socket != group->idle_sockets().end();
547 idle_socket++) {
548 int source_id = idle_socket->socket->NetLog().source().id;
549 idle_socket_list->Append(Value::CreateIntegerValue(source_id));
550 }
551 group_dict->Set("idle_sockets", idle_socket_list);
552
553 ListValue* connect_jobs_list = new ListValue();
[email protected]2c2bef152010-10-13 00:55:03554 std::set<ConnectJob*>::const_iterator job = group->jobs().begin();
[email protected]0496f9a32010-09-30 16:08:07555 for (job = group->jobs().begin(); job != group->jobs().end(); job++) {
556 int source_id = (*job)->net_log().source().id;
557 connect_jobs_list->Append(Value::CreateIntegerValue(source_id));
558 }
559 group_dict->Set("connect_jobs", connect_jobs_list);
[email protected]59d7a5a2010-08-30 16:44:27560
561 group_dict->SetBoolean("is_stalled",
562 group->IsStalled(max_sockets_per_group_));
563 group_dict->SetBoolean("has_backup_job", group->HasBackupJob());
564
565 all_groups_dict->SetWithoutPathExpansion(it->first, group_dict);
566 }
567 dict->Set("groups", all_groups_dict);
568 return dict;
569}
570
[email protected]d80a4322009-08-14 07:07:49571bool ClientSocketPoolBaseHelper::IdleSocket::ShouldCleanup(
[email protected]9bf28db2009-08-29 01:35:16572 base::TimeTicks now,
573 base::TimeDelta timeout) const {
574 bool timed_out = (now - start_time) >= timeout;
[email protected]0f873e82010-09-02 16:09:01575 if (timed_out)
576 return true;
577 if (socket->WasEverUsed())
578 return !socket->IsConnectedAndIdle();
579 return !socket->IsConnected();
[email protected]ff579d42009-06-24 15:47:02580}
581
[email protected]d80a4322009-08-14 07:07:49582void ClientSocketPoolBaseHelper::CleanupIdleSockets(bool force) {
[email protected]ff579d42009-06-24 15:47:02583 if (idle_socket_count_ == 0)
584 return;
585
586 // Current time value. Retrieving it once at the function start rather than
587 // inside the inner loop, since it shouldn't change by any meaningful amount.
588 base::TimeTicks now = base::TimeTicks::Now();
589
590 GroupMap::iterator i = group_map_.begin();
591 while (i != group_map_.end()) {
[email protected]aed99ef02010-08-26 14:04:32592 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02593
[email protected]e1b54dc2010-10-06 21:27:22594 std::list<IdleSocket>::iterator j = group->mutable_idle_sockets()->begin();
[email protected]aed99ef02010-08-26 14:04:32595 while (j != group->idle_sockets().end()) {
[email protected]9bf28db2009-08-29 01:35:16596 base::TimeDelta timeout =
[email protected]0f873e82010-09-02 16:09:01597 j->socket->WasEverUsed() ?
598 used_idle_socket_timeout_ : unused_idle_socket_timeout_;
[email protected]9bf28db2009-08-29 01:35:16599 if (force || j->ShouldCleanup(now, timeout)) {
[email protected]ff579d42009-06-24 15:47:02600 delete j->socket;
[email protected]aed99ef02010-08-26 14:04:32601 j = group->mutable_idle_sockets()->erase(j);
[email protected]ff579d42009-06-24 15:47:02602 DecrementIdleCount();
603 } else {
604 ++j;
605 }
606 }
607
608 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32609 if (group->IsEmpty()) {
610 RemoveGroup(i++);
[email protected]ff579d42009-06-24 15:47:02611 } else {
612 ++i;
613 }
614 }
615}
616
[email protected]aed99ef02010-08-26 14:04:32617ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup(
618 const std::string& group_name) {
619 GroupMap::iterator it = group_map_.find(group_name);
620 if (it != group_map_.end())
621 return it->second;
622 Group* group = new Group;
623 group_map_[group_name] = group;
624 return group;
625}
626
627void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) {
628 GroupMap::iterator it = group_map_.find(group_name);
629 CHECK(it != group_map_.end());
630
631 RemoveGroup(it);
632}
633
634void ClientSocketPoolBaseHelper::RemoveGroup(GroupMap::iterator it) {
635 delete it->second;
636 group_map_.erase(it);
637}
638
[email protected]06d94042010-08-25 01:45:22639// static
640void ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(bool enabled) {
641 g_connect_backup_jobs_enabled = enabled;
642}
643
644void ClientSocketPoolBaseHelper::EnableConnectBackupJobs() {
645 connect_backup_jobs_enabled_ = g_connect_backup_jobs_enabled;
646}
647
[email protected]d80a4322009-08-14 07:07:49648void ClientSocketPoolBaseHelper::IncrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02649 if (++idle_socket_count_ == 1)
650 timer_.Start(TimeDelta::FromSeconds(kCleanupInterval), this,
[email protected]d80a4322009-08-14 07:07:49651 &ClientSocketPoolBaseHelper::OnCleanupTimerFired);
[email protected]ff579d42009-06-24 15:47:02652}
653
[email protected]d80a4322009-08-14 07:07:49654void ClientSocketPoolBaseHelper::DecrementIdleCount() {
[email protected]ff579d42009-06-24 15:47:02655 if (--idle_socket_count_ == 0)
656 timer_.Stop();
657}
658
[email protected]eb5a99382010-07-11 03:18:26659void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name,
660 ClientSocket* socket,
661 int id) {
[email protected]ff579d42009-06-24 15:47:02662 GroupMap::iterator i = group_map_.find(group_name);
663 CHECK(i != group_map_.end());
664
[email protected]aed99ef02010-08-26 14:04:32665 Group* group = i->second;
[email protected]ff579d42009-06-24 15:47:02666
[email protected]b1f031dd2010-03-02 23:19:33667 CHECK_GT(handed_out_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53668 handed_out_socket_count_--;
669
[email protected]aed99ef02010-08-26 14:04:32670 CHECK_GT(group->active_socket_count(), 0);
671 group->DecrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02672
[email protected]a7e38572010-06-07 18:22:24673 const bool can_reuse = socket->IsConnectedAndIdle() &&
674 id == pool_generation_number_;
[email protected]ff579d42009-06-24 15:47:02675 if (can_reuse) {
[email protected]eb5a99382010-07-11 03:18:26676 // Add it to the idle list.
[email protected]0f873e82010-09-02 16:09:01677 AddIdleSocket(socket, group);
[email protected]aed99ef02010-08-26 14:04:32678 OnAvailableSocketSlot(group_name, group);
[email protected]ff579d42009-06-24 15:47:02679 } else {
680 delete socket;
681 }
[email protected]05ea9ff2010-07-15 19:08:21682
[email protected]eb5a99382010-07-11 03:18:26683 CheckForStalledSocketGroups();
684}
[email protected]ff579d42009-06-24 15:47:02685
[email protected]eb5a99382010-07-11 03:18:26686void ClientSocketPoolBaseHelper::CheckForStalledSocketGroups() {
687 // If we have idle sockets, see if we can give one to the top-stalled group.
688 std::string top_group_name;
689 Group* top_group = NULL;
[email protected]05ea9ff2010-07-15 19:08:21690 if (!FindTopStalledGroup(&top_group, &top_group_name))
[email protected]eb5a99382010-07-11 03:18:26691 return;
[email protected]4f2abec2010-02-03 18:10:16692
[email protected]eb5a99382010-07-11 03:18:26693 if (ReachedMaxSocketsLimit()) {
694 if (idle_socket_count() > 0) {
695 CloseOneIdleSocket();
[email protected]d7027bb2010-05-10 18:58:54696 } else {
[email protected]eb5a99382010-07-11 03:18:26697 // We can't activate more sockets since we're already at our global
698 // limit.
[email protected]4f2abec2010-02-03 18:10:16699 return;
[email protected]d7027bb2010-05-10 18:58:54700 }
[email protected]4f2abec2010-02-03 18:10:16701 }
[email protected]eb5a99382010-07-11 03:18:26702
703 // Note: we don't loop on waking stalled groups. If the stalled group is at
704 // its limit, may be left with other stalled groups that could be
[email protected]05ea9ff2010-07-15 19:08:21705 // woken. This isn't optimal, but there is no starvation, so to avoid
[email protected]eb5a99382010-07-11 03:18:26706 // the looping we leave it at this.
[email protected]05ea9ff2010-07-15 19:08:21707 OnAvailableSocketSlot(top_group_name, top_group);
[email protected]ff579d42009-06-24 15:47:02708}
709
[email protected]211d2172009-07-22 15:48:53710// Search for the highest priority pending request, amongst the groups that
711// are not at the |max_sockets_per_group_| limit. Note: for requests with
712// the same priority, the winner is based on group hash ordering (and not
713// insertion order).
[email protected]05ea9ff2010-07-15 19:08:21714bool ClientSocketPoolBaseHelper::FindTopStalledGroup(Group** group,
715 std::string* group_name) {
[email protected]211d2172009-07-22 15:48:53716 Group* top_group = NULL;
717 const std::string* top_group_name = NULL;
[email protected]05ea9ff2010-07-15 19:08:21718 bool has_stalled_group = false;
[email protected]211d2172009-07-22 15:48:53719 for (GroupMap::iterator i = group_map_.begin();
720 i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32721 Group* curr_group = i->second;
722 const RequestQueue& queue = curr_group->pending_requests();
[email protected]211d2172009-07-22 15:48:53723 if (queue.empty())
724 continue;
[email protected]aed99ef02010-08-26 14:04:32725 if (curr_group->IsStalled(max_sockets_per_group_)) {
[email protected]05ea9ff2010-07-15 19:08:21726 has_stalled_group = true;
[email protected]6427fe22010-04-16 22:27:41727 bool has_higher_priority = !top_group ||
[email protected]aed99ef02010-08-26 14:04:32728 curr_group->TopPendingPriority() < top_group->TopPendingPriority();
[email protected]6427fe22010-04-16 22:27:41729 if (has_higher_priority) {
[email protected]aed99ef02010-08-26 14:04:32730 top_group = curr_group;
[email protected]6427fe22010-04-16 22:27:41731 top_group_name = &i->first;
732 }
[email protected]211d2172009-07-22 15:48:53733 }
734 }
[email protected]05ea9ff2010-07-15 19:08:21735
[email protected]211d2172009-07-22 15:48:53736 if (top_group) {
737 *group = top_group;
738 *group_name = *top_group_name;
739 }
[email protected]05ea9ff2010-07-15 19:08:21740 return has_stalled_group;
[email protected]211d2172009-07-22 15:48:53741}
742
[email protected]d80a4322009-08-14 07:07:49743void ClientSocketPoolBaseHelper::OnConnectJobComplete(
744 int result, ConnectJob* job) {
[email protected]2ab05b52009-07-01 23:57:58745 DCHECK_NE(ERR_IO_PENDING, result);
746 const std::string group_name = job->group_name();
[email protected]ff579d42009-06-24 15:47:02747 GroupMap::iterator group_it = group_map_.find(group_name);
748 CHECK(group_it != group_map_.end());
[email protected]aed99ef02010-08-26 14:04:32749 Group* group = group_it->second;
[email protected]ff579d42009-06-24 15:47:02750
[email protected]5fc08e32009-07-15 17:09:57751 scoped_ptr<ClientSocket> socket(job->ReleaseSocket());
[email protected]ff579d42009-06-24 15:47:02752
[email protected]9e743cd2010-03-16 07:03:53753 BoundNetLog job_log = job->net_log();
[email protected]5fc08e32009-07-15 17:09:57754
[email protected]4d3b05d2010-01-27 21:27:29755 if (result == OK) {
756 DCHECK(socket.get());
[email protected]aed99ef02010-08-26 14:04:32757 RemoveConnectJob(job, group);
758 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29759 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02760 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17761 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]4d3b05d2010-01-27 21:27:29762 HandOutSocket(
763 socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32764 base::TimeDelta(), group, r->net_log());
[email protected]06650c52010-06-03 00:49:17765 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, NULL);
[email protected]05ea9ff2010-07-15 19:08:21766 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]5fc08e32009-07-15 17:09:57767 } else {
[email protected]0f873e82010-09-02 16:09:01768 AddIdleSocket(socket.release(), group);
[email protected]aed99ef02010-08-26 14:04:32769 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21770 CheckForStalledSocketGroups();
[email protected]5fc08e32009-07-15 17:09:57771 }
[email protected]94c20472010-01-14 08:14:36772 } else {
[email protected]e772db3f2010-07-12 18:11:13773 // If we got a socket, it must contain error information so pass that
774 // up so that the caller can retrieve it.
775 bool handed_out_socket = false;
[email protected]aed99ef02010-08-26 14:04:32776 if (!group->pending_requests().empty()) {
[email protected]4d3b05d2010-01-27 21:27:29777 scoped_ptr<const Request> r(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02778 group->mutable_pending_requests()->begin(), group));
[email protected]06650c52010-06-03 00:49:17779 LogBoundConnectJobToRequest(job_log.source(), r.get());
[email protected]e60e47a2010-07-14 03:37:18780 job->GetAdditionalErrorState(r->handle());
[email protected]aed99ef02010-08-26 14:04:32781 RemoveConnectJob(job, group);
[email protected]e772db3f2010-07-12 18:11:13782 if (socket.get()) {
783 handed_out_socket = true;
784 HandOutSocket(socket.release(), false /* unused socket */, r->handle(),
[email protected]aed99ef02010-08-26 14:04:32785 base::TimeDelta(), group, r->net_log());
[email protected]e772db3f2010-07-12 18:11:13786 }
[email protected]00cd9c42010-11-02 20:15:57787 r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, make_scoped_refptr(
788 new NetLogIntegerParameter("net_error", result)));
[email protected]05ea9ff2010-07-15 19:08:21789 InvokeUserCallbackLater(r->handle(), r->callback(), result);
[email protected]e60e47a2010-07-14 03:37:18790 } else {
[email protected]aed99ef02010-08-26 14:04:32791 RemoveConnectJob(job, group);
[email protected]4d3b05d2010-01-27 21:27:29792 }
[email protected]05ea9ff2010-07-15 19:08:21793 if (!handed_out_socket) {
[email protected]aed99ef02010-08-26 14:04:32794 OnAvailableSocketSlot(group_name, group);
[email protected]05ea9ff2010-07-15 19:08:21795 CheckForStalledSocketGroups();
796 }
[email protected]ff579d42009-06-24 15:47:02797 }
[email protected]ff579d42009-06-24 15:47:02798}
799
[email protected]66761b952010-06-25 21:30:38800void ClientSocketPoolBaseHelper::OnIPAddressChanged() {
801 Flush();
802}
803
[email protected]a7e38572010-06-07 18:22:24804void ClientSocketPoolBaseHelper::Flush() {
805 pool_generation_number_++;
[email protected]06f92462010-08-31 19:24:14806 CancelAllConnectJobs();
[email protected]a554a8262010-05-20 00:13:52807 CloseIdleSockets();
[email protected]06f92462010-08-31 19:24:14808 AbortAllRequests();
[email protected]a554a8262010-05-20 00:13:52809}
810
[email protected]2c2bef152010-10-13 00:55:03811void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job,
[email protected]4d3b05d2010-01-27 21:27:29812 Group* group) {
[email protected]b1f031dd2010-03-02 23:19:33813 CHECK_GT(connecting_socket_count_, 0);
[email protected]211d2172009-07-22 15:48:53814 connecting_socket_count_--;
815
[email protected]25eea382010-07-10 23:55:26816 DCHECK(group);
[email protected]aed99ef02010-08-26 14:04:32817 DCHECK(ContainsKey(group->jobs(), job));
818 group->RemoveJob(job);
[email protected]25eea382010-07-10 23:55:26819
820 // If we've got no more jobs for this group, then we no longer need a
821 // backup job either.
[email protected]aed99ef02010-08-26 14:04:32822 if (group->jobs().empty())
[email protected]25eea382010-07-10 23:55:26823 group->CleanupBackupJob();
824
[email protected]8ae03f42010-07-07 19:08:10825 DCHECK(job);
826 delete job;
[email protected]2ab05b52009-07-01 23:57:58827}
[email protected]ff579d42009-06-24 15:47:02828
[email protected]8ae03f42010-07-07 19:08:10829void ClientSocketPoolBaseHelper::OnAvailableSocketSlot(
[email protected]05ea9ff2010-07-15 19:08:21830 const std::string& group_name, Group* group) {
[email protected]2abfe90a2010-08-25 17:49:51831 DCHECK(ContainsKey(group_map_, group_name));
[email protected]05ea9ff2010-07-15 19:08:21832 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32833 RemoveGroup(group_name);
834 else if (!group->pending_requests().empty())
[email protected]2abfe90a2010-08-25 17:49:51835 ProcessPendingRequest(group_name, group);
[email protected]8ae03f42010-07-07 19:08:10836}
[email protected]06650c52010-06-03 00:49:17837
[email protected]8ae03f42010-07-07 19:08:10838void ClientSocketPoolBaseHelper::ProcessPendingRequest(
[email protected]05ea9ff2010-07-15 19:08:21839 const std::string& group_name, Group* group) {
840 int rv = RequestSocketInternal(group_name,
[email protected]aed99ef02010-08-26 14:04:32841 *group->pending_requests().begin());
[email protected]05ea9ff2010-07-15 19:08:21842 if (rv != ERR_IO_PENDING) {
843 scoped_ptr<const Request> request(RemoveRequestFromQueue(
[email protected]3f00be82010-09-27 19:50:02844 group->mutable_pending_requests()->begin(), group));
[email protected]2abfe90a2010-08-25 17:49:51845 if (group->IsEmpty())
[email protected]aed99ef02010-08-26 14:04:32846 RemoveGroup(group_name);
[email protected]8ae03f42010-07-07 19:08:10847
[email protected]05ea9ff2010-07-15 19:08:21848 scoped_refptr<NetLog::EventParameters> params;
849 if (rv != OK)
850 params = new NetLogIntegerParameter("net_error", rv);
851 request->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL, params);
852 InvokeUserCallbackLater(
853 request->handle(), request->callback(), rv);
[email protected]2ab05b52009-07-01 23:57:58854 }
855}
856
[email protected]d80a4322009-08-14 07:07:49857void ClientSocketPoolBaseHelper::HandOutSocket(
[email protected]2ab05b52009-07-01 23:57:58858 ClientSocket* socket,
859 bool reused,
860 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29861 base::TimeDelta idle_time,
[email protected]fd4fe0b2010-02-08 23:02:15862 Group* group,
[email protected]9e743cd2010-03-16 07:03:53863 const BoundNetLog& net_log) {
[email protected]2ab05b52009-07-01 23:57:58864 DCHECK(socket);
865 handle->set_socket(socket);
866 handle->set_is_reused(reused);
[email protected]f9d285c2009-08-17 19:54:29867 handle->set_idle_time(idle_time);
[email protected]a7e38572010-06-07 18:22:24868 handle->set_pool_id(pool_generation_number_);
[email protected]211d2172009-07-22 15:48:53869
[email protected]d13f51b2010-04-27 23:20:45870 if (reused) {
[email protected]ec11be62010-04-28 19:28:09871 net_log.AddEvent(
[email protected]d13f51b2010-04-27 23:20:45872 NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57873 make_scoped_refptr(new NetLogIntegerParameter(
874 "idle_ms", static_cast<int>(idle_time.InMilliseconds()))));
[email protected]fd4fe0b2010-02-08 23:02:15875 }
[email protected]d13f51b2010-04-27 23:20:45876
[email protected]06650c52010-06-03 00:49:17877 net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
[email protected]00cd9c42010-11-02 20:15:57878 make_scoped_refptr(new NetLogSourceParameter(
879 "source_dependency", socket->NetLog().source())));
[email protected]fd4fe0b2010-02-08 23:02:15880
[email protected]211d2172009-07-22 15:48:53881 handed_out_socket_count_++;
[email protected]aed99ef02010-08-26 14:04:32882 group->IncrementActiveSocketCount();
[email protected]ff579d42009-06-24 15:47:02883}
884
[email protected]d80a4322009-08-14 07:07:49885void ClientSocketPoolBaseHelper::AddIdleSocket(
[email protected]0f873e82010-09-02 16:09:01886 ClientSocket* socket, Group* group) {
[email protected]5fc08e32009-07-15 17:09:57887 DCHECK(socket);
888 IdleSocket idle_socket;
889 idle_socket.socket = socket;
890 idle_socket.start_time = base::TimeTicks::Now();
[email protected]5fc08e32009-07-15 17:09:57891
[email protected]aed99ef02010-08-26 14:04:32892 group->mutable_idle_sockets()->push_back(idle_socket);
[email protected]5fc08e32009-07-15 17:09:57893 IncrementIdleCount();
894}
895
[email protected]d80a4322009-08-14 07:07:49896void ClientSocketPoolBaseHelper::CancelAllConnectJobs() {
[email protected]74d75e0b2010-08-23 20:39:54897 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
[email protected]aed99ef02010-08-26 14:04:32898 Group* group = i->second;
899 connecting_socket_count_ -= group->jobs().size();
900 group->RemoveAllJobs();
[email protected]6b624c62010-03-14 08:37:32901
[email protected]5fc08e32009-07-15 17:09:57902 // Delete group if no longer needed.
[email protected]aed99ef02010-08-26 14:04:32903 if (group->IsEmpty()) {
[email protected]06f92462010-08-31 19:24:14904 // RemoveGroup() will call .erase() which will invalidate the iterator,
905 // but i will already have been incremented to a valid iterator before
906 // RemoveGroup() is called.
907 RemoveGroup(i++);
908 } else {
909 ++i;
910 }
911 }
912 DCHECK_EQ(0, connecting_socket_count_);
913}
914
915void ClientSocketPoolBaseHelper::AbortAllRequests() {
916 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end();) {
917 Group* group = i->second;
918
919 RequestQueue pending_requests;
920 pending_requests.swap(*group->mutable_pending_requests());
921 for (RequestQueue::iterator it2 = pending_requests.begin();
922 it2 != pending_requests.end(); ++it2) {
[email protected]2c2bef152010-10-13 00:55:03923 scoped_ptr<const Request> request(*it2);
[email protected]06f92462010-08-31 19:24:14924 InvokeUserCallbackLater(
925 request->handle(), request->callback(), ERR_ABORTED);
926 }
927
928 // Delete group if no longer needed.
929 if (group->IsEmpty()) {
930 // RemoveGroup() will call .erase() which will invalidate the iterator,
931 // but i will already have been incremented to a valid iterator before
932 // RemoveGroup() is called.
[email protected]aed99ef02010-08-26 14:04:32933 RemoveGroup(i++);
[email protected]74d75e0b2010-08-23 20:39:54934 } else {
935 ++i;
[email protected]5fc08e32009-07-15 17:09:57936 }
937 }
938}
939
[email protected]d80a4322009-08-14 07:07:49940bool ClientSocketPoolBaseHelper::ReachedMaxSocketsLimit() const {
[email protected]211d2172009-07-22 15:48:53941 // Each connecting socket will eventually connect and be handed out.
[email protected]43a21b82010-06-10 21:30:54942 int total = handed_out_socket_count_ + connecting_socket_count_ +
943 idle_socket_count();
[email protected]211d2172009-07-22 15:48:53944 DCHECK_LE(total, max_sockets_);
[email protected]c901f6d2010-04-27 17:48:28945 if (total < max_sockets_)
946 return false;
[email protected]c901f6d2010-04-27 17:48:28947 return true;
[email protected]211d2172009-07-22 15:48:53948}
949
[email protected]43a21b82010-06-10 21:30:54950void ClientSocketPoolBaseHelper::CloseOneIdleSocket() {
[email protected]dcbe168a2010-12-02 03:14:46951 CloseOneIdleSocketExceptInGroup(NULL);
952}
953
954bool ClientSocketPoolBaseHelper::CloseOneIdleSocketExceptInGroup(
955 const Group* exception_group) {
[email protected]43a21b82010-06-10 21:30:54956 CHECK_GT(idle_socket_count(), 0);
957
958 for (GroupMap::iterator i = group_map_.begin(); i != group_map_.end(); ++i) {
[email protected]aed99ef02010-08-26 14:04:32959 Group* group = i->second;
[email protected]dcbe168a2010-12-02 03:14:46960 if (exception_group == group)
961 continue;
[email protected]e1b54dc2010-10-06 21:27:22962 std::list<IdleSocket>* idle_sockets = group->mutable_idle_sockets();
[email protected]43a21b82010-06-10 21:30:54963
[email protected]e1b54dc2010-10-06 21:27:22964 if (!idle_sockets->empty()) {
965 delete idle_sockets->front().socket;
966 idle_sockets->pop_front();
[email protected]43a21b82010-06-10 21:30:54967 DecrementIdleCount();
[email protected]aed99ef02010-08-26 14:04:32968 if (group->IsEmpty())
969 RemoveGroup(i);
[email protected]43a21b82010-06-10 21:30:54970
[email protected]dcbe168a2010-12-02 03:14:46971 return true;
[email protected]43a21b82010-06-10 21:30:54972 }
973 }
974
[email protected]dcbe168a2010-12-02 03:14:46975 if (!exception_group)
976 LOG(DFATAL) << "No idle socket found to close!.";
977
978 return false;
[email protected]43a21b82010-06-10 21:30:54979}
980
[email protected]05ea9ff2010-07-15 19:08:21981void ClientSocketPoolBaseHelper::InvokeUserCallbackLater(
982 ClientSocketHandle* handle, CompletionCallback* callback, int rv) {
983 CHECK(!ContainsKey(pending_callback_map_, handle));
984 pending_callback_map_[handle] = CallbackResultPair(callback, rv);
985 MessageLoop::current()->PostTask(
986 FROM_HERE,
[email protected]2431756e2010-09-29 20:26:13987 method_factory_.NewRunnableMethod(
[email protected]05ea9ff2010-07-15 19:08:21988 &ClientSocketPoolBaseHelper::InvokeUserCallback,
989 handle));
990}
991
992void ClientSocketPoolBaseHelper::InvokeUserCallback(
993 ClientSocketHandle* handle) {
994 PendingCallbackMap::iterator it = pending_callback_map_.find(handle);
995
996 // Exit if the request has already been cancelled.
997 if (it == pending_callback_map_.end())
998 return;
999
1000 CHECK(!handle->is_initialized());
1001 CompletionCallback* callback = it->second.callback;
1002 int result = it->second.result;
1003 pending_callback_map_.erase(it);
1004 callback->Run(result);
1005}
1006
[email protected]aed99ef02010-08-26 14:04:321007ClientSocketPoolBaseHelper::Group::Group()
1008 : active_socket_count_(0),
1009 ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}
1010
1011ClientSocketPoolBaseHelper::Group::~Group() {
1012 CleanupBackupJob();
1013}
1014
1015void ClientSocketPoolBaseHelper::Group::StartBackupSocketTimer(
1016 const std::string& group_name,
1017 ClientSocketPoolBaseHelper* pool) {
1018 // Only allow one timer pending to create a backup socket.
1019 if (!method_factory_.empty())
1020 return;
1021
1022 MessageLoop::current()->PostDelayedTask(
1023 FROM_HERE,
1024 method_factory_.NewRunnableMethod(
1025 &Group::OnBackupSocketTimerFired, group_name, pool),
1026 pool->ConnectRetryIntervalMs());
1027}
1028
[email protected]2c2bef152010-10-13 00:55:031029bool ClientSocketPoolBaseHelper::Group::TryToUsePreconnectConnectJob() {
1030 for (std::set<ConnectJob*>::iterator it = jobs_.begin();
1031 it != jobs_.end(); ++it) {
1032 ConnectJob* job = *it;
1033 if (job->is_unused_preconnect()) {
1034 job->UseForNormalRequest();
1035 return true;
1036 }
1037 }
1038 return false;
1039}
1040
[email protected]aed99ef02010-08-26 14:04:321041void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired(
1042 std::string group_name,
1043 ClientSocketPoolBaseHelper* pool) {
1044 // If there are no more jobs pending, there is no work to do.
1045 // If we've done our cleanups correctly, this should not happen.
1046 if (jobs_.empty()) {
1047 NOTREACHED();
1048 return;
1049 }
1050
1051 // If our backup job is waiting on DNS, or if we can't create any sockets
1052 // right now due to limits, just reset the timer.
1053 if (pool->ReachedMaxSocketsLimit() ||
1054 !HasAvailableSocketSlot(pool->max_sockets_per_group_) ||
1055 (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) {
1056 StartBackupSocketTimer(group_name, pool);
1057 return;
1058 }
1059
[email protected]4baaf9d2010-08-31 15:15:441060 if (pending_requests_.empty()) {
1061 LOG(DFATAL) << "No pending request for backup job.";
1062 return;
1063 }
1064
[email protected]aed99ef02010-08-26 14:04:321065 ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob(
1066 group_name, **pending_requests_.begin(), pool);
1067 backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED, NULL);
1068 SIMPLE_STATS_COUNTER("socket.backup_created");
1069 int rv = backup_job->Connect();
1070 pool->connecting_socket_count_++;
1071 AddJob(backup_job);
1072 if (rv != ERR_IO_PENDING)
1073 pool->OnConnectJobComplete(rv, backup_job);
1074}
1075
1076void ClientSocketPoolBaseHelper::Group::RemoveAllJobs() {
1077 // Delete active jobs.
1078 STLDeleteElements(&jobs_);
1079
1080 // Cancel pending backup job.
1081 method_factory_.RevokeAll();
1082}
1083
[email protected]d80a4322009-08-14 07:07:491084} // namespace internal
1085
[email protected]ff579d42009-06-24 15:47:021086} // namespace net