base::Time multiplicative operator overloading
[chromium-blink-merge.git] / chrome / browser / browser_shutdown.cc
blob8974bd502d5ddcaa8cd004f7418bd55389d74b6b
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/files/file_path.h"
13 #include "base/files/file_util.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/strings/string_number_conversions.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/threading/thread.h"
21 #include "base/time/time.h"
22 #include "chrome/browser/about_flags.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/first_run/upgrade_util.h"
25 #include "chrome/browser/lifetime/application_lifetime.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/profiles/profile_metrics.h"
28 #include "chrome/common/chrome_paths.h"
29 #include "chrome/common/chrome_switches.h"
30 #include "chrome/common/crash_keys.h"
31 #include "chrome/common/pref_names.h"
32 #include "chrome/common/switch_utils.h"
33 #include "components/metrics/metrics_service.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "content/public/browser/render_process_host.h"
37 #if defined(OS_WIN)
38 #include "chrome/browser/browser_util_win.h"
39 #include "chrome/browser/first_run/upgrade_util_win.h"
40 #endif
42 #if defined(ENABLE_RLZ)
43 #include "chrome/browser/rlz/rlz.h"
44 #endif
46 #if defined(OS_CHROMEOS)
47 #include "chrome/browser/chromeos/boot_times_recorder.h"
48 #endif
50 #if defined(ENABLE_PRINT_PREVIEW)
51 #include "chrome/browser/service_process/service_process_control.h"
52 #endif
54 using base::Time;
55 using base::TimeDelta;
56 using content::BrowserThread;
58 namespace browser_shutdown {
59 namespace {
61 // Whether the browser is trying to quit (e.g., Quit chosen from menu).
62 bool g_trying_to_quit = false;
64 #if defined(OS_WIN)
65 upgrade_util::RelaunchMode g_relaunch_mode =
66 upgrade_util::RELAUNCH_MODE_DEFAULT;
67 #endif
69 Time* shutdown_started_ = NULL;
70 ShutdownType shutdown_type_ = NOT_VALID;
71 int shutdown_num_processes_;
72 int shutdown_num_processes_slow_;
74 const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";
76 const char* ToShutdownTypeString(ShutdownType type) {
77 switch (type) {
78 case NOT_VALID:
79 NOTREACHED();
80 return "";
81 case WINDOW_CLOSE:
82 return "close";
83 case BROWSER_EXIT:
84 return "exit";
85 case END_SESSION:
86 return "end";
88 return "";
91 } // namespace
93 void RegisterPrefs(PrefRegistrySimple* registry) {
94 registry->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
95 registry->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
96 registry->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
99 ShutdownType GetShutdownType() {
100 return shutdown_type_;
103 void OnShutdownStarting(ShutdownType type) {
104 if (shutdown_type_ != NOT_VALID)
105 return;
106 base::debug::SetCrashKeyValue(crash_keys::kShutdownType,
107 ToShutdownTypeString(type));
108 #if !defined(OS_CHROMEOS)
109 // Start the shutdown tracing. Note that On ChromeOS we have started this
110 // already.
111 chrome::StartShutdownTracing();
112 #endif
114 shutdown_type_ = type;
115 // For now, we're only counting the number of renderer processes
116 // since we can't safely count the number of plugin processes from this
117 // thread, and we'd really like to avoid anything which might add further
118 // delays to shutdown time.
119 DCHECK(!shutdown_started_);
120 shutdown_started_ = new Time(Time::Now());
122 // Call FastShutdown on all of the RenderProcessHosts. This will be
123 // a no-op in some cases, so we still need to go through the normal
124 // shutdown path for the ones that didn't exit here.
125 shutdown_num_processes_ = 0;
126 shutdown_num_processes_slow_ = 0;
127 for (content::RenderProcessHost::iterator i(
128 content::RenderProcessHost::AllHostsIterator());
129 !i.IsAtEnd(); i.Advance()) {
130 ++shutdown_num_processes_;
131 if (!i.GetCurrentValue()->FastShutdownIfPossible())
132 ++shutdown_num_processes_slow_;
136 base::FilePath GetShutdownMsPath() {
137 base::FilePath shutdown_ms_file;
138 PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
139 return shutdown_ms_file.AppendASCII(kShutdownMsFile);
142 bool ShutdownPreThreadsStop() {
143 #if defined(OS_CHROMEOS)
144 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker(
145 "BrowserShutdownStarted", false);
146 #endif
147 #if defined(ENABLE_PRINT_PREVIEW)
148 // Shutdown the IPC channel to the service processes.
149 ServiceProcessControl::GetInstance()->Disconnect();
150 #endif // ENABLE_PRINT_PREVIEW
152 // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
153 // time to get here. If you have something that *must* happen on end session,
154 // consider putting it in BrowserProcessImpl::EndSession.
155 PrefService* prefs = g_browser_process->local_state();
157 // Log the amount of times the user switched profiles during this session.
158 ProfileMetrics::LogNumberOfProfileSwitches();
160 metrics::MetricsService* metrics = g_browser_process->metrics_service();
161 if (metrics)
162 metrics->RecordCompletedSessionEnd();
164 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
165 // Record the shutdown info so that we can put it into a histogram at next
166 // startup.
167 prefs->SetInteger(prefs::kShutdownType, shutdown_type_);
168 prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);
169 prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
170 shutdown_num_processes_slow_);
173 // Check local state for the restart flag so we can restart the session below.
174 bool restart_last_session = false;
175 if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {
176 restart_last_session =
177 prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);
178 prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
179 #if defined(OS_WIN)
180 if (restart_last_session) {
181 if (prefs->HasPrefPath(prefs::kRelaunchMode)) {
182 g_relaunch_mode = upgrade_util::RelaunchModeStringToEnum(
183 prefs->GetString(prefs::kRelaunchMode));
184 prefs->ClearPref(prefs::kRelaunchMode);
187 #endif
190 prefs->CommitPendingWrite();
192 #if defined(ENABLE_RLZ)
193 // Cleanup any statics created by RLZ. Must be done before NotificationService
194 // is destroyed.
195 RLZTracker::CleanupRlz();
196 #endif
198 return restart_last_session;
201 void ShutdownPostThreadsStop(bool restart_last_session) {
202 delete g_browser_process;
203 g_browser_process = NULL;
205 // crbug.com/95079 - This needs to happen after the browser process object
206 // goes away.
207 ProfileManager::NukeDeletedProfilesFromDisk();
209 #if defined(OS_CHROMEOS)
210 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker("BrowserDeleted",
211 true);
212 #endif
214 #if defined(OS_WIN)
215 if (!browser_util::IsBrowserAlreadyRunning() &&
216 shutdown_type_ != browser_shutdown::END_SESSION) {
217 upgrade_util::SwapNewChromeExeIfPresent();
219 #endif
221 if (restart_last_session) {
222 #if !defined(OS_CHROMEOS)
223 // Make sure to relaunch the browser with the original command line plus
224 // the Restore Last Session flag. Note that Chrome can be launched (ie.
225 // through ShellExecute on Windows) with a switch argument terminator at
226 // the end (double dash, as described in b/1366444) plus a URL,
227 // which prevents us from appending to the command line directly (issue
228 // 46182). We therefore use GetSwitches to copy the command line (it stops
229 // at the switch argument terminator).
230 base::CommandLine old_cl(*base::CommandLine::ForCurrentProcess());
231 scoped_ptr<base::CommandLine> new_cl(
232 new base::CommandLine(old_cl.GetProgram()));
233 std::map<std::string, base::CommandLine::StringType> switches =
234 old_cl.GetSwitches();
235 // Remove the switches that shouldn't persist across restart.
236 about_flags::RemoveFlagsSwitches(&switches);
237 switches::RemoveSwitchesForAutostart(&switches);
238 // Append the old switches to the new command line.
239 for (
240 std::map<std::string, base::CommandLine::StringType>::const_iterator i =
241 switches.begin();
242 i != switches.end(); ++i) {
243 base::CommandLine::StringType switch_value = i->second;
244 if (!switch_value.empty())
245 new_cl->AppendSwitchNative(i->first, i->second);
246 else
247 new_cl->AppendSwitch(i->first);
250 #if defined(OS_WIN)
251 upgrade_util::RelaunchChromeWithMode(*new_cl.get(), g_relaunch_mode);
252 #else
253 upgrade_util::RelaunchChromeBrowser(*new_cl.get());
254 #endif // defined(OS_WIN)
256 #else
257 NOTIMPLEMENTED();
258 #endif // !defined(OS_CHROMEOS)
261 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
262 // Measure total shutdown time as late in the process as possible
263 // and then write it to a file to be read at startup.
264 // We can't use prefs since all services are shutdown at this point.
265 TimeDelta shutdown_delta = Time::Now() - *shutdown_started_;
266 std::string shutdown_ms =
267 base::Int64ToString(shutdown_delta.InMilliseconds());
268 int len = static_cast<int>(shutdown_ms.length()) + 1;
269 base::FilePath shutdown_ms_file = GetShutdownMsPath();
270 base::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
273 #if defined(OS_CHROMEOS)
274 chrome::NotifyAndTerminate(false);
275 #endif
278 void ReadLastShutdownFile(ShutdownType type,
279 int num_procs,
280 int num_procs_slow) {
281 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
283 base::FilePath shutdown_ms_file = GetShutdownMsPath();
284 std::string shutdown_ms_str;
285 int64 shutdown_ms = 0;
286 if (base::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
287 base::StringToInt64(shutdown_ms_str, &shutdown_ms);
288 base::DeleteFile(shutdown_ms_file, false);
290 if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
291 return;
293 const char* time_fmt = "Shutdown.%s.time";
294 const char* time_per_fmt = "Shutdown.%s.time_per_process";
295 std::string time;
296 std::string time_per;
297 if (type == WINDOW_CLOSE) {
298 time = base::StringPrintf(time_fmt, "window_close");
299 time_per = base::StringPrintf(time_per_fmt, "window_close");
300 } else if (type == BROWSER_EXIT) {
301 time = base::StringPrintf(time_fmt, "browser_exit");
302 time_per = base::StringPrintf(time_per_fmt, "browser_exit");
303 } else if (type == END_SESSION) {
304 time = base::StringPrintf(time_fmt, "end_session");
305 time_per = base::StringPrintf(time_per_fmt, "end_session");
306 } else {
307 NOTREACHED();
310 if (time.empty())
311 return;
313 // TODO(erikkay): change these to UMA histograms after a bit more testing.
314 UMA_HISTOGRAM_TIMES(time.c_str(),
315 TimeDelta::FromMilliseconds(shutdown_ms));
316 UMA_HISTOGRAM_TIMES(time_per.c_str(),
317 TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
318 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
319 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
322 void ReadLastShutdownInfo() {
323 PrefService* prefs = g_browser_process->local_state();
324 ShutdownType type =
325 static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
326 int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
327 int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
328 // clear the prefs immediately so we don't pick them up on a future run
329 prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
330 prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
331 prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);
333 // Read and delete the file on the file thread.
334 BrowserThread::PostTask(
335 BrowserThread::FILE, FROM_HERE,
336 base::Bind(&ReadLastShutdownFile, type, num_procs, num_procs_slow));
339 void SetTryingToQuit(bool quitting) {
340 g_trying_to_quit = quitting;
343 bool IsTryingToQuit() {
344 return g_trying_to_quit;
347 } // namespace browser_shutdown