1# Service Management 2## Overview 3### Function 4Service configuration allows you to configure services on demand to create different value-added services. Currently, the following value-added services are supported: startup control, on-demand startup, command execution, scheduled startup, FD proxy, and [sandbox](subsys-boot-init-sandbox.md). 5 6### Basic Concepts 7 8- init service parameter options 9 10 For details, see [Description of service Fields](#table14737791471). 11 12- init service startup control (for standard system or higher)<a name = "section56901555918"> 13 14 The init process classifies services into three types based on service configurations and starts the services in different phases. 15 16 - **boot**: services that need to be preferentially started in the system. This type of services are started in the init phase. 17 - **normal**: common services in the system. This type of services are started in the post-init phase. This is the default service type. 18 - **condition**: services that are started by running the startup command. You can add the **start xxxx** command to **jobs** to start the corresponding service. 19 20- init service command execution (for standard system or higher)<a name="section56901555919"></a> 21 22 The init module provides the service command execution function, which allows services to execute different commands in different phases. 23 24 - **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. 25 - **on-stop**: execution of commands in the init process when the service is stopped. 26 - **on-restart**: execution of commands in the init process when the service is restarted. 27 28 The following is an example of service configuration: 29 ``` 30 "services" : [{ 31 "name" : "serviceName", 32 "path" : ["/system/bin/serviceName"] 33 "jobs" : { 34 "on-boot" : "boot", 35 "on-start" : "services:serviceName_start", 36 "on-stop" : "services:serviceName_stop", 37 "on-restart" : "services:serviceName_restart" 38 } 39 }, 40 ``` 41 42 With the parallel startup and command execution capabilities, processes can be started concurrently. 43 44- init service on-demand startup<a name="section56901555920"> 45 46 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. 47 48 The following is an example configuration of the **ondemand** attribute: 49 ``` 50 "services" : [{ 51 "name" : "serviceName", 52 "path" : ["/system/bin/serviceName"] 53 "ondemand" : true 54 }] 55 ``` 56 - SA process on-demand startup 57 58 For details, see [samgr Usage](https://gitee.com/openharmony/systemabilitymgr_samgr/blob/master/README.md). 59 60 - Socket process on-demand startup 61 1. The init process creates a socket for socket processes in the pre-fork phase and listens to read/write events on this socket. 62 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. 63 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. 64 65 - Hot-swap service process on-demand startup 66 67 The hot-swap service process can be started to process hot swap events based on system parameter changes. 68 69- Enhanced init process startup and recycling 70 71 The CPU core binding, priority, MAC address, and AccessToken information of the service process can be configured in the configuration file during process startup. 72 73 - Support of CPU core binding for service processes (through modification of the <strong>*.cfg</strong> file) 74 - Support of priority setting for service processes (through modification of the <strong>*.cfg</strong> file) 75 - Support of MAC address setting (that is, SELinux tag setting) for service processes (through modification of the <strong>*.cfg</strong> file) 76 - Support of AccessToken setting for service processes and distributed capability setting for system service processes (through modification of the <strong>*.cfg</strong> file) 77 - Support of the suppression mechanism for service processes (through modification of the <strong>*.cfg</strong> file) 78 79 The following is the example configuration for enhanced init process startup and recycling: 80 ``` 81 "services" : [{ 82 "name" : "serviceName", 83 "path" : ["/system/bin/serviceName"] 84 "importance" : 1, // Priority setting for service processes 85 "cpucore" : [0], // CPU binding for service processes 86 "critical" : [1, 5, 10], // Suppression for service processes 87 "apl" : "normal", // Ability privilege level setting for service processes 88 "d-caps" : ["OHOS_DMS"], // Distributed capability setting for service processes 89 "secon" : "u:r:distributedsche:s0" // SELinux tag setting for service processes. In this example, u:r:distributedsche:s0 is the SELinux tag. 90 } 91 ``` 92 93- SELinux tag 94 95 To enable the SELinux policy for a service, add the SELinux tag to the service in the **secon** field. For example, to add the SELinux tag to watchdog_service, use the following code snippet: 96 97 ``` 98 "services" : [{ 99 "name" : "watchdog_service", 100 "secon" : "u:r:watchdog_service:s0" 101 }] 102 ``` 103 Note that you need to define the tag in SELinux. For details, see the appropriate SELinux guide. 104 105- init service FD proxy (for standard system or higher) 106 107 FD proxy is an extended mechanism for on-demand startup. It can ensure that the FD state handle is not lost before the service process exits. Specifically, a service process sends the FD to the init process before it exits, and then reclaims the FD from the init process when it is started again. 108 109 This mechanism is implemented using the API provided by the init process. Before a service process exits, it can call the related API to send the FD to the init process over the socket that supports IPC communication. After the service process is restarted, the init process returns the corresponding FD handle to it in the same way. For details about the APIs, see [FD Proxy APIs](#table14737791479). 110 111- Scheduled startup 112 113 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#parameters). 114 ``` 115 timer_start servicename timeout 116 ``` 117- Sandbox 118 119 For details, see [Sandbox Management](subsys-boot-init-sandbox.md). 120 121### Constraints 122 123The service management module is available only for the mini system and standard system. 124 125## How to Develop 126### Use Cases 127By parsing the <strong>*.cfg</strong> file, you can obtain **service** fields, and then set and start the service. 128 129### Parameters 130 **Table 1** Description of service fields<a name="table14737791471"></a> 131 | Name| Meaning| Description| Supported System Type| 132 | ---------- |-------- | --------| --------| 133 | name | Name of the current service. (Mandatory)| Type: string. The value cannot be empty and can contain a maximum of 32 bytes.| Small and standard systems | 134 | path | 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.| Small and standard systems| 135 | uid | User ID (UID) of the current service process.| Type: int or string.| Small and standard systems| 136 | gid | Group ID (GID) of the current service process.| Type: int, int[], string, or string array.| Small and standard systems| 137 | once | Whether the current service process is a one-off process.| <strong>1</strong>: The current service process is a one-off process. If the process exits, the init process does not restart it.<br><strong>0</strong>: The current service process is not a one-off process. If the process exits, the init process restarts it upon receiving the SIGCHLD signal.| Small and standard systems| 138 | importance | Standard system: service priority<br>Small system: service importance| <br>Standard system: The service priority ranges from -20 to 19. A value beyond the range is invalid.<br>Small system: The value <strong>0</strong> indicates an unimportant process and a value greater than <strong>0</strong> indicates an important process.| Small and standard systems| 139 | caps | 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.| Small and standard systems| 140 | critical | 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, <strong>"critical": [M, N, T]</strong>.<br>- <strong>M</strong>: enable flag (<strong>0</strong>: disable; <strong>1</strong>: enable).<br>- <strong>N</strong>: number of times the service is started.<br>- <strong>T</strong>: period of time, in seconds.<br> Both <strong>M</strong> and <strong>N</strong> are greater than <strong>0</strong>.<br> Small and standard systems:<br>Type: int, for example, <strong>"critical": M</strong>.<br><strong>M</strong>: enable flag (<strong>0</strong>: disable; <strong>1</strong>: enable).<br> By default, <strong>N</strong> is <strong>4</strong> and <strong>T</strong> is <strong>20</strong>.| Standard system| 141 | cpucore | Number of CPU cores bound to the service.| Type: int array, for example, <strong>"cpucore": [N1, N2, ...]</strong>. <strong>N1</strong> and <strong>N2</strong> indicate the indicate of the CPU cores to be bound. For a single-core device, <strong>cpucore</strong> is <strong>0</strong>.| Standard system| 142 | d-caps | Distributed service capability.| Type: string array, for example, <strong>"d-caps": ["OHOS_DMS"]</strong>.| Standard system| 143 | apl | Ability privilege level.| Type: string, for example, <strong>"apl": "system_core"</strong>.<br> The value can be <strong>system_core</strong> (default), <strong>normal</strong>, or <strong>system_basic</strong>.| Standard system| 144 | start-mode | Service startup mode.| Type: string, for example, **"start-mode": "condition"**.<br>The value can be <strong>boot</strong>, <strong>normal</strong>, or <strong>condition</strong>. For details, see [init service startup control](#section56901555918).| Standard system| 145 | ondemand | 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).| Small and standard systems| 146 | disable | Reserved.| None.| Small and standard systems| 147 | sandbox | Whether the sandbox function is enabled.| <strong>1</strong> (default): Enable the sandbox function.<br><strong>0</strong>: Disable the sandbox function.| Standard system| 148 149 **Table 2** Description of socket fields 150 | Name| Description| 151 | -------- | -------- | 152 | 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.| 153 | family | Address family to which the socket belongs. Currently, the AF_UNIX and AF_NETLINK families are supported.| 154 | type | Socket type. Currently, connection-based sockets, SOCK_SEQPACKET and SOCK_STREAM, and UDP-based connectionless socket, SOCK_DGRAM, are supported.| 155 | 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.| 156 | 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.| 157 | 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.| 158 | 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.| 159 | option | Socket option. This field is passed when **setsockopt** is called. Currently, the available options include <strong>SOCKET_OPTION_PASSCRED</strong>, <strong>SOCKET_OPTION_RCVBUFFORCE</strong>, <strong>SOCK_CLOEXEC</strong>, and <strong>SOCK_NONBLOCK</strong>.| 160 161### Available APIs 162 **Table 3** FD proxy APIs<a name="table14737791479"></a> 163 | API | Function| Description | 164 | ---------- | ---------- |--------| 165 | int *ServiceGetFd(const char *serviceName, size_t *outfdCount) | Obtains the proxy FD from the init process.| Return value: Returns the pointer to the fd array if the operation is successful; returns **NULL** otherwise. (Note: Manual release is required.)<br>Arguments:<br> **serviceName**: service name.<br>**outfdCount**: length of the returned FD array.| 166 | int ServiceSaveFd(const char *serviceName, int *fds, int fdCount) | Requests the init process for FD proxy.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **fds**: pointer to the FD array for FD proxy.<br>**fdCount**: length of the FD array. 167 | int ServiceSaveFdWithPoll(const char *serviceName, int *fds, int fdCount) | Requests FD proxy in poll mode.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **fds**: pointer to the FD array.<br> **fdCount**: length of the FD array. 168 169 **Table 4** Service control APIs 170 | API| Function| Description| 171 | :---------- | :---------- |:--------| 172 | int ServiceControlWithExtra(const char *serviceName, int action, const char *extArgv[], int extArgc) | Configures service parameters.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **action**: service action, which can be **start**, **stop**, or **restart**.<br> **extArgv**: parameter array.<br> **extArgc**: number of parameters.| 173 | int ServiceControl(const char *serviceName, int action) | Controls the service behavior.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **action**: service action, which can be **start**, **stop**, or **restart**.| 174 | int ServiceWaitForStatus(const char *serviceName, ServiceStatus status, int waitTimeout) | waiting for the service status.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br>**serviceName**: service name.<br> **status**: service status.<br> **waitTimeout**: waiting timeout interval.| 175 | int ServiceSetReady(const char *serviceName) | Sets a service as being ready.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.| 176 | int StartServiceByTimer(const char *serviceName, uint64_t timeout) | Starts a service by timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> timeout: timeout interval.| 177 | int StopServiceTimer(const char *serviceName) | Stops a service timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.| 178 179- DAC configuration for service control APIs 180 181 Go to **/base/startup/init/services/etc/group** and add the correct user ID to **servicectrl**. For example: 182 183 ```java 184 servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr 185 ``` 186 187- SELinux configuration for service control APIs 188 189 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**. 190 191 ```java 192 allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; 193 ``` 194 195### How to Develop 196 The following describes how to add a system service named **MySystemApp**: 197 198``` 199{ 200 "jobs" : [{ 201 "name" : "pre-init", 202 "cmds" : [ 203 "mkdir /storage/MyDir", // Create a folder before starting the MySystemApp service. This operation is executed in the pre-init job. 204 "chmod 0600 /storage/MyDir", // Modify the permission because the MySystemApp service requires that only the current user and its owner group have the read and write permissions on the file. 205 "chown 10 10 /storage/MyDir" 206 ] 207}, { 208 "name" : "init", 209 "cmds" : [ 210 "start MySystemApp" // Start the MySystemApp service in the init job. 211 ] 212}, { 213 "name" : "post-init", 214 "cmds" : [] // Do not configure the post-init job because no other operations are required after the MySystemApp system service is started. 215 } 216], 217 "services" : [{ 218 "name" : "MySystemApp", // Name of the system service 219 "path" : ["/bin/MySystemAppExe", "param1", "param2", "param3"], // The executable file path of the MySystemApp service is /bin/MySystemAppExe. To start the service, three parameters ("param1", "param2", and "param3") need to be passed. 220 "socket" : [{ 221 "name" : "ueventd", 222 "family" : "AF_NETLINK", 223 "type" : "SOCK_DGRAM", 224 "protocol" : "NETLINK_KOBJECT_UEVENT", 225 "permissions" : "0660", 226 "uid" : "system", 227 "gid" : "system", 228 "option" : [ 229 "SOCKET_OPTION_PASSCRED", 230 "SOCKET_OPTION_RCVBUFFORCE", 231 "SOCK_CLOEXEC", 232 "SOCK_NONBLOCK" 233 ] 234 }], 235 "uid" : 20, // UID of the MySystemApp service: 20 236 "gid" : 20, // GID of the MySystemApp service: 20 237 "once" : 0, // Not a one-off process of the MySystemApp service. If MySystemApp exits, the init process needs to restart it. 238 "importance" : 0, // Not a key system process of the MySystemApp service. If MySystemApp exits, the init process does not need to restart the development board. 239 "caps" : [], // Do not perform capability-related operations because capabilities are not required by the MySystemApp service. 240 "start-mode" : "condition", 241 "critical": [1, 2, 10], // Configure the critical field for MySystemApp system services. You need to pass three parameters, wherein, 1 means to enable system restarting, 2 means the number of times the critical service is restarted, and 10 means the time within which the critical service is restarted. 242 "cpucore" : [0, 1], // The device has two cores and both of them are bound to the CPU. 243 "apl" : "system_core", 244 "d-caps" : ["OHOS_DMS"], 245 "jobs" : { 246 "on-boot" : "boot", 247 "on-start" : "services:MySystemApp_start", 248 "on-stop" : "services:MySystemApp_stop", 249 "on-restart" : "services:MySystemApp_restart" 250 } 251 } 252 ] 253} 254``` 255 256After the configuration is complete, compile the package to burn the board. 257 1. Run the **task -a** command for liteos-a or **ps** for Linux to check whether the MySystemApp service process is started. 258 2. Run the **kill** command to kill the MySystemApp process, and verify that the process will be restarted. 259 3. Run the **kill** command to kill the MySystemApp process, and verify that the development board will not be restarted. 260 261 262## FAQs 263### Service Not Exist 264 265**Symptom** 266 267"Failed get servName" is recorded in the kernel log. 268 269**Cause Analysis** 270 271After a code review on the init process, it is found that the service does not exist. 272 273**Solution** 274 2751. Check whether the service is correctly configured in the **.cfg** file. 2762. Check whether the **.cfg** file of the service is loaded normally. 2773. Check whether the format of the **.cfg** file is correct. 278 279### Requesting FD Proxy for Other Services Failed 280 281**Symptom** 282 283"Service' xxx '(pid = xxx) is not valid or request with unexpected process(pid = xxx)" is recorded in the kernel log. 284 285**Cause Analysis** 286 287The kernel log is printed by the init process. After a code review on the init process, it is found that FD proxy is requested for other services. 288 289**Solution** 290 291Request FD proxy for the current service, but not other services. 292