blob: 942142d6a16f8b470ae27ec7dacb65e137bdbe44 [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.
[email protected]d80a4322009-08-14 07:07:494//
5// A ClientSocketPoolBase is used to restrict the number of sockets open at
6// a time. It also maintains a list of idle persistent sockets for reuse.
7// Subclasses of ClientSocketPool should compose ClientSocketPoolBase to handle
8// the core logic of (1) restricting the number of active (connected or
9// connecting) sockets per "group" (generally speaking, the hostname), (2)
10// maintaining a per-group list of idle, persistent sockets for reuse, and (3)
11// limiting the total number of active sockets in the system.
12//
13// ClientSocketPoolBase abstracts socket connection details behind ConnectJob,
14// ConnectJobFactory, and SocketParams. When a socket "slot" becomes available,
15// the ClientSocketPoolBase will ask the ConnectJobFactory to create a
16// ConnectJob with a SocketParams. Subclasses of ClientSocketPool should
17// implement their socket specific connection by subclassing ConnectJob and
18// implementing ConnectJob::ConnectInternal(). They can control the parameters
19// passed to each new ConnectJob instance via their ConnectJobFactory subclass
20// and templated SocketParams parameter.
21//
[email protected]ff579d42009-06-24 15:47:0222#ifndef NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
23#define NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
24
25#include <deque>
26#include <map>
[email protected]5fc08e32009-07-15 17:09:5727#include <set>
[email protected]ff579d42009-06-24 15:47:0228#include <string>
29
30#include "base/basictypes.h"
[email protected]6b624c62010-03-14 08:37:3231#include "base/compiler_specific.h"
[email protected]100d5fb92009-12-21 21:08:3532#include "base/ref_counted.h"
[email protected]ff579d42009-06-24 15:47:0233#include "base/scoped_ptr.h"
[email protected]6b624c62010-03-14 08:37:3234#include "base/task.h"
[email protected]ff579d42009-06-24 15:47:0235#include "base/time.h"
36#include "base/timer.h"
37#include "net/base/address_list.h"
38#include "net/base/completion_callback.h"
[email protected]ff579d42009-06-24 15:47:0239#include "net/base/load_states.h"
[email protected]d80a4322009-08-14 07:07:4940#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5341#include "net/base/net_log.h"
[email protected]a554a8262010-05-20 00:13:5242#include "net/base/network_change_notifier.h"
[email protected]ac790b42009-12-02 04:31:3143#include "net/base/request_priority.h"
[email protected]2ab05b52009-07-01 23:57:5844#include "net/socket/client_socket.h"
[email protected]ff579d42009-06-24 15:47:0245#include "net/socket/client_socket_pool.h"
46
47namespace net {
48
[email protected]ff579d42009-06-24 15:47:0249class ClientSocketHandle;
[email protected]ff579d42009-06-24 15:47:0250
51// ConnectJob provides an abstract interface for "connecting" a socket.
52// The connection may involve host resolution, tcp connection, ssl connection,
53// etc.
54class ConnectJob {
55 public:
[email protected]ab838892009-06-30 18:49:0556 class Delegate {
57 public:
58 Delegate() {}
59 virtual ~Delegate() {}
60
[email protected]2ab05b52009-07-01 23:57:5861 // Alerts the delegate that the connection completed.
62 virtual void OnConnectJobComplete(int result, ConnectJob* job) = 0;
[email protected]ab838892009-06-30 18:49:0563
64 private:
65 DISALLOW_COPY_AND_ASSIGN(Delegate);
66 };
67
[email protected]974ebd62009-08-03 23:14:3468 // A |timeout_duration| of 0 corresponds to no timeout.
[email protected]2ab05b52009-07-01 23:57:5869 ConnectJob(const std::string& group_name,
[email protected]974ebd62009-08-03 23:14:3470 base::TimeDelta timeout_duration,
[email protected]fd7b7c92009-08-20 19:38:3071 Delegate* delegate,
[email protected]9e743cd2010-03-16 07:03:5372 const BoundNetLog& net_log);
[email protected]2ab05b52009-07-01 23:57:5873 virtual ~ConnectJob();
[email protected]ff579d42009-06-24 15:47:0274
[email protected]2ab05b52009-07-01 23:57:5875 // Accessors
76 const std::string& group_name() const { return group_name_; }
[email protected]9e743cd2010-03-16 07:03:5377 const BoundNetLog& net_log() { return net_log_; }
[email protected]2ab05b52009-07-01 23:57:5878
[email protected]8e12ae02009-07-02 16:15:0479 // Releases |socket_| to the client. On connection error, this should return
80 // NULL.
[email protected]2ab05b52009-07-01 23:57:5881 ClientSocket* ReleaseSocket() { return socket_.release(); }
[email protected]ab838892009-06-30 18:49:0582
[email protected]ff579d42009-06-24 15:47:0283 // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it
84 // cannot complete synchronously without blocking, or another net error code
[email protected]2ab05b52009-07-01 23:57:5885 // on error. In asynchronous completion, the ConnectJob will notify
86 // |delegate_| via OnConnectJobComplete. In both asynchronous and synchronous
87 // completion, ReleaseSocket() can be called to acquire the connected socket
88 // if it succeeded.
[email protected]974ebd62009-08-03 23:14:3489 int Connect();
[email protected]ff579d42009-06-24 15:47:0290
[email protected]46451352009-09-01 14:54:2191 virtual LoadState GetLoadState() const = 0;
[email protected]fd7b7c92009-08-20 19:38:3092
[email protected]ab838892009-06-30 18:49:0593 protected:
[email protected]06650c52010-06-03 00:49:1794 void set_socket(ClientSocket* socket);
[email protected]2ab05b52009-07-01 23:57:5895 ClientSocket* socket() { return socket_.get(); }
[email protected]fd7b7c92009-08-20 19:38:3096 void NotifyDelegateOfCompletion(int rv);
[email protected]a796bcec2010-03-22 17:17:2697 void ResetTimer(base::TimeDelta remainingTime);
[email protected]ab838892009-06-30 18:49:0598
[email protected]ff579d42009-06-24 15:47:0299 private:
[email protected]974ebd62009-08-03 23:14:34100 virtual int ConnectInternal() = 0;
101
[email protected]06650c52010-06-03 00:49:17102 void LogConnectStart();
103 void LogConnectCompletion(int net_error);
104
[email protected]974ebd62009-08-03 23:14:34105 // Alerts the delegate that the ConnectJob has timed out.
106 void OnTimeout();
107
[email protected]2ab05b52009-07-01 23:57:58108 const std::string group_name_;
[email protected]974ebd62009-08-03 23:14:34109 const base::TimeDelta timeout_duration_;
110 // Timer to abort jobs that take too long.
111 base::OneShotTimer<ConnectJob> timer_;
112 Delegate* delegate_;
[email protected]2ab05b52009-07-01 23:57:58113 scoped_ptr<ClientSocket> socket_;
[email protected]9e743cd2010-03-16 07:03:53114 BoundNetLog net_log_;
[email protected]a2006ece2010-04-23 16:44:02115 // A ConnectJob is idle until Connect() has been called.
116 bool idle_;
[email protected]ab838892009-06-30 18:49:05117
[email protected]ff579d42009-06-24 15:47:02118 DISALLOW_COPY_AND_ASSIGN(ConnectJob);
119};
120
[email protected]d80a4322009-08-14 07:07:49121namespace internal {
122
123// ClientSocketPoolBaseHelper is an internal class that implements almost all
124// the functionality from ClientSocketPoolBase without using templates.
125// ClientSocketPoolBase adds templated definitions built on top of
126// ClientSocketPoolBaseHelper. This class is not for external use, please use
127// ClientSocketPoolBase instead.
128class ClientSocketPoolBaseHelper
129 : public base::RefCounted<ClientSocketPoolBaseHelper>,
[email protected]a554a8262010-05-20 00:13:52130 public ConnectJob::Delegate,
131 public NetworkChangeNotifier::Observer {
[email protected]ff579d42009-06-24 15:47:02132 public:
[email protected]d80a4322009-08-14 07:07:49133 class Request {
134 public:
[email protected]684970b2009-08-14 04:54:46135 Request(ClientSocketHandle* handle,
[email protected]ff579d42009-06-24 15:47:02136 CompletionCallback* callback,
[email protected]ac790b42009-12-02 04:31:31137 RequestPriority priority,
[email protected]9e743cd2010-03-16 07:03:53138 const BoundNetLog& net_log);
[email protected]ff579d42009-06-24 15:47:02139
[email protected]fd4fe0b2010-02-08 23:02:15140 virtual ~Request();
[email protected]d80a4322009-08-14 07:07:49141
142 ClientSocketHandle* handle() const { return handle_; }
143 CompletionCallback* callback() const { return callback_; }
[email protected]ac790b42009-12-02 04:31:31144 RequestPriority priority() const { return priority_; }
[email protected]9e743cd2010-03-16 07:03:53145 const BoundNetLog& net_log() const { return net_log_; }
[email protected]d80a4322009-08-14 07:07:49146
147 private:
148 ClientSocketHandle* const handle_;
149 CompletionCallback* const callback_;
[email protected]ac790b42009-12-02 04:31:31150 const RequestPriority priority_;
[email protected]9e743cd2010-03-16 07:03:53151 BoundNetLog net_log_;
[email protected]d80a4322009-08-14 07:07:49152
153 DISALLOW_COPY_AND_ASSIGN(Request);
[email protected]ff579d42009-06-24 15:47:02154 };
155
156 class ConnectJobFactory {
157 public:
158 ConnectJobFactory() {}
159 virtual ~ConnectJobFactory() {}
160
161 virtual ConnectJob* NewConnectJob(
162 const std::string& group_name,
163 const Request& request,
[email protected]06650c52010-06-03 00:49:17164 ConnectJob::Delegate* delegate) const = 0;
[email protected]ff579d42009-06-24 15:47:02165
[email protected]a796bcec2010-03-22 17:17:26166 virtual base::TimeDelta ConnectionTimeout() const = 0;
167
[email protected]ff579d42009-06-24 15:47:02168 private:
169 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
170 };
171
[email protected]100d5fb92009-12-21 21:08:35172 ClientSocketPoolBaseHelper(
173 int max_sockets,
174 int max_sockets_per_group,
175 base::TimeDelta unused_idle_socket_timeout,
176 base::TimeDelta used_idle_socket_timeout,
[email protected]a554a8262010-05-20 00:13:52177 ConnectJobFactory* connect_job_factory,
178 NetworkChangeNotifier* network_change_notifier);
[email protected]ff579d42009-06-24 15:47:02179
[email protected]d80a4322009-08-14 07:07:49180 // See ClientSocketPool::RequestSocket for documentation on this function.
[email protected]e7e99322010-05-04 23:30:17181 // ClientSocketPoolBaseHelper takes ownership of |request|, which must be
182 // heap allocated.
[email protected]d80a4322009-08-14 07:07:49183 int RequestSocket(const std::string& group_name, const Request* request);
[email protected]ff579d42009-06-24 15:47:02184
[email protected]d80a4322009-08-14 07:07:49185 // See ClientSocketPool::CancelRequest for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02186 void CancelRequest(const std::string& group_name,
187 const ClientSocketHandle* handle);
188
[email protected]d80a4322009-08-14 07:07:49189 // See ClientSocketPool::ReleaseSocket for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02190 void ReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24191 ClientSocket* socket,
192 int id);
[email protected]ff579d42009-06-24 15:47:02193
[email protected]a7e38572010-06-07 18:22:24194 // See ClientSocketPool::Flush for documentation on this function.
195 void Flush();
[email protected]241c5c2c2010-06-21 18:46:00196
[email protected]d80a4322009-08-14 07:07:49197 // See ClientSocketPool::CloseIdleSockets for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02198 void CloseIdleSockets();
199
[email protected]d80a4322009-08-14 07:07:49200 // See ClientSocketPool::IdleSocketCount() for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02201 int idle_socket_count() const {
202 return idle_socket_count_;
203 }
204
[email protected]d80a4322009-08-14 07:07:49205 // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this
206 // function.
[email protected]ff579d42009-06-24 15:47:02207 int IdleSocketCountInGroup(const std::string& group_name) const;
208
[email protected]d80a4322009-08-14 07:07:49209 // See ClientSocketPool::GetLoadState() for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02210 LoadState GetLoadState(const std::string& group_name,
211 const ClientSocketHandle* handle) const;
212
[email protected]6b624c62010-03-14 08:37:32213 int ConnectRetryIntervalMs() const {
214 // TODO(mbelshe): Make this tuned dynamically based on measured RTT.
215 // For now, just use the max retry interval.
216 return ClientSocketPool::kMaxConnectRetryIntervalMs;
217 }
218
[email protected]d80a4322009-08-14 07:07:49219 // ConnectJob::Delegate methods:
[email protected]2ab05b52009-07-01 23:57:58220 virtual void OnConnectJobComplete(int result, ConnectJob* job);
[email protected]ff579d42009-06-24 15:47:02221
[email protected]a554a8262010-05-20 00:13:52222 // NetworkChangeNotifier::Observer methods:
[email protected]a7e38572010-06-07 18:22:24223 virtual void OnIPAddressChanged() { Flush(); }
[email protected]a554a8262010-05-20 00:13:52224
[email protected]211d2172009-07-22 15:48:53225 // For testing.
226 bool may_have_stalled_group() const { return may_have_stalled_group_; }
[email protected]d80a4322009-08-14 07:07:49227
[email protected]974ebd62009-08-03 23:14:34228 int NumConnectJobsInGroup(const std::string& group_name) const {
229 return group_map_.find(group_name)->second.jobs.size();
230 }
[email protected]211d2172009-07-22 15:48:53231
[email protected]9bf28db2009-08-29 01:35:16232 // Closes all idle sockets if |force| is true. Else, only closes idle
233 // sockets that timed out or can't be reused. Made public for testing.
234 void CleanupIdleSockets(bool force);
235
[email protected]a796bcec2010-03-22 17:17:26236 base::TimeDelta ConnectionTimeout() const {
237 return connect_job_factory_->ConnectionTimeout();
238 }
239
[email protected]43a21b82010-06-10 21:30:54240 void EnableBackupJobs() { backup_jobs_enabled_ = true; }
[email protected]7c28e9a2010-03-20 01:16:13241
[email protected]ff579d42009-06-24 15:47:02242 private:
[email protected]5389bc72009-11-05 23:34:24243 friend class base::RefCounted<ClientSocketPoolBaseHelper>;
244
245 ~ClientSocketPoolBaseHelper();
246
[email protected]ff579d42009-06-24 15:47:02247 // Entry for a persistent socket which became idle at time |start_time|.
248 struct IdleSocket {
[email protected]5fc08e32009-07-15 17:09:57249 IdleSocket() : socket(NULL), used(false) {}
[email protected]ff579d42009-06-24 15:47:02250 ClientSocket* socket;
251 base::TimeTicks start_time;
[email protected]5fc08e32009-07-15 17:09:57252 bool used; // Indicates whether or not the socket has been used yet.
[email protected]ff579d42009-06-24 15:47:02253
254 // An idle socket should be removed if it can't be reused, or has been idle
255 // for too long. |now| is the current time value (TimeTicks::Now()).
[email protected]9bf28db2009-08-29 01:35:16256 // |timeout| is the length of time to wait before timing out an idle socket.
[email protected]ff579d42009-06-24 15:47:02257 //
258 // An idle socket can't be reused if it is disconnected or has received
259 // data unexpectedly (hence no longer idle). The unread data would be
260 // mistaken for the beginning of the next response if we were to reuse the
261 // socket for a new request.
[email protected]9bf28db2009-08-29 01:35:16262 bool ShouldCleanup(base::TimeTicks now, base::TimeDelta timeout) const;
[email protected]ff579d42009-06-24 15:47:02263 };
264
[email protected]d80a4322009-08-14 07:07:49265 typedef std::deque<const Request*> RequestQueue;
266 typedef std::map<const ClientSocketHandle*, const Request*> RequestMap;
[email protected]ff579d42009-06-24 15:47:02267
268 // A Group is allocated per group_name when there are idle sockets or pending
269 // requests. Otherwise, the Group object is removed from the map.
[email protected]5edbf8d2010-01-13 18:44:11270 // |active_socket_count| tracks the number of sockets held by clients. Of
271 // this number of sockets held by clients, some of them may be released soon,
272 // since ReleaseSocket() was called of them, but the DoReleaseSocket() task
273 // has not run yet for them. |num_releasing_sockets| tracks these values,
[email protected]6b624c62010-03-14 08:37:32274 // which is useful for not starting up new ConnectJobs when sockets may
275 // become available really soon.
[email protected]ff579d42009-06-24 15:47:02276 struct Group {
[email protected]6b624c62010-03-14 08:37:32277 Group()
278 : active_socket_count(0),
279 num_releasing_sockets(0),
280 backup_job(NULL),
281 backup_task(NULL) {
282 }
283
284 ~Group() {
285 CleanupBackupJob();
286 }
[email protected]2ab05b52009-07-01 23:57:58287
288 bool IsEmpty() const {
[email protected]2b7523d2009-07-29 20:29:23289 return active_socket_count == 0 && idle_sockets.empty() && jobs.empty() &&
[email protected]4d3b05d2010-01-27 21:27:29290 pending_requests.empty();
[email protected]2ab05b52009-07-01 23:57:58291 }
292
293 bool HasAvailableSocketSlot(int max_sockets_per_group) const {
[email protected]5fc08e32009-07-15 17:09:57294 return active_socket_count + static_cast<int>(jobs.size()) <
[email protected]2ab05b52009-07-01 23:57:58295 max_sockets_per_group;
296 }
297
[email protected]5edbf8d2010-01-13 18:44:11298 bool HasReleasingSockets() const {
299 return num_releasing_sockets > 0;
300 }
301
[email protected]ac790b42009-12-02 04:31:31302 RequestPriority TopPendingPriority() const {
[email protected]d80a4322009-08-14 07:07:49303 return pending_requests.front()->priority();
[email protected]211d2172009-07-22 15:48:53304 }
305
[email protected]6b624c62010-03-14 08:37:32306 void CleanupBackupJob() {
307 if (backup_job) {
308 delete backup_job;
309 backup_job = NULL;
310 }
311 if (backup_task) {
312 backup_task->Cancel();
313 backup_task = NULL;
314 }
315 }
316
[email protected]ff579d42009-06-24 15:47:02317 std::deque<IdleSocket> idle_sockets;
[email protected]5fc08e32009-07-15 17:09:57318 std::set<const ConnectJob*> jobs;
[email protected]ff579d42009-06-24 15:47:02319 RequestQueue pending_requests;
[email protected]2ab05b52009-07-01 23:57:58320 int active_socket_count; // number of active sockets used by clients
[email protected]5edbf8d2010-01-13 18:44:11321 // Number of sockets being released within one loop through the MessageLoop.
322 int num_releasing_sockets;
[email protected]6b624c62010-03-14 08:37:32323 // A backup job in case the connect for this group takes too long.
324 ConnectJob* backup_job;
325 CancelableTask* backup_task;
[email protected]ff579d42009-06-24 15:47:02326 };
327
328 typedef std::map<std::string, Group> GroupMap;
329
[email protected]5fc08e32009-07-15 17:09:57330 typedef std::set<const ConnectJob*> ConnectJobSet;
[email protected]ff579d42009-06-24 15:47:02331
[email protected]d80a4322009-08-14 07:07:49332 static void InsertRequestIntoQueue(const Request* r,
[email protected]ff579d42009-06-24 15:47:02333 RequestQueue* pending_requests);
[email protected]fd7b7c92009-08-20 19:38:30334 static const Request* RemoveRequestFromQueue(RequestQueue::iterator it,
335 RequestQueue* pending_requests);
[email protected]ff579d42009-06-24 15:47:02336
[email protected]ff579d42009-06-24 15:47:02337 // Called when the number of idle sockets changes.
338 void IncrementIdleCount();
339 void DecrementIdleCount();
340
341 // Called via PostTask by ReleaseSocket.
[email protected]a7e38572010-06-07 18:22:24342 void DoReleaseSocket(
343 const std::string& group_name, ClientSocket* socket, int id);
[email protected]ff579d42009-06-24 15:47:02344
[email protected]211d2172009-07-22 15:48:53345 // Scans the group map for groups which have an available socket slot and
346 // at least one pending request. Returns number of groups found, and if found
347 // at least one, fills |group| and |group_name| with data of the stalled group
348 // having highest priority.
349 int FindTopStalledGroup(Group** group, std::string* group_name);
350
[email protected]ff579d42009-06-24 15:47:02351 // Called when timer_ fires. This method scans the idle sockets removing
352 // sockets that timed out or can't be reused.
353 void OnCleanupTimerFired() {
354 CleanupIdleSockets(false);
355 }
356
[email protected]4d3b05d2010-01-27 21:27:29357 // Removes |job| from |connect_job_set_|. Also updates |group| if non-NULL.
358 void RemoveConnectJob(const ConnectJob* job, Group* group);
[email protected]ff579d42009-06-24 15:47:02359
[email protected]2ab05b52009-07-01 23:57:58360 // Same as OnAvailableSocketSlot except it looks up the Group first to see if
361 // it's there.
362 void MaybeOnAvailableSocketSlot(const std::string& group_name);
[email protected]ff579d42009-06-24 15:47:02363
[email protected]2ab05b52009-07-01 23:57:58364 // Might delete the Group from |group_map_|.
365 void OnAvailableSocketSlot(const std::string& group_name, Group* group);
[email protected]ff579d42009-06-24 15:47:02366
367 // Process a request from a group's pending_requests queue.
368 void ProcessPendingRequest(const std::string& group_name, Group* group);
369
[email protected]2ab05b52009-07-01 23:57:58370 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
371 void HandOutSocket(ClientSocket* socket,
372 bool reused,
373 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29374 base::TimeDelta time_idle,
[email protected]fd4fe0b2010-02-08 23:02:15375 Group* group,
[email protected]9e743cd2010-03-16 07:03:53376 const BoundNetLog& net_log);
[email protected]2ab05b52009-07-01 23:57:58377
[email protected]5fc08e32009-07-15 17:09:57378 // Adds |socket| to the list of idle sockets for |group|. |used| indicates
379 // whether or not the socket has previously been used.
380 void AddIdleSocket(ClientSocket* socket, bool used, Group* group);
381
382 // Iterates through |connect_job_map_|, canceling all ConnectJobs.
383 // Afterwards, it iterates through all groups and deletes them if they are no
384 // longer needed.
385 void CancelAllConnectJobs();
386
[email protected]211d2172009-07-22 15:48:53387 // Returns true if we can't create any more sockets due to the total limit.
388 // TODO(phajdan.jr): Also take idle sockets into account.
389 bool ReachedMaxSocketsLimit() const;
390
[email protected]fd4fe0b2010-02-08 23:02:15391 // This is the internal implementation of RequestSocket(). It differs in that
[email protected]9e743cd2010-03-16 07:03:53392 // it does not handle logging into NetLog of the queueing status of
[email protected]fd4fe0b2010-02-08 23:02:15393 // |request|.
394 int RequestSocketInternal(const std::string& group_name,
395 const Request* request);
396
[email protected]06650c52010-06-03 00:49:17397 static void LogBoundConnectJobToRequest(
398 const NetLog::Source& connect_job_source, const Request* request);
399
[email protected]6b624c62010-03-14 08:37:32400 // Set a timer to create a backup socket if it takes too long to create one.
401 void StartBackupSocketTimer(const std::string& group_name);
402
403 // Called when the backup socket timer fires.
404 void OnBackupSocketTimerFired(const std::string& group_name);
405
[email protected]43a21b82010-06-10 21:30:54406 // Closes one idle socket. Picks the first one encountered.
407 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we
408 // should keep an ordered list of idle sockets, and close them in order.
409 // Requires maintaining more state. It's not clear if it's worth it since
410 // I'm not sure if we hit this situation often.
411 void CloseOneIdleSocket();
412
[email protected]ff579d42009-06-24 15:47:02413 GroupMap group_map_;
414
[email protected]ff579d42009-06-24 15:47:02415 // Timer used to periodically prune idle sockets that timed out or can't be
416 // reused.
[email protected]d80a4322009-08-14 07:07:49417 base::RepeatingTimer<ClientSocketPoolBaseHelper> timer_;
[email protected]ff579d42009-06-24 15:47:02418
419 // The total number of idle sockets in the system.
420 int idle_socket_count_;
421
[email protected]211d2172009-07-22 15:48:53422 // Number of connecting sockets across all groups.
423 int connecting_socket_count_;
424
425 // Number of connected sockets we handed out across all groups.
426 int handed_out_socket_count_;
427
[email protected]d7027bb2010-05-10 18:58:54428 // Number of sockets being released.
429 int num_releasing_sockets_;
430
[email protected]211d2172009-07-22 15:48:53431 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
432 const int max_sockets_;
433
[email protected]ff579d42009-06-24 15:47:02434 // The maximum number of sockets kept per group.
435 const int max_sockets_per_group_;
436
[email protected]9bf28db2009-08-29 01:35:16437 // The time to wait until closing idle sockets.
438 const base::TimeDelta unused_idle_socket_timeout_;
439 const base::TimeDelta used_idle_socket_timeout_;
440
[email protected]211d2172009-07-22 15:48:53441 // Until the maximum number of sockets limit is reached, a group can only
442 // have pending requests if it exceeds the "max sockets per group" limit.
443 //
444 // This means when a socket is released, the only pending requests that can
445 // be started next belong to the same group.
446 //
447 // However once the |max_sockets_| limit is reached, this stops being true:
448 // groups can now have pending requests without having first reached the
449 // |max_sockets_per_group_| limit. So choosing the next request involves
450 // selecting the highest priority request across *all* groups.
451 //
[email protected]43a21b82010-06-10 21:30:54452 // |may_have_stalled_group_| is not conclusive, since when we cancel pending
[email protected]241c5c2c2010-06-21 18:46:00453 // requests, we may reach the situation where we have the maximum number of
[email protected]43a21b82010-06-10 21:30:54454 // sockets, but no request is stalled because of the global socket limit
455 // (although some requests may be blocked on the socket per group limit).
456 // We don't strictly maintain |may_have_stalled_group_|, since that would
[email protected]241c5c2c2010-06-21 18:46:00457 // require a linear search through all groups in |group_map_| to see if one
[email protected]43a21b82010-06-10 21:30:54458 // of them is stalled.
[email protected]211d2172009-07-22 15:48:53459 bool may_have_stalled_group_;
460
[email protected]ab838892009-06-30 18:49:05461 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
[email protected]ff579d42009-06-24 15:47:02462
[email protected]a554a8262010-05-20 00:13:52463 NetworkChangeNotifier* const network_change_notifier_;
464
[email protected]7c28e9a2010-03-20 01:16:13465 // TODO(vandebo) Remove when backup jobs move to TCPClientSocketPool
466 bool backup_jobs_enabled_;
467
[email protected]6b624c62010-03-14 08:37:32468 // A factory to pin the backup_job tasks.
469 ScopedRunnableMethodFactory<ClientSocketPoolBaseHelper> method_factory_;
[email protected]a7e38572010-06-07 18:22:24470
471 // A unique id for the pool. It gets incremented every time we Flush() the
472 // pool. This is so that when sockets get released back to the pool, we can
473 // make sure that they are discarded rather than reused.
474 int pool_generation_number_;
[email protected]d80a4322009-08-14 07:07:49475};
476
477} // namespace internal
478
[email protected]9bf28db2009-08-29 01:35:16479// The maximum duration, in seconds, to keep used idle persistent sockets alive.
480static const int kUsedIdleSocketTimeout = 300; // 5 minutes
481
[email protected]d80a4322009-08-14 07:07:49482template <typename SocketParams>
483class ClientSocketPoolBase {
484 public:
485 class Request : public internal::ClientSocketPoolBaseHelper::Request {
486 public:
487 Request(ClientSocketHandle* handle,
488 CompletionCallback* callback,
[email protected]ac790b42009-12-02 04:31:31489 RequestPriority priority,
[email protected]d80a4322009-08-14 07:07:49490 const SocketParams& params,
[email protected]9e743cd2010-03-16 07:03:53491 const BoundNetLog& net_log)
[email protected]d80a4322009-08-14 07:07:49492 : internal::ClientSocketPoolBaseHelper::Request(
[email protected]9e743cd2010-03-16 07:03:53493 handle, callback, priority, net_log),
[email protected]d80a4322009-08-14 07:07:49494 params_(params) {}
495
496 const SocketParams& params() const { return params_; }
497
498 private:
499 SocketParams params_;
500 };
501
502 class ConnectJobFactory {
503 public:
504 ConnectJobFactory() {}
505 virtual ~ConnectJobFactory() {}
506
507 virtual ConnectJob* NewConnectJob(
508 const std::string& group_name,
509 const Request& request,
[email protected]06650c52010-06-03 00:49:17510 ConnectJob::Delegate* delegate) const = 0;
[email protected]d80a4322009-08-14 07:07:49511
[email protected]a796bcec2010-03-22 17:17:26512 virtual base::TimeDelta ConnectionTimeout() const = 0;
513
[email protected]d80a4322009-08-14 07:07:49514 private:
515 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
516 };
517
[email protected]9bf28db2009-08-29 01:35:16518 // |max_sockets| is the maximum number of sockets to be maintained by this
519 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
520 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
521 // long to leave an unused idle socket open before closing it.
522 // |used_idle_socket_timeout| specifies how long to leave a previously used
523 // idle socket open before closing it.
[email protected]100d5fb92009-12-21 21:08:35524 ClientSocketPoolBase(
525 int max_sockets,
526 int max_sockets_per_group,
[email protected]b89f7e42010-05-20 20:37:00527 const scoped_refptr<ClientSocketPoolHistograms>& histograms,
[email protected]100d5fb92009-12-21 21:08:35528 base::TimeDelta unused_idle_socket_timeout,
529 base::TimeDelta used_idle_socket_timeout,
[email protected]a554a8262010-05-20 00:13:52530 ConnectJobFactory* connect_job_factory,
531 NetworkChangeNotifier* network_change_notifier)
[email protected]b89f7e42010-05-20 20:37:00532 : histograms_(histograms),
[email protected]a796bcec2010-03-22 17:17:26533 helper_(new internal::ClientSocketPoolBaseHelper(
[email protected]d80a4322009-08-14 07:07:49534 max_sockets, max_sockets_per_group,
[email protected]9bf28db2009-08-29 01:35:16535 unused_idle_socket_timeout, used_idle_socket_timeout,
[email protected]a554a8262010-05-20 00:13:52536 new ConnectJobFactoryAdaptor(connect_job_factory),
537 network_change_notifier)) {}
[email protected]d80a4322009-08-14 07:07:49538
[email protected]20cb5f482009-12-16 01:01:25539 virtual ~ClientSocketPoolBase() {}
[email protected]d80a4322009-08-14 07:07:49540
541 // These member functions simply forward to ClientSocketPoolBaseHelper.
542
543 // RequestSocket bundles up the parameters into a Request and then forwards to
544 // ClientSocketPoolBaseHelper::RequestSocket(). Note that the memory
545 // ownership is transferred in the asynchronous (ERR_IO_PENDING) case.
546 int RequestSocket(const std::string& group_name,
547 const SocketParams& params,
[email protected]ac790b42009-12-02 04:31:31548 RequestPriority priority,
[email protected]d80a4322009-08-14 07:07:49549 ClientSocketHandle* handle,
550 CompletionCallback* callback,
[email protected]9e743cd2010-03-16 07:03:53551 const BoundNetLog& net_log) {
[email protected]e7e99322010-05-04 23:30:17552 Request* request = new Request(handle, callback, priority, params, net_log);
553 return helper_->RequestSocket(group_name, request);
[email protected]d80a4322009-08-14 07:07:49554 }
555
556 void CancelRequest(const std::string& group_name,
557 const ClientSocketHandle* handle) {
558 return helper_->CancelRequest(group_name, handle);
559 }
560
[email protected]241c5c2c2010-06-21 18:46:00561 void ReleaseSocket(const std::string& group_name, ClientSocket* socket,
562 int id) {
[email protected]a7e38572010-06-07 18:22:24563 return helper_->ReleaseSocket(group_name, socket, id);
[email protected]d80a4322009-08-14 07:07:49564 }
565
566 void CloseIdleSockets() { return helper_->CloseIdleSockets(); }
567
568 int idle_socket_count() const { return helper_->idle_socket_count(); }
569
570 int IdleSocketCountInGroup(const std::string& group_name) const {
571 return helper_->IdleSocketCountInGroup(group_name);
572 }
573
574 LoadState GetLoadState(const std::string& group_name,
575 const ClientSocketHandle* handle) const {
576 return helper_->GetLoadState(group_name, handle);
577 }
578
579 virtual void OnConnectJobComplete(int result, ConnectJob* job) {
580 return helper_->OnConnectJobComplete(result, job);
581 }
582
583 // For testing.
584 bool may_have_stalled_group() const {
585 return helper_->may_have_stalled_group();
586 }
587
588 int NumConnectJobsInGroup(const std::string& group_name) const {
589 return helper_->NumConnectJobsInGroup(group_name);
590 }
591
[email protected]9bf28db2009-08-29 01:35:16592 void CleanupIdleSockets(bool force) {
593 return helper_->CleanupIdleSockets(force);
594 }
595
[email protected]a796bcec2010-03-22 17:17:26596 base::TimeDelta ConnectionTimeout() const {
597 return helper_->ConnectionTimeout();
598 }
599
[email protected]b89f7e42010-05-20 20:37:00600 scoped_refptr<ClientSocketPoolHistograms> histograms() const {
601 return histograms_;
602 }
[email protected]a796bcec2010-03-22 17:17:26603
[email protected]43a21b82010-06-10 21:30:54604 void EnableBackupJobs() { helper_->EnableBackupJobs(); }
[email protected]7c28e9a2010-03-20 01:16:13605
[email protected]a7e38572010-06-07 18:22:24606 void Flush() { helper_->Flush(); }
607
[email protected]d80a4322009-08-14 07:07:49608 private:
609 // This adaptor class exists to bridge the
610 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
611 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
612 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
613 // static_cast themselves.
614 class ConnectJobFactoryAdaptor
615 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory {
616 public:
617 typedef typename ClientSocketPoolBase<SocketParams>::ConnectJobFactory
618 ConnectJobFactory;
619
620 explicit ConnectJobFactoryAdaptor(
621 ConnectJobFactory* connect_job_factory)
622 : connect_job_factory_(connect_job_factory) {}
623 virtual ~ConnectJobFactoryAdaptor() {}
624
625 virtual ConnectJob* NewConnectJob(
626 const std::string& group_name,
627 const internal::ClientSocketPoolBaseHelper::Request& request,
[email protected]06650c52010-06-03 00:49:17628 ConnectJob::Delegate* delegate) const {
[email protected]d80a4322009-08-14 07:07:49629 const Request* casted_request = static_cast<const Request*>(&request);
630 return connect_job_factory_->NewConnectJob(
[email protected]06650c52010-06-03 00:49:17631 group_name, *casted_request, delegate);
[email protected]d80a4322009-08-14 07:07:49632 }
633
[email protected]a796bcec2010-03-22 17:17:26634 virtual base::TimeDelta ConnectionTimeout() const {
635 return connect_job_factory_->ConnectionTimeout();
636 }
637
[email protected]d80a4322009-08-14 07:07:49638 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
639 };
640
[email protected]b89f7e42010-05-20 20:37:00641 // Histograms for the pool
642 const scoped_refptr<ClientSocketPoolHistograms> histograms_;
[email protected]a796bcec2010-03-22 17:17:26643
[email protected]d80a4322009-08-14 07:07:49644 // One might ask why ClientSocketPoolBaseHelper is also refcounted if its
645 // containing ClientSocketPool is already refcounted. The reason is because
646 // DoReleaseSocket() posts a task. If ClientSocketPool gets deleted between
647 // the posting of the task and the execution, then we'll hit the DCHECK that
648 // |ClientSocketPoolBaseHelper::group_map_| is empty.
649 scoped_refptr<internal::ClientSocketPoolBaseHelper> helper_;
650
[email protected]ff579d42009-06-24 15:47:02651 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase);
652};
653
[email protected]ff579d42009-06-24 15:47:02654} // namespace net
655
656#endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_