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/service_process/service_process_control.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/metrics/histogram_base.h"
12 #include "base/metrics/histogram_delta_serialization.h"
13 #include "base/process/kill.h"
14 #include "base/process/launch.h"
15 #include "base/stl_util.h"
16 #include "base/threading/thread.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "chrome/browser/browser_process.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/upgrade_detector.h"
21 #include "chrome/common/service_messages.h"
22 #include "chrome/common/service_process_util.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "content/public/browser/notification_service.h"
26 using content::BrowserThread
;
30 // Test: On Mac, launchd_msg_send tries to allocate a 10MB buffer, but doesn't
31 // handle errors and makes ugly crash dumps when close to OOM.
32 // TODO(vitalybuka): Remove after few Canary builds.
33 // See http://crbug.com/406227
34 void AllocDebugTest() {
35 #if defined(OS_MACOSX)
36 void* buffer
= malloc(20 * 1024 * 1024);
44 // ServiceProcessControl implementation.
45 ServiceProcessControl::ServiceProcessControl() {
48 ServiceProcessControl::~ServiceProcessControl() {
51 void ServiceProcessControl::ConnectInternal() {
52 // If the channel has already been established then we run the task
55 RunConnectDoneTasks();
59 // Actually going to connect.
60 VLOG(1) << "Connecting to Service Process IPC Server";
62 // TODO(hclam): Handle error connecting to channel.
63 const IPC::ChannelHandle channel_id
= GetServiceProcessChannel();
64 SetChannel(IPC::ChannelProxy::Create(
66 IPC::Channel::MODE_NAMED_CLIENT
,
68 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
).get()));
71 void ServiceProcessControl::SetChannel(scoped_ptr
<IPC::ChannelProxy
> channel
) {
72 channel_
= channel
.Pass();
75 void ServiceProcessControl::RunConnectDoneTasks() {
76 // The tasks executed here may add more tasks to the vector. So copy
77 // them to the stack before executing them. This way recursion is
82 tasks
.swap(connect_success_tasks_
);
83 RunAllTasksHelper(&tasks
);
84 DCHECK(tasks
.empty());
85 connect_failure_tasks_
.clear();
87 tasks
.swap(connect_failure_tasks_
);
88 RunAllTasksHelper(&tasks
);
89 DCHECK(tasks
.empty());
90 connect_success_tasks_
.clear();
95 void ServiceProcessControl::RunAllTasksHelper(TaskList
* task_list
) {
96 TaskList::iterator index
= task_list
->begin();
97 while (index
!= task_list
->end()) {
99 index
= task_list
->erase(index
);
103 bool ServiceProcessControl::IsConnected() const {
104 return channel_
!= NULL
;
107 void ServiceProcessControl::Launch(const base::Closure
& success_task
,
108 const base::Closure
& failure_task
) {
109 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
111 base::Closure failure
= failure_task
;
112 if (!success_task
.is_null())
113 connect_success_tasks_
.push_back(success_task
);
115 if (!failure
.is_null())
116 connect_failure_tasks_
.push_back(failure
);
118 // If we already in the process of launching, then we are done.
122 // If the service process is already running then connects to it.
123 if (CheckServiceProcessReady()) {
128 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCH
,
131 scoped_ptr
<base::CommandLine
> cmd_line(CreateServiceProcessCommandLine());
132 // And then start the process asynchronously.
133 launcher_
= new Launcher(this, cmd_line
.Pass());
134 launcher_
->Run(base::Bind(&ServiceProcessControl::OnProcessLaunched
,
135 base::Unretained(this)));
138 void ServiceProcessControl::Disconnect() {
139 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
143 void ServiceProcessControl::OnProcessLaunched() {
144 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
145 if (launcher_
->launched()) {
146 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
147 SERVICE_EVENT_LAUNCHED
, SERVICE_EVENT_MAX
);
148 // After we have successfully created the service process we try to connect
149 // to it. The launch task is transfered to a connect task.
152 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
153 SERVICE_EVENT_LAUNCH_FAILED
, SERVICE_EVENT_MAX
);
154 // If we don't have process handle that means launching the service process
156 RunConnectDoneTasks();
159 // We don't need the launcher anymore.
163 bool ServiceProcessControl::OnMessageReceived(const IPC::Message
& message
) {
165 IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl
, message
)
166 IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_Info
,
167 OnCloudPrintProxyInfo
)
168 IPC_MESSAGE_HANDLER(ServiceHostMsg_Histograms
, OnHistograms
)
169 IPC_MESSAGE_HANDLER(ServiceHostMsg_Printers
, OnPrinters
)
170 IPC_MESSAGE_UNHANDLED(handled
= false)
171 IPC_END_MESSAGE_MAP()
175 void ServiceProcessControl::OnChannelConnected(int32 peer_pid
) {
176 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
178 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
179 SERVICE_EVENT_CHANNEL_CONNECTED
, SERVICE_EVENT_MAX
);
181 // We just established a channel with the service process. Notify it if an
182 // upgrade is available.
183 if (UpgradeDetector::GetInstance()->notify_upgrade()) {
184 Send(new ServiceMsg_UpdateAvailable
);
186 if (registrar_
.IsEmpty())
187 registrar_
.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED
,
188 content::NotificationService::AllSources());
190 RunConnectDoneTasks();
193 void ServiceProcessControl::OnChannelError() {
194 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
196 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
197 SERVICE_EVENT_CHANNEL_ERROR
, SERVICE_EVENT_MAX
);
200 RunConnectDoneTasks();
203 bool ServiceProcessControl::Send(IPC::Message
* message
) {
204 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
207 return channel_
->Send(message
);
210 // content::NotificationObserver implementation.
211 void ServiceProcessControl::Observe(
213 const content::NotificationSource
& source
,
214 const content::NotificationDetails
& details
) {
215 if (type
== chrome::NOTIFICATION_UPGRADE_RECOMMENDED
) {
216 Send(new ServiceMsg_UpdateAvailable
);
220 void ServiceProcessControl::OnCloudPrintProxyInfo(
221 const cloud_print::CloudPrintProxyInfo
& proxy_info
) {
222 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
223 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
224 SERVICE_EVENT_INFO_REPLY
, SERVICE_EVENT_MAX
);
225 if (!cloud_print_info_callback_
.is_null()) {
226 cloud_print_info_callback_
.Run(proxy_info
);
227 cloud_print_info_callback_
.Reset();
231 void ServiceProcessControl::OnHistograms(
232 const std::vector
<std::string
>& pickled_histograms
) {
233 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
234 SERVICE_EVENT_HISTOGRAMS_REPLY
, SERVICE_EVENT_MAX
);
235 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
236 base::HistogramDeltaSerialization::DeserializeAndAddSamples(
238 RunHistogramsCallback();
241 void ServiceProcessControl::RunHistogramsCallback() {
243 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
244 if (!histograms_callback_
.is_null()) {
245 histograms_callback_
.Run();
246 histograms_callback_
.Reset();
248 histograms_timeout_callback_
.Cancel();
251 void ServiceProcessControl::OnPrinters(
252 const std::vector
<std::string
>& printers
) {
253 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
254 UMA_HISTOGRAM_ENUMERATION(
255 "CloudPrint.ServiceEvents", SERVICE_PRINTERS_REPLY
, SERVICE_EVENT_MAX
);
256 UMA_HISTOGRAM_COUNTS_10000("CloudPrint.AvailablePrinters", printers
.size());
257 if (!printers_callback_
.is_null()) {
258 printers_callback_
.Run(printers
);
259 printers_callback_
.Reset();
263 bool ServiceProcessControl::GetCloudPrintProxyInfo(
264 const CloudPrintProxyInfoCallback
& cloud_print_info_callback
) {
265 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
266 DCHECK(!cloud_print_info_callback
.is_null());
267 cloud_print_info_callback_
.Reset();
268 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
269 SERVICE_EVENT_INFO_REQUEST
, SERVICE_EVENT_MAX
);
270 if (!Send(new ServiceMsg_GetCloudPrintProxyInfo()))
272 cloud_print_info_callback_
= cloud_print_info_callback
;
276 bool ServiceProcessControl::GetHistograms(
277 const base::Closure
& histograms_callback
,
278 const base::TimeDelta
& timeout
) {
280 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
281 DCHECK(!histograms_callback
.is_null());
282 histograms_callback_
.Reset();
284 // If the service process is already running then connect to it.
285 if (!CheckServiceProcessReady())
289 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
290 SERVICE_EVENT_HISTOGRAMS_REQUEST
,
293 if (!Send(new ServiceMsg_GetHistograms()))
296 // Run timeout task to make sure |histograms_callback| is called.
297 histograms_timeout_callback_
.Reset(
298 base::Bind(&ServiceProcessControl::RunHistogramsCallback
,
299 base::Unretained(this)));
300 BrowserThread::PostDelayedTask(BrowserThread::UI
, FROM_HERE
,
301 histograms_timeout_callback_
.callback(),
304 histograms_callback_
= histograms_callback
;
308 bool ServiceProcessControl::GetPrinters(
309 const PrintersCallback
& printers_callback
) {
310 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
311 DCHECK(!printers_callback
.is_null());
312 printers_callback_
.Reset();
313 UMA_HISTOGRAM_ENUMERATION(
314 "CloudPrint.ServiceEvents", SERVICE_PRINTERS_REQUEST
, SERVICE_EVENT_MAX
);
315 if (!Send(new ServiceMsg_GetPrinters()))
317 printers_callback_
= printers_callback
;
321 bool ServiceProcessControl::Shutdown() {
322 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
323 bool ret
= Send(new ServiceMsg_Shutdown());
329 ServiceProcessControl
* ServiceProcessControl::GetInstance() {
330 return Singleton
<ServiceProcessControl
>::get();
333 ServiceProcessControl::Launcher::Launcher(
334 ServiceProcessControl
* process
,
335 scoped_ptr
<base::CommandLine
> cmd_line
)
337 cmd_line_(cmd_line
.Pass()),
340 process_handle_(base::kNullProcessHandle
) {
343 // Execute the command line to start the process asynchronously.
344 // After the command is executed, |task| is called with the process handle on
346 void ServiceProcessControl::Launcher::Run(const base::Closure
& task
) {
347 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
349 BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER
, FROM_HERE
,
350 base::Bind(&Launcher::DoRun
, this));
353 ServiceProcessControl::Launcher::~Launcher() {
354 CloseProcessHandle();
358 void ServiceProcessControl::Launcher::Notify() {
359 DCHECK(!notify_task_
.is_null());
361 notify_task_
.Reset();
364 void ServiceProcessControl::Launcher::CloseProcessHandle() {
365 if (process_handle_
!= base::kNullProcessHandle
) {
366 base::CloseProcessHandle(process_handle_
);
367 process_handle_
= base::kNullProcessHandle
;
371 #if !defined(OS_MACOSX)
372 void ServiceProcessControl::Launcher::DoDetectLaunched() {
373 DCHECK(!notify_task_
.is_null());
375 const uint32 kMaxLaunchDetectRetries
= 10;
376 launched_
= CheckServiceProcessReady();
379 if (launched_
|| (retry_count_
>= kMaxLaunchDetectRetries
) ||
380 base::WaitForExitCodeWithTimeout(process_handle_
, &exit_code
,
381 base::TimeDelta())) {
382 CloseProcessHandle();
383 BrowserThread::PostTask(
384 BrowserThread::UI
, FROM_HERE
, base::Bind(&Launcher::Notify
, this));
389 // If the service process is not launched yet then check again in 2 seconds.
390 const base::TimeDelta kDetectLaunchRetry
= base::TimeDelta::FromSeconds(2);
391 base::MessageLoop::current()->PostDelayedTask(
392 FROM_HERE
, base::Bind(&Launcher::DoDetectLaunched
, this),
396 void ServiceProcessControl::Launcher::DoRun() {
397 DCHECK(!notify_task_
.is_null());
399 base::LaunchOptions options
;
401 options
.start_hidden
= true;
403 if (base::LaunchProcess(*cmd_line_
, options
, &process_handle_
)) {
404 BrowserThread::PostTask(
405 BrowserThread::IO
, FROM_HERE
,
406 base::Bind(&Launcher::DoDetectLaunched
, this));
408 BrowserThread::PostTask(
409 BrowserThread::UI
, FROM_HERE
, base::Bind(&Launcher::Notify
, this));