README.md
1# Samgr
2## Introduction
3
4The System Ability Manager (Samgr) component is a core component of OpenHarmony. It provides functions related to system abilities (also called system services), including the startup, registration, and query.
5
6## System Architecture
7
8Figure 1 Architecture of Samgr
9
10
11
12
13## Directory Structure
14
15```
16/foundation/systemabilitymgr
17├── samgr
18│ ├── bundle.json # Description and build file of Samgr
19│ ├── frameworks # Framework implementation
20│ ├── interfaces # APIs
21│ ├── services # Directory for the Samgr service
22│ ├── test # Test code
23│ ├── utils # Utils
24```
25
26## Description
27
281. Upon receiving a registration message from the system ability framework, the Samgr service saves the system ability information in the local cache.
29
30 ```
31 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
32 const SAExtraProp& extraProp)
33 {
34 if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
35 HILOGE("AddSystemAbilityExtra input params is invalid.");
36 return ERR_INVALID_VALUE;
37 }
38 {
39 unique_lock<shared_mutex> writeLock(abilityMapLock_);
40 auto saSize = abilityMap_.size();
41 if (saSize >= MAX_SERVICES) {
42 HILOGE("map size error, (Has been greater than %zu)", saSize);
43 return ERR_INVALID_VALUE;
44 }
45 SAInfo saInfo;
46 saInfo.remoteObj = ability;
47 saInfo.isDistributed = extraProp.isDistributed;
48 saInfo.capability = extraProp.capability;
49 saInfo.permission = Str16ToStr8(extraProp.permission);
50 abilityMap_[systemAbilityId] = std::move(saInfo);
51 HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
52 }
53 RemoveCheckLoadedMsg(systemAbilityId);
54 if (abilityDeath_ != nullptr) {
55 ability->AddDeathRecipient(abilityDeath_);
56 }
57
58 u16string strName = Str8ToStr16(to_string(systemAbilityId));
59 if (extraProp.isDistributed && dBinderService_ != nullptr) {
60 dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
61 HILOGD("AddSystemAbility RegisterRemoteProxy, serviceId is %{public}d", systemAbilityId);
62 }
63 if (systemAbilityId == SOFTBUS_SERVER_SA_ID && !isDbinderStart_) {
64 if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
65 bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
66 HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
67 isDbinderStart_ = true;
68 }
69 }
70 SendSystemAbilityAddedMsg(systemAbilityId, ability);
71 return ERR_OK;
72 }
73 ```
74
752. If the system service requested by the system ability framework is a local service, the Samgr service locates the proxy object of the system service based on the service ID and returns the proxy object to the system ability framework.
76
77 ```
78 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
79 {
80 if (!CheckInputSysAbilityId(systemAbilityId)) {
81 HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
82 return nullptr;
83 }
84
85 shared_lock<shared_mutex> readLock(abilityMapLock_);
86 auto iter = abilityMap_.find(systemAbilityId);
87 if (iter != abilityMap_.end()) {
88 HILOGI("found service : %{public}d.", systemAbilityId);
89 return iter->second.remoteObj;
90 }
91 HILOGI("NOT found service : %{public}d", systemAbilityId);
92 return nullptr;
93 }
94 ```
95
963. The Samgr service dynamically loads the system service process and system ability. Instead of starting upon system startup, the process starts when the system ability is accessed and loads the specified system ability.
97
98 3.1 Inherit from the **SystemAbilityLoadCallbackStub** class and override the **OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)** and **OnLoadSystemAbilityFail(int32_t systemAbilityId)** methods.
99
100 ```
101 class OnDemandLoadCallback : public SystemAbilityLoadCallbackStub {
102 public:
103 void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject) override;
104 void OnLoadSystemAbilityFail(int32_t systemAbilityId) override;
105 };
106
107 void OnDemandLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId,
108 const sptr<IRemoteObject>& remoteObject) // systemAbilityId is the ID of the system ability to be loaded, and remoteObject indicates the proxy object of the system ability.
109 {
110 cout << "OnLoadSystemAbilitySuccess systemAbilityId:" << systemAbilityId << " IRemoteObject result:" <<
111 ((remoteObject != nullptr) ? "succeed" : "failed") << endl;
112 }
113
114 void OnDemandLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) // systemAbilityId is the ID of the system ability to be loaded.
115 {
116 cout << "OnLoadSystemAbilityFail systemAbilityId:" << systemAbilityId << endl;
117 }
118 ```
119
120 3.2 Call **LoadSystemAbility(int32_t systemAbilityId, const sptr<ISystemAbilityLoadCallback>& callback)** provided by Samgr.
121
122 ```
123 // Construct a SystemAbilityLoadCallbackStub instance (mentioned in step 3.1).
124 sptr<OnDemandLoadCallback> loadCallback_ = new OnDemandLoadCallback();
125 // Call the LoadSystemAbility method.
126 sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
127 if (sm == nullptr) {
128 cout << "GetSystemAbilityManager samgr object null!" << endl;
129 return;
130 }
131 int32_t result = sm->LoadSystemAbility(systemAbilityId, loadCallback_);
132 if (result != ERR_OK) {
133 cout << "systemAbilityId:" << systemAbilityId << " load failed, result code:" << result << endl;
134 return;
135 }
136 ```
137>NOTE
138>
139>1. After **LoadSystemAbility** is called, the **OnLoadSystemAbilitySuccess** callback will be invoked if the specified system ability is successfully loaded and the **OnLoadSystemAbilityFail** callback will be invoked if the system ability fails to be loaded.
140>
141>2. The dynamically loaded process cannot start upon system startup. You must set **"ondemand": true** in the .cfg file. The following is an example:
142>
143>```
144>{
145> "services" : [{
146> "name" : "listen_test",
147> "path" : ["/system/bin/sa_main", "/system/profile/listen_test.json"],
148> "ondemand" : true,
149> "uid" : "system",
150> "gid" : ["system", "shell"]
151> }
152> ]
153>}
154>```
155>3. The **LoadSystemAbility** method applies to dynamic loading of system abilities. In other scenarios, use the **CheckSystemAbility** method to obtain a system ability.
156>4. The process name in the .cfg file must be the same as that in the .json configuration file of the system ability.
157
158## Repositories Involved
159
160Samgr
161
162[systemabilitymgr\_safwk](https://gitee.com/openharmony/systemabilitymgr_safwk)
163
164[**systemabilitymgr\_samgr**](https://gitee.com/openharmony/systemabilitymgr_samgr)
165
166[systemabilitymgr\_safwk\_lite](https://gitee.com/openharmony/systemabilitymgr_safwk_lite)
167
168[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite)
169
README_zh.md
1# 系统服务管理部件<a name="ZH-CN_TOPIC_0000001162068341"></a>
2## 简介<a name="section11660541593"></a>
3
4samgr组件是OpenHarmony的核心组件,提供OpenHarmony系统服务启动、注册、查询等功能。
5
6## 系统架构<a name="section342962219551"></a>
7
8**图 1** 系统服务管理系统架构图
9
10
11
12
13## 目录<a name="section161941989596"></a>
14
15```
16/foundation/systemabilitymgr
17├── samgr
18│ ├── bundle.json # 部件描述及编译文件
19│ ├── frameworks # 框架实现存在目录
20│ ├── interfaces # 接口目录
21│ ├── services # 组件服务端目录
22│ ├── test # 测试代码存放目录
23│ ├── utils # 工具类目录
24```
25
26## 说明<a name="section1312121216216"></a>
27
281. samgr服务接收到sa框架层发送的注册消息,会在本地缓存中存入系统服务相关信息。
29
30 ```
31 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
32 const SAExtraProp& extraProp)
33 {
34 if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
35 HILOGE("AddSystemAbilityExtra input params is invalid.");
36 return ERR_INVALID_VALUE;
37 }
38 {
39 unique_lock<shared_mutex> writeLock(abilityMapLock_);
40 auto saSize = abilityMap_.size();
41 if (saSize >= MAX_SERVICES) {
42 HILOGE("map size error, (Has been greater than %zu)", saSize);
43 return ERR_INVALID_VALUE;
44 }
45 SAInfo saInfo;
46 saInfo.remoteObj = ability;
47 saInfo.isDistributed = extraProp.isDistributed;
48 saInfo.capability = extraProp.capability;
49 saInfo.permission = Str16ToStr8(extraProp.permission);
50 abilityMap_[systemAbilityId] = std::move(saInfo);
51 HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
52 }
53 RemoveCheckLoadedMsg(systemAbilityId);
54 if (abilityDeath_ != nullptr) {
55 ability->AddDeathRecipient(abilityDeath_);
56 }
57
58 u16string strName = Str8ToStr16(to_string(systemAbilityId));
59 if (extraProp.isDistributed && dBinderService_ != nullptr) {
60 dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
61 HILOGD("AddSystemAbility RegisterRemoteProxy, serviceId is %{public}d", systemAbilityId);
62 }
63 if (systemAbilityId == SOFTBUS_SERVER_SA_ID && !isDbinderStart_) {
64 if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
65 bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
66 HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
67 isDbinderStart_ = true;
68 }
69 }
70 SendSystemAbilityAddedMsg(systemAbilityId, ability);
71 return ERR_OK;
72 }
73 ```
74
752. 对于本地服务而言,samgr服务接收到sa框架层发送的获取消息,会通过服务id,查找到对应服务的代理对象,然后返回给sa框架。
76
77 ```
78 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
79 {
80 if (!CheckInputSysAbilityId(systemAbilityId)) {
81 HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
82 return nullptr;
83 }
84
85 shared_lock<shared_mutex> readLock(abilityMapLock_);
86 auto iter = abilityMap_.find(systemAbilityId);
87 if (iter != abilityMap_.end()) {
88 HILOGI("found service : %{public}d.", systemAbilityId);
89 return iter->second.remoteObj;
90 }
91 HILOGI("NOT found service : %{public}d", systemAbilityId);
92 return nullptr;
93 }
94 ```
95
963. 动态加载系统服务进程及SystemAbility, 系统进程无需开机启动,而是在SystemAbility被访问的时候按需拉起,并加载指定SystemAbility。
97 3.1 继承SystemAbilityLoadCallbackStub类,并覆写OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)、OnLoadSystemAbilityFail(int32_t systemAbilityId)方法。
98
99 ```
100 class OnDemandLoadCallback : public SystemAbilityLoadCallbackStub {
101 public:
102 void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject) override;
103 void OnLoadSystemAbilityFail(int32_t systemAbilityId) override;
104 };
105
106 void OnDemandLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId,
107 const sptr<IRemoteObject>& remoteObject) // systemAbilityId为指定加载的SAID,remoteObject为指定systemAbility的代理对象
108 {
109 cout << "OnLoadSystemAbilitySuccess systemAbilityId:" << systemAbilityId << " IRemoteObject result:" <<
110 ((remoteObject != nullptr) ? "succeed" : "failed") << endl;
111 }
112
113 void OnDemandLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) // systemAbilityId为指定加载的SAID
114 {
115 cout << "OnLoadSystemAbilityFail systemAbilityId:" << systemAbilityId << endl;
116 }
117 ```
118
119 3.2 调用samgr提供的动态加载接口LoadSystemAbility(int32_t systemAbilityId, const sptr<ISystemAbilityLoadCallback>& callback)。
120 ```
121 // 构造步骤1的SystemAbilityLoadCallbackStub子类的实例
122 sptr<OnDemandLoadCallback> loadCallback_ = new OnDemandLoadCallback();
123 // 调用LoadSystemAbility方法
124 sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
125 if (sm == nullptr) {
126 cout << "GetSystemAbilityManager samgr object null!" << endl;
127 return;
128 }
129 int32_t result = sm->LoadSystemAbility(systemAbilityId, loadCallback_);
130 if (result != ERR_OK) {
131 cout << "systemAbilityId:" << systemAbilityId << " load failed, result code:" << result << endl;
132 return;
133 }
134 ```
135>说明:
136>1.LoadSystemAbility方法调用成功后,指定SystemAbility加载成功后会触发回调OnLoadSystemAbilitySuccess,加载失败触发回调OnLoadSystemAbilityFail。
137>2.动态加载的进程cfg文件不能配置为开机启动,需指定"ondemand" : true, 示例如下:
138>```
139>{
140> "services" : [{
141> "name" : "listen_test",
142> "path" : ["/system/bin/sa_main", "/system/profile/listen_test.json"],
143> "ondemand" : true,
144> "uid" : "system",
145> "gid" : ["system", "shell"]
146> }
147> ]
148>}
149>```
150>3.LoadSystemAbility方法适用于动态加载场景,其他获取SystemAbility场景建议使用CheckSystemAbility方法。
151>4.cfg里进程名称需要与SA的配置json文件里进程名保持一致
152
153## 相关仓<a name="section1371113476307"></a>
154
155系统服务管理子系统
156
157[systemabilitymgr\_safwk](https://gitee.com/openharmony/systemabilitymgr_safwk)
158
159[**systemabilitymgr\_samgr**](https://gitee.com/openharmony/systemabilitymgr_samgr)
160
161[systemabilitymgr\_safwk\_lite](https://gitee.com/openharmony/systemabilitymgr_safwk_lite)
162
163[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite)
164
165