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| Small and standard systems| 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> Type: int[], 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> By default, **N** is **4** and **T** is **240**.| 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 | env | Optional| Standard system| Environment variable configuration.| Type: key-value pair array.<br>Multiple environment variables can be configured. For example:<br>"env" : [{<br> "name" : "SERVICE_NALE", <br>"value" : "ueventd"},{<br> "name" : "TEST",<br> "value" : "test_value" <br>}]| 41 | period | Optional| Standard system| Scheduled startup upon service exit.| Type: int, for example, 60. This field specifies the interval for starting a scheduled task, in seconds.<br>If this function is enabled, a timer is started to periodically start the service upon service exit. For example, **"period": 60** indicates that the service is started 60 seconds upon service exit.| 42 43 **Table 2** Description of socket fields 44 | Field| Description| 45 | -------- | -------- | 46 | 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.| 47 | family | Address family to which the socket belongs. Currently, the AF_UNIX and AF_NETLINK families are supported.| 48 | type | Socket type. Currently, connection-based sockets, SOCK_SEQPACKET and SOCK_STREAM, and UDP-based connectionless socket, SOCK_DGRAM, are supported.| 49 | 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.| 50 | 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.| 51 | 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.| 52 | 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.| 53 | 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**.| 54 55 - init service startup control (for standard system or higher)<a name = "section56901555918"> 56 57 The init process classifies services into three types based on service configurations and starts the services in different phases. 58 59 - **boot**: services that need to be preferentially started in the system. This type of services are started in the init phase. 60 - **normal**: common services in the system. This type of services are started in the post-init phase. This is the default service type. 61 - **condition**: services that are started by running the startup command. You can add the **start xxxx** command to **jobs** to start the corresponding service. 62 63 - init service command execution (for standard system or higher)<a name="section56901555919"></a> 64 65 The init module provides the service command execution function, which allows services to execute different commands in different phases. 66 67 - **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. 68 - **on-stop**: execution of commands in the init process when the service is stopped. 69 - **on-restart**: execution of commands in the init process when the service is restarted. 70 71 Configure the parameters as follows: 72 ``` 73 "services" : [{ 74 "name" : "serviceName", 75 "path" : ["/system/bin/serviceName"] 76 "jobs" : { 77 "on-start" : "services:serviceName_start", 78 "on-stop" : "services:serviceName_stop", 79 "on-restart" : "services:serviceName_restart" 80 } 81 }, 82 ``` 83 84 With the parallel startup and command execution capabilities, processes can be started concurrently. 85 86 - init service on-demand startup<a name="section56901555920"> 87 88 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. 89 90 The following is an example configuration of the **ondemand** attribute: 91 ``` 92 "services" : [{ 93 "name" : "serviceName", 94 "path" : ["/system/bin/serviceName"] 95 "ondemand" : true 96 }] 97 ``` 98 - SA process on-demand startup 99 100 For details, see [samgr Usage](https://gitee.com/openharmony/systemabilitymgr_samgr/blob/master/README.md). 101 102 - Socket process on-demand startup 103 1. The init process creates a socket for socket processes in the pre-fork phase and listens to read/write events on this socket. 104 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. 105 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. 106 107 - Hot-swap service process on-demand startup 108 109 The hot-swap service process can be started to process hot swap events based on system parameter changes. 110 111 - Enhanced init process startup and recycling 112 113 The CPU core binding, priority, MAC address, and AccessToken information of the service process can be configured in the configuration file during process startup. 114 115 - Support of CPU core binding for service processes (through modification of the **.cfg** file) 116 - Support of priority setting for service processes (through modification of the **.cfg** file) 117 - Support of MAC address setting (that is, SELinux tag setting) for service processes (through modification of the **.cfg** file) 118 - Support of AccessToken setting for service processes and distributed capability setting for system service processes (through modification of the **.cfg** file) 119 - Support of the suppression mechanism for service processes (through modification of the **.cfg** file) 120 121 The following is the example configuration for enhanced init process startup and recycling: 122 ``` 123 "services" : [{ 124 "name" : "serviceName", 125 "path" : ["/system/bin/serviceName"] 126 "importance" : 1, // Priority for service processes 127 "cpucore" : [0], // CPU binding for service processes 128 "critical" : [1, 5, 10], // Suppression for service processes 129 "apl" : "normal", // Ability privilege level for service processes 130 "d-caps" : ["OHOS_DMS"], // Distributed capabilities for service processes 131 "secon" : "u:r:distributedsche:s0" // SELinux tag for service processes. In this example, the SELinux tag is u:r:distributedsche:s0. 132 } 133 ``` 134 135 - Scheduled startup 136 137 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). 138 ``` 139 timer_start servicename timeout 140 ``` 141## Basic Process of Creating a Service Process 142 143### Configuring the Service Process Configuration File 144 145 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. 146 147 Install the configuration file in the corresponding directory. Configure the **/base/startup/init/services/etc/BUILD.gn** file of the init module as follows: 148 149 ``` 150 ohos_prebuilt_etc("watchdog.cfg") { 151 source = "//base/startup/init/services/etc/watchdog.cfg" 152 relative_install_dir = "init" 153 part_name = "init" 154 subsystem_name = "startup" 155 } 156 157 ohos_prebuilt_etc("console.cfg") { 158 source = "//base/startup/init/services/etc/console.cfg" 159 relative_install_dir = "init" 160 part_name = "init" 161 subsystem_name = "startup" 162 } 163 164 ``` 165 166 Add the build path of the configuration file to the **bundle.json** file of the corresponding module. For example: 167 168 ``` 169 "build": { 170 "group_type": { 171 "base_group": [], 172 "fwk_group": [], 173 "service_group": [ 174 "//base/startup/init/ueventd:startup_ueventd", 175 "//base/startup/init/services/etc:ueventd.cfg" 176 ] 177 }, 178 } 179 ``` 180### Configuring the DAC Permission for a Service Process 181 182 Configure the DAC permission for the desired service process based on the GID and UID in the service process configuration file. 183 184 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. 185 186 - Description of the **passwd** file: 187 188 - Each entry corresponds to a user. User information is separated by colons (:) and divided into seven fields, as shown below: 189 190 ```js 191 root:x:0:0:::/bin/false 192 bin:x:2:2:::/bin/false 193 system:x:1000:1000:::/bin/false 194 ``` 195 196 Fields in the **passwd** file 197 | SN | Field | Description | 198 | ---------- | --------- | ------------------------------------------------------------ | 199 | 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.| 200 | 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.| 201 | 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| 202 | 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.| 203 | 5| Description | This field provides a simple description of the user. It is usually left blank. | 204 | 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. | 205 | 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**.| 206 207 - Description of the **group** file 208 209 - Each entry corresponds to a user group. User group information is separated by colons (:) and divided into four fields, as shown below: 210 211 ```js 212 root:x:0: 213 bin:x:2: 214 system:x:1000: 215 servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr,foundation,update 216 ``` 217 218 Fields in the **group** file 219 | SN | Field | Description | 220 | ---------- | --------- | -------------------------------------------------- | 221 | 1| Group name| This field indicates the user group name. For example, **servicectrl** indicates that the user group name is **servicectrl**.| 222 | 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.| 223 | 3| GID | GIDs are used to identify different user groups.| 224 | 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**.| 225 226 - 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: 227 228 ``` 229 { 230 "high_privilege_process_list": [ 231 { 232 "name": "appspawn", 233 "uid": "root", 234 "gid": "root" 235 }, 236 { 237 "name": "console", 238 "uid": "root" 239 }, 240 { 241 "name": "testService", 242 "uid": "root", 243 "gid": "root" 244 }, 245 { 246 "name": "media_service", 247 "gid": ["root", "system"] 248 }, 249 { 250 "name": "misc", 251 "uid": "root", 252 "gid": "root" 253 } ... ... 254 ] 255 } 256 257 ``` 258### Configuring the SELinux Permission for a Service Process 259 260- Configuring the SELinux permission 261 262 1. Check whether the service process can be started in permissive mode. If yes, you do not need to configure the **selinux** tag. 263 264 2. To configure SELinux rules, you need to set the SELinux tag in the **secon** field in the configuration file of the service process. 265 266 3. Define the service process tag in the SELinux module. The procedure is as follows: 267 268 Define the tag for program execution in the **base/security/selinux_adapter/sepolicy/base/system/file_contexts** file. For example: 269 270 ``` 271 /system/bin/watchdog_service u:object_r:watchdog_service_exec:s0 272 /system/bin/hdcd u:object_r:hdcd_exec:s0 273 ``` 274 275 Define the applicable scope of the tag in the **base/security/selinux_adapter/sepolicy/base/public/type.te** file. For example: 276 277 ``` 278 type watchdog_service, sadomain, domain; 279 type watchdog_service_exec, exec_attr, file_attr, system_file_attr; 280 ``` 281 282## Error Codes 283 284Description of error codes 285 286| Enum | Value| Error Message | Description | 287| ------------------ | ------ | ------------------------ | ----------------------- | 288| INIT_OK | 0 | | Operation success. | 289| INIT_EPARAMETER | 1 | parameter | Invalid parameter. | 290| INIT_EFORMAT | 2 | Format string fail | String format error. | 291| INIT_ECFG | 3 | cfg error | Configuration parsing error. | 292| INIT_EPATH | 4 | Invalid path | Incorrect service path. | 293| INIT_EFORK | 5 | Fork fail | Failed to fork a subprocess. | 294| INIT_ESANDBOX | 6 | Create sandbox fail | Failed to add a service to the sandbox. | 295| INIT_EACCESSTOKEN | 7 | Set access token fail | Failed to set the access token. | 296| INIT_ESOCKET | 8 | Create socket fail | Failed to create a socket. | 297| INIT_EFILE | 9 | Create file fail | Failed to create a file. | 298| INIT_ECONSOLE | 10 | Open console fail | Failed to open the console. | 299| INIT_EHOLDER | 11 | Publish holder fail | Failed to publish the holder. | 300| INIT_EBINDCORE | 12 | Bind core fail | Failed to bind cores. | 301| INIT_EKEEPCAP | 13 | Set keep capability fail | Failed to set **keep capability**.| 302| INIT_EGIDSET | 14 | Set gid fail | Failed to set the service GID. | 303| INIT_ESECCOMP | 15 | Set SECCOMP fail | Failed to set the service security policy. | 304| INIT_EUIDSET | 16 | Set uid fail | Failed to set the service UID. | 305| INIT_ECAP | 17 | Set capability fail | Failed to set the service capability. | 306| INIT_EWRITEPID | 18 | Write pid fail | Failed to write the PID. | 307| INIT_ECONTENT | 19 | Set sub content fail | Failed to set the service security context. | 308| INIT_EPRIORITY | 20 | Set priority fail | Failed to set the service priority. | 309| INIT_EEXEC_CONTENT | 21 | Set exec content fail | Failed to set the SELinux tag. | 310| INIT_EEXEC | 22 | Exec fail | Failed to run exec. | 311 312## Service Process Configuration Example 313 314### Example Code 315 316### Example Configuration 317 318## Available APIs 319 320 **Table 3** Service control APIs 321| Function| Description| Parameter Description| 322| :---------- | :---------- |:--------| 323| 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.| 324| 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**.| 325| 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.| 326| 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.| 327| 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.| 328| 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.| 329 330 - The service management APIs are privileged APIs. Therefore, you need to configure the DAC and SELinux permissions as follows: 331 332 - Go to **/base/startup/init/services/etc/group** and add the correct user ID to **servicectrl**. For example: 333 334 ``` 335 servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr 336 ``` 337 338 - SELinux configuration for service control APIs 339 340 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**. 341 342 ```java 343 allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; 344 ``` 345## Constraints 346 347The service management module is available only for the mini system and standard system. 348## FAQs 349 350For details, see [init Module FAQs](./subsys-boot-init-faqs.md). 351