Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / net / proxy / multi_threaded_proxy_resolver.cc
blobb8fea4456787e98ddad5d0c3e4e968dfe9b64945
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/proxy/multi_threaded_proxy_resolver.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/message_loop/message_loop_proxy.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/threading/thread.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "net/base/net_errors.h"
15 #include "net/log/net_log.h"
16 #include "net/proxy/proxy_info.h"
17 #include "net/proxy/proxy_resolver_factory.h"
19 // TODO(eroman): Have the MultiThreadedProxyResolver clear its PAC script
20 // data when SetPacScript fails. That will reclaim memory when
21 // testing bogus scripts.
23 namespace net {
25 // An "executor" is a job-runner for PAC requests. It encapsulates a worker
26 // thread and a synchronous ProxyResolver (which will be operated on said
27 // thread.)
28 class MultiThreadedProxyResolver::Executor
29 : public base::RefCountedThreadSafe<MultiThreadedProxyResolver::Executor > {
30 public:
31 // |coordinator| must remain valid throughout our lifetime. It is used to
32 // signal when the executor is ready to receive work by calling
33 // |coordinator->OnExecutorReady()|.
34 // The constructor takes ownership of |resolver|.
35 // |thread_number| is an identifier used when naming the worker thread.
36 Executor(MultiThreadedProxyResolver* coordinator,
37 scoped_ptr<ProxyResolver> resolver,
38 int thread_number);
40 // Submit a job to this executor.
41 void StartJob(Job* job);
43 // Callback for when a job has completed running on the executor's thread.
44 void OnJobCompleted(Job* job);
46 // Cleanup the executor. Cancels all outstanding work, and frees the thread
47 // and resolver.
48 void Destroy();
50 // Returns the outstanding job, or NULL.
51 Job* outstanding_job() const { return outstanding_job_.get(); }
53 ProxyResolver* resolver() { return resolver_.get(); }
55 int thread_number() const { return thread_number_; }
57 private:
58 friend class base::RefCountedThreadSafe<Executor>;
59 ~Executor();
61 MultiThreadedProxyResolver* coordinator_;
62 const int thread_number_;
64 // The currently active job for this executor (either a SetPacScript or
65 // GetProxyForURL task).
66 scoped_refptr<Job> outstanding_job_;
68 // The synchronous resolver implementation.
69 scoped_ptr<ProxyResolver> resolver_;
71 // The thread where |resolver_| is run on.
72 // Note that declaration ordering is important here. |thread_| needs to be
73 // destroyed *before* |resolver_|, in case |resolver_| is currently
74 // executing on |thread_|.
75 scoped_ptr<base::Thread> thread_;
78 // MultiThreadedProxyResolver::Job ---------------------------------------------
80 class MultiThreadedProxyResolver::Job
81 : public base::RefCountedThreadSafe<MultiThreadedProxyResolver::Job> {
82 public:
83 // Identifies the subclass of Job (only being used for debugging purposes).
84 enum Type {
85 TYPE_GET_PROXY_FOR_URL,
86 TYPE_SET_PAC_SCRIPT,
87 TYPE_SET_PAC_SCRIPT_INTERNAL,
90 Job(Type type, const CompletionCallback& callback)
91 : type_(type),
92 callback_(callback),
93 executor_(NULL),
94 was_cancelled_(false) {
97 void set_executor(Executor* executor) {
98 executor_ = executor;
101 // The "executor" is the job runner that is scheduling this job. If
102 // this job has not been submitted to an executor yet, this will be
103 // NULL (and we know it hasn't started yet).
104 Executor* executor() {
105 return executor_;
108 // Mark the job as having been cancelled.
109 void Cancel() {
110 was_cancelled_ = true;
113 // Returns true if Cancel() has been called.
114 bool was_cancelled() const { return was_cancelled_; }
116 Type type() const { return type_; }
118 // Returns true if this job still has a user callback. Some jobs
119 // do not have a user callback, because they were helper jobs
120 // scheduled internally (for example TYPE_SET_PAC_SCRIPT_INTERNAL).
122 // Otherwise jobs that correspond with user-initiated work will
123 // have a non-null callback up until the callback is run.
124 bool has_user_callback() const { return !callback_.is_null(); }
126 // This method is called when the job is inserted into a wait queue
127 // because no executors were ready to accept it.
128 virtual void WaitingForThread() {}
130 // This method is called just before the job is posted to the work thread.
131 virtual void FinishedWaitingForThread() {}
133 // This method is called on the worker thread to do the job's work. On
134 // completion, implementors are expected to call OnJobCompleted() on
135 // |origin_loop|.
136 virtual void Run(scoped_refptr<base::MessageLoopProxy> origin_loop) = 0;
138 protected:
139 void OnJobCompleted() {
140 // |executor_| will be NULL if the executor has already been deleted.
141 if (executor_)
142 executor_->OnJobCompleted(this);
145 void RunUserCallback(int result) {
146 DCHECK(has_user_callback());
147 CompletionCallback callback = callback_;
148 // Reset the callback so has_user_callback() will now return false.
149 callback_.Reset();
150 callback.Run(result);
153 friend class base::RefCountedThreadSafe<MultiThreadedProxyResolver::Job>;
155 virtual ~Job() {}
157 private:
158 const Type type_;
159 CompletionCallback callback_;
160 Executor* executor_;
161 bool was_cancelled_;
164 // MultiThreadedProxyResolver::SetPacScriptJob ---------------------------------
166 // Runs on the worker thread to call ProxyResolver::SetPacScript.
167 class MultiThreadedProxyResolver::SetPacScriptJob
168 : public MultiThreadedProxyResolver::Job {
169 public:
170 SetPacScriptJob(const scoped_refptr<ProxyResolverScriptData>& script_data,
171 const CompletionCallback& callback)
172 : Job(!callback.is_null() ? TYPE_SET_PAC_SCRIPT :
173 TYPE_SET_PAC_SCRIPT_INTERNAL,
174 callback),
175 script_data_(script_data) {
178 // Runs on the worker thread.
179 void Run(scoped_refptr<base::MessageLoopProxy> origin_loop) override {
180 ProxyResolver* resolver = executor()->resolver();
181 int rv = resolver->SetPacScript(script_data_, CompletionCallback());
183 DCHECK_NE(rv, ERR_IO_PENDING);
184 origin_loop->PostTask(
185 FROM_HERE,
186 base::Bind(&SetPacScriptJob::RequestComplete, this, rv));
189 protected:
190 ~SetPacScriptJob() override {}
192 private:
193 // Runs the completion callback on the origin thread.
194 void RequestComplete(int result_code) {
195 // The task may have been cancelled after it was started.
196 if (!was_cancelled() && has_user_callback()) {
197 RunUserCallback(result_code);
199 OnJobCompleted();
202 const scoped_refptr<ProxyResolverScriptData> script_data_;
205 // MultiThreadedProxyResolver::GetProxyForURLJob ------------------------------
207 class MultiThreadedProxyResolver::GetProxyForURLJob
208 : public MultiThreadedProxyResolver::Job {
209 public:
210 // |url| -- the URL of the query.
211 // |results| -- the structure to fill with proxy resolve results.
212 GetProxyForURLJob(const GURL& url,
213 ProxyInfo* results,
214 const CompletionCallback& callback,
215 const BoundNetLog& net_log)
216 : Job(TYPE_GET_PROXY_FOR_URL, callback),
217 results_(results),
218 net_log_(net_log),
219 url_(url),
220 was_waiting_for_thread_(false) {
221 DCHECK(!callback.is_null());
224 BoundNetLog* net_log() { return &net_log_; }
226 void WaitingForThread() override {
227 was_waiting_for_thread_ = true;
228 net_log_.BeginEvent(NetLog::TYPE_WAITING_FOR_PROXY_RESOLVER_THREAD);
231 void FinishedWaitingForThread() override {
232 DCHECK(executor());
234 if (was_waiting_for_thread_) {
235 net_log_.EndEvent(NetLog::TYPE_WAITING_FOR_PROXY_RESOLVER_THREAD);
238 net_log_.AddEvent(
239 NetLog::TYPE_SUBMITTED_TO_RESOLVER_THREAD,
240 NetLog::IntegerCallback("thread_number", executor()->thread_number()));
243 // Runs on the worker thread.
244 void Run(scoped_refptr<base::MessageLoopProxy> origin_loop) override {
245 ProxyResolver* resolver = executor()->resolver();
246 int rv = resolver->GetProxyForURL(
247 url_, &results_buf_, CompletionCallback(), NULL, net_log_);
248 DCHECK_NE(rv, ERR_IO_PENDING);
250 origin_loop->PostTask(
251 FROM_HERE,
252 base::Bind(&GetProxyForURLJob::QueryComplete, this, rv));
255 protected:
256 ~GetProxyForURLJob() override {}
258 private:
259 // Runs the completion callback on the origin thread.
260 void QueryComplete(int result_code) {
261 // The Job may have been cancelled after it was started.
262 if (!was_cancelled()) {
263 if (result_code >= OK) { // Note: unit-tests use values > 0.
264 results_->Use(results_buf_);
266 RunUserCallback(result_code);
268 OnJobCompleted();
271 // Must only be used on the "origin" thread.
272 ProxyInfo* results_;
274 // Can be used on either "origin" or worker thread.
275 BoundNetLog net_log_;
276 const GURL url_;
278 // Usable from within DoQuery on the worker thread.
279 ProxyInfo results_buf_;
281 bool was_waiting_for_thread_;
284 // MultiThreadedProxyResolver::Executor ----------------------------------------
286 MultiThreadedProxyResolver::Executor::Executor(
287 MultiThreadedProxyResolver* coordinator,
288 scoped_ptr<ProxyResolver> resolver,
289 int thread_number)
290 : coordinator_(coordinator),
291 thread_number_(thread_number),
292 resolver_(resolver.Pass()) {
293 DCHECK(coordinator);
294 DCHECK(resolver_);
295 // Start up the thread.
296 thread_.reset(new base::Thread(base::StringPrintf("PAC thread #%d",
297 thread_number)));
298 CHECK(thread_->Start());
301 void MultiThreadedProxyResolver::Executor::StartJob(Job* job) {
302 DCHECK(!outstanding_job_.get());
303 outstanding_job_ = job;
305 // Run the job. Once it has completed (regardless of whether it was
306 // cancelled), it will invoke OnJobCompleted() on this thread.
307 job->set_executor(this);
308 job->FinishedWaitingForThread();
309 thread_->message_loop()->PostTask(
310 FROM_HERE,
311 base::Bind(&Job::Run, job, base::MessageLoopProxy::current()));
314 void MultiThreadedProxyResolver::Executor::OnJobCompleted(Job* job) {
315 DCHECK_EQ(job, outstanding_job_.get());
316 outstanding_job_ = NULL;
317 coordinator_->OnExecutorReady(this);
320 void MultiThreadedProxyResolver::Executor::Destroy() {
321 DCHECK(coordinator_);
324 // See http://crbug.com/69710.
325 base::ThreadRestrictions::ScopedAllowIO allow_io;
327 // Join the worker thread.
328 thread_.reset();
331 // Cancel any outstanding job.
332 if (outstanding_job_.get()) {
333 outstanding_job_->Cancel();
334 // Orphan the job (since this executor may be deleted soon).
335 outstanding_job_->set_executor(NULL);
338 // It is now safe to free the ProxyResolver, since all the tasks that
339 // were using it on the resolver thread have completed.
340 resolver_.reset();
342 // Null some stuff as a precaution.
343 coordinator_ = NULL;
344 outstanding_job_ = NULL;
347 MultiThreadedProxyResolver::Executor::~Executor() {
348 // The important cleanup happens as part of Destroy(), which should always be
349 // called first.
350 DCHECK(!coordinator_) << "Destroy() was not called";
351 DCHECK(!thread_.get());
352 DCHECK(!resolver_.get());
353 DCHECK(!outstanding_job_.get());
356 // MultiThreadedProxyResolver --------------------------------------------------
358 MultiThreadedProxyResolver::MultiThreadedProxyResolver(
359 LegacyProxyResolverFactory* resolver_factory,
360 size_t max_num_threads)
361 : ProxyResolver(resolver_factory->expects_pac_bytes()),
362 resolver_factory_(resolver_factory),
363 max_num_threads_(max_num_threads) {
364 DCHECK_GE(max_num_threads, 1u);
367 MultiThreadedProxyResolver::~MultiThreadedProxyResolver() {
368 // We will cancel all outstanding requests.
369 pending_jobs_.clear();
370 ReleaseAllExecutors();
373 int MultiThreadedProxyResolver::GetProxyForURL(
374 const GURL& url, ProxyInfo* results, const CompletionCallback& callback,
375 RequestHandle* request, const BoundNetLog& net_log) {
376 DCHECK(CalledOnValidThread());
377 DCHECK(!callback.is_null());
378 DCHECK(current_script_data_.get())
379 << "Resolver is un-initialized. Must call SetPacScript() first!";
381 scoped_refptr<GetProxyForURLJob> job(
382 new GetProxyForURLJob(url, results, callback, net_log));
384 // Completion will be notified through |callback|, unless the caller cancels
385 // the request using |request|.
386 if (request)
387 *request = reinterpret_cast<RequestHandle>(job.get());
389 // If there is an executor that is ready to run this request, submit it!
390 Executor* executor = FindIdleExecutor();
391 if (executor) {
392 DCHECK_EQ(0u, pending_jobs_.size());
393 executor->StartJob(job.get());
394 return ERR_IO_PENDING;
397 // Otherwise queue this request. (We will schedule it to a thread once one
398 // becomes available).
399 job->WaitingForThread();
400 pending_jobs_.push_back(job);
402 // If we haven't already reached the thread limit, provision a new thread to
403 // drain the requests more quickly.
404 if (executors_.size() < max_num_threads_) {
405 executor = AddNewExecutor();
406 executor->StartJob(
407 new SetPacScriptJob(current_script_data_, CompletionCallback()));
410 return ERR_IO_PENDING;
413 void MultiThreadedProxyResolver::CancelRequest(RequestHandle req) {
414 DCHECK(CalledOnValidThread());
415 DCHECK(req);
417 Job* job = reinterpret_cast<Job*>(req);
418 DCHECK_EQ(Job::TYPE_GET_PROXY_FOR_URL, job->type());
420 if (job->executor()) {
421 // If the job was already submitted to the executor, just mark it
422 // as cancelled so the user callback isn't run on completion.
423 job->Cancel();
424 } else {
425 // Otherwise the job is just sitting in a queue.
426 PendingJobsQueue::iterator it =
427 std::find(pending_jobs_.begin(), pending_jobs_.end(), job);
428 DCHECK(it != pending_jobs_.end());
429 pending_jobs_.erase(it);
433 LoadState MultiThreadedProxyResolver::GetLoadState(RequestHandle req) const {
434 DCHECK(CalledOnValidThread());
435 DCHECK(req);
436 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
439 void MultiThreadedProxyResolver::CancelSetPacScript() {
440 DCHECK(CalledOnValidThread());
441 DCHECK_EQ(0u, pending_jobs_.size());
442 DCHECK_EQ(1u, executors_.size());
443 DCHECK_EQ(Job::TYPE_SET_PAC_SCRIPT,
444 executors_[0]->outstanding_job()->type());
446 // Defensively clear some data which shouldn't be getting used
447 // anymore.
448 current_script_data_ = NULL;
450 ReleaseAllExecutors();
453 int MultiThreadedProxyResolver::SetPacScript(
454 const scoped_refptr<ProxyResolverScriptData>& script_data,
455 const CompletionCallback&callback) {
456 DCHECK(CalledOnValidThread());
457 DCHECK(!callback.is_null());
459 // Save the script details, so we can provision new executors later.
460 current_script_data_ = script_data;
462 // The user should not have any outstanding requests when they call
463 // SetPacScript().
464 CheckNoOutstandingUserRequests();
466 // Destroy all of the current threads and their proxy resolvers.
467 ReleaseAllExecutors();
469 // Provision a new executor, and run the SetPacScript request. On completion
470 // notification will be sent through |callback|.
471 Executor* executor = AddNewExecutor();
472 executor->StartJob(new SetPacScriptJob(script_data, callback));
473 return ERR_IO_PENDING;
476 void MultiThreadedProxyResolver::CheckNoOutstandingUserRequests() const {
477 DCHECK(CalledOnValidThread());
478 CHECK_EQ(0u, pending_jobs_.size());
480 for (ExecutorList::const_iterator it = executors_.begin();
481 it != executors_.end(); ++it) {
482 const Executor* executor = it->get();
483 Job* job = executor->outstanding_job();
484 // The "has_user_callback()" is to exclude jobs for which the callback
485 // has already been invoked, or was not user-initiated (as in the case of
486 // lazy thread provisions). User-initiated jobs may !has_user_callback()
487 // when the callback has already been run. (Since we only clear the
488 // outstanding job AFTER the callback has been invoked, it is possible
489 // for a new request to be started from within the callback).
490 CHECK(!job || job->was_cancelled() || !job->has_user_callback());
494 void MultiThreadedProxyResolver::ReleaseAllExecutors() {
495 DCHECK(CalledOnValidThread());
496 for (ExecutorList::iterator it = executors_.begin();
497 it != executors_.end(); ++it) {
498 Executor* executor = it->get();
499 executor->Destroy();
501 executors_.clear();
504 MultiThreadedProxyResolver::Executor*
505 MultiThreadedProxyResolver::FindIdleExecutor() {
506 DCHECK(CalledOnValidThread());
507 for (ExecutorList::iterator it = executors_.begin();
508 it != executors_.end(); ++it) {
509 Executor* executor = it->get();
510 if (!executor->outstanding_job())
511 return executor;
513 return NULL;
516 MultiThreadedProxyResolver::Executor*
517 MultiThreadedProxyResolver::AddNewExecutor() {
518 DCHECK(CalledOnValidThread());
519 DCHECK_LT(executors_.size(), max_num_threads_);
520 // The "thread number" is used to give the thread a unique name.
521 int thread_number = executors_.size();
522 scoped_ptr<ProxyResolver> resolver = resolver_factory_->CreateProxyResolver();
523 Executor* executor = new Executor(this, resolver.Pass(), thread_number);
524 executors_.push_back(make_scoped_refptr(executor));
525 return executor;
528 void MultiThreadedProxyResolver::OnExecutorReady(Executor* executor) {
529 DCHECK(CalledOnValidThread());
530 if (pending_jobs_.empty())
531 return;
533 // Get the next job to process (FIFO). Transfer it from the pending queue
534 // to the executor.
535 scoped_refptr<Job> job = pending_jobs_.front();
536 pending_jobs_.pop_front();
537 executor->StartJob(job.get());
540 } // namespace net