1# Service Management 2## Overview 3 4Service management is implemented by using the init process to parse the service process configuration files (**xxx.cfg** files), which are used to configure services based on service scenarios. Currently, the supported value-added services include startup control, on-demand startup, command execution, scheduled startup, FD proxy, and sandbox management. 5 6## Description of Service Process Configuration Files 7 8- Naming: 9 10 Generally, the configuration file is named in the format of **serviceName.cfg**, where **serviceName** is the service process name, for example, **appspawn.cfg**. 11 12- Format: 13 14 The configuration file is based on the JSON format and complies with the basic rules of the JSON file. 15 16- Content: 17 18 The configuration file contains the following fields. Except mandatory fields, other fields can be configured based on service features. 19 20 Table 1 Service configuration fields 21 22 | Field| Configuration|Supported System Type| Description| Remarks| 23 | ---------- | ------- | -------- | --------| --------| 24 | name | Mandatory| Small and standard systems | Name of the current service. (Mandatory)| Type: string. The value cannot be empty and can contain a maximum of 32 bytes.| 25 | path | Mandatory| Small and standard systems| Full path (including parameters) of the executable file for the current service. This is an array. (Mandatory)| The first element is the path of the executable file, and the maximum number of elements is 20.<br> Each element is a string that contains a maximum of 64 bytes.| 26 | uid | Mandatory| Small and standard systems| User ID (UID) of the current service process.| Type: int or string.| 27 | gid | Mandatory| Small and standard systems| Group ID (GID) of the current service process.| Type: int, int[], string, or string array.| 28 | once | Optional| Small and standard systems| Whether the current service process is a one-off process.| **1**: The current service process is a one-off process. If the process exits, the init process does not restart it.<br>**0**: The current service process is not a one-off process. If the process exits, the init process restarts it upon receiving the SIGCHLD signal.| 29 | importance | Optional| Small and standard systems| <br>Standard system: service priority<br>Small system: service importance| <br>Standard system: The service priority ranges from **-20** to **19**. A smaller value indicates a higher priority. A value beyond the range is invalid.<br>Small system: The value **0** indicates an unimportant process and a value greater than **0** indicates an important process.| 30 | caps | Optional| Small and standard systems| Capabilities required by the current service. They are evaluated based on the capabilities supported by the security subsystem and configured in accordance with the principle of least permission.| Type: number or string array. If you set the value to a number, use the standard Linux capability. If you set the value to a string array, use the standard macro name.| 31 | critical | Optional| Standard system| Suppression mechanism for services. If the number of times a service is restarted exceeds the value N within the specified period T, the system will be restarted.| <br>Standard system:<br>Type: int array, for example, **"critical": [M, N, T]**.<br>- **M**: enable flag (**0**: disable; **1**: enable).<br>- **N**: number of times the service is started.<br>- **T**: period of time, in seconds.<br> Both **M** and **N** are greater than **0**.<br> Small and standard systems:<br>Type: int, for example, **critical: M**.<br>**M**: enable flag (**0**: disable; **1**: enable).<br> By default, **N** is **4** and **T** is **20**.| 32 | cpucore | Optional| Standard system| Number of CPU cores bound to the service.| Type: int array, for example, **"cpucore": [N1, N2, ...]**. **N1** and **N2** indicate the indices of the CPU cores to be bound. For a single-core device, **cpucore** is **0**.| 33 | d-caps | Optional| Standard system| Distributed service capability.| Type: string array, for example, **"d-caps": ["OHOS_DMS"]**.| 34 | apl | Optional| Standard system| Ability privilege level.| Type: string, for example, **"apl": "system_core"**.<br> The value can be **system_core** (default), **normal**, or **system_basic**.| 35 | start-mode | Optional| Standard system| Service startup mode.| Type: string, for example, **start-mode: condition**.<br>The value can be **boot**, **normal**, or **condition**. For details, see init Service Startup Control.| 36 | ondemand | Optional| Small and standard systems| Whether on-demand startup is enabled.| Type: bool, for example, **ondemand: true**. For small systems, this feature is available only on the Linux kernel.<br>For details, see [init Service On-Demand Startup](#section56901555920).| 37 | disable | Optional| Small and standard systems| Reserved.| None.| 38 | sandbox | Optional| Standard system| Whether the sandbox function is enabled.| **1** (default): Enable the sandbox function.<br>**0**: Disable the sandbox function.| 39 | socket | Optional| Standard system| Socket attribute configuration.| This field is required for services that uses a socket connection.| 40 41 **Table 2** Description of socket fields 42 | Field| Description| 43 | -------- | -------- | 44 | name | Name of the socket. It does not need to be the same as the service name. The value must not be empty and can contain a maximum of 32 bytes.| 45 | family | Address family to which the socket belongs. Currently, the AF_UNIX and AF_NETLINK families are supported.| 46 | type | Socket type. Currently, connection-based sockets, SOCK_SEQPACKET and SOCK_STREAM, and UDP-based connectionless socket, SOCK_DGRAM, are supported.| 47 | protocol | Protocol used for socket communication. Unless otherwise required, set the value to **default** so that the socket automatically selects a proper protocol based on the socket address family and socket type. In addition to the default protocol, the NETLINK_KOBJECT_UEVENT protocol is also supported.| 48 | permissions | Permissions of the socket node file. This field is valid only for sockets that have entity node files, such as the AF_UNIX address family.| 49 | uid | User ID of the socket node file. This field is valid only for sockets that have entity node files, such as the AF_UNIX address family.| 50 | gid | Group ID of the socket node file. This field is valid only for sockets that have entity node files, such as the AF_UNIX address family.| 51 | option | Socket option. This field is passed when **setsockopt** is called. Currently, the available options include **SOCKET_OPTION_PASSCRED**, **SOCKET_OPTION_RCVBUFFORCE**, **SOCK_CLOEXEC**, and **SOCK_NONBLOCK**.| 52 53 - init service startup control (for standard system or higher)<a name = "section56901555918"> 54 55 The init process classifies services into three types based on service configurations and starts the services in different phases. 56 57 - **boot**: services that need to be preferentially started in the system. This type of services are started in the init phase. 58 - **normal**: common services in the system. This type of services are started in the post-init phase. This is the default service type. 59 - **condition**: services that are started by running the startup command. You can add the **start xxxx** command to **jobs** to start the corresponding service. 60 61 - init service command execution (for standard system or higher)<a name="section56901555919"></a> 62 63 The init module provides the service command execution function, which allows services to execute different commands in different phases. 64 65 - **on-start**: execution of commands after the service process is forked. The on-start job is executed in the subprocess of the service and affects only the subprocess. 66 - **on-stop**: execution of commands in the init process when the service is stopped. 67 - **on-restart**: execution of commands in the init process when the service is restarted. 68 69 Configure the parameters as follows: 70 ``` 71 "services" : [{ 72 "name" : "serviceName", 73 "path" : ["/system/bin/serviceName"] 74 "jobs" : { 75 "on-boot" : "boot", 76 "on-start" : "services:serviceName_start", 77 "on-stop" : "services:serviceName_stop", 78 "on-restart" : "services:serviceName_restart" 79 } 80 }, 81 ``` 82 83 With the parallel startup and command execution capabilities, processes can be started concurrently. 84 85 - init service on-demand startup<a name="section56901555920"> 86 87 If on-demand startup is enabled, the init process starts a service only when it is required. The **ondemand** attribute is used to determine whether to enable on-demand startup for a service. 88 89 The following is an example configuration of the **ondemand** attribute: 90 ``` 91 "services" : [{ 92 "name" : "serviceName", 93 "path" : ["/system/bin/serviceName"] 94 "ondemand" : true 95 }] 96 ``` 97 - SA process on-demand startup 98 99 For details, see [samgr Usage](https://gitee.com/openharmony/systemabilitymgr_samgr/blob/master/README.md). 100 101 - Socket process on-demand startup 102 1. The init process creates a socket for socket processes in the pre-fork phase and listens to read/write events on this socket. 103 2. If a read/write event is received over the socket, the init process starts the native service corresponding to the socket process, cancels event listening on the socket, and transfers the socket to the corresponding native service for management. 104 3. The native service automatically exits if no more packets need to be processed. When reclaiming subprocesses, the init process starts event listening over the socket again based on the service configuration. 105 106 - Hot-swap service process on-demand startup 107 108 The hot-swap service process can be started to process hot swap events based on system parameter changes. 109 110 - Enhanced init process startup and recycling 111 112 The CPU core binding, priority, MAC address, and AccessToken information of the service process can be configured in the configuration file during process startup. 113 114 - Support of CPU core binding for service processes (through modification of the **.cfg** file) 115 - Support of priority setting for service processes (through modification of the **.cfg** file) 116 - Support of MAC address setting (that is, SELinux tag setting) for service processes (through modification of the **.cfg** file) 117 - Support of AccessToken setting for service processes and distributed capability setting for system service processes (through modification of the **.cfg** file) 118 - Support of the suppression mechanism for service processes (through modification of the **.cfg** file) 119 120 The following is the example configuration for enhanced init process startup and recycling: 121 ``` 122 "services" : [{ 123 "name" : "serviceName", 124 "path" : ["/system/bin/serviceName"] 125 "importance" : 1, // Priority for service processes 126 "cpucore" : [0], // CPU binding for service processes 127 "critical" : [1, 5, 10], // Suppression for service processes 128 "apl" : "normal", // Ability privilege level for service processes 129 "d-caps" : ["OHOS_DMS"], // Distributed capabilities for service processes 130 "secon" : "u:r:distributedsche:s0" // SELinux tag for service processes. In this example, the SELinux tag is u:r:distributedsche:s0. 131 } 132 ``` 133 134 - Scheduled startup 135 136 Scheduled startup means to start a service at the specified time. If the service has been started, it will not be started again. For details about the command, see [Description of begetctl Commands](subsys-boot-init-plugin.md). 137 ``` 138 timer_start servicename timeout 139 ``` 140## Basic Process of Creating a Service Process 141 142### Configuring the Service Process Configuration File 143 144 After finishing the service process code, create the **serviceName.cfg** file (**serviceName** indicates the service process name) and configure the file content based on service features. 145 146 Install the configuration file in the corresponding directory. Configure the **/base/startup/init/services/etc/BUILD.gn** file of the init module as follows: 147 148 ``` 149 ohos_prebuilt_etc("watchdog.cfg") { 150 source = "//base/startup/init/services/etc/watchdog.cfg" 151 relative_install_dir = "init" 152 part_name = "init" 153 subsystem_name = "startup" 154 } 155 156 ohos_prebuilt_etc("console.cfg") { 157 source = "//base/startup/init/services/etc/console.cfg" 158 relative_install_dir = "init" 159 part_name = "init" 160 subsystem_name = "startup" 161 } 162 163 ``` 164 165 Add the build path of the configuration file to the **bundle.json** file of the corresponding module. For example: 166 167 ``` 168 "build": { 169 "group_type": { 170 "base_group": [], 171 "fwk_group": [], 172 "service_group": [ 173 "//base/startup/init/ueventd:startup_ueventd", 174 "//base/startup/init/services/etc:ueventd.cfg" 175 ] 176 }, 177 } 178 ``` 179### Configuring the DAC Permission for a Service Process 180 181 Configure the DAC permission for the desired service process based on the GID and UID in the service process configuration file. 182 183 If the corresponding GID and UID do not exist, add them to the **/init/services/etc/passwd** and **/init/services/etc/group** files of the init module. 184 185 - Description of the **passwd** file: 186 187 - Each entry corresponds to a user. User information is separated by colons (:) and divided into seven fields, as shown below: 188 189 ```js 190 root:x:0:0:::/bin/false 191 bin:x:2:2:::/bin/false 192 system:x:1000:1000:::/bin/false 193 ``` 194 195 Fields in the **passwd** file 196 | SN | Field | Description | 197 | ---------- | --------- | ------------------------------------------------------------ | 198 | 1| User name | Use a name that is easy to remember, for example, **root**. Based on the mapping between user names and user ID (UIDs), the system identifies a user and grants the required user permissions.| 199 | 2| Password flag | **x** indicates that a password has bee set, but not the real password. The real password is stored in the **/etc/shadow** file.| 200 | 3| UID | Each user has a unique UID. The system identifies a user based on the UID.<br>A valid UID ranges from 0 to 65535. Numbers in different ranges represent different UIDs.<br>1. 0: administrator<br>2. 1 to 499: system users<br>3. 500 to 65535: common users| 201 | 4| GID | A GID indicates an initial group. A user has the permissions of the initial group once logging in to the system. Each user can have only one initial group. Generally, the initial group has the same name as the user name.| 202 | 5| Description | This field provides a simple description of the user. It is usually left blank. | 203 | 6| Home directory | This field specifies the home directory of a user. For example, the home directory of the **root** user is **/root**. This field is usually left blank. | 204 | 7| Default shell| Shell is a Linux command interpreter and serves as a bridge between users and the Linux kernel. It is used to convert commands entered by users into machine languages that can be identified by the system. By default, the command interpreter used by the Linux system is usually **/bin/bash**.| 205 206 - Description of the **group** file 207 208 - Each entry corresponds to a user group. User group information is separated by colons (:) and divided into four fields, as shown below: 209 210 ```js 211 root:x:0: 212 bin:x:2: 213 system:x:1000: 214 servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr,foundation,update 215 ``` 216 217 Fields in the **group** file 218 | SN | Field | Description | 219 | ---------- | --------- | -------------------------------------------------- | 220 | 1| Group name| This field indicates the user group name. For example, **servicectrl** indicates that the user group name is **servicectrl**.| 221 | 2| Password flag| Similar to the **/etc/passwd** file, **x** is only the password flag. The encrypted group password is stored in the **/etc/gshdow** file.| 222 | 3| GID | GIDs are used to identify different user groups.| 223 | 4| Group member| This field indicates the members of a user group. For example, the members of the **servicectrl** group include **root**, **shell**, **system**, **samgr**, **hdf_devmgr**, **foundation**, and **update**.| 224 225 - If the GID and UID are set to **root** or **system**, add a trustlist to the **security_config/high_privilege_process_list.json** file in the corresponding product directory. For example: 226 227 ``` 228 { 229 "high_privilege_process_list": [ 230 { 231 "name": "appspawn", 232 "uid": "root", 233 "gid": "root" 234 }, 235 { 236 "name": "console", 237 "uid": "root" 238 }, 239 { 240 "name": "testService", 241 "uid": "root", 242 "gid": "root" 243 }, 244 { 245 "name": "media_service", 246 "gid": ["root", "system"] 247 }, 248 { 249 "name": "misc", 250 "uid": "root", 251 "gid": "root" 252 } ... ... 253 ] 254 } 255 256 ``` 257### Configuring the SELinux Permission for a Service Process 258 259- Configuring the SELinux permission 260 261 1. Check whether the service process can be started in permissive mode. If yes, you do not need to configure the **selinux** tag. 262 263 2. To configure SELinux rules, you need to set the SELinux tag in the **secon** field in the configuration file of the service process. 264 265 3. Define the service process tag in the SELinux module. The procedure is as follows: 266 267 Define the tag for program execution in the **base/security/selinux_adapter/sepolicy/base/system/file_contexts** file. For example: 268 269 ``` 270 /system/bin/watchdog_service u:object_r:watchdog_service_exec:s0 271 /system/bin/hdcd u:object_r:hdcd_exec:s0 272 ``` 273 274 Define the applicable scope of the tag in the **base/security/selinux_adapter/sepolicy/base/public/type.te** file. For example: 275 276 ``` 277 type watchdog_service, sadomain, domain; 278 type watchdog_service_exec, exec_attr, file_attr, system_file_attr; 279 ``` 280 281## Error Codes 282 283Description of error codes 284 285| Enum | Value| Error Message | Description | 286| ------------------ | ------ | ------------------------ | ----------------------- | 287| INIT_OK | 0 | | Operation success. | 288| INIT_EPARAMETER | 1 | parameter | Invalid parameter. | 289| INIT_EFORMAT | 2 | Format string fail | String format error. | 290| INIT_ECFG | 3 | cfg error | Configuration parsing error. | 291| INIT_EPATH | 4 | Invalid path | Incorrect service path. | 292| INIT_EFORK | 5 | Fork fail | Failed to fork a subprocess. | 293| INIT_ESANDBOX | 6 | Create sandbox fail | Failed to add a service to the sandbox. | 294| INIT_EACCESSTOKEN | 7 | Set access token fail | Failed to set the access token. | 295| INIT_ESOCKET | 8 | Create socket fail | Failed to create a socket. | 296| INIT_EFILE | 9 | Create file fail | Failed to create a file. | 297| INIT_ECONSOLE | 10 | Open console fail | Failed to open the console. | 298| INIT_EHOLDER | 11 | Publish holder fail | Failed to publish the holder. | 299| INIT_EBINDCORE | 12 | Bind core fail | Failed to bind cores. | 300| INIT_EKEEPCAP | 13 | Set keep capability fail | Failed to set **keep capability**.| 301| INIT_EGIDSET | 14 | Set gid fail | Failed to set the service GID. | 302| INIT_ESECCOMP | 15 | Set SECCOMP fail | Failed to set the service security policy. | 303| INIT_EUIDSET | 16 | Set uid fail | Failed to set the service UID. | 304| INIT_ECAP | 17 | Set capability fail | Failed to set the service capability. | 305| INIT_EWRITEPID | 18 | Write pid fail | Failed to write the PID. | 306| INIT_ECONTENT | 19 | Set sub content fail | Failed to set the service security context. | 307| INIT_EPRIORITY | 20 | Set priority fail | Failed to set the service priority. | 308| INIT_EEXEC_CONTENT | 21 | Set exec content fail | Failed to set the SELinux tag. | 309| INIT_EEXEC | 22 | Exec fail | Failed to run exec. | 310 311## Service Process Configuration Example 312 313### Example Code 314 315### Example Configuration 316 317## Available APIs 318 319 **Table 3** Service control APIs 320| Function| Description| Parameter Description| 321| :---------- | :---------- |:--------| 322| int ServiceControlWithExtra(const char *serviceName, int action, const char *extArgv[], int extArgc) | Configures service parameters.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br> **serviceName**: service name.<br> **action**: service action, which can be **start**, **stop**, or **restart**.<br> **extArgv**: parameter array.<br> **extArgc**: number of parameters.| 323| int ServiceControl(const char *serviceName, int action) | Controls the service behavior.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br> **serviceName**: service name.<br> **action**: service action, which can be **start**, **stop**, or **restart**.| 324| int ServiceWaitForStatus(const char *serviceName, ServiceStatus status, int waitTimeout) | Sets the service waiting status.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br>**serviceName**: service name.<br> **status**: service status.<br> waitTimeout: timeout interval.| 325| int ServiceSetReady(const char *serviceName) | Sets a service as being ready.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br> **serviceName**: service name.| 326| int StartServiceByTimer(const char *serviceName, uint64_t timeout) | Starts a service by timer.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br> **serviceName**: service name.<br> timeout: timeout interval.| 327| int StopServiceTimer(const char *serviceName) | Stops a service timer.| Return value: **0** if the operation is successful; **-1** otherwise.<br> Parameters:<br> **serviceName**: service name.| 328 329 - The service management APIs are privileged APIs. Therefore, you need to configure the DAC and SELinux permissions as follows: 330 331 - Go to **/base/startup/init/services/etc/group** and add the correct user ID to **servicectrl**. For example: 332 333 ``` 334 servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr 335 ``` 336 337 - SELinux configuration for service control APIs 338 339 Add the required SELinux permissions to the **init.te** file. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**. 340 341 ```java 342 allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; 343 ``` 344## Constraints 345 346The service management module is available only for the mini system and standard system. 347## FAQs 348 349For details, see [init Module FAQs](./subsys-boot-init-faqs.md). 350