未验证 提交 1b6e92c9 编写于 作者: O openharmony_ci 提交者: Gitee

!7290 翻译已完成6298

Merge pull request !7290 from shawn_he/6298-a
# Data Request
>![](public_sys-resources/icon-note.gif) **NOTE**
This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE**
>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
......@@ -18,17 +20,17 @@ import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
......@@ -48,7 +50,7 @@ httpRequest.request(
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete.
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
......@@ -79,7 +81,7 @@ let httpRequest = http.createHttp();
## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request
......@@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ----------------------- |
| url | string | Yes | URL for initiating an HTTP request.|
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | Yes | URL for initiating an HTTP request.|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example**
......@@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | -------------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value**
| Type | Description |
| :-------------------- | :-------------------------------- |
| Type | Description |
| :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
......@@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE**
>
> This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack
......@@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE**
>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- |
| method | [RequestMethod](#requestmethod) | No | Request method. |
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.|
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
## RequestMethod
......@@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. |
| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. |
| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.|
| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. |
......@@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request.
| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. |
| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. |
| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. |
| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. |
......@@ -433,6 +433,17 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error|
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
## Error Codes
| Error Code| Description |
| ------ | ------------------------------------------------------------ |
| -1 | Incorrect parameters. |
| 3 | Incorrect URL format. |
| 4 | Built-in request function, protocol, or option not found during build. |
| 5 | Unable to resolve the proxy. |
| 6 | Unable to resolve the host. |
| 7 | Unable to connect to the proxy or host. |
# HiSysEvent Logging<a name="EN-US_TOPIC_0000001231373947"></a>
## Overview<a name="section77571101789"></a>
### Introduction<a name="section123133332175224"></a>
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics.
### Constraints<a name="section123181432175224"></a>
Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines<a name="section314416685113"></a>
### Available APIs<a name="section13480315886"></a>
The following table lists the C++ APIs provided by the HiSysEvent class.
For details about the HiSysEvent class, see the API reference.
**Table 1** C++ APIs provided by HiSysEvent
| API| Description|
| -------- | --------- |
| template&lt;typename... Types&gt; static int Write(const std::string &amp;domain, const std::string &amp;eventName, EventType type, Types... keyValues) | Logs system events. <br><br>Input arguments: <ul><li>**domain**: Indicates the domain related to the event. You can use a preconfigured domain or customize a domain as needed. The name of a custom domain can contain a maximum of 16 characters, including digits (0-9) and uppercase letters (A-Z). It must start with a letter. </li><li>**eventName**: Indicates the event name. The value contains a maximum of 32 characters, including digits (0 to 9), letters (A-Z), and underscores (&#95;). It must start with a letter and cannot end with an underscore. </li><li>**type**: Indicates the event type. For details, see EventType. </li><li>**keyValues**: Indicates the key-value pairs of event parameters. It can be in the format of the basic data type, std::string, std::vector&lt;basic data type&gt;, or std:vector&lt;std::string&gt;. The value contains a maximum of 48 characters, including digits (0 to 9), letters (A-Z), and underscores (&#95;). It must start with a letter and cannot end with an underscore. The number of parameter names cannot exceed 32. </li></ul>Return value: <ul><li>**0**: The logging is successful. </li><li>Negative value: The logging has failed.</li></ul> |
**Table 2** Description of HiSysEvent::Domain APIs
| API| Description|
| -------- | --------- |
| static const std::string AAFWK | Atomic ability subsystem|
| static const std::string APPEXECFWK | User program framework subsystem|
| static const std::string ACCOUNT | Account subsystem|
| static const std::string ARKUI | ARKUI subsystem|
| static const std::string AI | AI subsystem|
| static const std::string BARRIER_FREE | Accessibility subsystem|
| static const std::string BIOMETRICS | Biometric recognition subsystem|
| static const std::string CCRUNTIME |C/C++ operating environment subsystem|
| static const std::string COMMUNICATION | Public communication subsystem|
| static const std::string DEVELOPTOOLS | Development toolchain subsystem|
| static const std::string DISTRIBUTED_DATAMGR | Distributed data management subsystem|
| static const std::string DISTRIBUTED_SCHEDULE | Distributed Scheduler subsystem|
| static const std::string GLOBAL | Globalization subsystem|
| static const std::string GRAPHIC | Graphics subsystem|
| static const std::string HIVIEWDFX | DFX subsystem|
| static const std::string IAWARE | Scheduling and resource management subsystem|
| static const std::string INTELLI_ACCESSORIES | Smart accessory subsystem|
| static const std::string INTELLI_TV | Smart TV subsystem|
| static const std::string IVI_HARDWARE | IVI-dedicated hardware subsystem|
| static const std::string LOCATION | LBS subsystem|
| static const std::string MSDP | MSDP subsystem|
| static const std::string MULTI_MEDIA | Media subsystem|
| static const std::string MULTI_MODAL_INPUT | Multimode input subsystem|
| static const std::string NOTIFICATION | Common event and notification subsystem|
| static const std::string POWERMGR | Power management subsystem|
| static const std::string ROUTER | Router subsystem|
| static const std::string SECURITY | Security subsystem|
| static const std::string SENSORS | Pan-sensor subsystem|
| static const std::string SOURCE_CODE_TRANSFORMER | Application porting subsystem|
| static const std::string STARTUP | Startup subsystem|
| static const std::string TELEPHONY | Telephony subsystem|
| static const std::string UPDATE | Update subsystem|
| static const std::string USB | USB subsystem|
| static const std::string WEARABLE_HARDWARE | Wearable-dedicated hardware subsystem|
| static const std::string WEARABLE_HARDWARE | Wearable-dedicated service subsystem|
| static const std::string OTHERS | Others|
**Table 3** Description of HiSysEvent::EventType
| Name| Description|
| -------- | --------- |
| FAULT | Fault event|
# HiSysEvent Logging
## Overview
### Introduction
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running. Besides, it supports shielding of event logging by event domain, helping you to evaluate the impact of event logging.
### Working Principles
Before logging system events, you need to complete HiSysEvent logging configuration. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines
### When to Use
Use HiSysEvent logging to flush logged event data to disks.
### Available APIs
#### C++ Event Logging APIs
HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> In OpenHarmony-3.2-Beta3, HiSysEvent logging is open for restricted use to avoid event storms. The **HiSysEvent::Write** API in Table 1 is replaced by the **HiSysEventWrite** API in Table 2. The **HiSysEvent::Write** API has been deprecated. Use the **HiSysEventWrite** API instead for HiSysEvent logging.
**Table 1** C++ event logging API (deprecated)
| API | Description |
| ------------------------------------------------------------ | ---------------------- |
| template&lt;typename...&nbsp;Types&gt;&nbsp;<br>static&nbsp;int&nbsp;Write(const&nbsp;std::string&nbsp;&amp;domain,&nbsp;const&nbsp;std::string&nbsp;&amp;eventName,&nbsp;EventType&nbsp;type,&nbsp;Types...&nbsp;keyValues) | Flushes logged event data to disks.|
**Table 2** C++ event logging API (in use)
| API | Description |
| ------------------------------------------------------------ | ---------------------- |
| HiSysEventWrite(domain, eventName, type, ...) | Flushes logged event data to disks.|
**Table 3** Event types
| Event | Description |
| --------- | ------------ |
| FAULT | Fault event|
| STATISTIC | Statistical event|
| SECURITY | Security event|
| BEHAVIOR | Behavior event|
#### Kernel Event Logging APIs
The following table describes the kernel event logging APIs.
**Table 4** Description of kernel event logging APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------ |
| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | Creates a **hisysevent** object. |
| void hisysevent_destroy(struct hiview_hisysevent *event); | Destroys a **hisysevent** object. |
| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | Adds event parameters of the integer type to a **hisysevent** object. |
| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | Adds event parameters of the string type to a **hisysevent** object.|
| int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to disks. |
Table 5 Kernel event types
| Event | Description |
| --------- | ------------ |
| FAULT | Fault event|
| STATISTIC | Statistical event|
| SECURITY | Security event|
| BEHAVIOR | System behavior event|
| SECURITY | Security event|
| BEHAVIOR | Behavior event|
### How to Develop
#### C++ Event Logging
1. Call the event logging API wherever needed, with required event parameters passed to the API.
```c++
HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo");
```
#### Kernel Event Logging
1. Create a **hisysevent** object based on the specified event domain, event name, and event type.
```c
struct hiview_hisysevent *event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR);
```
2. Pass the customized event parameters to the **hisysevent** object.
### Development Example<a name="section112771171317"></a>
```c
// Add a parameter of the integer type.
hisysevent_put_integer(event, "BOOT_TIME", 100);
C++
// Add a parameter of the string type.
hisysevent_put_string(event, "MSG", "This is a test message");
```
1. Develop the source code.
3. Trigger reporting of the **hisysevent** event.
Include the HiSysEvent header file in the class definition header file or class implementation source file. For example:
```c
hisysevent_write(event);
```
4. Manually destroy the **hisysevent** object.
```c
hisysevent_destroy(&event);
```
#### Shielding of Event Logging by Event Domain
1. In the corresponding file, define the **DOMAIN_MASKS** macro with content similar to DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n. There are three scenarios:
- Shielding only event logging for the event domains configured in the current source code file: Define the **DOMAIN_MASKS** macro before importing the **.cpp** file to the **hisysevent.h** file.
```c++
#define DOMAIN_MASKS "DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n"
#include "hisysevent.h"
```
- Shielding event logging for event domains of the entire module: Define the **DOMAIN_MASKS** macro in the **BUILD.gn** file of the module.
```gn
config("module_a"){
cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""]
}
```
- Shielding event logging for event domains globally: Define the **DOMAIN_MASKS** macro in **/build/config/compiler/BUILD.gn**.
```gn
cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""]
```
2. Perform event logging by using the **HiSysEventWrite** API.
```c++
constexpr char DOMAIN[] = "DOMAIN_NAME_1";
const std::string eventName = "EVENT_NAME1";
OHOS:HiviewDFX::HiSysEvent::EventType eventType = OHOS:HiviewDFX::HiSysEvent::EventType::FAULT;
HiSysEventWrite(domain, eventName, eventType); // Event logging is shielded for DOMAIN_NAME_1 because it has been defined in the DOMAIN_MASKS macro.
```
### Development Examples
#### C++ Event Logging
Assume that a service module needs to trigger event logging during application startup to record the application startup event and application bundle name. The following is the complete sample code:
1. Add the HiSysEvent component dependency to the **BUILD.gn** file of the service module.
```c++
external_deps = [ "hisysevent_native:libhisysevent" ]
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in.
```c++
#include "hisysevent.h"
int StartAbility()
{
... // Other service logic
int ret = HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo");
... // Other service logic
}
```
#### Kernel Event Logging
Assume that the kernel service module needs to trigger event logging during device startup to record the device startup event. The following is the complete sample code:
1. In the device startup function **device_boot()**, construct a **hisysevent** object. After that, trigger event reporting, and then destroy the **hisysevent** object.
```c
#include <dfx/hiview_hisysevent.h>
#include <linux/errno.h>
#include <linux/printk.h>
int device_boot()
{
... // Other service logic
struct hiview_hisysevent *event = NULL;
int ret = 0;
event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR);
if (!event) {
pr_err("failed to create event");
return -EINVAL;
}
ret = hisysevent_put_string(event, "MSG", "This is a test message");
if (ret != 0) {
pr_err("failed to put sting to event, ret=%d", ret);
goto hisysevent_end;
}
ret = hisysevent_write(event);
hisysevent_end:
hisysevent_destroy(&event);
... // Other service logic
}
```
#### Shielding of Event Logging by Event Domain
- If you want to shield event logging for the **AAFWK** and **POWER** domains in a **.cpp** file, define the **DOMAIN_MASKS** macro before including the **hisysevent.h** header file to the **.cpp** file.
```c++
#define DOMAIN_MASKS "AAFWK|POWER"
#include "hisysevent.h"
```
... // Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "MODULE", "com.ohos.module"); // HiSysEvent logging is not performed.
... // Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER, "POWER_RUNNINGLOCK", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "NAME", "com.ohos.module"); // HiSysEvent logging is not performed.
Add the event logging code. For example, if you want to log events specific to the app start time (start\_app), then add the following code to the service implementation source file:
```
- If you want to shield event logging for the **AAFWK** and **POWER** domains of the entire service module, define the **DOMAIN_MASKS** macro as follows in the **BUILG.gn** file of the service module.
```gn
config("module_a") {
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
}
```
HiSysEvent::Write(HiSysEvent::Domain::AAFWK, "start_app", HiSysEvent::EventType::FAULT, "app_name", "com.demo");
- If you want to shield event logging for the **AAFWK** and **POWER** domains globally, define the **DOMAIN_MASKS** macro as follows in **/build/config/compiler/BUILD.gn**.
```gn
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
```
2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**.
# Reference
```
external_deps = [ "hisysevent_native:libhisysevent" ]
```
The HiSysEvent module writes the logged event data to the node file, and the Hiview module parses and processes the event data in a unified manner. For details, see the [Hiview Development Guide](subsys-dfx-hiview.md).
# HiSysEvent Overview
## Introduction
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics.
The key modules of HiSysEvent are described as follows:
- Event configuration: enables you to define HiSysEvent events in YAML files.
- Trace point configuration: provides trace point APIs and supports flushing of HiSysEvent events to disks.
- Event subscription: provides APIs for you to subscribe to HiSysEvent events by event domain and event name.
- Event query: provides APIs for you to query HiSysEvent events by event domain and event name.
- Event debugging tool: allows you to subscribe to real-time HiSysEvent events and query historical HiSysEvent events.
## Reference
For more information about the source code and usage of HiSysEvent, access the HiSysEvent code repository(https://gitee.com/openharmony/hiviewdfx_hisysevent).
# HiSysEvent Development<a name="EN-US_TOPIC_0000001195021448"></a>
- **[HiSysEvent Overview](subsys-dfx-hisysevent-overview.md)**
- **[HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md)**
- **[HiSysEvent Logging](subsys-dfx-hisysevent-logging.md)**
......
# Hiview Development Guide
## Introduction
### Function Overview
Hiview is a module that provides toolkits for device maintenance across different platforms. It consists of the plugin management platform and the service plugins running on the platform. Hiview works in event-driven mode. The core of Hiview is a collection of HiSysEvent stubs distributed in the system. Formatted events are reported to Hiview through the HiSysEvent API for processing. The following figure shows the data interaction process.
**Figure 1** Data interaction between Hiview modules
![Hiview_module_data_interaction](figure/Hiview_module_data_interaction.png)
1. The service process calls the event logging API to report logged event information and writes the information to the node file.
2. SysEventSource of the Hiview process asynchronously reads event information from the node file and distributes the event to SysEventPipeline for processing.
- The SysEventService plugin verifies events and flushes them to disks.
- The Faultlogger plugin processes fault-related events.
- The EventLogger plugin collects event-related log information.
3. On completion of event processing, SysEventPipeline sends the events to the event subscription queue and then dispatches the events to the subscription plugin for processing.
- FreezeDetectorPlugin processes screen freezing events.
- HiCollieCollector processes suspension events.
### Basic Concepts
Before you get started, familiarize yourself with the following concepts:
- Plug-in
An independent module running in the Hiview process. A plugin is delivered with the Hiview binary file to implement maintenance and fault management functions independently. Plug-ins can be disassembled independently during compilation, and can be hosted on the platform during running and dynamically configured.
- Pipeline
An ordered set of event processing plugins. Events entering the pipeline are processed by plugins on the pipeline in sequence.
- Event source
A special plugin that can produce events. Different from common plugins, a special plugin can be bound to a pipeline, and can produce events and distribute them to the pipeline.
- Pipeline group
A group of pipelines configured on the same event source.
### Working Principles
Hiview supports plugin development on the plugin management platform and provides the required plugin development capabilities. You can add plugins to the Hiview platform to implement HiSysEvent event processing. Before you get started, you're expected to have a basic understanding of plugin working principles.
#### Plug-in Registration
A plugin can be registered in any of the following modes.
| Mode | Description |
| ------------------ | ------------------------------------------------------------ |
| Static registration | Use the **REGISTER(xxx);** macro to register the plugin. Such a plugin cannot be unloaded.|
| Proxy registration | Use the **REGISTER_PROXY(xxx);** macro to register the plugin. Such a plugin is not loaded upon startup and can be loaded and unloaded dynamically during system running.|
| Proxy registration and loading upon startup| Use the **REGISTER_PROXY_WITH_LOADED(xxx);** macro to register the plugin. Such a plugin is loaded upon startup and can be unloaded and loaded dynamically during system running.|
#### Plug-in Event-Driven Modes
There are two event-driven modes available for plugins: pipeline-driven and subscription-driven. The differences are as follows:
- Pipeline-driven plugins need to be configured on the pipeline. After an event is distributed from an event source to the pipeline, the event traverses the plugins configured on the pipeline in sequence for processing.
- Subscription-driven plugins do not need to be configured on the pipeline. However, a listener needs to be registered with the Hiview platform upon plugin startup, and the plugin needs to implement the event listener function.
#### Plug-in Loading
Depending on your service demand, you can compile all or some plugins into the Hiview binary file.
Multiple plugins can be built into an independent plugin package and preset in the system as an independent **.so** file. One **.so** file corresponds to one **plugin_config** file. For example, **libxxx.z.so** corresponds to the** xxx_plugin_config** file. When the Hiview process starts, it scans for the plugin package (**.so** file) and the corresponding configuration file and loads the plugins in the plugin package.
The plugin package is described as follows:
1. The plugin package runs on the plugin management platform as an independent entity. The plugins, pipelines, or event sources in it provide the same functions as the plugins in the Hiview binary.
2. Plug-ins in the plugin package can be inserted into the Hiview binary pipeline.
3. Subscribers, wherever they are located, can receive events sent by the platform based on the subscription rules.
## Plug-in Development Guide
### When to Use
You can deploy a plugin on the Hiview platform if you want to perform specific service processing on the HiSysEvent events distributed from the event source. The following table describes the APIs used for plugin development.
### Available APIs
The following table lists the APIs related to plugin development. For details about the APIs, see the API Reference.
Table 1 Description of Plugin APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| virtual void OnLoad() | Loads plugins. After plugins are loaded, you can call this API to initialize data.|
| virtual void OnUnload() | Unloads plugins. Before plugins are unloaded, you can call this API to reclaim data. |
| virtual bool ReadyToLoad() | Checks whether the current plugin can be loaded when the Hiview starts plugin loading. |
| virtual bool OnEvent(std::shared_ptr\<Event\>& event) | Implements event processing. You can call this API to receive events distributed by the pipeline or platform perform service processing.|
| virtual bool CanProcessEvent(std::shared_ptr\<Event\> event) | Checks whether an event can traverse backward throughout the entire pipeline. This function takes effect only when the plugin is the first one in the pipeline.|
| HiviewContext* GetHiviewContext() | Obtains the context of the Hiview plugin management platform. |
**Table 2** Description of Event APIs
| API | Description |
| ---------------------- | ---------------------------- |
| domain_ | Event domain. |
| eventName_ | Event name. |
| happenTime_ | Time when an event occurs. |
| jsonExtraInfo_ | Event data in JSON format. |
| bool IsPipelineEvent() | Whether an event is a pipeline event. |
| bool HasFinish() | Whether an event can continue to traverse backward.|
### How to Develop
1. Define a service plugin class, namely, **PluginExample**, which inherits from the **Plugin** class.
```c++
#include "event.h"
#include "plugin.h"
class PluginExample : public Plugin {
public:
bool OnEvent(std::shared_ptr<Event>& event) override;
void OnLoad() override;
void OnUnload() override;
};
```
2. In the plugin class implementation code, register the plugin and overwrite the corresponding functions based on the service requirements.
```c++
#include "plugin_factory.h"
// Register the plugin in static registration mode.
REGISTER(PluginExample);
void PluginExample::OnLoad()
{
... // Initialize plugin resources while the plugin is loaded.
printf("PluginExample OnLoad \n");
}
void PluginExample::OnUnload()
{
... // Release plugin resources while the plugin is unloaded.
printf("PluginExample OnUnload \n");
}
bool PluginExample::OnEvent(std::shared_ptr<Event>& event)
{
... // Perform specific service processing on the event using the event processing function.
printf("PluginExample OnEvent \n");
// If the plugin focuses only on events of a certain domain, log only the events of this domain.
if (event->domain_ == "TEST_DOMAIN") {
printf("The event data received is %s \n", event->jsonExtraInfo_);
return true;
}
return false;
}
```
3. Configure the plugin in the **plugin_build.json** file and compile the plugin with the Hiview binary file.
```json
{
"plugins": {
"PluginExample": {
"path": "plugins/PluginExample",
"name": "PluginExample"
}
},
"rules": [
{
"info": {
"loadorder": {
"PluginExample": {
"loadtime": 0
}
},
"pipelines": {
"SysEventPipeline": [
PluginExample
]
}
}
}
]
}
```
## Reference
For more information about the source code and usage of HiSysEvent, access the Hiview code repository(https://gitee.com/openharmony/hiviewdfx_hiview).
......@@ -12,6 +12,7 @@ The DFX subsystem provides the following functions:
- HiChecker: implements defect scanning. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- HiDumper: exports system information. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- FaultLogger: implements crash detection. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- Hiview: implements device maintenance across different platforms. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
## Basic Concepts<a name="section5635178134811"></a>
......
......@@ -8,3 +8,4 @@
- **[HiSysEvent Development](subsys-dfx-hisysevent.md)**
- **[HiDumper Development](subsys-dfx-hidumper.md)**
- **[HiChecker Development](subsys-dfx-hichecker.md)**
- **[Hiview Development](subsys-dfx-hiview.md)**
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册