1# HiTraceChain Development
2
3## Overview
4
5HiTraceChain tracks the call chain with the same **traceid** throughout the inter-device, inter-process, and inter-thread service processes. It associates and displays the call relationship and various output information during the entire process, helping you analyze and locate faults and optimize the system.
6
7
8## When to Use
9
10HiTraceChain can be used for the following purposes:
11
12- Associates and reports service process information (such as logs and events) on the device.
13
14- Displays and analyzes reported information on the cloud to facilitate fault location.
15
16- Works with the IDE to debug the detailed service process and time consumption distribution for system optimization.
17
18    **Figure 1** Use cases of HiTraceChain
19    ![](figures/use-cases-of-hitrace.png "use-cases-of-hitrace")
20
21
22### Usage Example
23
24  **Figure 2** Service calling process \(inter-device and inter-process synchronous call\)
25
26  ![](figures/service-calling-process-(inter-device-and-inter-process-synchronous-call).png "service-calling-process-(inter-device-and-inter-process-synchronous-call)")
27
281. Display the call relationship in the service process, analyze key paths and function dependency, and determine the time consumption and call frequency at each call point to detect performance bottlenecks.
29
30     **Figure 3** Service calling process
31     ![](figures/service-calling-process.png "service-calling-process")
32
33
34     **Figure 4** Time delay in the service calling process
35     ![](figures/time-delay-in-the-service-calling-process.png "time-delay-in-the-service-calling-process")
36
372. Add **traceid** to logs and events automatically to facilitate comprehensive analysis and quick fault location.
38
39
40## Available APIs
41
42HiTraceChain provides C++ and C APIs. The upper-layer services mainly use HiTraceChain to start and stop call chain trace.
43
44HiTraceChain is implemented at layer C. It works by transferring **traceid** throughout the service calling process. Before service processing, HiTrace sets **traceid** in the thread local storage (TLS) of the calling thread. During service processing, HiTrace obtains **traceid** from the contextual TLS of the calling thread and automatically adds it to the log and event information. After service processing is complete, HiTrace clears **traceid** from the TLS of the calling thread.
45
46
47### Java, C++, and C APIs
48
49  **Table 1** Description of C++ and C APIs
50
51|  | **C++** | **C** |
52| -------- | -------- | -------- |
53| **Class**| **Function**| **Function**|
54| HiTraceChain | HiTraceId Begin(const std::string& name, int flags) | HiTraceIdStruct HiTraceChainBegin(const char* name, int flags) |
55|  | void End(const HiTraceId& id) | void HiTraceChainEnd(const HiTraceIdStruct* pId) |
56|  | HiTraceId GetId(); | HiTraceIdStruct HiTraceChainGetId() |
57|  | void SetId(const HiTraceId& id) | void HiTraceChainSetId(const HiTraceIdStruct* pId) |
58|  | void ClearId() | void HiTraceChainClearId() |
59|  | HiTraceId CreateSpan() | HiTraceIdStruct HiTraceChainCreateSpan() |
60|  | void Tracepoint(HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | void HiTraceChainTracepoint(HiTraceTracepointType type, const HiTraceIdStruct* pId, const char* fmt, ...) |
61|  | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId& id, const char* fmt, ...) | void HiTraceChainTracepointEx(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceIdStruct* pId, const char* fmt, ...) |
62| HiTraceId | HiTraceId(); | void HiTraceChainInitId(HiTraceIdStruct* pId) |
63|  | HiTraceId(const uint8_t* pIdArray, int len) | HiTraceIdStruct HiTraceChainBytesToId(const uint8_t* pIdArray, int len) |
64|  | bool IsValid() | int HiTraceChainIsValid(const HiTraceIdStruct* pId) |
65|  | bool IsFlagEnabled(HiTraceFlag flag) | int HiTraceChainIsFlagEnabled(const HiTraceIdStruct* pId, HiTraceFlag flag) |
66|  | void EnableFlag(HiTraceFlag flag) | void HiTraceChainEnableFlag(HiTraceIdStruct* pId, HiTraceFlag flag) |
67|  | int GetFlags() | int HiTraceChainGetFlags(const HiTraceIdStruct* pId) |
68|  | void SetFlags(int flags) | void HiTraceChainSetFlags(HiTraceIdStruct* pId, int flags) |
69|  | uint64_t GetChainId() | uint64_t HiTraceChainGetChainId(const HiTraceIdStruct* pId) |
70|  | void SetChainId(uint64_t chainId) | void HiTraceChainSetChainId(HiTraceIdStruct* pId, uint64_t chainId) |
71|  | uint64_t GetSpanId() | uint64_t HiTraceChainGetSpanId(const HiTraceIdStruct* pId) |
72|  | void SetSpanId(uint64_t spanId) | void HiTraceChainSetSpanId(HiTraceIdStruct* pId, uint64_t spanId) |
73|  | uint64_t GetParentSpanId() | uint64_t HiTraceChainGetParentSpanId(const HiTraceIdStruct* pId) |
74|  | void SetParentSpanId(uint64_t parentSpanId) | void HiTraceChainSetParentSpanId(HiTraceIdStruct* pId, uint64_t parentSpanId) |
75|  | int ToBytes(uint8_t* pIdArray, int len) | int HiTraceChainIdToBytes(const HiTraceIdStruct_ pId, uint8_t* pIdArray, int len) |
76
77
78### Parameters of C++ APIs
79
80  **Table 2** Trace flag combination types
81
82| **Name**| **Value**| **Description**|
83| -------- | -------- | -------- |
84| HITRACE_FLAG_DEFAULT           | 0      | Default flag.      |
85| HITRACE_FLAG_INCLUDE_ASYNC | 1      | Asynchronous call flag. By default, only synchronous calls are traced. If this flag is set, both synchronous and asynchronous calls will be traced.  |
86| HITRACE_FLAG_DONOT_CREATE_SPAN | 1 << 1 | No span flag. By default, spans are created within a trace of synchronous and asynchronous service calls. If this flag is set, no spans are created.    |
87| HITRACE_FLAG_TP_INFO           | 1 << 2 | Trace point flag. By default, no trace point is added when trace is enabled. This flag is used for debugging. If this flag is set, trace points will be automatically added on the TX and RX sides of synchronous and asynchronous calls to output trace point and timestamp information. Trace points are classified into four types: client send (CS), server receive (SR), server send (SS), and client receive (CR). For a synchronous call, the output trace points are CS, SR, SS, and CR; for an asynchronous call, the output trace points are CS, SR, and SS.      |
88| HITRACE_FLAG_NO_BE_INFO        | 1 << 3 | No begin/end flag. By default, information about the start and end of the trace task is printed. If this flag is set, information about the start and end of the trace task will not be printed.|
89| HITRACE_FLAG_DONOT_ENABLE_LOG       | 1 << 4 | Log association flag. If this flag is set, information about the trace task will not be printed. |
90| HITRACE_FLAG_FAULT_TRIGGER   | 1 << 5 | Failure trigger flag. This flag is reserved for future use. |
91| HITRACE_FLAG_D2D_TP_INFO       | 1 << 6 | Device-to-device trace point flag. It is a subset of **TP_INFO**. If this flag is set, trace points are added only for call chain trace between devices.|
92
93  **Table 3** Trace point types
94
95| **Name**| **Value**| **Description**|
96| -------- | -------- | -------- |
97| HITRACE_TP_CS       | 0 | CS trace point.       |
98| HITRACE_TP_CR       | 1 | CR trace point.       |
99| HITRACE_TP_SS       | 2 | SS trace point.       |
100| HITRACE_TP_SR       | 3 | SR trace point.       |
101| HITRACE_TP_GENERAL  | 4 | General trace points except CS, CR, SS, and SR.|
102
103  **Table 4** Communication modes
104
105| **Name**| **Value**| **Description**|
106| -------- | -------- | -------- |
107| HITRACE_CM_DEFAULT  | 0 | Default communication mode.   |
108| HITRACE_CM_THREAD   | 1 | Inter-thread communication. |
109| HITRACE_CM_PROCESS  | 2 | Inter-process communication. |
110| HITRACE_CM_DEVICE   | 3 | Inter-device communication. |
111
112  **Table 5** Description of C++ APIs
113
114| **Class**| **API**| **Description**|
115| -------- | -------- | -------- |
116| HiTraceChain | HiTraceId Begin(const std::string&amp; name, int flags) | Starts HiTraceChain, generates a **HiTraceId** object, and sets it in the TLS of the calling thread.<br>Input arguments:<br>- **name**: name of the service process.<br>- **flags**: trace flags, which can be used in combination. For details, see Table 2.<br>Output arguments: none<br>Return value: a valid **HiTraceId** object if call chain trace is triggered successfully; returns an invalid object otherwise.<br>Note: In nested trace mode, an invalid object will be returned if trace is started at the nested layer.|
117|  | void End(const HiTraceId&amp; id) | Stops HiTraceChain based on the **HiTraceId** object returned by the **Begin** API, and clears the **HiTraceId** object in the TLS of the calling thread.<br>Input arguments:<br>- **id**: **HiTraceId** object.<br>Output arguments: none<br>Return value: none|
118|  | HiTraceId GetId(); | Obtains the **HiTraceId** object from the TLS of the calling thread.<br>Input arguments: none<br>Output arguments: none<br>Return value: **HiTraceId** object in the contextual TLS of the calling thread.|
119|  | void SetId(const HiTraceId&amp; id) | Purpose: Sets the **HiTraceId** object in the TLS of the calling thread.<br>Input arguments:<br>- **id**: **HiTraceId** object.<br>Output arguments: none<br>Return value: none|
120|  | void ClearId() | Clears the **HiTraceId** object in the TLS of the calling thread.<br>Input arguments: none<br>Output arguments: none<br>Return value: none|
121|  | HiTraceId CreateSpan() | Obtains the span ID from the current **HiTraceId** object.<br>Input arguments: none<br>Output arguments: none<br>Return value: current span ID.|
122|  | void Tracepoint(HiTraceTracepointType type, const HiTraceId&amp; id, const char* fmt, ...) | Outputs HiTraceChain trace point information based on the information type. The information includes the timestamp and **HiTraceId** object of the span.<br>Input arguments:<br>- **type**: trace point type. For details, see Table 3.<br>- **id**: ID of the current span.<br>- **fmt**: string describing the format variable parameter.<br>- **args**: variable parameter.<br>Output arguments: none<br>Return value: none|
123|  | void Tracepoint(HiTraceCommunicationMode mode, HiTraceTracepointType type, const HiTraceId&amp; id, const char* fmt, ...) | Outputs HiTraceChain trace point information based on the communication mode and information type. The information includes the timestamp and **HiTraceId** object of the span.<br>Input arguments:<br>- **mode**: communication mode. For details, see Table 4.<br>- **type**: trace point type. For details, see Table 3.<br>- **id**: ID of the current span.<br>- **fmt**: string describing the format variable parameter.<br>- **args**: variable parameter.<br>Output arguments: none<br>Return value: none|
124| HiTraceId | HiTraceId(); | Represents the default constructor used to generate an invalid **HiTraceId** object. <br>Input arguments: none<br>Output arguments: none<br>Return value: none|
125|  | HiTraceId(const uint8_t* pIdArray, int len) | Represents the constructor used to create a **HiTraceId** object based on the specified byte array. <br>Input arguments:<br>- **pIdArray**: pointer to a byte array.<br>- **len**: length of the byte array.<br>Output arguments: none<br>Return value: none|
126|  | bool IsValid() | Checks whether the **HiTraceId** object is valid.<br>Input arguments: none<br>Output arguments: none<br>Return value: **true** if the **HiTraceId** object is valid; **false** otherwise.|
127|  | bool IsFlagEnabled(HiTraceFlag flag) | Checks whether the trace flag of the **HiTraceId** object is enabled.<br>Input arguments:<br>- **flag**: trace flag. For details, see the description in the **Begin** function.<br>Output arguments: none<br>Return value: **true** if the trace flag is enabled; **false** otherwise.|
128|  | void EnableFlag(HiTraceFlag flag) | Enables the trace flag of the **HiTraceId** object.<br>Input arguments:<br>- **flag**: trace flag. For details, see the description in the **Begin** function.<br>Output arguments: none<br>Return value: none|
129|  | int GetFlags() | Obtains the trace flag set in the **HiTraceId** object.<br>Input arguments: none<br>Output arguments: none<br>Return value: Returns the combination of trace flags. For details, see the description in the **Begin** function.|
130|  | void SetFlags(int flags) | Sets a trace flag in the **HiTraceId** object.<br>Input arguments:<br>- **flags**: combination of trace flags. For details, see the description in the **Begin** function.<br>Output arguments: none<br>Return value: none|
131|  | uint64_t GetChainId() | Obtains the call chain ID.<br>Input arguments: none<br>Output arguments: none<br>Return value: call chain ID.|
132|  | void SetChainId(uint64_t chainId) | Sets the call chain ID in the **HiTraceId** object.<br>Input arguments:<br>- **chainId**: call chain ID.<br>Output arguments: none<br>Return value: none|
133|  | uint64_t GetSpanId() | Obtains the span ID from the current **HiTraceId** object.<br>Input arguments: none<br>Output arguments: none<br>Return value: current span ID.|
134|  | void SetSpanId(uint64_t spanId) | Sets the span ID in the **HiTraceId** object.<br>Input arguments:<br>- **spanId**: span ID.<br>Output arguments: none<br>Return value: none|
135|  | uint64_t GetParentSpanId() | Obtains the parent span ID from the current **HiTraceId** object.<br>Input arguments: none<br>Output arguments: none<br>Return value: parent span ID.|
136|  | void SetParentSpanId(uint64_t parentSpanId) | Sets the parent span ID in the **HiTraceId** object.<br>Input arguments:<br>- **parentSpanId**: parent span ID.<br>Output arguments: none<br>Return value: none|
137|  | int ToBytes(uint8_t* pIdArray, int len) | Converts the **HiTraceId** object into a byte array to facilitate caching or communication transfer.<br>Input arguments:<br>- **pIdArray**: pointer to a byte array. The minimum length of the byte array is **HITRACE_ID_LEN**.<br>- **len**: length of the byte array.<br>Output parameters:<br>- **pIdArray**: pointer to a byte array. If the object is valid, the object data after conversion is stored.<br>Return value: a value greater than **0** (indicating a valid array of object data) if the conversion is successful; **0** otherwise.|
138
139
140### Call Chain Processing
141
142Inter-device, inter-process, and inter-thread calls are implemented through the communication mechanism. HiTraceChain requires transfer of **traceid** in the communication mechanism.
143
144Some built-in communication mechanisms (such as ZIDL) of OpenHarmony already support the transfer of **traceid**.
145
146The following figure shows the process of transferring **traceid** in synchronous call. The process of transferring **traceid** in asynchronous call is similar.
147
148  Extended communication mechanisms can also follow this implementation.
149  **Figure 5** Call chain trace in synchronous communication
150  ![](figures/call-chain-trace-in-synchronous-communication.png "call-chain-trace-in-synchronous-communication")
151
152The process is as follows:
153
1541. The service module on the client calls the **begin()** function to start call chain trace.
155
1562. The service module on the client synchronously calls the **transact** function to the communication component on the client.
157
1583. The communication component on the client performs the following:
159   1. Obtains **traceid** from the TLS of the calling thread.
160   2. Generates child **traceid**.
161   3. Writes child **traceid** into the transaction data (synchronous communication data).
162   4. Performs CS trace.
163   5. Sends communication data to the communication component on the server.
164
1654. On receiving the communication data, the communication component on the server performs the following:
166   1. Obtains **traceid** from the data message package.
167   2. Sets **traceid** in the TLS of the calling thread.
168   3. Performs SR trace.
169   4. Synchronously calls the **onTransact** callback to the service module on the server.
170
1715. The service module on the server processes the service and sends the transact reply message carrying the processing result to the communication component.
172
1736. The communication component on the server performs the following:
174   1. Performs SS trace.
175   2. Sends communication data to the communication component on the client.
176   3. Clears **traceid** from the TLS of the calling thread.
177
1787. On receiving the communication data, the communication component on the client performs the following:
179   1. Performs CR trace.
180   2. Sends a transact reply response to the service module on the client.
181
1828. The service module on the client processes the transact reply response.
183
1849. When the process ends, the service module on the client calls the **end()** function to stop call chain trace.
185
186
187## How to Develop
188
189
190### **C++**
191
1921. Develop the source code.
193     Include the **hitracechain** header file in the class definition header file or class implementation source file. For example:
194
195   ```
196   #include "hitrace/tracechain.h"
197   ```
198
199     Add the code to start and stop call chain trace in the class implementation source file.
200
201   ```
202   using namespace OHOS::HiviewDFX;
203   auto traceId = HiTraceChain::Begin("MyServiceFlow", HITRACE_FLAG_DEFAULT);
204   ......
205   HiTraceChain::End(traceId);
206   ```
207
2082. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**.
209
210   ```
211   external_deps = [ "hitrace:libhitracechain" ]
212   ```
213
214
215### **C**
216
2171. Develop the source code.
218     Include the **hitracechain** header file in the source file.
219
220   ```
221   #include "hitrace/tracechain.h"
222   ```
223
224     Add the code to start and stop call chain trace in the class implementation source file.
225
226   ```
227   HiTraceIdStruct traceId = HiTraceChainBegin("MyServiceFlow", HITRACE_FLAG_DEFAULT);
228   ......
229   HiTraceChainEnd(traceId);
230   ```
231
2322. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**.
233
234   ```
235   external_deps = [ "hitrace:libhitracechain" ]
236   ```
237