Override server-side simple-cache trial with commandline switches.
[chromium-blink-merge.git] / chrome / browser / browser_shutdown.cc
blob18be43cec084c5859280cf7d6f7a429d5811fc06
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 "chrome/browser/browser_shutdown.h"
7 #include <map>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/file_util.h"
13 #include "base/files/file_path.h"
14 #include "base/metrics/histogram.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_registry_simple.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/process_util.h"
19 #include "base/stringprintf.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/threading/thread.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/time.h"
24 #include "build/build_config.h"
25 #include "chrome/browser/about_flags.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/first_run/upgrade_util.h"
28 #include "chrome/browser/jankometer.h"
29 #include "chrome/browser/lifetime/application_lifetime.h"
30 #include "chrome/browser/metrics/metrics_service.h"
31 #include "chrome/browser/profiles/profile_manager.h"
32 #include "chrome/browser/service/service_process_control.h"
33 #include "chrome/common/chrome_paths.h"
34 #include "chrome/common/chrome_switches.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/common/switch_utils.h"
37 #include "content/public/browser/browser_thread.h"
38 #include "content/public/browser/render_process_host.h"
39 #include "content/public/browser/render_view_host.h"
40 #include "ui/base/resource/resource_bundle.h"
42 #if defined(OS_WIN)
43 #include "chrome/browser/browser_util_win.h"
44 #include "chrome/browser/first_run/upgrade_util_win.h"
45 #endif
47 #if defined(ENABLE_RLZ)
48 #include "chrome/browser/rlz/rlz.h"
49 #endif
51 #if defined(OS_CHROMEOS)
52 #include "chrome/browser/chromeos/boot_times_loader.h"
53 #include "chrome/browser/chromeos/cros/cros_library.h"
54 #endif
56 using base::Time;
57 using base::TimeDelta;
58 using content::BrowserThread;
60 namespace browser_shutdown {
62 // Whether the browser is trying to quit (e.g., Quit chosen from menu).
63 bool g_trying_to_quit = false;
65 // Whether the browser should quit without closing browsers.
66 bool g_shutting_down_without_closing_browsers = false;
68 #if defined(OS_WIN)
69 // Whether the next restart should happen in the opposite mode; desktop or
70 // metro mode. Windows 8 only.
71 bool g_mode_switch = false;
72 #endif
74 Time* shutdown_started_ = NULL;
75 ShutdownType shutdown_type_ = NOT_VALID;
76 int shutdown_num_processes_;
77 int shutdown_num_processes_slow_;
79 const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";
81 void RegisterPrefs(PrefRegistrySimple* registry) {
82 registry->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
83 registry->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
84 registry->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
87 ShutdownType GetShutdownType() {
88 return shutdown_type_;
91 void OnShutdownStarting(ShutdownType type) {
92 if (shutdown_type_ != NOT_VALID)
93 return;
95 shutdown_type_ = type;
96 // For now, we're only counting the number of renderer processes
97 // since we can't safely count the number of plugin processes from this
98 // thread, and we'd really like to avoid anything which might add further
99 // delays to shutdown time.
100 DCHECK(!shutdown_started_);
101 shutdown_started_ = new Time(Time::Now());
103 // Call FastShutdown on all of the RenderProcessHosts. This will be
104 // a no-op in some cases, so we still need to go through the normal
105 // shutdown path for the ones that didn't exit here.
106 shutdown_num_processes_ = 0;
107 shutdown_num_processes_slow_ = 0;
108 for (content::RenderProcessHost::iterator i(
109 content::RenderProcessHost::AllHostsIterator());
110 !i.IsAtEnd(); i.Advance()) {
111 ++shutdown_num_processes_;
112 if (!i.GetCurrentValue()->FastShutdownIfPossible())
113 ++shutdown_num_processes_slow_;
117 base::FilePath GetShutdownMsPath() {
118 base::FilePath shutdown_ms_file;
119 PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
120 return shutdown_ms_file.AppendASCII(kShutdownMsFile);
123 bool ShutdownPreThreadsStop() {
124 #if defined(OS_CHROMEOS)
125 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
126 "BrowserShutdownStarted", false);
127 #endif
129 // Shutdown the IPC channel to the service processes.
130 ServiceProcessControl::GetInstance()->Disconnect();
132 // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
133 // time to get here. If you have something that *must* happen on end session,
134 // consider putting it in BrowserProcessImpl::EndSession.
135 PrefService* prefs = g_browser_process->local_state();
137 MetricsService* metrics = g_browser_process->metrics_service();
138 if (metrics)
139 metrics->RecordCompletedSessionEnd();
141 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
142 // Record the shutdown info so that we can put it into a histogram at next
143 // startup.
144 prefs->SetInteger(prefs::kShutdownType, shutdown_type_);
145 prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);
146 prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
147 shutdown_num_processes_slow_);
150 // Check local state for the restart flag so we can restart the session below.
151 bool restart_last_session = false;
152 if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {
153 restart_last_session =
154 prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);
155 prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
156 #if defined(OS_WIN)
157 if (restart_last_session) {
158 if (prefs->HasPrefPath(prefs::kRestartSwitchMode)) {
159 g_mode_switch = prefs->GetBoolean(prefs::kRestartSwitchMode);
160 prefs->SetBoolean(prefs::kRestartSwitchMode, false);
163 #endif
166 prefs->CommitPendingWrite();
168 #if defined(ENABLE_RLZ)
169 // Cleanup any statics created by RLZ. Must be done before NotificationService
170 // is destroyed.
171 RLZTracker::CleanupRlz();
172 #endif
174 return restart_last_session;
177 void ShutdownPostThreadsStop(bool restart_last_session) {
178 // The jank'o'meter requires that the browser process has been destroyed
179 // before calling UninstallJankometer().
180 delete g_browser_process;
181 g_browser_process = NULL;
183 // crbug.com/95079 - This needs to happen after the browser process object
184 // goes away.
185 ProfileManager::NukeDeletedProfilesFromDisk();
187 #if defined(OS_CHROMEOS)
188 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("BrowserDeleted",
189 true);
190 #endif
192 // Uninstall Jank-O-Meter here after the IO thread is no longer running.
193 UninstallJankometer();
195 #if defined(OS_WIN)
196 if (!browser_util::IsBrowserAlreadyRunning() &&
197 shutdown_type_ != browser_shutdown::END_SESSION) {
198 upgrade_util::SwapNewChromeExeIfPresent();
200 #endif
202 if (restart_last_session) {
203 #if !defined(OS_CHROMEOS)
204 // Make sure to relaunch the browser with the original command line plus
205 // the Restore Last Session flag. Note that Chrome can be launched (ie.
206 // through ShellExecute on Windows) with a switch argument terminator at
207 // the end (double dash, as described in b/1366444) plus a URL,
208 // which prevents us from appending to the command line directly (issue
209 // 46182). We therefore use GetSwitches to copy the command line (it stops
210 // at the switch argument terminator).
211 CommandLine old_cl(*CommandLine::ForCurrentProcess());
212 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram()));
213 std::map<std::string, CommandLine::StringType> switches =
214 old_cl.GetSwitches();
215 // Remove the switches that shouldn't persist across restart.
216 about_flags::RemoveFlagsSwitches(&switches);
217 switches::RemoveSwitchesForAutostart(&switches);
218 // Append the old switches to the new command line.
219 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
220 switches.begin(); i != switches.end(); ++i) {
221 CommandLine::StringType switch_value = i->second;
222 if (!switch_value.empty())
223 new_cl->AppendSwitchNative(i->first, i->second);
224 else
225 new_cl->AppendSwitch(i->first);
228 #if defined(OS_WIN)
229 // On Windows 8 we can relaunch in metro or desktop mode.
230 if (g_mode_switch)
231 upgrade_util::RelaunchChromeWithModeSwitch(*new_cl.get());
232 else
233 upgrade_util::RelaunchChromeBrowser(*new_cl.get());
234 #else
235 upgrade_util::RelaunchChromeBrowser(*new_cl.get());
236 #endif // defined(OS_WIN)
238 #else
239 NOTIMPLEMENTED();
240 #endif // !defined(OS_CHROMEOS)
243 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
244 // Measure total shutdown time as late in the process as possible
245 // and then write it to a file to be read at startup.
246 // We can't use prefs since all services are shutdown at this point.
247 TimeDelta shutdown_delta = Time::Now() - *shutdown_started_;
248 std::string shutdown_ms =
249 base::Int64ToString(shutdown_delta.InMilliseconds());
250 int len = static_cast<int>(shutdown_ms.length()) + 1;
251 base::FilePath shutdown_ms_file = GetShutdownMsPath();
252 file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
255 #if defined(OS_CHROMEOS)
256 chrome::NotifyAndTerminate(false);
257 #endif
260 void ReadLastShutdownFile(ShutdownType type,
261 int num_procs,
262 int num_procs_slow) {
263 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
265 base::FilePath shutdown_ms_file = GetShutdownMsPath();
266 std::string shutdown_ms_str;
267 int64 shutdown_ms = 0;
268 if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
269 base::StringToInt64(shutdown_ms_str, &shutdown_ms);
270 file_util::Delete(shutdown_ms_file, false);
272 if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
273 return;
275 const char* time_fmt = "Shutdown.%s.time";
276 const char* time_per_fmt = "Shutdown.%s.time_per_process";
277 std::string time;
278 std::string time_per;
279 if (type == WINDOW_CLOSE) {
280 time = base::StringPrintf(time_fmt, "window_close");
281 time_per = base::StringPrintf(time_per_fmt, "window_close");
282 } else if (type == BROWSER_EXIT) {
283 time = base::StringPrintf(time_fmt, "browser_exit");
284 time_per = base::StringPrintf(time_per_fmt, "browser_exit");
285 } else if (type == END_SESSION) {
286 time = base::StringPrintf(time_fmt, "end_session");
287 time_per = base::StringPrintf(time_per_fmt, "end_session");
288 } else {
289 NOTREACHED();
292 if (time.empty())
293 return;
295 // TODO(erikkay): change these to UMA histograms after a bit more testing.
296 UMA_HISTOGRAM_TIMES(time.c_str(),
297 TimeDelta::FromMilliseconds(shutdown_ms));
298 UMA_HISTOGRAM_TIMES(time_per.c_str(),
299 TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
300 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
301 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
304 void ReadLastShutdownInfo() {
305 PrefService* prefs = g_browser_process->local_state();
306 ShutdownType type =
307 static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
308 int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
309 int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
310 // clear the prefs immediately so we don't pick them up on a future run
311 prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
312 prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
313 prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);
315 // Read and delete the file on the file thread.
316 BrowserThread::PostTask(
317 BrowserThread::FILE, FROM_HERE,
318 base::Bind(&ReadLastShutdownFile, type, num_procs, num_procs_slow));
321 void SetTryingToQuit(bool quitting) {
322 g_trying_to_quit = quitting;
325 bool IsTryingToQuit() {
326 return g_trying_to_quit;
329 bool ShuttingDownWithoutClosingBrowsers() {
330 return g_shutting_down_without_closing_browsers;
333 void SetShuttingDownWithoutClosingBrowsers(bool without_close) {
334 g_shutting_down_without_closing_browsers = without_close;
337 } // namespace browser_shutdown