forked from keyou/chromium_demo
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdemo_services.cc
406 lines (367 loc) · 16.4 KB
/
demo_services.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#include "base/at_exit.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/no_destructor.h"
#include "base/task/post_task.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/thread_pool/thread_pool_instance.h"
//#include "base/task/task_scheduler/task_scheduler.h"
#include <mojo/core/embedder/embedder.h>
#include <mojo/core/embedder/scoped_ipc_support.h>
#include "mojo/public/c/system/buffer.h"
#include "mojo/public/c/system/data_pipe.h"
#include "mojo/public/c/system/message_pipe.h"
#include "mojo/public/cpp/system/buffer.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "mojo/public/cpp/system/wait.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
// For services
#include "services/service_manager/embedder/main.h"
#include "services/service_manager/embedder/main_delegate.h"
#include "services/service_manager/embedder/switches.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/manifest.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#include "services/service_manager/public/cpp/service.h"
#include "services/service_manager/public/cpp/service_binding.h"
#include "services/service_manager/public/cpp/service_executable/service_executable_environment.h"
#include "services/service_manager/public/cpp/service_executable/switches.h"
#include "services/service_manager/sandbox/sandbox_type.h"
#include "services/service_manager/sandbox/switches.h"
#include "services/service_manager/service_manager.h"
#include "services/service_manager/service_process_host.h"
#include "services/service_manager/service_process_launcher.h"
#include "services/service_manager/service_process_launcher_delegate.h"
#include "demo/mojom/test_service.mojom.h"
// 在新版本中这些类被重命名,这里模拟新版本
// template <class T>
// using Remote = mojo::InterfacePtr<T>;
// template <class T>
// using PendingRemote = mojo::InterfacePtrInfo<T>;
// template <class T>
// using Receiver = mojo::Binding<T>;
// template <class T>
// using PendingReceiver = mojo::InterfaceRequest<T>;
// template <class T>
// using ReceiverSet = mojo::BindingSet<T>;
using namespace demo::mojom;
using namespace mojo;
class TestInterfaceImpl : public demo::mojom::TestInterface {
public:
TestInterfaceImpl(PendingReceiver<TestInterface> receiver)
: receiver_(this, std::move(receiver)) {}
void Hello(const std::string& who) {
LOG(INFO) << "TestInterfaceImpl run: Hello " << who;
}
private:
// 也可以用StrongBinding
// 要想让当前接口的一个实例可以服务多个Remote,这里可以使用ReceiverSet
Receiver<demo::mojom::TestInterface> receiver_;
};
// 这里故意把Service的实现和接口的实现分开,因为很多情况下一个Service会提供多个接口
class TestService : public service_manager::Service {
public:
TestService(service_manager::mojom::ServiceRequest request) {
service_binding_ = std::make_unique<service_manager::ServiceBinding>(
this, std::move(request));
}
TestService() {
service_binding_ = std::make_unique<service_manager::ServiceBinding>(this);
}
void OnStart() override {
LOG(INFO) << "TestService Start.";
// 演示从一个服务内请求其它服务提供的接口
Remote<RootInterface> root;
service_binding_->GetConnector()->BindInterface(
"consumer_service", root.BindNewPipeAndPassReceiver());
root->Hi("TestService");
}
// 当其他服务调用connector->Connect()时会触发这里
void OnBindInterface(const service_manager::BindSourceInfo& source,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) override {
LOG(INFO) << "OnBindInterface: " << interface_name;
// 如果当前服务提供多个接口,可以使用BinderRegistry消除这里大量的if/else
if (interface_name == TestInterface::Name_) {
// 这样写有个bug,只有最后一个发起服务请求的Remote有效,因为前面的pipe被销毁了
// 要想保证一个TestInterfaceImpl实例可以服务多个Remote,可以在TestInterface的实现中使用ReceiverSet
test_interface_.reset(new TestInterfaceImpl(
PendingReceiver<TestInterface>(std::move(interface_pipe))));
}
}
private:
std::unique_ptr<TestInterfaceImpl> test_interface_;
// 这里为了demo简单,不使用BinderRegistry
// service_manager::BinderRegistry registry_;
std::unique_ptr<service_manager::ServiceBinding> service_binding_;
};
const service_manager::Manifest& GetTestManifest() {
static base::NoDestructor<service_manager::Manifest> manifest{
service_manager::ManifestBuilder()
.WithServiceName("test_service")
.WithOptions(
service_manager::ManifestOptionsBuilder()
.WithExecutionMode(service_manager::Manifest::ExecutionMode::
kOutOfProcessBuiltin)
.WithSandboxType("none")
.Build())
.ExposeCapability("test", service_manager::Manifest::InterfaceList<
demo::mojom::TestInterface>())
.RequireCapability("consumer_service", "root")
.Build()};
return *manifest;
}
class RootInterfaceImpl : public demo::mojom::RootInterface {
public:
RootInterfaceImpl(PendingReceiver<RootInterface> receiver)
: receiver_(this, std::move(receiver)) {}
void Hi(const std::string& who) override {
LOG(INFO) << "RootInterfaceImpl run: Hi " << who;
}
private:
Receiver<RootInterface> receiver_;
};
class ConsumerService : public service_manager::Service {
public:
ConsumerService() : service_binding_(this) {}
ConsumerService(service_manager::mojom::ServiceRequest request)
: service_binding_(this, std::move(request)) {}
void OnStart() override { LOG(INFO) << "ConsumerService Start."; }
void OnBindInterface(const service_manager::BindSourceInfo& source,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) override {
LOG(INFO) << "OnBindInterface: " << interface_name;
// 如果当前服务提供多个接口,可以使用BinderRegistry消除这里大量的if/else
if (interface_name == RootInterface::Name_) {
// 这样写有个bug,只有最后一个发起服务请求的Remote有效,因为前面的pipe被销毁了
// 要想保证一个TestInterfaceImpl实例可以服务多个Remote,可以在TestInterface的实现中使用ReceiverSet
root_interface_.reset(new RootInterfaceImpl(
PendingReceiver<RootInterface>(std::move(interface_pipe))));
}
}
private:
std::unique_ptr<RootInterfaceImpl> root_interface_;
service_manager::ServiceBinding service_binding_;
};
const service_manager::Manifest& GetConsumerManifest() {
static base::NoDestructor<service_manager::Manifest> manifest{
service_manager::ManifestBuilder()
.WithServiceName("consumer_service")
.ExposeCapability("root", service_manager::Manifest::InterfaceList<
demo::mojom::RootInterface>())
.RequireCapability("test_service", "test")
.Build()};
return *manifest;
}
const char kProcessTypeEmbedderService[] = "service-embedder";
class ServiceProcessLauncherDelegateImpl
: public service_manager::ServiceProcessLauncherDelegate {
public:
explicit ServiceProcessLauncherDelegateImpl(
service_manager::MainDelegate* main_delegate)
: main_delegate_(main_delegate) {}
~ServiceProcessLauncherDelegateImpl() override {}
private:
// service_manager::ServiceProcessLauncherDelegate:
void AdjustCommandLineArgumentsForTarget(
const service_manager::Identity& target,
base::CommandLine* command_line) override {
if (main_delegate_->ShouldLaunchAsServiceProcess(target)) {
// 本来应该是 service_manager::switches::kProcessTypeService ,但是它有bug
command_line->AppendSwitchASCII(service_manager::switches::kProcessType,
kProcessTypeEmbedderService);
}
main_delegate_->AdjustServiceProcessCommandLine(target, command_line);
}
service_manager::MainDelegate* const main_delegate_;
DISALLOW_COPY_AND_ASSIGN(ServiceProcessLauncherDelegateImpl);
};
class DemoServiceProcessHost : public service_manager::ServiceProcessHost {
public:
DemoServiceProcessHost(ServiceProcessLauncherDelegateImpl* delegate_)
: launcher_(delegate_,
base::CommandLine::ForCurrentProcess()->GetProgram()) {}
mojo::PendingRemote<service_manager::mojom::Service> Launch(
const service_manager::Identity& identity,
service_manager::SandboxType sandbox_type,
const base::string16& display_name,
LaunchCallback callback) override {
return launcher_
.Start(identity, service_manager::SandboxType::SANDBOX_TYPE_NO_SANDBOX,
std::move(callback))
.PassInterface();
}
private:
service_manager::ServiceProcessLauncher launcher_;
};
class DemoServiceManagerDelegate
: public service_manager::ServiceManager::Delegate {
public:
DemoServiceManagerDelegate(ServiceProcessLauncherDelegateImpl* delegate)
: delegate_(delegate) {}
// 用于启动独立进程的服务
std::unique_ptr<service_manager::ServiceProcessHost>
CreateProcessHostForBuiltinServiceInstance(
const service_manager::Identity& identity) override {
return std::make_unique<DemoServiceProcessHost>(delegate_);
}
//用于启动运行在ServiceManager进程中的服务
bool RunBuiltinServiceInstanceInCurrentProcess(
const service_manager::Identity& identity,
mojo::PendingReceiver<service_manager::mojom::Service> receiver)
override {
LOG(INFO) << "RunBuiltinServiceInstanceInCurrentProcess";
// 在实际代码中需要考虑如何维护Service实例,而不是像这样泄露
new ConsumerService(std::move(receiver));
return true;
}
//用于启动运行在专门的服务进程中的服务
std::unique_ptr<service_manager::ServiceProcessHost>
CreateProcessHostForServiceExecutable(
const base::FilePath& executable_path) override {
LOG(INFO) << "CreateProcessHostForServiceExecutable";
return nullptr;
}
private:
ServiceProcessLauncherDelegateImpl* delegate_;
};
class DemoServerManagerMainDelegate : public service_manager::MainDelegate {
public:
int Initialize(
const service_manager::MainDelegate::InitializeParams& params) override {
// 设置日志格式
logging::SetLogItems(true, false, true, false);
LOG(INFO) << "Command Line: "
<< base::CommandLine::ForCurrentProcess()->GetCommandLineString();
return -1;
}
// service_manager
// 在调用RunEmbedderProcess之前已经执行了很多必要的初始化动作,包括:
// - 初始化CommanLine
// - 初始化mojo
int RunEmbedderProcess() override {
LOG(INFO) << "RunEmbedderProcess";
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
if (command_line->GetSwitchValueASCII(
service_manager::switches::kProcessType) ==
kProcessTypeEmbedderService) {
std::string service_name =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
service_manager::switches::kServiceName);
if (service_name.empty()) {
LOG(ERROR) << "Service process requires --service-name";
return 1;
}
// 在它之前不能有MessageLoop或其等价类
service_manager::ServiceExecutableEnvironment environment;
// 用MessageLoop也可以
base::SingleThreadTaskExecutor main_task_executor;
auto service = this->CreateEmbeddedService(
service_name, environment.TakeServiceRequestFromCommandLine());
service->RunUntilTermination();
base::ThreadPoolInstance::Get()->Shutdown();
return 0;
}
// 创建主消息循环
base::MessageLoop message_loop;
// 初始化线程池,会创建新的线程,在新的线程中会创建新消息循环MessageLoop
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Demo");
base::Thread ipc_thread("IPC thread");
ipc_thread.StartWithOptions(
base::Thread::Options(base::MessagePumpType::IO, 0));
mojo::core::ScopedIPCSupport ipc_support(
ipc_thread.task_runner(),
mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST);
ServiceProcessLauncherDelegateImpl service_process_launcher_delegate(this);
// service_manager::BackgroundServiceManager service_manager(
// &service_process_launcher_delegate, this->GetServiceManifests());
auto service_manager = std::make_unique<service_manager::ServiceManager>(
this->GetServiceManifests(),
std::make_unique<DemoServiceManagerDelegate>(
&service_process_launcher_delegate));
// auto service_manager = std::make_unique<service_manager::ServiceManager>(
// this->GetServiceManifests(),service_manager::ServiceManager::ServiceExecutablePolicy::kSupported);
// 可以使用以下方式手动启动一个Service
service_manager->StartService("test_service");
// service_manager.StartService(service_manager::Identity("consumer_service"));
// 手动注册一个Service实例
// mojom::ServicePtr service;
// context_ =
// std::make_unique<ServiceContext>(std::make_unique<ConsumerService>(),mojo::MakeRequest(&service));
// service_manager.RegisterService(service_manager::Identity("consumer_service",
// mojom::kRootUserID),std::move(service),nullptr);
// 即使服务请求由自己提供的接口也需要权限
// demo::mojom::RootInterfacePtr root;
// context_->connector()->BindInterface("consumer_service", &root);
// root->Hi("consumer_service");
// 演示通过consumer_service的context请求由test_service服务提供的test接口
// demo::mojom::TestInterfacePtr test;
// context_->connector()->BindInterface("test_service", &test);
// test->Hello("consumer_service");
LOG(INFO) << "running...";
base::RunLoop().Run();
ipc_thread.Stop();
base::ThreadPoolInstance::Get()->Shutdown();
return 0;
}
std::vector<service_manager::Manifest> GetServiceManifests() override {
LOG(INFO) << "GetServiceManifests";
return std::vector<service_manager::Manifest>(
{GetTestManifest(), GetConsumerManifest()});
}
service_manager::ProcessType OverrideProcessType() override {
LOG(INFO) << "OverrideProcessType";
return service_manager::ProcessType::kDefault;
}
void OnServiceManagerInitialized(
base::OnceClosure quit_closure,
service_manager::BackgroundServiceManager* service_manager) override {
LOG(INFO) << "OnServiceManagerInitialized";
}
bool ShouldLaunchAsServiceProcess(
const service_manager::Identity& identity) override {
return true;
}
void AdjustServiceProcessCommandLine(
const service_manager::Identity& identity,
base::CommandLine* command_line) override {
if (identity.name() == "consumer_service") {
// command_line->AppendSwitchASCII();
}
}
// 在Service进程中被调用,用来创建Service实例
std::unique_ptr<service_manager::Service> CreateEmbeddedService(
const std::string& service_name) override {
return CreateEmbeddedService(service_name, nullptr);
}
std::unique_ptr<service_manager::Service> CreateEmbeddedService(
const std::string& service_name,
service_manager::mojom::ServiceRequest request) {
LOG(INFO) << "CreateEmbeddedService: " << service_name;
if (service_name == "test_service") {
return std::make_unique<TestService>(std::move(request));
}
if (service_name == "consumer_service") {
return std::make_unique<ConsumerService>(std::move(request));
}
return nullptr;
}
};
int main(int argc, const char** argv) {
base::AtExitManager at_exit;
DemoServerManagerMainDelegate delegate;
service_manager::MainParams main_params(&delegate);
main_params.argc = argc;
main_params.argv = argv;
return service_manager::Main(main_params);
}