blob: 8fcb5719a398477a2b34bad7afd34acc025ad96e [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_
[email protected]32b76ef2010-07-26 23:08:2424#pragma once
[email protected]ff579d42009-06-24 15:47:0225
26#include <deque>
[email protected]e1b54dc2010-10-06 21:27:2227#include <list>
[email protected]ff579d42009-06-24 15:47:0228#include <map>
[email protected]5fc08e32009-07-15 17:09:5729#include <set>
[email protected]ff579d42009-06-24 15:47:0230#include <string>
31
32#include "base/basictypes.h"
[email protected]100d5fb92009-12-21 21:08:3533#include "base/ref_counted.h"
[email protected]ff579d42009-06-24 15:47:0234#include "base/scoped_ptr.h"
[email protected]6b624c62010-03-14 08:37:3235#include "base/task.h"
[email protected]ff579d42009-06-24 15:47:0236#include "base/time.h"
37#include "base/timer.h"
38#include "net/base/address_list.h"
39#include "net/base/completion_callback.h"
[email protected]ff579d42009-06-24 15:47:0240#include "net/base/load_states.h"
[email protected]d80a4322009-08-14 07:07:4941#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5342#include "net/base/net_log.h"
[email protected]a554a8262010-05-20 00:13:5243#include "net/base/network_change_notifier.h"
[email protected]ac790b42009-12-02 04:31:3144#include "net/base/request_priority.h"
[email protected]2ab05b52009-07-01 23:57:5845#include "net/socket/client_socket.h"
[email protected]ff579d42009-06-24 15:47:0246#include "net/socket/client_socket_pool.h"
47
48namespace net {
49
[email protected]ff579d42009-06-24 15:47:0250class ClientSocketHandle;
[email protected]ff579d42009-06-24 15:47:0251
52// ConnectJob provides an abstract interface for "connecting" a socket.
53// The connection may involve host resolution, tcp connection, ssl connection,
54// etc.
55class ConnectJob {
56 public:
[email protected]ab838892009-06-30 18:49:0557 class Delegate {
58 public:
59 Delegate() {}
60 virtual ~Delegate() {}
61
[email protected]2ab05b52009-07-01 23:57:5862 // Alerts the delegate that the connection completed.
63 virtual void OnConnectJobComplete(int result, ConnectJob* job) = 0;
[email protected]ab838892009-06-30 18:49:0564
65 private:
66 DISALLOW_COPY_AND_ASSIGN(Delegate);
67 };
68
[email protected]974ebd62009-08-03 23:14:3469 // A |timeout_duration| of 0 corresponds to no timeout.
[email protected]2ab05b52009-07-01 23:57:5870 ConnectJob(const std::string& group_name,
[email protected]974ebd62009-08-03 23:14:3471 base::TimeDelta timeout_duration,
[email protected]fd7b7c92009-08-20 19:38:3072 Delegate* delegate,
[email protected]9e743cd2010-03-16 07:03:5373 const BoundNetLog& net_log);
[email protected]2ab05b52009-07-01 23:57:5874 virtual ~ConnectJob();
[email protected]ff579d42009-06-24 15:47:0275
[email protected]2ab05b52009-07-01 23:57:5876 // Accessors
77 const std::string& group_name() const { return group_name_; }
[email protected]9e743cd2010-03-16 07:03:5378 const BoundNetLog& net_log() { return net_log_; }
[email protected]2c2bef152010-10-13 00:55:0379 bool is_preconnect() const { return preconnect_state_ != NOT_PRECONNECT; }
80 bool is_unused_preconnect() const {
81 return preconnect_state_ == UNUSED_PRECONNECT;
82 }
83
84 // Initialized by the ClientSocketPoolBaseHelper.
85 // TODO(willchan): Move most of the constructor arguments over here. We
86 // shouldn't give the ConnectJobFactory (subclasses) the ability to screw up
87 // the initialization.
88 void Initialize(bool is_preconnect);
[email protected]2ab05b52009-07-01 23:57:5889
[email protected]8e12ae02009-07-02 16:15:0490 // Releases |socket_| to the client. On connection error, this should return
91 // NULL.
[email protected]2ab05b52009-07-01 23:57:5892 ClientSocket* ReleaseSocket() { return socket_.release(); }
[email protected]ab838892009-06-30 18:49:0593
[email protected]ff579d42009-06-24 15:47:0294 // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it
95 // cannot complete synchronously without blocking, or another net error code
[email protected]2ab05b52009-07-01 23:57:5896 // on error. In asynchronous completion, the ConnectJob will notify
97 // |delegate_| via OnConnectJobComplete. In both asynchronous and synchronous
98 // completion, ReleaseSocket() can be called to acquire the connected socket
99 // if it succeeded.
[email protected]974ebd62009-08-03 23:14:34100 int Connect();
[email protected]ff579d42009-06-24 15:47:02101
[email protected]2c2bef152010-10-13 00:55:03102 // Precondition: is_unused_preconnect() must be true. Marks the job as a
103 // used preconnect job.
104 void UseForNormalRequest();
105
[email protected]46451352009-09-01 14:54:21106 virtual LoadState GetLoadState() const = 0;
[email protected]fd7b7c92009-08-20 19:38:30107
[email protected]e60e47a2010-07-14 03:37:18108 // If Connect returns an error (or OnConnectJobComplete reports an error
109 // result) this method will be called, allowing the pool to add
110 // additional error state to the ClientSocketHandle (post late-binding).
111 virtual void GetAdditionalErrorState(ClientSocketHandle* handle) {}
112
[email protected]0496f9a32010-09-30 16:08:07113 const BoundNetLog& net_log() const { return net_log_; }
114
[email protected]ab838892009-06-30 18:49:05115 protected:
[email protected]06650c52010-06-03 00:49:17116 void set_socket(ClientSocket* socket);
[email protected]2ab05b52009-07-01 23:57:58117 ClientSocket* socket() { return socket_.get(); }
[email protected]fd7b7c92009-08-20 19:38:30118 void NotifyDelegateOfCompletion(int rv);
[email protected]a796bcec2010-03-22 17:17:26119 void ResetTimer(base::TimeDelta remainingTime);
[email protected]ab838892009-06-30 18:49:05120
[email protected]ff579d42009-06-24 15:47:02121 private:
[email protected]2c2bef152010-10-13 00:55:03122 enum PreconnectState {
123 NOT_PRECONNECT,
124 UNUSED_PRECONNECT,
125 USED_PRECONNECT,
126 };
127
[email protected]974ebd62009-08-03 23:14:34128 virtual int ConnectInternal() = 0;
129
[email protected]06650c52010-06-03 00:49:17130 void LogConnectStart();
131 void LogConnectCompletion(int net_error);
132
[email protected]974ebd62009-08-03 23:14:34133 // Alerts the delegate that the ConnectJob has timed out.
134 void OnTimeout();
135
[email protected]2ab05b52009-07-01 23:57:58136 const std::string group_name_;
[email protected]974ebd62009-08-03 23:14:34137 const base::TimeDelta timeout_duration_;
138 // Timer to abort jobs that take too long.
139 base::OneShotTimer<ConnectJob> timer_;
140 Delegate* delegate_;
[email protected]2ab05b52009-07-01 23:57:58141 scoped_ptr<ClientSocket> socket_;
[email protected]9e743cd2010-03-16 07:03:53142 BoundNetLog net_log_;
[email protected]a2006ece2010-04-23 16:44:02143 // A ConnectJob is idle until Connect() has been called.
144 bool idle_;
[email protected]2c2bef152010-10-13 00:55:03145 PreconnectState preconnect_state_;
[email protected]ab838892009-06-30 18:49:05146
[email protected]ff579d42009-06-24 15:47:02147 DISALLOW_COPY_AND_ASSIGN(ConnectJob);
148};
149
[email protected]d80a4322009-08-14 07:07:49150namespace internal {
151
152// ClientSocketPoolBaseHelper is an internal class that implements almost all
153// the functionality from ClientSocketPoolBase without using templates.
154// ClientSocketPoolBase adds templated definitions built on top of
155// ClientSocketPoolBaseHelper. This class is not for external use, please use
156// ClientSocketPoolBase instead.
157class ClientSocketPoolBaseHelper
[email protected]2431756e2010-09-29 20:26:13158 : public ConnectJob::Delegate,
[email protected]232a5812011-03-04 22:42:08159 public NetworkChangeNotifier::IPAddressObserver {
[email protected]ff579d42009-06-24 15:47:02160 public:
[email protected]f48b9432011-01-11 07:25:40161 typedef uint32 Flags;
162
[email protected]2c2bef152010-10-13 00:55:03163 // Used to specify specific behavior for the ClientSocketPool.
164 enum Flag {
165 NORMAL = 0, // Normal behavior.
166 NO_IDLE_SOCKETS = 0x1, // Do not return an idle socket. Create a new one.
167 };
168
[email protected]d80a4322009-08-14 07:07:49169 class Request {
170 public:
[email protected]684970b2009-08-14 04:54:46171 Request(ClientSocketHandle* handle,
[email protected]ff579d42009-06-24 15:47:02172 CompletionCallback* callback,
[email protected]ac790b42009-12-02 04:31:31173 RequestPriority priority,
[email protected]2c2bef152010-10-13 00:55:03174 Flags flags,
[email protected]9e743cd2010-03-16 07:03:53175 const BoundNetLog& net_log);
[email protected]ff579d42009-06-24 15:47:02176
[email protected]fd4fe0b2010-02-08 23:02:15177 virtual ~Request();
[email protected]d80a4322009-08-14 07:07:49178
179 ClientSocketHandle* handle() const { return handle_; }
180 CompletionCallback* callback() const { return callback_; }
[email protected]ac790b42009-12-02 04:31:31181 RequestPriority priority() const { return priority_; }
[email protected]6a166f812010-10-13 02:27:23182 Flags flags() const { return flags_; }
[email protected]9e743cd2010-03-16 07:03:53183 const BoundNetLog& net_log() const { return net_log_; }
[email protected]d80a4322009-08-14 07:07:49184
185 private:
186 ClientSocketHandle* const handle_;
187 CompletionCallback* const callback_;
[email protected]ac790b42009-12-02 04:31:31188 const RequestPriority priority_;
[email protected]2c2bef152010-10-13 00:55:03189 const Flags flags_;
[email protected]9e743cd2010-03-16 07:03:53190 BoundNetLog net_log_;
[email protected]d80a4322009-08-14 07:07:49191
192 DISALLOW_COPY_AND_ASSIGN(Request);
[email protected]ff579d42009-06-24 15:47:02193 };
194
195 class ConnectJobFactory {
196 public:
197 ConnectJobFactory() {}
198 virtual ~ConnectJobFactory() {}
199
200 virtual ConnectJob* NewConnectJob(
201 const std::string& group_name,
202 const Request& request,
[email protected]06650c52010-06-03 00:49:17203 ConnectJob::Delegate* delegate) const = 0;
[email protected]ff579d42009-06-24 15:47:02204
[email protected]a796bcec2010-03-22 17:17:26205 virtual base::TimeDelta ConnectionTimeout() const = 0;
206
[email protected]ff579d42009-06-24 15:47:02207 private:
208 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
209 };
210
[email protected]100d5fb92009-12-21 21:08:35211 ClientSocketPoolBaseHelper(
212 int max_sockets,
213 int max_sockets_per_group,
214 base::TimeDelta unused_idle_socket_timeout,
215 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38216 ConnectJobFactory* connect_job_factory);
[email protected]ff579d42009-06-24 15:47:02217
[email protected]2431756e2010-09-29 20:26:13218 ~ClientSocketPoolBaseHelper();
219
[email protected]d80a4322009-08-14 07:07:49220 // See ClientSocketPool::RequestSocket for documentation on this function.
[email protected]e7e99322010-05-04 23:30:17221 // ClientSocketPoolBaseHelper takes ownership of |request|, which must be
222 // heap allocated.
[email protected]d80a4322009-08-14 07:07:49223 int RequestSocket(const std::string& group_name, const Request* request);
[email protected]ff579d42009-06-24 15:47:02224
[email protected]2c2bef152010-10-13 00:55:03225 // See ClientSocketPool::RequestSocket for documentation on this function.
226 void RequestSockets(const std::string& group_name,
227 const Request& request,
228 int num_sockets);
229
[email protected]d80a4322009-08-14 07:07:49230 // See ClientSocketPool::CancelRequest for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02231 void CancelRequest(const std::string& group_name,
[email protected]05ea9ff2010-07-15 19:08:21232 ClientSocketHandle* handle);
[email protected]ff579d42009-06-24 15:47:02233
[email protected]d80a4322009-08-14 07:07:49234 // See ClientSocketPool::ReleaseSocket for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02235 void ReleaseSocket(const std::string& group_name,
[email protected]a7e38572010-06-07 18:22:24236 ClientSocket* socket,
237 int id);
[email protected]ff579d42009-06-24 15:47:02238
[email protected]a7e38572010-06-07 18:22:24239 // See ClientSocketPool::Flush for documentation on this function.
240 void Flush();
[email protected]241c5c2c2010-06-21 18:46:00241
[email protected]d80a4322009-08-14 07:07:49242 // See ClientSocketPool::CloseIdleSockets for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02243 void CloseIdleSockets();
244
[email protected]d80a4322009-08-14 07:07:49245 // See ClientSocketPool::IdleSocketCount() for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02246 int idle_socket_count() const {
247 return idle_socket_count_;
248 }
249
[email protected]d80a4322009-08-14 07:07:49250 // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this
251 // function.
[email protected]ff579d42009-06-24 15:47:02252 int IdleSocketCountInGroup(const std::string& group_name) const;
253
[email protected]d80a4322009-08-14 07:07:49254 // See ClientSocketPool::GetLoadState() for documentation on this function.
[email protected]ff579d42009-06-24 15:47:02255 LoadState GetLoadState(const std::string& group_name,
256 const ClientSocketHandle* handle) const;
257
[email protected]6b624c62010-03-14 08:37:32258 int ConnectRetryIntervalMs() const {
259 // TODO(mbelshe): Make this tuned dynamically based on measured RTT.
260 // For now, just use the max retry interval.
261 return ClientSocketPool::kMaxConnectRetryIntervalMs;
262 }
263
[email protected]974ebd62009-08-03 23:14:34264 int NumConnectJobsInGroup(const std::string& group_name) const {
[email protected]aed99ef02010-08-26 14:04:32265 return group_map_.find(group_name)->second->jobs().size();
[email protected]974ebd62009-08-03 23:14:34266 }
[email protected]211d2172009-07-22 15:48:53267
[email protected]2c2bef152010-10-13 00:55:03268 int NumActiveSocketsInGroup(const std::string& group_name) const {
269 return group_map_.find(group_name)->second->active_socket_count();
270 }
271
[email protected]2abfe90a2010-08-25 17:49:51272 bool HasGroup(const std::string& group_name) const;
273
[email protected]9bf28db2009-08-29 01:35:16274 // Closes all idle sockets if |force| is true. Else, only closes idle
275 // sockets that timed out or can't be reused. Made public for testing.
276 void CleanupIdleSockets(bool force);
277
[email protected]59d7a5a2010-08-30 16:44:27278 // See ClientSocketPool::GetInfoAsValue for documentation on this function.
[email protected]ba00b492010-09-08 14:53:38279 DictionaryValue* GetInfoAsValue(const std::string& name,
280 const std::string& type) const;
[email protected]59d7a5a2010-08-30 16:44:27281
[email protected]a796bcec2010-03-22 17:17:26282 base::TimeDelta ConnectionTimeout() const {
283 return connect_job_factory_->ConnectionTimeout();
284 }
285
[email protected]106c27f42011-03-09 01:39:00286 static bool connect_backup_jobs_enabled();
[email protected]06d94042010-08-25 01:45:22287 static void set_connect_backup_jobs_enabled(bool enabled);
[email protected]106c27f42011-03-09 01:39:00288
[email protected]06d94042010-08-25 01:45:22289 void EnableConnectBackupJobs();
[email protected]7c28e9a2010-03-20 01:16:13290
[email protected]f48b9432011-01-11 07:25:40291 // ConnectJob::Delegate methods:
292 virtual void OnConnectJobComplete(int result, ConnectJob* job);
293
[email protected]232a5812011-03-04 22:42:08294 // NetworkChangeNotifier::IPAddressObserver methods:
[email protected]f48b9432011-01-11 07:25:40295 virtual void OnIPAddressChanged();
296
[email protected]ff579d42009-06-24 15:47:02297 private:
[email protected]5389bc72009-11-05 23:34:24298 friend class base::RefCounted<ClientSocketPoolBaseHelper>;
299
[email protected]ff579d42009-06-24 15:47:02300 // Entry for a persistent socket which became idle at time |start_time|.
301 struct IdleSocket {
[email protected]0f873e82010-09-02 16:09:01302 IdleSocket() : socket(NULL) {}
[email protected]ff579d42009-06-24 15:47:02303
304 // An idle socket should be removed if it can't be reused, or has been idle
305 // for too long. |now| is the current time value (TimeTicks::Now()).
[email protected]9bf28db2009-08-29 01:35:16306 // |timeout| is the length of time to wait before timing out an idle socket.
[email protected]ff579d42009-06-24 15:47:02307 //
308 // An idle socket can't be reused if it is disconnected or has received
309 // data unexpectedly (hence no longer idle). The unread data would be
310 // mistaken for the beginning of the next response if we were to reuse the
311 // socket for a new request.
[email protected]9bf28db2009-08-29 01:35:16312 bool ShouldCleanup(base::TimeTicks now, base::TimeDelta timeout) const;
[email protected]be1a48b2011-01-20 00:12:13313
314 ClientSocket* socket;
315 base::TimeTicks start_time;
[email protected]ff579d42009-06-24 15:47:02316 };
317
[email protected]2c2bef152010-10-13 00:55:03318 typedef std::deque<const Request* > RequestQueue;
[email protected]d80a4322009-08-14 07:07:49319 typedef std::map<const ClientSocketHandle*, const Request*> RequestMap;
[email protected]ff579d42009-06-24 15:47:02320
321 // A Group is allocated per group_name when there are idle sockets or pending
322 // requests. Otherwise, the Group object is removed from the map.
[email protected]eb5a99382010-07-11 03:18:26323 // |active_socket_count| tracks the number of sockets held by clients.
[email protected]aed99ef02010-08-26 14:04:32324 class Group {
325 public:
326 Group();
327 ~Group();
[email protected]2ab05b52009-07-01 23:57:58328
329 bool IsEmpty() const {
[email protected]aed99ef02010-08-26 14:04:32330 return active_socket_count_ == 0 && idle_sockets_.empty() &&
331 jobs_.empty() && pending_requests_.empty();
[email protected]2ab05b52009-07-01 23:57:58332 }
333
334 bool HasAvailableSocketSlot(int max_sockets_per_group) const {
[email protected]2c2bef152010-10-13 00:55:03335 return NumActiveSocketSlots() < max_sockets_per_group;
336 }
337
338 int NumActiveSocketSlots() const {
339 return active_socket_count_ + static_cast<int>(jobs_.size()) +
340 static_cast<int>(idle_sockets_.size());
[email protected]2ab05b52009-07-01 23:57:58341 }
342
[email protected]05ea9ff2010-07-15 19:08:21343 bool IsStalled(int max_sockets_per_group) const {
344 return HasAvailableSocketSlot(max_sockets_per_group) &&
[email protected]aed99ef02010-08-26 14:04:32345 pending_requests_.size() > jobs_.size();
[email protected]05ea9ff2010-07-15 19:08:21346 }
347
[email protected]ac790b42009-12-02 04:31:31348 RequestPriority TopPendingPriority() const {
[email protected]aed99ef02010-08-26 14:04:32349 return pending_requests_.front()->priority();
[email protected]211d2172009-07-22 15:48:53350 }
351
[email protected]aed99ef02010-08-26 14:04:32352 bool HasBackupJob() const { return !method_factory_.empty(); }
353
[email protected]6b624c62010-03-14 08:37:32354 void CleanupBackupJob() {
[email protected]aed99ef02010-08-26 14:04:32355 method_factory_.RevokeAll();
[email protected]6b624c62010-03-14 08:37:32356 }
357
[email protected]aed99ef02010-08-26 14:04:32358 // Set a timer to create a backup socket if it takes too long to create one.
359 void StartBackupSocketTimer(const std::string& group_name,
360 ClientSocketPoolBaseHelper* pool);
361
[email protected]2c2bef152010-10-13 00:55:03362 // Searches |jobs_| to see if there's a preconnect ConnectJob, and if so,
363 // uses it. Returns true on success. Otherwise, returns false.
364 bool TryToUsePreconnectConnectJob();
[email protected]aed99ef02010-08-26 14:04:32365
[email protected]2c2bef152010-10-13 00:55:03366 void AddJob(ConnectJob* job) { jobs_.insert(job); }
367 void RemoveJob(ConnectJob* job) { jobs_.erase(job); }
[email protected]aed99ef02010-08-26 14:04:32368 void RemoveAllJobs();
369
370 void IncrementActiveSocketCount() { active_socket_count_++; }
371 void DecrementActiveSocketCount() { active_socket_count_--; }
372
[email protected]2c2bef152010-10-13 00:55:03373 const std::set<ConnectJob*>& jobs() const { return jobs_; }
[email protected]e1b54dc2010-10-06 21:27:22374 const std::list<IdleSocket>& idle_sockets() const { return idle_sockets_; }
[email protected]aed99ef02010-08-26 14:04:32375 const RequestQueue& pending_requests() const { return pending_requests_; }
376 int active_socket_count() const { return active_socket_count_; }
377 RequestQueue* mutable_pending_requests() { return &pending_requests_; }
[email protected]e1b54dc2010-10-06 21:27:22378 std::list<IdleSocket>* mutable_idle_sockets() { return &idle_sockets_; }
[email protected]aed99ef02010-08-26 14:04:32379
380 private:
[email protected]2c2bef152010-10-13 00:55:03381 // Called when the backup socket timer fires.
382 void OnBackupSocketTimerFired(
383 std::string group_name,
384 ClientSocketPoolBaseHelper* pool);
385
[email protected]e1b54dc2010-10-06 21:27:22386 std::list<IdleSocket> idle_sockets_;
[email protected]2c2bef152010-10-13 00:55:03387 std::set<ConnectJob*> jobs_;
[email protected]aed99ef02010-08-26 14:04:32388 RequestQueue pending_requests_;
389 int active_socket_count_; // number of active sockets used by clients
390 // A factory to pin the backup_job tasks.
391 ScopedRunnableMethodFactory<Group> method_factory_;
[email protected]ff579d42009-06-24 15:47:02392 };
393
[email protected]aed99ef02010-08-26 14:04:32394 typedef std::map<std::string, Group*> GroupMap;
[email protected]ff579d42009-06-24 15:47:02395
[email protected]2c2bef152010-10-13 00:55:03396 typedef std::set<ConnectJob*> ConnectJobSet;
[email protected]ff579d42009-06-24 15:47:02397
[email protected]05ea9ff2010-07-15 19:08:21398 struct CallbackResultPair {
399 CallbackResultPair() : callback(NULL), result(OK) {}
400 CallbackResultPair(CompletionCallback* callback_in, int result_in)
401 : callback(callback_in), result(result_in) {}
402
403 CompletionCallback* callback;
404 int result;
405 };
406
407 typedef std::map<const ClientSocketHandle*, CallbackResultPair>
408 PendingCallbackMap;
409
[email protected]d80a4322009-08-14 07:07:49410 static void InsertRequestIntoQueue(const Request* r,
[email protected]ff579d42009-06-24 15:47:02411 RequestQueue* pending_requests);
[email protected]417da102011-03-11 17:45:05412 static const Request* RemoveRequestFromQueue(const RequestQueue::iterator& it,
[email protected]3f00be82010-09-27 19:50:02413 Group* group);
[email protected]ff579d42009-06-24 15:47:02414
[email protected]aed99ef02010-08-26 14:04:32415 Group* GetOrCreateGroup(const std::string& group_name);
416 void RemoveGroup(const std::string& group_name);
417 void RemoveGroup(GroupMap::iterator it);
418
[email protected]ff579d42009-06-24 15:47:02419 // Called when the number of idle sockets changes.
420 void IncrementIdleCount();
421 void DecrementIdleCount();
422
[email protected]211d2172009-07-22 15:48:53423 // Scans the group map for groups which have an available socket slot and
[email protected]05ea9ff2010-07-15 19:08:21424 // at least one pending request. Returns true if any groups are stalled, and
425 // if so, fills |group| and |group_name| with data of the stalled group
[email protected]211d2172009-07-22 15:48:53426 // having highest priority.
[email protected]05ea9ff2010-07-15 19:08:21427 bool FindTopStalledGroup(Group** group, std::string* group_name);
[email protected]211d2172009-07-22 15:48:53428
[email protected]ff579d42009-06-24 15:47:02429 // Called when timer_ fires. This method scans the idle sockets removing
430 // sockets that timed out or can't be reused.
431 void OnCleanupTimerFired() {
432 CleanupIdleSockets(false);
433 }
434
[email protected]4d3b05d2010-01-27 21:27:29435 // Removes |job| from |connect_job_set_|. Also updates |group| if non-NULL.
[email protected]2c2bef152010-10-13 00:55:03436 void RemoveConnectJob(ConnectJob* job, Group* group);
[email protected]ff579d42009-06-24 15:47:02437
[email protected]05ea9ff2010-07-15 19:08:21438 // Tries to see if we can handle any more requests for |group|.
439 void OnAvailableSocketSlot(const std::string& group_name, Group* group);
[email protected]8ae03f42010-07-07 19:08:10440
[email protected]eb5a99382010-07-11 03:18:26441 // Process a pending socket request for a group.
[email protected]05ea9ff2010-07-15 19:08:21442 void ProcessPendingRequest(const std::string& group_name, Group* group);
[email protected]ff579d42009-06-24 15:47:02443
[email protected]2ab05b52009-07-01 23:57:58444 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
445 void HandOutSocket(ClientSocket* socket,
446 bool reused,
447 ClientSocketHandle* handle,
[email protected]f9d285c2009-08-17 19:54:29448 base::TimeDelta time_idle,
[email protected]fd4fe0b2010-02-08 23:02:15449 Group* group,
[email protected]9e743cd2010-03-16 07:03:53450 const BoundNetLog& net_log);
[email protected]2ab05b52009-07-01 23:57:58451
[email protected]0f873e82010-09-02 16:09:01452 // Adds |socket| to the list of idle sockets for |group|.
453 void AddIdleSocket(ClientSocket* socket, Group* group);
[email protected]5fc08e32009-07-15 17:09:57454
[email protected]06f92462010-08-31 19:24:14455 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
456 // groups if they are no longer needed.
[email protected]5fc08e32009-07-15 17:09:57457 void CancelAllConnectJobs();
458
[email protected]06f92462010-08-31 19:24:14459 // Iterates through |group_map_|, posting ERR_ABORTED callbacks for all
460 // requests, and then deleting groups if they are no longer needed.
461 void AbortAllRequests();
462
[email protected]211d2172009-07-22 15:48:53463 // Returns true if we can't create any more sockets due to the total limit.
[email protected]211d2172009-07-22 15:48:53464 bool ReachedMaxSocketsLimit() const;
465
[email protected]fd4fe0b2010-02-08 23:02:15466 // This is the internal implementation of RequestSocket(). It differs in that
[email protected]9e743cd2010-03-16 07:03:53467 // it does not handle logging into NetLog of the queueing status of
[email protected]fd4fe0b2010-02-08 23:02:15468 // |request|.
469 int RequestSocketInternal(const std::string& group_name,
470 const Request* request);
471
[email protected]eb5a99382010-07-11 03:18:26472 // Assigns an idle socket for the group to the request.
473 // Returns |true| if an idle socket is available, false otherwise.
[email protected]aed99ef02010-08-26 14:04:32474 bool AssignIdleSocketToGroup(const Request* request, Group* group);
[email protected]eb5a99382010-07-11 03:18:26475
[email protected]06650c52010-06-03 00:49:17476 static void LogBoundConnectJobToRequest(
477 const NetLog::Source& connect_job_source, const Request* request);
478
[email protected]43a21b82010-06-10 21:30:54479 // Closes one idle socket. Picks the first one encountered.
480 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we
481 // should keep an ordered list of idle sockets, and close them in order.
482 // Requires maintaining more state. It's not clear if it's worth it since
483 // I'm not sure if we hit this situation often.
484 void CloseOneIdleSocket();
485
[email protected]dcbe168a2010-12-02 03:14:46486 // Same as CloseOneIdleSocket() except it won't close an idle socket in
487 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
488 // socket.
489 bool CloseOneIdleSocketExceptInGroup(const Group* group);
490
[email protected]eb5a99382010-07-11 03:18:26491 // Checks if there are stalled socket groups that should be notified
492 // for possible wakeup.
493 void CheckForStalledSocketGroups();
494
[email protected]05ea9ff2010-07-15 19:08:21495 // Posts a task to call InvokeUserCallback() on the next iteration through the
496 // current message loop. Inserts |callback| into |pending_callback_map_|,
497 // keyed by |handle|.
498 void InvokeUserCallbackLater(
499 ClientSocketHandle* handle, CompletionCallback* callback, int rv);
500
501 // Invokes the user callback for |handle|. By the time this task has run,
502 // it's possible that the request has been cancelled, so |handle| may not
503 // exist in |pending_callback_map_|. We look up the callback and result code
504 // in |pending_callback_map_|.
505 void InvokeUserCallback(ClientSocketHandle* handle);
[email protected]eb5a99382010-07-11 03:18:26506
[email protected]ff579d42009-06-24 15:47:02507 GroupMap group_map_;
508
[email protected]05ea9ff2010-07-15 19:08:21509 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
510 // callback. This is necessary since, before we invoke said callback, it's
511 // possible that the request is cancelled.
512 PendingCallbackMap pending_callback_map_;
513
[email protected]ff579d42009-06-24 15:47:02514 // Timer used to periodically prune idle sockets that timed out or can't be
515 // reused.
[email protected]d80a4322009-08-14 07:07:49516 base::RepeatingTimer<ClientSocketPoolBaseHelper> timer_;
[email protected]ff579d42009-06-24 15:47:02517
518 // The total number of idle sockets in the system.
519 int idle_socket_count_;
520
[email protected]211d2172009-07-22 15:48:53521 // Number of connecting sockets across all groups.
522 int connecting_socket_count_;
523
524 // Number of connected sockets we handed out across all groups.
525 int handed_out_socket_count_;
526
527 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
528 const int max_sockets_;
529
[email protected]ff579d42009-06-24 15:47:02530 // The maximum number of sockets kept per group.
531 const int max_sockets_per_group_;
532
[email protected]9bf28db2009-08-29 01:35:16533 // The time to wait until closing idle sockets.
534 const base::TimeDelta unused_idle_socket_timeout_;
535 const base::TimeDelta used_idle_socket_timeout_;
536
[email protected]ab838892009-06-30 18:49:05537 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
[email protected]ff579d42009-06-24 15:47:02538
[email protected]7c28e9a2010-03-20 01:16:13539 // TODO(vandebo) Remove when backup jobs move to TCPClientSocketPool
[email protected]06d94042010-08-25 01:45:22540 bool connect_backup_jobs_enabled_;
[email protected]7c28e9a2010-03-20 01:16:13541
[email protected]a7e38572010-06-07 18:22:24542 // A unique id for the pool. It gets incremented every time we Flush() the
543 // pool. This is so that when sockets get released back to the pool, we can
544 // make sure that they are discarded rather than reused.
545 int pool_generation_number_;
[email protected]09d6ecb02010-07-22 20:10:45546
[email protected]2431756e2010-09-29 20:26:13547 ScopedRunnableMethodFactory<ClientSocketPoolBaseHelper> method_factory_;
548
[email protected]3598c6022010-09-17 23:13:09549 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper);
[email protected]d80a4322009-08-14 07:07:49550};
551
552} // namespace internal
553
[email protected]9bf28db2009-08-29 01:35:16554// The maximum duration, in seconds, to keep used idle persistent sockets alive.
555static const int kUsedIdleSocketTimeout = 300; // 5 minutes
556
[email protected]d80a4322009-08-14 07:07:49557template <typename SocketParams>
558class ClientSocketPoolBase {
559 public:
560 class Request : public internal::ClientSocketPoolBaseHelper::Request {
561 public:
562 Request(ClientSocketHandle* handle,
563 CompletionCallback* callback,
[email protected]ac790b42009-12-02 04:31:31564 RequestPriority priority,
[email protected]2c2bef152010-10-13 00:55:03565 internal::ClientSocketPoolBaseHelper::Flags flags,
[email protected]df4b4ef2010-07-12 18:25:21566 const scoped_refptr<SocketParams>& params,
[email protected]9e743cd2010-03-16 07:03:53567 const BoundNetLog& net_log)
[email protected]d80a4322009-08-14 07:07:49568 : internal::ClientSocketPoolBaseHelper::Request(
[email protected]2c2bef152010-10-13 00:55:03569 handle, callback, priority, flags, net_log),
[email protected]d80a4322009-08-14 07:07:49570 params_(params) {}
571
[email protected]df4b4ef2010-07-12 18:25:21572 const scoped_refptr<SocketParams>& params() const { return params_; }
[email protected]d80a4322009-08-14 07:07:49573
574 private:
[email protected]2c2bef152010-10-13 00:55:03575 const scoped_refptr<SocketParams> params_;
[email protected]d80a4322009-08-14 07:07:49576 };
577
578 class ConnectJobFactory {
579 public:
580 ConnectJobFactory() {}
581 virtual ~ConnectJobFactory() {}
582
583 virtual ConnectJob* NewConnectJob(
584 const std::string& group_name,
585 const Request& request,
[email protected]06650c52010-06-03 00:49:17586 ConnectJob::Delegate* delegate) const = 0;
[email protected]d80a4322009-08-14 07:07:49587
[email protected]a796bcec2010-03-22 17:17:26588 virtual base::TimeDelta ConnectionTimeout() const = 0;
589
[email protected]d80a4322009-08-14 07:07:49590 private:
591 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
592 };
593
[email protected]9bf28db2009-08-29 01:35:16594 // |max_sockets| is the maximum number of sockets to be maintained by this
595 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
596 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
597 // long to leave an unused idle socket open before closing it.
598 // |used_idle_socket_timeout| specifies how long to leave a previously used
599 // idle socket open before closing it.
[email protected]100d5fb92009-12-21 21:08:35600 ClientSocketPoolBase(
601 int max_sockets,
602 int max_sockets_per_group,
[email protected]2431756e2010-09-29 20:26:13603 ClientSocketPoolHistograms* histograms,
[email protected]100d5fb92009-12-21 21:08:35604 base::TimeDelta unused_idle_socket_timeout,
605 base::TimeDelta used_idle_socket_timeout,
[email protected]66761b952010-06-25 21:30:38606 ConnectJobFactory* connect_job_factory)
[email protected]b89f7e42010-05-20 20:37:00607 : histograms_(histograms),
[email protected]2431756e2010-09-29 20:26:13608 helper_(max_sockets, max_sockets_per_group,
609 unused_idle_socket_timeout, used_idle_socket_timeout,
610 new ConnectJobFactoryAdaptor(connect_job_factory)) {}
[email protected]d80a4322009-08-14 07:07:49611
[email protected]20cb5f482009-12-16 01:01:25612 virtual ~ClientSocketPoolBase() {}
[email protected]d80a4322009-08-14 07:07:49613
614 // These member functions simply forward to ClientSocketPoolBaseHelper.
615
616 // RequestSocket bundles up the parameters into a Request and then forwards to
[email protected]2c2bef152010-10-13 00:55:03617 // ClientSocketPoolBaseHelper::RequestSocket().
[email protected]d80a4322009-08-14 07:07:49618 int RequestSocket(const std::string& group_name,
[email protected]df4b4ef2010-07-12 18:25:21619 const scoped_refptr<SocketParams>& params,
[email protected]ac790b42009-12-02 04:31:31620 RequestPriority priority,
[email protected]d80a4322009-08-14 07:07:49621 ClientSocketHandle* handle,
622 CompletionCallback* callback,
[email protected]9e743cd2010-03-16 07:03:53623 const BoundNetLog& net_log) {
[email protected]2c2bef152010-10-13 00:55:03624 Request* request =
625 new Request(handle, callback, priority,
626 internal::ClientSocketPoolBaseHelper::NORMAL,
627 params, net_log);
[email protected]2431756e2010-09-29 20:26:13628 return helper_.RequestSocket(group_name, request);
[email protected]d80a4322009-08-14 07:07:49629 }
630
[email protected]2c2bef152010-10-13 00:55:03631 // RequestSockets bundles up the parameters into a Request and then forwards
632 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
633 // priority to LOWEST and specifies the NO_IDLE_SOCKETS flag.
634 void RequestSockets(const std::string& group_name,
635 const scoped_refptr<SocketParams>& params,
636 int num_sockets,
637 const BoundNetLog& net_log) {
638 const Request request(NULL /* no handle */,
639 NULL /* no callback */,
640 LOWEST,
641 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS,
642 params,
643 net_log);
644 helper_.RequestSockets(group_name, request, num_sockets);
645 }
646
[email protected]d80a4322009-08-14 07:07:49647 void CancelRequest(const std::string& group_name,
[email protected]05ea9ff2010-07-15 19:08:21648 ClientSocketHandle* handle) {
[email protected]2431756e2010-09-29 20:26:13649 return helper_.CancelRequest(group_name, handle);
[email protected]d80a4322009-08-14 07:07:49650 }
651
[email protected]241c5c2c2010-06-21 18:46:00652 void ReleaseSocket(const std::string& group_name, ClientSocket* socket,
653 int id) {
[email protected]2431756e2010-09-29 20:26:13654 return helper_.ReleaseSocket(group_name, socket, id);
[email protected]d80a4322009-08-14 07:07:49655 }
656
[email protected]2431756e2010-09-29 20:26:13657 void CloseIdleSockets() { return helper_.CloseIdleSockets(); }
[email protected]d80a4322009-08-14 07:07:49658
[email protected]2431756e2010-09-29 20:26:13659 int idle_socket_count() const { return helper_.idle_socket_count(); }
[email protected]d80a4322009-08-14 07:07:49660
661 int IdleSocketCountInGroup(const std::string& group_name) const {
[email protected]2431756e2010-09-29 20:26:13662 return helper_.IdleSocketCountInGroup(group_name);
[email protected]d80a4322009-08-14 07:07:49663 }
664
665 LoadState GetLoadState(const std::string& group_name,
666 const ClientSocketHandle* handle) const {
[email protected]2431756e2010-09-29 20:26:13667 return helper_.GetLoadState(group_name, handle);
[email protected]d80a4322009-08-14 07:07:49668 }
669
670 virtual void OnConnectJobComplete(int result, ConnectJob* job) {
[email protected]2431756e2010-09-29 20:26:13671 return helper_.OnConnectJobComplete(result, job);
[email protected]d80a4322009-08-14 07:07:49672 }
673
[email protected]d80a4322009-08-14 07:07:49674 int NumConnectJobsInGroup(const std::string& group_name) const {
[email protected]2431756e2010-09-29 20:26:13675 return helper_.NumConnectJobsInGroup(group_name);
[email protected]d80a4322009-08-14 07:07:49676 }
677
[email protected]2c2bef152010-10-13 00:55:03678 int NumActiveSocketsInGroup(const std::string& group_name) const {
679 return helper_.NumActiveSocketsInGroup(group_name);
680 }
681
[email protected]2abfe90a2010-08-25 17:49:51682 bool HasGroup(const std::string& group_name) const {
[email protected]2431756e2010-09-29 20:26:13683 return helper_.HasGroup(group_name);
[email protected]2abfe90a2010-08-25 17:49:51684 }
685
[email protected]9bf28db2009-08-29 01:35:16686 void CleanupIdleSockets(bool force) {
[email protected]2431756e2010-09-29 20:26:13687 return helper_.CleanupIdleSockets(force);
[email protected]9bf28db2009-08-29 01:35:16688 }
689
[email protected]ba00b492010-09-08 14:53:38690 DictionaryValue* GetInfoAsValue(const std::string& name,
691 const std::string& type) const {
[email protected]2431756e2010-09-29 20:26:13692 return helper_.GetInfoAsValue(name, type);
[email protected]59d7a5a2010-08-30 16:44:27693 }
694
[email protected]a796bcec2010-03-22 17:17:26695 base::TimeDelta ConnectionTimeout() const {
[email protected]2431756e2010-09-29 20:26:13696 return helper_.ConnectionTimeout();
[email protected]a796bcec2010-03-22 17:17:26697 }
698
[email protected]2431756e2010-09-29 20:26:13699 ClientSocketPoolHistograms* histograms() const {
[email protected]b89f7e42010-05-20 20:37:00700 return histograms_;
701 }
[email protected]a796bcec2010-03-22 17:17:26702
[email protected]2431756e2010-09-29 20:26:13703 void EnableConnectBackupJobs() { helper_.EnableConnectBackupJobs(); }
[email protected]7c28e9a2010-03-20 01:16:13704
[email protected]2431756e2010-09-29 20:26:13705 void Flush() { helper_.Flush(); }
[email protected]a7e38572010-06-07 18:22:24706
[email protected]d80a4322009-08-14 07:07:49707 private:
708 // This adaptor class exists to bridge the
709 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
710 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
711 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
712 // static_cast themselves.
713 class ConnectJobFactoryAdaptor
714 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory {
715 public:
716 typedef typename ClientSocketPoolBase<SocketParams>::ConnectJobFactory
717 ConnectJobFactory;
718
[email protected]9008c86f2010-08-06 07:10:24719 explicit ConnectJobFactoryAdaptor(ConnectJobFactory* connect_job_factory)
[email protected]d80a4322009-08-14 07:07:49720 : connect_job_factory_(connect_job_factory) {}
721 virtual ~ConnectJobFactoryAdaptor() {}
722
723 virtual ConnectJob* NewConnectJob(
724 const std::string& group_name,
725 const internal::ClientSocketPoolBaseHelper::Request& request,
[email protected]06650c52010-06-03 00:49:17726 ConnectJob::Delegate* delegate) const {
[email protected]d80a4322009-08-14 07:07:49727 const Request* casted_request = static_cast<const Request*>(&request);
728 return connect_job_factory_->NewConnectJob(
[email protected]06650c52010-06-03 00:49:17729 group_name, *casted_request, delegate);
[email protected]d80a4322009-08-14 07:07:49730 }
731
[email protected]a796bcec2010-03-22 17:17:26732 virtual base::TimeDelta ConnectionTimeout() const {
733 return connect_job_factory_->ConnectionTimeout();
734 }
735
[email protected]d80a4322009-08-14 07:07:49736 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
737 };
738
[email protected]b89f7e42010-05-20 20:37:00739 // Histograms for the pool
[email protected]2431756e2010-09-29 20:26:13740 ClientSocketPoolHistograms* const histograms_;
741 internal::ClientSocketPoolBaseHelper helper_;
[email protected]d80a4322009-08-14 07:07:49742
[email protected]ff579d42009-06-24 15:47:02743 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase);
744};
745
[email protected]ff579d42009-06-24 15:47:02746} // namespace net
747
748#endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_