Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(27)

Side by Side Diff: chrome/browser/net/predictor.cc

Issue 7467012: Modifying prefetch to account for multi-profile. (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: '' Created 9 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/net/predictor.h" 5 #include "chrome/browser/net/predictor.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <cmath> 8 #include <cmath>
9 #include <set> 9 #include <set>
10 #include <sstream> 10 #include <sstream>
11 11
12 #include "base/bind.h"
13 #include "base/command_line.h"
12 #include "base/compiler_specific.h" 14 #include "base/compiler_specific.h"
13 #include "base/metrics/histogram.h" 15 #include "base/metrics/histogram.h"
16 #include "base/stl_util.h"
14 #include "base/stringprintf.h" 17 #include "base/stringprintf.h"
18 #include "base/synchronization/waitable_event.h"
15 #include "base/time.h" 19 #include "base/time.h"
16 #include "base/values.h" 20 #include "base/values.h"
21 #include "chrome/browser/io_thread.h"
17 #include "chrome/browser/net/preconnect.h" 22 #include "chrome/browser/net/preconnect.h"
23 #include "chrome/browser/prefs/browser_prefs.h"
24 #include "chrome/browser/prefs/pref_service.h"
25 #include "chrome/browser/prefs/scoped_user_pref_update.h"
26 #include "chrome/browser/prefs/session_startup_pref.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/pref_names.h"
18 #include "content/browser/browser_thread.h" 29 #include "content/browser/browser_thread.h"
19 #include "net/base/address_list.h" 30 #include "net/base/address_list.h"
20 #include "net/base/completion_callback.h" 31 #include "net/base/completion_callback.h"
21 #include "net/base/host_port_pair.h" 32 #include "net/base/host_port_pair.h"
22 #include "net/base/host_resolver.h" 33 #include "net/base/host_resolver.h"
23 #include "net/base/net_errors.h" 34 #include "net/base/net_errors.h"
24 #include "net/base/net_log.h" 35 #include "net/base/net_log.h"
25 #include "net/base/single_request_host_resolver.h" 36 #include "net/base/single_request_host_resolver.h"
26 37
27 using base::TimeDelta; 38 using base::TimeDelta;
28 39
29 namespace chrome_browser_net { 40 namespace chrome_browser_net {
30 41
42 static void DnsPrefetchMotivatedList(const UrlList& urls,
43 UrlInfo::ResolutionMotivation motivation);
31 // static 44 // static
32 const double Predictor::kPreconnectWorthyExpectedValue = 0.8; 45 const double Predictor::kPreconnectWorthyExpectedValue = 0.8;
33 // static 46 // static
34 const double Predictor::kDNSPreresolutionWorthyExpectedValue = 0.1; 47 const double Predictor::kDNSPreresolutionWorthyExpectedValue = 0.1;
35 // static 48 // static
36 const double Predictor::kDiscardableExpectedValue = 0.05; 49 const double Predictor::kDiscardableExpectedValue = 0.05;
37 // The goal is of trimming is to to reduce the importance (number of expected 50 // The goal is of trimming is to to reduce the importance (number of expected
38 // subresources needed) by a factor of 2 after about 24 hours of uptime. We will 51 // subresources needed) by a factor of 2 after about 24 hours of uptime. We will
39 // trim roughly once-an-hour of uptime. The ratio to use in each trim operation 52 // trim roughly once-an-hour of uptime. The ratio to use in each trim operation
40 // is then the 24th root of 0.5. If a user only surfs for 4 hours a day, then 53 // is then the 24th root of 0.5. If a user only surfs for 4 hours a day, then
41 // after about 6 days they will have halved all their estimates of subresource 54 // after about 6 days they will have halved all their estimates of subresource
42 // connections. Once this falls below kDiscardableExpectedValue the referrer 55 // connections. Once this falls below kDiscardableExpectedValue the referrer
43 // will be discarded. 56 // will be discarded.
44 // TODO(jar): Measure size of referrer lists in the field. Consider an adaptive 57 // TODO(jar): Measure size of referrer lists in the field. Consider an adaptive
45 // system that uses a higher trim ratio when the list is large. 58 // system that uses a higher trim ratio when the list is large.
46 // static 59 // static
47 const double Predictor::kReferrerTrimRatio = 0.97153; 60 const double Predictor::kReferrerTrimRatio = 0.97153;
48 61
49 // static 62 // static
50 const TimeDelta Predictor::kDurationBetweenTrimmings = TimeDelta::FromHours(1); 63 const TimeDelta Predictor::kDurationBetweenTrimmings = TimeDelta::FromHours(1);
51 // static 64 // static
52 const TimeDelta Predictor::kDurationBetweenTrimmingIncrements = 65 const TimeDelta Predictor::kDurationBetweenTrimmingIncrements =
53 TimeDelta::FromSeconds(15); 66 TimeDelta::FromSeconds(15);
54 // static 67 // static
55 const size_t Predictor::kUrlsTrimmedPerIncrement = 5u; 68 const size_t Predictor::kUrlsTrimmedPerIncrement = 5u;
69 // static
70 const size_t Predictor::kMaxSpeculativeParallelResolves = 3;
71 // To control our congestion avoidance system, which discards a queue when
72 // resolutions are "taking too long," we need an expected resolution time.
73 // Common average is in the range of 300-500ms.
74 const int kExpectedResolutionTimeMs = 500;
75 // static
76 const int Predictor::kTypicalSpeculativeGroupSize = 8;
77 // static
78 const int Predictor::kMaxSpeculativeResolveQueueDelayMs =
79 (kExpectedResolutionTimeMs * Predictor::kTypicalSpeculativeGroupSize) /
80 Predictor::kMaxSpeculativeParallelResolves;
81
82 static int g_max_queueing_delay_ms = 0;
83 static size_t g_max_parallel_resolves = 0u;
84
85 // A version number for prefs that are saved. This should be incremented when
86 // we change the format so that we discard old data.
87 static const int kPredictorStartupFormatVersion = 1;
56 88
57 class Predictor::LookupRequest { 89 class Predictor::LookupRequest {
58 public: 90 public:
59 LookupRequest(Predictor* predictor, 91 LookupRequest(Predictor* predictor,
60 net::HostResolver* host_resolver, 92 net::HostResolver* host_resolver,
61 const GURL& url) 93 const GURL& url)
62 : ALLOW_THIS_IN_INITIALIZER_LIST( 94 : ALLOW_THIS_IN_INITIALIZER_LIST(
63 net_callback_(this, &LookupRequest::OnLookupFinished)), 95 net_callback_(this, &LookupRequest::OnLookupFinished)),
64 predictor_(predictor), 96 predictor_(predictor),
65 url_(url), 97 url_(url),
(...skipping 26 matching lines...) Expand all
92 124
93 Predictor* predictor_; // The predictor which started us. 125 Predictor* predictor_; // The predictor which started us.
94 126
95 const GURL url_; // Hostname to resolve. 127 const GURL url_; // Hostname to resolve.
96 net::SingleRequestHostResolver resolver_; 128 net::SingleRequestHostResolver resolver_;
97 net::AddressList addresses_; 129 net::AddressList addresses_;
98 130
99 DISALLOW_COPY_AND_ASSIGN(LookupRequest); 131 DISALLOW_COPY_AND_ASSIGN(LookupRequest);
100 }; 132 };
101 133
102 Predictor::Predictor(net::HostResolver* host_resolver, 134 Predictor::Predictor(bool preconnect_enabled)
103 TimeDelta max_dns_queue_delay, 135 : initial_observer_(NULL),
104 size_t max_concurrent, 136 predictor_enabled_(true),
105 bool preconnect_enabled) 137 peak_pending_lookups_(0),
106 : peak_pending_lookups_(0),
107 shutdown_(false), 138 shutdown_(false),
108 max_concurrent_dns_lookups_(max_concurrent), 139 max_concurrent_dns_lookups_(g_max_parallel_resolves),
109 max_dns_queue_delay_(max_dns_queue_delay), 140 max_dns_queue_delay_(
110 host_resolver_(host_resolver), 141 TimeDelta::FromMilliseconds(g_max_queueing_delay_ms)),
142 host_resolver_(NULL),
111 preconnect_enabled_(preconnect_enabled), 143 preconnect_enabled_(preconnect_enabled),
112 consecutive_omnibox_preconnect_count_(0), 144 consecutive_omnibox_preconnect_count_(0),
113 next_trim_time_(base::TimeTicks::Now() + kDurationBetweenTrimmings), 145 next_trim_time_(base::TimeTicks::Now() + kDurationBetweenTrimmings) {
114 ALLOW_THIS_IN_INITIALIZER_LIST(trim_task_factory_(this)) { 146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
115 } 147 }
116 148
117 Predictor::~Predictor() { 149 Predictor::~Predictor() {
150 // TODO(rlp): Add DCHECK for CurrentlyOn(BrowserThread::IO) when the
151 // ProfileManagerTest has been updated with a mock profile.
118 DCHECK(shutdown_); 152 DCHECK(shutdown_);
119 } 153 }
120 154
121 void Predictor::Shutdown() { 155 // static
122 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 156 Predictor* Predictor::CreatePredictor(
123 DCHECK(!shutdown_); 157 bool preconnect_enabled, bool simple_shutdown) {
124 shutdown_ = true; 158 if (simple_shutdown)
125 159 return new SimpleShutdownPredictor(preconnect_enabled);
126 std::set<LookupRequest*>::iterator it; 160 return new Predictor(preconnect_enabled);
127 for (it = pending_lookups_.begin(); it != pending_lookups_.end(); ++it)
128 delete *it;
129 } 161 }
130 162
131 // Overloaded Resolve() to take a vector of names. 163 void Predictor::RegisterUserPrefs(PrefService* user_prefs) {
132 void Predictor::ResolveList(const UrlList& urls, 164 user_prefs->RegisterListPref(prefs::kDnsPrefetchingStartupList,
133 UrlInfo::ResolutionMotivation motivation) { 165 PrefService::UNSYNCABLE_PREF);
134 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 166 user_prefs->RegisterListPref(prefs::kDnsPrefetchingHostReferralList,
135 167 PrefService::UNSYNCABLE_PREF);
136 for (UrlList::const_iterator it = urls.begin(); it < urls.end(); ++it) {
137 AppendToResolutionQueue(*it, motivation);
138 }
139 } 168 }
140 169
141 // Basic Resolve() takes an invidual name, and adds it 170 // --------------------- Start UI methods. ------------------------------------
142 // to the queue. 171
143 void Predictor::Resolve(const GURL& url, 172 void Predictor::InitNetworkPredictor(PrefService* user_prefs,
144 UrlInfo::ResolutionMotivation motivation) { 173 PrefService* local_state,
145 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 174 IOThread* io_thread) {
146 if (!url.has_host()) 175 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
147 return; 176
148 AppendToResolutionQueue(url, motivation); 177 predictor_enabled_ = user_prefs->GetBoolean(prefs::kNetworkPredictionEnabled);
178
179 // Gather the list of hostnames to prefetch on startup.
180 UrlList urls = GetPredictedUrlListAtStartup(user_prefs, local_state);
181
182 base::ListValue* referral_list =
183 static_cast<base::ListValue*>(user_prefs->GetList(
184 prefs::kDnsPrefetchingHostReferralList)->DeepCopy());
185
186 // Remove obsolete preferences from local state if necessary.
187 int current_version =
188 local_state->GetInteger(prefs::kMultipleProfilePrefMigration);
189 if ((current_version & browser::DNS_PREFS) == 0) {
190 local_state->RegisterListPref(prefs::kDnsStartupPrefetchList,
191 PrefService::UNSYNCABLE_PREF);
192 local_state->RegisterListPref(prefs::kDnsHostReferralList,
193 PrefService::UNSYNCABLE_PREF);
194 local_state->ClearPref(prefs::kDnsStartupPrefetchList);
195 local_state->ClearPref(prefs::kDnsHostReferralList);
196 local_state->SetInteger(prefs::kMultipleProfilePrefMigration,
197 current_version | browser::DNS_PREFS);
198 }
199
200 BrowserThread::PostTask(
201 BrowserThread::IO,
202 FROM_HERE,
203 base::Bind(
204 &Predictor::FinalizeInitializationOnIOThread,
205 base::Unretained(this),
206 urls, referral_list,
207 io_thread));
149 } 208 }
150 209
151 void Predictor::LearnFromNavigation(const GURL& referring_url,
152 const GURL& target_url) {
153 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
154 DCHECK_EQ(referring_url, Predictor::CanonicalizeUrl(referring_url));
155 DCHECK_NE(referring_url, GURL::EmptyGURL());
156 DCHECK_EQ(target_url, Predictor::CanonicalizeUrl(target_url));
157 DCHECK_NE(target_url, GURL::EmptyGURL());
158
159 referrers_[referring_url].SuggestHost(target_url);
160 // Possibly do some referrer trimming.
161 TrimReferrers();
162 }
163
164 enum SubresourceValue {
165 PRECONNECTION,
166 PRERESOLUTION,
167 TOO_NEW,
168 SUBRESOURCE_VALUE_MAX
169 };
170
171 void Predictor::AnticipateOmniboxUrl(const GURL& url, bool preconnectable) { 210 void Predictor::AnticipateOmniboxUrl(const GURL& url, bool preconnectable) {
211 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
212 if (!predictor_enabled_)
213 return;
214 if (!url.is_valid() || !url.has_host())
215 return;
172 std::string host = url.HostNoBrackets(); 216 std::string host = url.HostNoBrackets();
173 bool is_new_host_request = (host != last_omnibox_host_); 217 bool is_new_host_request = (host != last_omnibox_host_);
174 last_omnibox_host_ = host; 218 last_omnibox_host_ = host;
175 219
176 UrlInfo::ResolutionMotivation motivation(UrlInfo::OMNIBOX_MOTIVATED); 220 UrlInfo::ResolutionMotivation motivation(UrlInfo::OMNIBOX_MOTIVATED);
177 base::TimeTicks now = base::TimeTicks::Now(); 221 base::TimeTicks now = base::TimeTicks::Now();
178 222
179 if (preconnect_enabled()) { 223 if (preconnect_enabled()) {
180 if (preconnectable && !is_new_host_request) { 224 if (preconnectable && !is_new_host_request) {
181 ++consecutive_omnibox_preconnect_count_; 225 ++consecutive_omnibox_preconnect_count_;
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
225 const int kMinPreresolveSeconds(10); 269 const int kMinPreresolveSeconds(10);
226 if (kMinPreresolveSeconds > (now - last_omnibox_preresolve_).InSeconds()) 270 if (kMinPreresolveSeconds > (now - last_omnibox_preresolve_).InSeconds())
227 return; 271 return;
228 } 272 }
229 last_omnibox_preresolve_ = now; 273 last_omnibox_preresolve_ = now;
230 274
231 // Perform at least DNS pre-resolution. 275 // Perform at least DNS pre-resolution.
232 BrowserThread::PostTask( 276 BrowserThread::PostTask(
233 BrowserThread::IO, 277 BrowserThread::IO,
234 FROM_HERE, 278 FROM_HERE,
235 NewRunnableMethod(this, &Predictor::Resolve, CanonicalizeUrl(url), 279 base::Bind(&Predictor::Resolve, base::Unretained(this),
236 motivation)); 280 CanonicalizeUrl(url), motivation));
237 } 281 }
238 282
239 void Predictor::PreconnectUrlAndSubresources(const GURL& url) { 283 void Predictor::PreconnectUrlAndSubresources(const GURL& url) {
284 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
285 if (!predictor_enabled_)
286 return;
287 if (!url.is_valid() || !url.has_host())
288 return;
240 if (preconnect_enabled()) { 289 if (preconnect_enabled()) {
241 std::string host = url.HostNoBrackets(); 290 std::string host = url.HostNoBrackets();
242 UrlInfo::ResolutionMotivation motivation(UrlInfo::EARLY_LOAD_MOTIVATED); 291 UrlInfo::ResolutionMotivation motivation(UrlInfo::EARLY_LOAD_MOTIVATED);
243 const int kConnectionsNeeded = 1; 292 const int kConnectionsNeeded = 1;
244 PreconnectOnUIThread(CanonicalizeUrl(url), motivation, 293 PreconnectOnUIThread(CanonicalizeUrl(url), motivation,
245 kConnectionsNeeded); 294 kConnectionsNeeded);
246 PredictFrameSubresources(url.GetWithEmptyPath()); 295 PredictFrameSubresources(url.GetWithEmptyPath());
247 } 296 }
248 } 297 }
249 298
250 void Predictor::PredictFrameSubresources(const GURL& url) { 299 UrlList Predictor::GetPredictedUrlListAtStartup(
251 DCHECK_EQ(url.GetWithEmptyPath(), url); 300 PrefService* user_prefs,
252 // Add one pass through the message loop to allow current navigation to 301 PrefService* local_state) {
253 // proceed. 302 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
303 UrlList urls;
304 // Recall list of URLs we learned about during last session.
305 // This may catch secondary hostnames, pulled in by the homepages. It will
306 // also catch more of the "primary" home pages, since that was (presumably)
307 // rendered first (and will be rendered first this time too).
308 const ListValue* startup_list =
309 user_prefs->GetList(prefs::kDnsPrefetchingStartupList);
310
311 if (startup_list) {
312 base::ListValue::const_iterator it = startup_list->begin();
313 int format_version = -1;
314 if (it != startup_list->end() &&
315 (*it)->GetAsInteger(&format_version) &&
316 format_version == kPredictorStartupFormatVersion) {
317 ++it;
318 for (; it != startup_list->end(); ++it) {
319 std::string url_spec;
320 if (!(*it)->GetAsString(&url_spec)) {
321 LOG(DFATAL);
322 break; // Format incompatibility.
323 }
324 GURL url(url_spec);
325 if (!url.has_host() || !url.has_scheme()) {
326 LOG(DFATAL);
327 break; // Format incompatibility.
328 }
329
330 urls.push_back(url);
331 }
332 }
333 }
334
335 // Prepare for any static home page(s) the user has in prefs. The user may
336 // have a LOT of tab's specified, so we may as well try to warm them all.
337 SessionStartupPref tab_start_pref =
338 SessionStartupPref::GetStartupPref(user_prefs);
339 if (SessionStartupPref::URLS == tab_start_pref.type) {
340 for (size_t i = 0; i < tab_start_pref.urls.size(); i++) {
341 GURL gurl = tab_start_pref.urls[i];
342 if (!gurl.is_valid() || gurl.SchemeIsFile() || gurl.host().empty())
343 continue;
344 if (gurl.SchemeIs("http") || gurl.SchemeIs("https"))
345 urls.push_back(gurl.GetWithEmptyPath());
346 }
347 }
348
349 if (urls.empty())
350 urls.push_back(GURL("http://www.google.com:80"));
351
352 return urls;
353 }
354
355 void Predictor::set_max_queueing_delay(int max_queueing_delay_ms) {
356 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
357 g_max_queueing_delay_ms = max_queueing_delay_ms;
358 }
359
360 void Predictor::set_max_parallel_resolves(size_t max_parallel_resolves) {
361 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
362 g_max_parallel_resolves = max_parallel_resolves;
363 }
364
365 void Predictor::ShutdownOnUIThread(PrefService* user_prefs) {
366 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
367
368 SaveStateForNextStartupAndTrim(user_prefs);
369
254 BrowserThread::PostTask( 370 BrowserThread::PostTask(
255 BrowserThread::IO, 371 BrowserThread::IO,
256 FROM_HERE, 372 FROM_HERE,
257 NewRunnableMethod(this, &Predictor::PrepareFrameSubresources, url)); 373 base::Bind(&Predictor::Shutdown, base::Unretained(this)));
258 } 374 }
259 375
260 void Predictor::PrepareFrameSubresources(const GURL& url) { 376 // ---------------------- End UI methods. -------------------------------------
377
378 // --------------------- Start IO methods. ------------------------------------
379
380 void Predictor::Shutdown() {
261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 381 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
262 DCHECK_EQ(url.GetWithEmptyPath(), url); 382 DCHECK(!shutdown_);
263 Referrers::iterator it = referrers_.find(url); 383 shutdown_ = true;
264 if (referrers_.end() == it) { 384
265 // Only when we don't know anything about this url, make 2 connections 385 STLDeleteElements(&pending_lookups_);
266 // available. We could do this completely via learning (by prepopulating 386 }
267 // the referrer_ list with this expected value), but it would swell the 387
268 // size of the list with all the "Leaf" nodes in the tree (nodes that don't 388 void Predictor::DiscardAllResults() {
269 // load any subresources). If we learn about this resource, we will instead 389 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
270 // provide a more carefully estimated preconnection count. 390 // Delete anything listed so far in this session that shows in about:dns.
271 if (preconnect_enabled_) 391 referrers_.clear();
272 PreconnectOnIOThread(url, UrlInfo::SELF_REFERAL_MOTIVATED, 2); 392
393
394 // Try to delete anything in our work queue.
395 while (!work_queue_.IsEmpty()) {
396 // Emulate processing cycle as though host was not found.
397 GURL url = work_queue_.Pop();
398 UrlInfo* info = &results_[url];
399 DCHECK(info->HasUrl(url));
400 info->SetAssignedState();
401 info->SetNoSuchNameState();
402 }
403 // Now every result_ is either resolved, or is being resolved
404 // (see LookupRequest).
405
406 // Step through result_, recording names of all hosts that can't be erased.
407 // We can't erase anything being worked on.
408 Results assignees;
409 for (Results::iterator it = results_.begin(); results_.end() != it; ++it) {
410 GURL url(it->first);
411 UrlInfo* info = &it->second;
412 DCHECK(info->HasUrl(url));
413 if (info->is_assigned()) {
414 info->SetPendingDeleteState();
415 assignees[url] = *info;
416 }
417 }
418 DCHECK_LE(assignees.size(), max_concurrent_dns_lookups_);
419 results_.clear();
420 // Put back in the names being worked on.
421 for (Results::iterator it = assignees.begin(); assignees.end() != it; ++it) {
422 DCHECK(it->second.is_marked_to_delete());
423 results_[it->first] = it->second;
424 }
425 }
426
427 // Overloaded Resolve() to take a vector of names.
428 void Predictor::ResolveList(const UrlList& urls,
429 UrlInfo::ResolutionMotivation motivation) {
430 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
431
432 for (UrlList::const_iterator it = urls.begin(); it < urls.end(); ++it) {
433 AppendToResolutionQueue(*it, motivation);
434 }
435 }
436
437 // Basic Resolve() takes an invidual name, and adds it
438 // to the queue.
439 void Predictor::Resolve(const GURL& url,
440 UrlInfo::ResolutionMotivation motivation) {
441 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
442 if (!url.has_host())
273 return; 443 return;
444 AppendToResolutionQueue(url, motivation);
445 }
446
447 void Predictor::LearnFromNavigation(const GURL& referring_url,
448 const GURL& target_url) {
449 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
450 if (!predictor_enabled_)
451 return;
452 DCHECK_EQ(referring_url, Predictor::CanonicalizeUrl(referring_url));
453 DCHECK_NE(referring_url, GURL::EmptyGURL());
454 DCHECK_EQ(target_url, Predictor::CanonicalizeUrl(target_url));
455 DCHECK_NE(target_url, GURL::EmptyGURL());
456
457 referrers_[referring_url].SuggestHost(target_url);
458 // Possibly do some referrer trimming.
459 TrimReferrers();
460 }
461
462 //-----------------------------------------------------------------------------
463 // This section supports the about:dns page.
464
465 void Predictor::PredictorGetHtmlInfo(Predictor* predictor,
466 std::string* output) {
467 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
468
469 output->append("<html><head><title>About DNS</title>"
470 // We'd like the following no-cache... but it doesn't work.
471 // "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">"
472 "</head><body>");
473 if (predictor && predictor->predictor_enabled()) {
474 predictor->GetHtmlInfo(output);
475 } else {
476 output->append("DNS pre-resolution and TCP pre-connection is disabled.");
274 } 477 }
275 478 output->append("</body></html>");
276 Referrer* referrer = &(it->second);
277 referrer->IncrementUseCount();
278 const UrlInfo::ResolutionMotivation motivation =
279 UrlInfo::LEARNED_REFERAL_MOTIVATED;
280 for (Referrer::iterator future_url = referrer->begin();
281 future_url != referrer->end(); ++future_url) {
282 SubresourceValue evalution(TOO_NEW);
283 double connection_expectation = future_url->second.subresource_use_rate();
284 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.PreconnectSubresourceExpectation",
285 static_cast<int>(connection_expectation * 100),
286 10, 5000, 50);
287 future_url->second.ReferrerWasObserved();
288 if (preconnect_enabled_ &&
289 connection_expectation > kPreconnectWorthyExpectedValue) {
290 evalution = PRECONNECTION;
291 future_url->second.IncrementPreconnectionCount();
292 int count = static_cast<int>(std::ceil(connection_expectation));
293 if (url.host() == future_url->first.host())
294 ++count;
295 PreconnectOnIOThread(future_url->first, motivation, count);
296 } else if (connection_expectation > kDNSPreresolutionWorthyExpectedValue) {
297 evalution = PRERESOLUTION;
298 future_url->second.preresolution_increment();
299 UrlInfo* queued_info = AppendToResolutionQueue(future_url->first,
300 motivation);
301 if (queued_info)
302 queued_info->SetReferringHostname(url);
303 }
304 UMA_HISTOGRAM_ENUMERATION("Net.PreconnectSubresourceEval", evalution,
305 SUBRESOURCE_VALUE_MAX);
306 }
307 } 479 }
308 480
309 // Provide sort order so all .com's are together, etc. 481 // Provide sort order so all .com's are together, etc.
310 struct RightToLeftStringSorter { 482 struct RightToLeftStringSorter {
311 bool operator()(const GURL& left, 483 bool operator()(const GURL& left,
312 const GURL& right) const { 484 const GURL& right) const {
313 return string_compare(left.host(), right.host()); 485 return string_compare(left.host(), right.host());
314 } 486 }
315 487
316 static bool string_compare(const std::string& left_host, 488 static bool string_compare(const std::string& left_host,
(...skipping 94 matching lines...) Expand 10 before | Expand all | Expand 10 after
411 static_cast<int>(future_url->second.preresolution_count()), 583 static_cast<int>(future_url->second.preresolution_count()),
412 static_cast<double>(future_url->second.subresource_use_rate()), 584 static_cast<double>(future_url->second.subresource_use_rate()),
413 future_url->first.spec().c_str()); 585 future_url->first.spec().c_str());
414 } 586 }
415 } 587 }
416 output->append("</table>"); 588 output->append("</table>");
417 } 589 }
418 590
419 void Predictor::GetHtmlInfo(std::string* output) { 591 void Predictor::GetHtmlInfo(std::string* output) {
420 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 592 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
593 if (initial_observer_.get())
594 initial_observer_->GetFirstResolutionsHtml(output);
595 // Show list of subresource predictions and stats.
596 GetHtmlReferrerLists(output);
597
421 // Local lists for calling UrlInfo 598 // Local lists for calling UrlInfo
422 UrlInfo::UrlInfoTable name_not_found; 599 UrlInfo::UrlInfoTable name_not_found;
423 UrlInfo::UrlInfoTable name_preresolved; 600 UrlInfo::UrlInfoTable name_preresolved;
424 601
425 // Get copies of all useful data. 602 // Get copies of all useful data.
426 typedef std::map<GURL, UrlInfo, RightToLeftStringSorter> SortedUrlInfo; 603 typedef std::map<GURL, UrlInfo, RightToLeftStringSorter> SortedUrlInfo;
427 SortedUrlInfo snapshot; 604 SortedUrlInfo snapshot;
428 // UrlInfo supports value semantics, so we can do a shallow copy. 605 // UrlInfo supports value semantics, so we can do a shallow copy.
429 for (Results::iterator it(results_.begin()); it != results_.end(); it++) 606 for (Results::iterator it(results_.begin()); it != results_.end(); it++)
430 snapshot[it->first] = it->second; 607 snapshot[it->first] = it->second;
(...skipping 15 matching lines...) Expand all
446 brief = true; 623 brief = true;
447 #endif // NDEBUG 624 #endif // NDEBUG
448 625
449 // Call for display of each table, along with title. 626 // Call for display of each table, along with title.
450 UrlInfo::GetHtmlTable(name_preresolved, 627 UrlInfo::GetHtmlTable(name_preresolved,
451 "Preresolution DNS records performed for ", brief, output); 628 "Preresolution DNS records performed for ", brief, output);
452 UrlInfo::GetHtmlTable(name_not_found, 629 UrlInfo::GetHtmlTable(name_not_found,
453 "Preresolving DNS records revealed non-existence for ", brief, output); 630 "Preresolving DNS records revealed non-existence for ", brief, output);
454 } 631 }
455 632
456 UrlInfo* Predictor::AppendToResolutionQueue( 633 void Predictor::TrimReferrersNow() {
457 const GURL& url, 634 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
635 // Just finish up work if an incremental trim is in progress.
636 if (urls_being_trimmed_.empty())
637 LoadUrlsForTrimming();
638 IncrementalTrimReferrers(true); // Do everything now.
639 }
640
641 void Predictor::SerializeReferrers(base::ListValue* referral_list) {
642 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
643 referral_list->Clear();
644 referral_list->Append(new base::FundamentalValue(PREDICTOR_REFERRER_VERSION));
645 for (Referrers::const_iterator it = referrers_.begin();
646 it != referrers_.end(); ++it) {
647 // Serialize the list of subresource names.
648 Value* subresource_list(it->second.Serialize());
649
650 // Create a list for each referer.
651 ListValue* motivator(new ListValue);
652 motivator->Append(new StringValue(it->first.spec()));
653 motivator->Append(subresource_list);
654
655 referral_list->Append(motivator);
656 }
657 }
658
659 void Predictor::DeserializeReferrers(const base::ListValue& referral_list) {
660 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
661 int format_version = -1;
662 if (referral_list.GetSize() > 0 &&
663 referral_list.GetInteger(0, &format_version) &&
664 format_version == PREDICTOR_REFERRER_VERSION) {
665 for (size_t i = 1; i < referral_list.GetSize(); ++i) {
666 base::ListValue* motivator;
667 if (!referral_list.GetList(i, &motivator)) {
668 NOTREACHED();
669 return;
670 }
671 std::string motivating_url_spec;
672 if (!motivator->GetString(0, &motivating_url_spec)) {
673 NOTREACHED();
674 return;
675 }
676
677 Value* subresource_list;
678 if (!motivator->Get(1, &subresource_list)) {
679 NOTREACHED();
680 return;
681 }
682
683 referrers_[GURL(motivating_url_spec)].Deserialize(*subresource_list);
684 }
685 }
686 }
687
688 void Predictor::DeserializeReferrersThenDelete(
689 base::ListValue* referral_list) {
690 DeserializeReferrers(*referral_list);
691 delete referral_list;
692 }
693
694 void Predictor::DiscardInitialNavigationHistory() {
695 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
696 if (initial_observer_.get())
697 initial_observer_->DiscardInitialNavigationHistory();
698 }
699
700 void Predictor::FinalizeInitializationOnIOThread(
701 const UrlList& startup_urls,
702 base::ListValue* referral_list,
703 IOThread* io_thread) {
704 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
705
706 initial_observer_.reset(new InitialObserver());
707 host_resolver_ = io_thread->globals()->host_resolver.get();
708
709 // ScopedRunnableMethodFactory instances need to be created and destroyed
710 // on the same thread. The predictor lives on the IO thread and will die
711 // from there so now that we're on the IO thread we need to properly
712 // initialize the ScopedrunnableMethodFactory.
713 trim_task_factory_.reset(new ScopedRunnableMethodFactory<Predictor>(this));
714
715 // Prefetch these hostnames on startup.
716 DnsPrefetchMotivatedList(startup_urls, UrlInfo::STARTUP_LIST_MOTIVATED);
717 DeserializeReferrersThenDelete(referral_list);
718 }
719
720 //-----------------------------------------------------------------------------
721 // This section intermingles prefetch results with actual browser HTTP
722 // network activity. It supports calculating of the benefit of a prefetch, as
723 // well as recording what prefetched hostname resolutions might be potentially
724 // helpful during the next chrome-startup.
725 //-----------------------------------------------------------------------------
726
727 void Predictor::LearnAboutInitialNavigation(const GURL& url) {
728 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
729 if (!predictor_enabled_ || NULL == initial_observer_.get() )
730 return;
731 initial_observer_->Append(url, this);
732 }
733
734 // This API is only used in the browser process.
735 // It is called from an IPC message originating in the renderer. It currently
736 // includes both Page-Scan, and Link-Hover prefetching.
737 // TODO(jar): Separate out link-hover prefetching, and page-scan results.
738 void Predictor::DnsPrefetchList(const NameList& hostnames) {
739 // TODO(jar): Push GURL transport further back into renderer, but this will
740 // require a Webkit change in the observer :-/.
741 UrlList urls;
742 for (NameList::const_iterator it = hostnames.begin();
743 it < hostnames.end();
744 ++it) {
745 urls.push_back(GURL("http://" + *it + ":80"));
746 }
747
748 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
749 DnsPrefetchMotivatedList(urls, UrlInfo::PAGE_SCAN_MOTIVATED);
750 }
751
752 void Predictor::DnsPrefetchMotivatedList(
753 const UrlList& urls,
458 UrlInfo::ResolutionMotivation motivation) { 754 UrlInfo::ResolutionMotivation motivation) {
459 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 755 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
460 DCHECK(url.has_host()); 756 BrowserThread::CurrentlyOn(BrowserThread::IO));
461 757 if (!predictor_enabled_)
462 if (shutdown_) 758 return;
463 return NULL; 759
464 760 if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
465 UrlInfo* info = &results_[url]; 761 ResolveList(urls, motivation);
466 info->SetUrl(url); // Initialize or DCHECK. 762 } else {
467 // TODO(jar): I need to discard names that have long since expired. 763 BrowserThread::PostTask(
468 // Currently we only add to the domain map :-/ 764 BrowserThread::IO,
469 765 FROM_HERE,
470 DCHECK(info->HasUrl(url)); 766 base::Bind(&Predictor::ResolveList, base::Unretained(this),
471 767 urls, motivation));
472 if (!info->NeedsDnsUpdate()) { 768 }
473 info->DLogResultsStats("DNS PrefetchNotUpdated"); 769 }
474 return NULL; 770
475 } 771 //-----------------------------------------------------------------------------
476 772 // Functions to handle saving of hostnames from one session to the next, to
477 info->SetQueuedState(motivation); 773 // expedite startup times.
478 work_queue_.Push(url, motivation); 774
479 StartSomeQueuedResolutions(); 775 static void SaveDnsPrefetchStateForNextStartupAndTrimOnIOThread(
480 return info; 776 base::ListValue* startup_list,
481 } 777 base::ListValue* referral_list,
482 778 base::WaitableEvent* completion,
483 void Predictor::StartSomeQueuedResolutions() { 779 Predictor* predictor) {
484 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 780 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
485 781
486 while (!work_queue_.IsEmpty() && 782 if (NULL == predictor) {
487 pending_lookups_.size() < max_concurrent_dns_lookups_) { 783 completion->Signal();
488 const GURL url(work_queue_.Pop()); 784 return;
489 UrlInfo* info = &results_[url]; 785 }
490 DCHECK(info->HasUrl(url)); 786 predictor->SaveDnsPrefetchStateForNextStartupAndTrim(
491 info->SetAssignedState(); 787 startup_list, referral_list, completion);
492 788 }
493 if (CongestionControlPerformed(info)) { 789
494 DCHECK(work_queue_.IsEmpty()); 790 void Predictor::SaveStateForNextStartupAndTrim(PrefService* prefs) {
495 return; 791 if (!predictor_enabled_)
792 return;
793
794 base::WaitableEvent completion(true, false);
795
796 ListPrefUpdate update_startup_list(prefs, prefs::kDnsPrefetchingStartupList);
797 ListPrefUpdate update_referral_list(prefs,
798 prefs::kDnsPrefetchingHostReferralList);
799 if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
800 SaveDnsPrefetchStateForNextStartupAndTrimOnIOThread(
801 update_startup_list.Get(),
802 update_referral_list.Get(),
803 &completion,
804 this);
805 } else {
806 bool posted = BrowserThread::PostTask(
807 BrowserThread::IO,
808 FROM_HERE,
809 base::Bind(
810 SaveDnsPrefetchStateForNextStartupAndTrimOnIOThread,
811 update_startup_list.Get(),
812 update_referral_list.Get(),
813 &completion,
814 this));
815
816 // TODO(jar): Synchronous waiting for the IO thread is a potential source
817 // to deadlocks and should be investigated. See http://crbug.com/78451.
818 DCHECK(posted);
819 if (posted)
820 completion.Wait();
821 }
822 }
823
824 void Predictor::SaveDnsPrefetchStateForNextStartupAndTrim(
825 base::ListValue* startup_list,
826 base::ListValue* referral_list,
827 base::WaitableEvent* completion) {
828 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
829 if (initial_observer_.get())
830 initial_observer_->GetInitialDnsResolutionList(startup_list);
831
832 // Do at least one trim at shutdown, in case the user wasn't running long
833 // enough to do any regular trimming of referrers.
834 TrimReferrersNow();
835 SerializeReferrers(referral_list);
836
837 completion->Signal();
838 }
839
840 void Predictor::EnablePredictor(bool enable) {
841 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
842 BrowserThread::CurrentlyOn(BrowserThread::IO));
843
844 if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
845 EnablePredictorOnIOThread(enable);
846 } else {
847 BrowserThread::PostTask(
848 BrowserThread::IO,
849 FROM_HERE,
850 base::Bind(&Predictor::EnablePredictorOnIOThread,
851 base::Unretained(this), enable));
852 }
853 }
854
855 void Predictor::EnablePredictorOnIOThread(bool enable) {
856 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
857 predictor_enabled_ = enable;
858 }
859
860 void Predictor::PredictFrameSubresources(const GURL& url) {
861 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
862 BrowserThread::CurrentlyOn(BrowserThread::IO));
863 if (!predictor_enabled_)
864 return;
865 DCHECK_EQ(url.GetWithEmptyPath(), url);
866 // Add one pass through the message loop to allow current navigation to
867 // proceed.
868 if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
869 PrepareFrameSubresources(url);
870 } else {
871 BrowserThread::PostTask(
872 BrowserThread::IO,
873 FROM_HERE,
874 base::Bind(&Predictor::PrepareFrameSubresources,
875 base::Unretained(this), url));
876 }
877 }
878
879 enum SubresourceValue {
880 PRECONNECTION,
881 PRERESOLUTION,
882 TOO_NEW,
883 SUBRESOURCE_VALUE_MAX
884 };
885
886 void Predictor::PrepareFrameSubresources(const GURL& url) {
887 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
888 DCHECK_EQ(url.GetWithEmptyPath(), url);
889 Referrers::iterator it = referrers_.find(url);
890 if (referrers_.end() == it) {
891 // Only when we don't know anything about this url, make 2 connections
892 // available. We could do this completely via learning (by prepopulating
893 // the referrer_ list with this expected value), but it would swell the
894 // size of the list with all the "Leaf" nodes in the tree (nodes that don't
895 // load any subresources). If we learn about this resource, we will instead
896 // provide a more carefully estimated preconnection count.
897 if (preconnect_enabled_)
898 PreconnectOnIOThread(url, UrlInfo::SELF_REFERAL_MOTIVATED, 2);
899 return;
900 }
901
902 Referrer* referrer = &(it->second);
903 referrer->IncrementUseCount();
904 const UrlInfo::ResolutionMotivation motivation =
905 UrlInfo::LEARNED_REFERAL_MOTIVATED;
906 for (Referrer::iterator future_url = referrer->begin();
907 future_url != referrer->end(); ++future_url) {
908 SubresourceValue evalution(TOO_NEW);
909 double connection_expectation = future_url->second.subresource_use_rate();
910 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.PreconnectSubresourceExpectation",
911 static_cast<int>(connection_expectation * 100),
912 10, 5000, 50);
913 future_url->second.ReferrerWasObserved();
914 if (preconnect_enabled_ &&
915 connection_expectation > kPreconnectWorthyExpectedValue) {
916 evalution = PRECONNECTION;
917 future_url->second.IncrementPreconnectionCount();
918 int count = static_cast<int>(std::ceil(connection_expectation));
919 if (url.host() == future_url->first.host())
920 ++count;
921 PreconnectOnIOThread(future_url->first, motivation, count);
922 } else if (connection_expectation > kDNSPreresolutionWorthyExpectedValue) {
923 evalution = PRERESOLUTION;
924 future_url->second.preresolution_increment();
925 UrlInfo* queued_info = AppendToResolutionQueue(future_url->first,
926 motivation);
927 if (queued_info)
928 queued_info->SetReferringHostname(url);
496 } 929 }
497 930 UMA_HISTOGRAM_ENUMERATION("Net.PreconnectSubresourceEval", evalution,
498 LookupRequest* request = new LookupRequest(this, host_resolver_, url); 931 SUBRESOURCE_VALUE_MAX);
499 int status = request->Start(); 932 }
500 if (status == net::ERR_IO_PENDING) {
501 // Will complete asynchronously.
502 pending_lookups_.insert(request);
503 peak_pending_lookups_ = std::max(peak_pending_lookups_,
504 pending_lookups_.size());
505 } else {
506 // Completed synchronously (was already cached by HostResolver), or else
507 // there was (equivalently) some network error that prevents us from
508 // finding the name. Status net::OK means it was "found."
509 LookupFinished(request, url, status == net::OK);
510 delete request;
511 }
512 }
513 }
514
515 bool Predictor::CongestionControlPerformed(UrlInfo* info) {
516 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
517 // Note: queue_duration is ONLY valid after we go to assigned state.
518 if (info->queue_duration() < max_dns_queue_delay_)
519 return false;
520 // We need to discard all entries in our queue, as we're keeping them waiting
521 // too long. By doing this, we'll have a chance to quickly service urgent
522 // resolutions, and not have a bogged down system.
523 while (true) {
524 info->RemoveFromQueue();
525 if (work_queue_.IsEmpty())
526 break;
527 info = &results_[work_queue_.Pop()];
528 info->SetAssignedState();
529 }
530 return true;
531 } 933 }
532 934
533 void Predictor::OnLookupFinished(LookupRequest* request, const GURL& url, 935 void Predictor::OnLookupFinished(LookupRequest* request, const GURL& url,
534 bool found) { 936 bool found) {
535 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 937 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
536 938
537 LookupFinished(request, url, found); 939 LookupFinished(request, url, found);
538 pending_lookups_.erase(request); 940 pending_lookups_.erase(request);
539 delete request; 941 delete request;
540 942
541 StartSomeQueuedResolutions(); 943 StartSomeQueuedResolutions();
542 } 944 }
543 945
544 void Predictor::LookupFinished(LookupRequest* request, const GURL& url, 946 void Predictor::LookupFinished(LookupRequest* request, const GURL& url,
545 bool found) { 947 bool found) {
546 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 948 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
547 UrlInfo* info = &results_[url]; 949 UrlInfo* info = &results_[url];
548 DCHECK(info->HasUrl(url)); 950 DCHECK(info->HasUrl(url));
549 if (info->is_marked_to_delete()) { 951 if (info->is_marked_to_delete()) {
550 results_.erase(url); 952 results_.erase(url);
551 } else { 953 } else {
552 if (found) 954 if (found)
553 info->SetFoundState(); 955 info->SetFoundState();
554 else 956 else
555 info->SetNoSuchNameState(); 957 info->SetNoSuchNameState();
556 } 958 }
557 } 959 }
558 960
559 void Predictor::DiscardAllResults() { 961 UrlInfo* Predictor::AppendToResolutionQueue(
962 const GURL& url,
963 UrlInfo::ResolutionMotivation motivation) {
560 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 964 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
561 // Delete anything listed so far in this session that shows in about:dns. 965 DCHECK(url.has_host());
562 referrers_.clear();
563 966
967 if (shutdown_)
968 return NULL;
564 969
565 // Try to delete anything in our work queue. 970 UrlInfo* info = &results_[url];
566 while (!work_queue_.IsEmpty()) { 971 info->SetUrl(url); // Initialize or DCHECK.
567 // Emulate processing cycle as though host was not found. 972 // TODO(jar): I need to discard names that have long since expired.
568 GURL url = work_queue_.Pop(); 973 // Currently we only add to the domain map :-/
974
975 DCHECK(info->HasUrl(url));
976
977 if (!info->NeedsDnsUpdate()) {
978 info->DLogResultsStats("DNS PrefetchNotUpdated");
979 return NULL;
980 }
981
982 info->SetQueuedState(motivation);
983 work_queue_.Push(url, motivation);
984 StartSomeQueuedResolutions();
985 return info;
986 }
987
988 bool Predictor::CongestionControlPerformed(UrlInfo* info) {
989 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
990 // Note: queue_duration is ONLY valid after we go to assigned state.
991 if (info->queue_duration() < max_dns_queue_delay_)
992 return false;
993 // We need to discard all entries in our queue, as we're keeping them waiting
994 // too long. By doing this, we'll have a chance to quickly service urgent
995 // resolutions, and not have a bogged down system.
996 while (true) {
997 info->RemoveFromQueue();
998 if (work_queue_.IsEmpty())
999 break;
1000 info = &results_[work_queue_.Pop()];
1001 info->SetAssignedState();
1002 }
1003 return true;
1004 }
1005
1006 void Predictor::StartSomeQueuedResolutions() {
1007 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1008
1009 while (!work_queue_.IsEmpty() &&
1010 pending_lookups_.size() < max_concurrent_dns_lookups_) {
1011 const GURL url(work_queue_.Pop());
569 UrlInfo* info = &results_[url]; 1012 UrlInfo* info = &results_[url];
570 DCHECK(info->HasUrl(url)); 1013 DCHECK(info->HasUrl(url));
571 info->SetAssignedState(); 1014 info->SetAssignedState();
572 info->SetNoSuchNameState();
573 }
574 // Now every result_ is either resolved, or is being resolved
575 // (see LookupRequest).
576 1015
577 // Step through result_, recording names of all hosts that can't be erased. 1016 if (CongestionControlPerformed(info)) {
578 // We can't erase anything being worked on. 1017 DCHECK(work_queue_.IsEmpty());
579 Results assignees; 1018 return;
580 for (Results::iterator it = results_.begin(); results_.end() != it; ++it) {
581 GURL url(it->first);
582 UrlInfo* info = &it->second;
583 DCHECK(info->HasUrl(url));
584 if (info->is_assigned()) {
585 info->SetPendingDeleteState();
586 assignees[url] = *info;
587 } 1019 }
588 }
589 DCHECK(assignees.size() <= max_concurrent_dns_lookups_);
590 results_.clear();
591 // Put back in the names being worked on.
592 for (Results::iterator it = assignees.begin(); assignees.end() != it; ++it) {
593 DCHECK(it->second.is_marked_to_delete());
594 results_[it->first] = it->second;
595 }
596 }
597 1020
598 void Predictor::TrimReferrersNow() { 1021 LookupRequest* request = new LookupRequest(this, host_resolver_, url);
599 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 1022 int status = request->Start();
600 // Just finish up work if an incremental trim is in progress. 1023 if (status == net::ERR_IO_PENDING) {
601 if (urls_being_trimmed_.empty()) 1024 // Will complete asynchronously.
602 LoadUrlsForTrimming(); 1025 pending_lookups_.insert(request);
603 IncrementalTrimReferrers(true); // Do everything now. 1026 peak_pending_lookups_ = std::max(peak_pending_lookups_,
604 } 1027 pending_lookups_.size());
605 1028 } else {
606 void Predictor::SerializeReferrers(ListValue* referral_list) { 1029 // Completed synchronously (was already cached by HostResolver), or else
607 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 1030 // there was (equivalently) some network error that prevents us from
608 referral_list->Clear(); 1031 // finding the name. Status net::OK means it was "found."
609 referral_list->Append(new base::FundamentalValue(PREDICTOR_REFERRER_VERSION)); 1032 LookupFinished(request, url, status == net::OK);
610 for (Referrers::const_iterator it = referrers_.begin(); 1033 delete request;
611 it != referrers_.end(); ++it) {
612 // Serialize the list of subresource names.
613 Value* subresource_list(it->second.Serialize());
614
615 // Create a list for each referer.
616 ListValue* motivator(new ListValue);
617 motivator->Append(new StringValue(it->first.spec()));
618 motivator->Append(subresource_list);
619
620 referral_list->Append(motivator);
621 }
622 }
623
624 void Predictor::DeserializeReferrers(const ListValue& referral_list) {
625 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
626 int format_version = -1;
627 if (referral_list.GetSize() > 0 &&
628 referral_list.GetInteger(0, &format_version) &&
629 format_version == PREDICTOR_REFERRER_VERSION) {
630 for (size_t i = 1; i < referral_list.GetSize(); ++i) {
631 ListValue* motivator;
632 if (!referral_list.GetList(i, &motivator)) {
633 NOTREACHED();
634 return;
635 }
636 std::string motivating_url_spec;
637 if (!motivator->GetString(0, &motivating_url_spec)) {
638 NOTREACHED();
639 return;
640 }
641
642 Value* subresource_list;
643 if (!motivator->Get(1, &subresource_list)) {
644 NOTREACHED();
645 return;
646 }
647
648 referrers_[GURL(motivating_url_spec)].Deserialize(*subresource_list);
649 } 1034 }
650 } 1035 }
651 } 1036 }
652 1037
653 void Predictor::TrimReferrers() { 1038 void Predictor::TrimReferrers() {
654 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 1039 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
655 if (!urls_being_trimmed_.empty()) 1040 if (!urls_being_trimmed_.empty())
656 return; // There is incremental trimming in progress already. 1041 return; // There is incremental trimming in progress already.
657 1042
658 // Check to see if it is time to trim yet. 1043 // Check to see if it is time to trim yet.
(...skipping 12 matching lines...) Expand all
671 it != referrers_.end(); ++it) 1056 it != referrers_.end(); ++it)
672 urls_being_trimmed_.push_back(it->first); 1057 urls_being_trimmed_.push_back(it->first);
673 UMA_HISTOGRAM_COUNTS("Net.PredictionTrimSize", urls_being_trimmed_.size()); 1058 UMA_HISTOGRAM_COUNTS("Net.PredictionTrimSize", urls_being_trimmed_.size());
674 } 1059 }
675 1060
676 void Predictor::PostIncrementalTrimTask() { 1061 void Predictor::PostIncrementalTrimTask() {
677 if (urls_being_trimmed_.empty()) 1062 if (urls_being_trimmed_.empty())
678 return; 1063 return;
679 MessageLoop::current()->PostDelayedTask( 1064 MessageLoop::current()->PostDelayedTask(
680 FROM_HERE, 1065 FROM_HERE,
681 trim_task_factory_.NewRunnableMethod(&Predictor::IncrementalTrimReferrers, 1066 trim_task_factory_->NewRunnableMethod(
682 false), 1067 &Predictor::IncrementalTrimReferrers, false),
683 kDurationBetweenTrimmingIncrements.InMilliseconds()); 1068 kDurationBetweenTrimmingIncrements.InMilliseconds());
684 } 1069 }
685 1070
686 void Predictor::IncrementalTrimReferrers(bool trim_all_now) { 1071 void Predictor::IncrementalTrimReferrers(bool trim_all_now) {
687 size_t trim_count = urls_being_trimmed_.size(); 1072 size_t trim_count = urls_being_trimmed_.size();
688 if (!trim_all_now) 1073 if (!trim_all_now)
689 trim_count = std::min(trim_count, kUrlsTrimmedPerIncrement); 1074 trim_count = std::min(trim_count, kUrlsTrimmedPerIncrement);
690 while (trim_count-- != 0) { 1075 while (trim_count-- != 0) {
691 Referrers::iterator it = referrers_.find(urls_being_trimmed_.back()); 1076 Referrers::iterator it = referrers_.find(urls_being_trimmed_.back());
692 urls_being_trimmed_.pop_back(); 1077 urls_being_trimmed_.pop_back();
693 if (it == referrers_.end()) 1078 if (it == referrers_.end())
694 continue; // Defensive code: It got trimmed away already. 1079 continue; // Defensive code: It got trimmed away already.
695 if (!it->second.Trim(kReferrerTrimRatio, kDiscardableExpectedValue)) 1080 if (!it->second.Trim(kReferrerTrimRatio, kDiscardableExpectedValue))
696 referrers_.erase(it); 1081 referrers_.erase(it);
697 } 1082 }
698 PostIncrementalTrimTask(); 1083 PostIncrementalTrimTask();
699 } 1084 }
700 1085
701 //------------------------------------------------------------------------------ 1086 // ---------------------- End IO methods. -------------------------------------
1087
1088 //-----------------------------------------------------------------------------
702 1089
703 Predictor::HostNameQueue::HostNameQueue() { 1090 Predictor::HostNameQueue::HostNameQueue() {
704 } 1091 }
705 1092
706 Predictor::HostNameQueue::~HostNameQueue() { 1093 Predictor::HostNameQueue::~HostNameQueue() {
707 } 1094 }
708 1095
709 void Predictor::HostNameQueue::Push(const GURL& url, 1096 void Predictor::HostNameQueue::Push(const GURL& url,
710 UrlInfo::ResolutionMotivation motivation) { 1097 UrlInfo::ResolutionMotivation motivation) {
711 switch (motivation) { 1098 switch (motivation) {
(...skipping 15 matching lines...) Expand all
727 1114
728 GURL Predictor::HostNameQueue::Pop() { 1115 GURL Predictor::HostNameQueue::Pop() {
729 DCHECK(!IsEmpty()); 1116 DCHECK(!IsEmpty());
730 std::queue<GURL> *queue(rush_queue_.empty() ? &background_queue_ 1117 std::queue<GURL> *queue(rush_queue_.empty() ? &background_queue_
731 : &rush_queue_); 1118 : &rush_queue_);
732 GURL url(queue->front()); 1119 GURL url(queue->front());
733 queue->pop(); 1120 queue->pop();
734 return url; 1121 return url;
735 } 1122 }
736 1123
737 void Predictor::DeserializeReferrersThenDelete(ListValue* referral_list) { 1124 //-----------------------------------------------------------------------------
738 DeserializeReferrers(*referral_list); 1125 // Member definitions for InitialObserver class.
739 delete referral_list; 1126
1127 void Predictor::InitialObserver::Append(const GURL& url,
1128 Predictor* predictor) {
1129 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1130
1131 // TODO(rlp): Do we really need the predictor check here?
1132 if (NULL == predictor)
1133 return;
1134 if (kStartupResolutionCount <= first_navigations_.size())
1135 return;
1136
1137 DCHECK(url.SchemeIs("http") || url.SchemeIs("https"));
1138 DCHECK_EQ(url, Predictor::CanonicalizeUrl(url));
1139 if (first_navigations_.find(url) == first_navigations_.end())
1140 first_navigations_[url] = base::TimeTicks::Now();
740 } 1141 }
741 1142
1143 void Predictor::InitialObserver::GetInitialDnsResolutionList(
1144 base::ListValue* startup_list) {
1145 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1146 DCHECK(startup_list);
1147 startup_list->Clear();
1148 DCHECK_EQ(0u, startup_list->GetSize());
1149 startup_list->Append(
1150 new base::FundamentalValue(kPredictorStartupFormatVersion));
1151 for (FirstNavigations::iterator it = first_navigations_.begin();
1152 it != first_navigations_.end();
1153 ++it) {
1154 DCHECK(it->first == Predictor::CanonicalizeUrl(it->first));
1155 startup_list->Append(new StringValue(it->first.spec()));
1156 }
1157 }
742 1158
743 //------------------------------------------------------------------------------ 1159 void Predictor::InitialObserver::GetFirstResolutionsHtml(
1160 std::string* output) {
1161 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1162
1163 UrlInfo::UrlInfoTable resolution_list;
1164 {
1165 for (FirstNavigations::iterator it(first_navigations_.begin());
1166 it != first_navigations_.end();
1167 it++) {
1168 UrlInfo info;
1169 info.SetUrl(it->first);
1170 info.set_time(it->second);
1171 resolution_list.push_back(info);
1172 }
1173 }
1174 UrlInfo::GetHtmlTable(resolution_list,
1175 "Future startups will prefetch DNS records for ", false, output);
1176 }
1177
1178 //-----------------------------------------------------------------------------
744 // Helper functions 1179 // Helper functions
745 //------------------------------------------------------------------------------ 1180 //-----------------------------------------------------------------------------
746 1181
747 // static 1182 // static
748 GURL Predictor::CanonicalizeUrl(const GURL& url) { 1183 GURL Predictor::CanonicalizeUrl(const GURL& url) {
749 if (!url.has_host()) 1184 if (!url.has_host())
750 return GURL::EmptyGURL(); 1185 return GURL::EmptyGURL();
751 1186
752 std::string scheme; 1187 std::string scheme;
753 if (url.has_scheme()) { 1188 if (url.has_scheme()) {
754 scheme = url.scheme(); 1189 scheme = url.scheme();
755 if (scheme != "http" && scheme != "https") 1190 if (scheme != "http" && scheme != "https")
756 return GURL::EmptyGURL(); 1191 return GURL::EmptyGURL();
757 if (url.has_port()) 1192 if (url.has_port())
758 return url.GetWithEmptyPath(); 1193 return url.GetWithEmptyPath();
759 } else { 1194 } else {
760 scheme = "http"; 1195 scheme = "http";
761 } 1196 }
762 1197
763 // If we omit a port, it will default to 80 or 443 as appropriate. 1198 // If we omit a port, it will default to 80 or 443 as appropriate.
764 std::string colon_plus_port; 1199 std::string colon_plus_port;
765 if (url.has_port()) 1200 if (url.has_port())
766 colon_plus_port = ":" + url.port(); 1201 colon_plus_port = ":" + url.port();
767 1202
768 return GURL(scheme + "://" + url.host() + colon_plus_port); 1203 return GURL(scheme + "://" + url.host() + colon_plus_port);
769 } 1204 }
770 1205
771
772 } // namespace chrome_browser_net 1206 } // namespace chrome_browser_net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698