Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / chromecast / browser / cast_browser_main_parts.cc
blob45edf44d13197469e5dcf302f1364e341e19a9b4
1 // Copyright 2014 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 "chromecast/browser/cast_browser_main_parts.h"
7 #if !defined(OS_ANDROID)
8 #include <signal.h>
9 #include <sys/prctl.h>
10 #endif
12 #include "base/command_line.h"
13 #include "base/files/file_util.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_registry_simple.h"
17 #include "base/run_loop.h"
18 #include "cc/base/switches.h"
19 #include "chromecast/base/cast_paths.h"
20 #include "chromecast/base/metrics/cast_metrics_helper.h"
21 #include "chromecast/base/metrics/grouped_histogram.h"
22 #include "chromecast/browser/cast_browser_context.h"
23 #include "chromecast/browser/cast_browser_process.h"
24 #include "chromecast/browser/devtools/remote_debugging_server.h"
25 #include "chromecast/browser/metrics/cast_metrics_prefs.h"
26 #include "chromecast/browser/metrics/cast_metrics_service_client.h"
27 #include "chromecast/browser/pref_service_helper.h"
28 #include "chromecast/browser/service/cast_service.h"
29 #include "chromecast/browser/url_request_context_factory.h"
30 #include "chromecast/common/chromecast_switches.h"
31 #include "chromecast/common/platform_client_auth.h"
32 #include "chromecast/net/connectivity_checker.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "content/public/common/content_switches.h"
35 #include "media/base/browser_cdm_factory.h"
36 #include "media/base/media_switches.h"
38 #if defined(OS_ANDROID)
39 #include "chromecast/crash/android/crash_handler.h"
40 #include "components/crash/browser/crash_dump_manager_android.h"
41 #include "net/android/network_change_notifier_factory_android.h"
42 #else
43 #include "chromecast/browser/media/cast_browser_cdm_factory.h"
44 #endif
46 #if defined(USE_AURA)
47 #include "ui/aura/test/test_screen.h"
48 #include "ui/gfx/screen.h"
49 #endif
51 namespace {
53 #if !defined(OS_ANDROID)
54 int kSignalsToRunClosure[] = { SIGTERM, SIGINT, };
56 // Closure to run on SIGTERM and SIGINT.
57 base::Closure* g_signal_closure = NULL;
59 void RunClosureOnSignal(int signum) {
60 LOG(ERROR) << "Got signal " << signum;
61 DCHECK(g_signal_closure);
62 // Expect main thread got this signal. Otherwise, weak_ptr of run_loop will
63 // crash the process.
64 g_signal_closure->Run();
67 void RegisterClosureOnSignal(const base::Closure& closure) {
68 DCHECK(!g_signal_closure);
69 DCHECK_GT(arraysize(kSignalsToRunClosure), 0U);
71 // Allow memory leak by intention.
72 g_signal_closure = new base::Closure(closure);
74 struct sigaction sa_new;
75 memset(&sa_new, 0, sizeof(sa_new));
76 sa_new.sa_handler = RunClosureOnSignal;
77 sigfillset(&sa_new.sa_mask);
78 sa_new.sa_flags = SA_RESTART;
80 for (size_t i = 0; i < arraysize(kSignalsToRunClosure); i++) {
81 struct sigaction sa_old;
82 if (sigaction(kSignalsToRunClosure[i], &sa_new, &sa_old) == -1) {
83 NOTREACHED();
84 } else {
85 DCHECK_EQ(sa_old.sa_handler, SIG_DFL);
89 // Get the first signal to exit when the parent process dies.
90 prctl(PR_SET_PDEATHSIG, kSignalsToRunClosure[0]);
93 const int kKillOnAlarmTimeoutSec = 5; // 5 seconds
95 void KillOnAlarm(int signum) {
96 LOG(ERROR) << "Got alarm signal for termination: " << signum;
97 raise(SIGKILL);
100 void RegisterKillOnAlarm(int timeout_seconds) {
101 struct sigaction sa_new;
102 memset(&sa_new, 0, sizeof(sa_new));
103 sa_new.sa_handler = KillOnAlarm;
104 sigfillset(&sa_new.sa_mask);
105 sa_new.sa_flags = SA_RESTART;
107 struct sigaction sa_old;
108 if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) {
109 NOTREACHED();
110 } else {
111 DCHECK_EQ(sa_old.sa_handler, SIG_DFL);
114 if (alarm(timeout_seconds) > 0)
115 NOTREACHED() << "Previous alarm() was cancelled";
118 void DeregisterKillOnAlarm() {
119 // Explicitly cancel any outstanding alarm() calls.
120 alarm(0);
122 struct sigaction sa_new;
123 memset(&sa_new, 0, sizeof(sa_new));
124 sa_new.sa_handler = SIG_DFL;
125 sigfillset(&sa_new.sa_mask);
126 sa_new.sa_flags = SA_RESTART;
128 struct sigaction sa_old;
129 if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) {
130 NOTREACHED();
131 } else {
132 DCHECK_EQ(sa_old.sa_handler, KillOnAlarm);
135 #endif // !defined(OS_ANDROID)
137 } // namespace
139 namespace chromecast {
140 namespace shell {
142 namespace {
144 struct DefaultCommandLineSwitch {
145 const char* const switch_name;
146 const char* const switch_value;
149 DefaultCommandLineSwitch g_default_switches[] = {
150 #if defined(OS_ANDROID)
151 // Disables Chromecast-specific WiFi-related features on ATV for now.
152 { switches::kNoWifi, "" },
153 { switches::kEnableOverlayFullscreenVideo, ""},
154 { switches::kDisableInfobarForProtectedMediaIdentifier, ""},
155 { switches::kDisableGestureRequirementForMediaPlayback, ""},
156 #endif
157 // Always enable HTMLMediaElement logs.
158 { switches::kBlinkPlatformLogChannels, "Media"},
159 #if defined(DISABLE_DISPLAY)
160 { switches::kDisableGpu, "" },
161 #endif
162 #if defined(OS_LINUX)
163 #if defined(ARCH_CPU_X86_FAMILY)
164 // This is needed for now to enable the egltest Ozone platform to work with
165 // current Linux/NVidia OpenGL drivers.
166 { switches::kIgnoreGpuBlacklist, ""},
167 #elif defined(ARCH_CPU_ARM_FAMILY) && !defined(DISABLE_DISPLAY)
168 // On Linux arm, enable CMA pipeline by default.
169 { switches::kEnableCmaMediaPipeline, "" },
170 #endif
171 #endif // defined(OS_LINUX)
172 // Needed to fix a bug where the raster thread doesn't get scheduled for a
173 // substantial time (~5 seconds). See https://crbug.com/441895.
174 { switches::kUseNormalPriorityForTileTaskWorkerThreads, "" },
175 { NULL, NULL }, // Termination
178 void AddDefaultCommandLineSwitches(base::CommandLine* command_line) {
179 int i = 0;
180 while (g_default_switches[i].switch_name != NULL) {
181 command_line->AppendSwitchASCII(
182 std::string(g_default_switches[i].switch_name),
183 std::string(g_default_switches[i].switch_value));
184 ++i;
188 } // namespace
190 CastBrowserMainParts::CastBrowserMainParts(
191 const content::MainFunctionParams& parameters,
192 URLRequestContextFactory* url_request_context_factory)
193 : BrowserMainParts(),
194 cast_browser_process_(new CastBrowserProcess()),
195 parameters_(parameters),
196 url_request_context_factory_(url_request_context_factory) {
197 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
198 AddDefaultCommandLineSwitches(command_line);
201 CastBrowserMainParts::~CastBrowserMainParts() {
204 void CastBrowserMainParts::PreMainMessageLoopStart() {
205 // GroupedHistograms needs to be initialized before any threads are created
206 // to prevent race conditions between calls to Preregister and those threads
207 // attempting to collect metrics.
208 // This call must also be before NetworkChangeNotifier, as it generates
209 // Net/DNS metrics.
210 metrics::PreregisterAllGroupedHistograms();
212 #if defined(OS_ANDROID)
213 net::NetworkChangeNotifier::SetFactory(
214 new net::NetworkChangeNotifierFactoryAndroid());
215 #endif // defined(OS_ANDROID)
218 void CastBrowserMainParts::PostMainMessageLoopStart() {
219 cast_browser_process_->SetMetricsHelper(make_scoped_ptr(
220 new metrics::CastMetricsHelper(base::MessageLoopProxy::current())));
222 #if defined(OS_ANDROID)
223 base::MessageLoopForUI::current()->Start();
224 #endif // defined(OS_ANDROID)
227 int CastBrowserMainParts::PreCreateThreads() {
228 #if defined(OS_ANDROID)
229 // GPU process is started immediately after threads are created, requiring
230 // CrashDumpManager to be initialized beforehand.
231 base::FilePath crash_dumps_dir;
232 if (!chromecast::CrashHandler::GetCrashDumpLocation(&crash_dumps_dir)) {
233 LOG(ERROR) << "Could not find crash dump location.";
235 cast_browser_process_->SetCrashDumpManager(
236 make_scoped_ptr(new breakpad::CrashDumpManager(crash_dumps_dir)));
237 #else
238 base::FilePath home_dir;
239 CHECK(PathService::Get(DIR_CAST_HOME, &home_dir));
240 if (!base::CreateDirectory(home_dir))
241 return 1;
242 #endif
244 #if defined(USE_AURA)
245 // Screen can (and should) exist even with no displays connected. Its presence
246 // is assumed as an interface to access display information, e.g. from metrics
247 // code. See CastContentWindow::CreateWindowTree for update when resolution
248 // is available.
249 DCHECK(!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE));
250 gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE,
251 aura::TestScreen::Create(gfx::Size(0, 0)));
252 #endif
253 return 0;
256 void CastBrowserMainParts::PreMainMessageLoopRun() {
257 scoped_refptr<PrefRegistrySimple> pref_registry(new PrefRegistrySimple());
258 metrics::RegisterPrefs(pref_registry.get());
259 cast_browser_process_->SetPrefService(
260 PrefServiceHelper::CreatePrefService(pref_registry.get()));
262 #if !defined(OS_ANDROID)
263 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
264 if (cmd_line->HasSwitch(switches::kEnableCmaMediaPipeline))
265 ::media::SetBrowserCdmFactory(new media::CastBrowserCdmFactory);
266 #endif // !defined(OS_ANDROID)
268 cast_browser_process_->SetConnectivityChecker(
269 make_scoped_refptr(new ConnectivityChecker(
270 content::BrowserThread::GetMessageLoopProxyForThread(
271 content::BrowserThread::IO))));
273 url_request_context_factory_->InitializeOnUIThread();
275 cast_browser_process_->SetBrowserContext(
276 make_scoped_ptr(new CastBrowserContext(url_request_context_factory_)));
277 cast_browser_process_->SetMetricsServiceClient(
278 metrics::CastMetricsServiceClient::Create(
279 content::BrowserThread::GetBlockingPool(),
280 cast_browser_process_->pref_service(),
281 cast_browser_process_->browser_context()->GetRequestContext()));
283 if (!PlatformClientAuth::Initialize())
284 LOG(ERROR) << "PlatformClientAuth::Initialize failed.";
286 cast_browser_process_->SetRemoteDebuggingServer(
287 make_scoped_ptr(new RemoteDebuggingServer()));
289 cast_browser_process_->SetCastService(CastService::Create(
290 cast_browser_process_->browser_context(),
291 cast_browser_process_->pref_service(),
292 cast_browser_process_->metrics_service_client(),
293 url_request_context_factory_->GetSystemGetter()));
294 cast_browser_process_->cast_service()->Initialize();
296 // Initializing metrics service and network delegates must happen after cast
297 // service is intialized because CastMetricsServiceClient and
298 // CastNetworkDelegate may use components initialized by cast service.
299 cast_browser_process_->metrics_service_client()
300 ->Initialize(cast_browser_process_->cast_service());
301 url_request_context_factory_->InitializeNetworkDelegates();
303 cast_browser_process_->cast_service()->Start();
306 bool CastBrowserMainParts::MainMessageLoopRun(int* result_code) {
307 #if defined(OS_ANDROID)
308 // Android does not use native main MessageLoop.
309 NOTREACHED();
310 return true;
311 #else
312 base::RunLoop run_loop;
313 base::Closure quit_closure(run_loop.QuitClosure());
314 RegisterClosureOnSignal(quit_closure);
316 // If parameters_.ui_task is not NULL, we are running browser tests.
317 if (parameters_.ui_task) {
318 base::MessageLoop* message_loop = base::MessageLoopForUI::current();
319 message_loop->PostTask(FROM_HERE, *parameters_.ui_task);
320 message_loop->PostTask(FROM_HERE, quit_closure);
323 run_loop.Run();
325 // Once the main loop has stopped running, we give the browser process a few
326 // seconds to stop cast service and finalize all resources. If a hang occurs
327 // and cast services refuse to terminate successfully, then we SIGKILL the
328 // current process to avoid indefinte hangs.
329 RegisterKillOnAlarm(kKillOnAlarmTimeoutSec);
331 cast_browser_process_->cast_service()->Stop();
332 return true;
333 #endif
336 void CastBrowserMainParts::PostMainMessageLoopRun() {
337 #if defined(OS_ANDROID)
338 // Android does not use native main MessageLoop.
339 NOTREACHED();
340 #else
341 cast_browser_process_->cast_service()->Finalize();
342 cast_browser_process_->metrics_service_client()->Finalize();
343 cast_browser_process_.reset();
344 DeregisterKillOnAlarm();
345 #endif
348 } // namespace shell
349 } // namespace chromecast