1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "trace_data_cache.h"
17
18 #include <fcntl.h>
19 #include <stack>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23
24 #include "animation_table.h"
25 #include "app_startup_table.h"
26 #include "args_table.h"
27 #include "bio_latency_sample_table.h"
28 #include "callstack_table.h"
29 #include "clk_event_filter_table.h"
30 #include "clock_event_filter_table.h"
31 #include "clock_snapshot_table.h"
32 #include "cpu_measure_filter_table.h"
33 #include "cpu_usage_info_table.h"
34 #include "data_dict_table.h"
35 #include "data_type_table.h"
36 #include "datasource_clockid_table.h"
37 #include "device_info_table.h"
38 #include "device_state_table.h"
39 #include "disk_io_table.h"
40 #include "dynamic_frame_table.h"
41 #include "ebpf_callstack_table.h"
42 #include "file.h"
43 #include "file_system_sample_table.h"
44 #include "filter_table.h"
45 #include "frame_maps_table.h"
46 #include "frame_slice_table.h"
47 #include "gpu_slice_table.h"
48 #include "js_config_table.h"
49 #include "js_cpu_profiler_node_table.h"
50 #include "js_cpu_profiler_sample_table.h"
51 #include "js_heap_edges_table.h"
52 #include "js_heap_files_table.h"
53 #include "js_heap_info_table.h"
54 #include "js_heap_location_table.h"
55 #include "js_heap_nodes_table.h"
56 #include "js_heap_sample_table.h"
57 #include "js_heap_string_table.h"
58 #include "js_heap_trace_function_info_table.h"
59 #include "js_heap_trace_node_table.h"
60 #include "hidump_table.h"
61 #include "instants_table.h"
62 #include "irq_table.h"
63 #include "live_process_table.h"
64 #include "log_table.h"
65 #include "measure_table.h"
66 #include "memory_ashmem_table.h"
67 #include "memory_dma_table.h"
68 #include "memory_process_gpu_table.h"
69 #include "memory_window_gpu_table.h"
70 #include "memory_cpu_table.h"
71 #include "memory_profile_table.h"
72 #include "memory_rs_image_table.h"
73 #include "meta_table.h"
74 #include "native_hook_frame_table.h"
75 #include "native_hook_statistic_table.h"
76 #include "native_hook_table.h"
77 #include "native_hook_statistic_table.h"
78 #include "network_table.h"
79 #include "paged_memory_sample_table.h"
80 #include "ebpf_data_structure.h"
81 #include "perf_call_chain_table.h"
82 #include "perf_files_table.h"
83 #include "perf_report_table.h"
84 #include "perf_sample_table.h"
85 #include "perf_thread_table.h"
86 #include "process_measure_filter_table.h"
87 #include "process_table.h"
88 #include "range_table.h"
89 #include "raw_table.h"
90 #include "sched_slice_table.h"
91 #include "smaps_table.h"
92 #include "span_join.h"
93 #include "sqlite3.h"
94 #include "stat_table.h"
95 #include "so_static_initalization_table.h"
96 #include "string_to_numerical.h"
97 #include "symbols_table.h"
98 #include "sysevent_all_event_table.h"
99 #include "sysevent_measure_table.h"
100 #include "sysevent_subkey_table.h"
101 #include "system_call_table.h"
102 #include "system_event_filter_table.h"
103 #include "table_base.h"
104 #include "task_pool_table.h"
105 #include "thread_state_table.h"
106 #include "thread_table.h"
107 #include "trace_config_table.h"
108
109 namespace SysTuning {
110 namespace TraceStreamer {
111 constexpr uint8_t CPU_ID_FORMAT_WIDTH = 3;
112 constexpr uint8_t TIME_PRECISION_SIX = 6;
TraceDataCache()113 TraceDataCache::TraceDataCache()
114 {
115 InitDB();
116 }
117
~TraceDataCache()118 TraceDataCache::~TraceDataCache() {}
InitEbpfDB()119 void TraceDataCache::InitEbpfDB()
120 {
121 TableBase::TableDeclare<EbpfCallStackTable>(*db_, this, "ebpf_callstack");
122 TableBase::TableDeclare<BioLatencySampleTable>(*db_, this, "bio_latency_sample");
123 TableBase::TableDeclare<FileSystemSampleTable>(*db_, this, "file_system_sample");
124 TableBase::TableDeclare<PagedMemorySampleTable>(*db_, this, "paged_memory_sample");
125 }
InitNativeMemoryDB()126 void TraceDataCache::InitNativeMemoryDB()
127 {
128 TableBase::TableDeclare<NativeHookTable>(*db_, this, "native_hook");
129 TableBase::TableDeclare<NativeHookFrameTable>(*db_, this, "native_hook_frame");
130 TableBase::TableDeclare<NativeHookStatisticTable>(*db_, this, "native_hook_statistic");
131 }
InitArkTsDB()132 void TraceDataCache::InitArkTsDB()
133 {
134 TableBase::TableDeclare<JsHeapFilesTable>(*db_, this, "js_heap_files");
135 TableBase::TableDeclare<JsHeapEdgesTable>(*db_, this, "js_heap_edges");
136 TableBase::TableDeclare<JsHeapInfoTable>(*db_, this, "js_heap_info");
137 TableBase::TableDeclare<JsHeapLocationTable>(*db_, this, "js_heap_location");
138 TableBase::TableDeclare<JsHeapNodesTable>(*db_, this, "js_heap_nodes");
139 TableBase::TableDeclare<JsHeapSampleTable>(*db_, this, "js_heap_sample");
140 TableBase::TableDeclare<JsHeapStringTable>(*db_, this, "js_heap_string");
141 TableBase::TableDeclare<JsHeapTraceFunctionInfoTable>(*db_, this, "js_heap_trace_function_info");
142 TableBase::TableDeclare<JsHeapTraceNodeTable>(*db_, this, "js_heap_trace_node");
143 TableBase::TableDeclare<JsCpuProfilerNodeTable>(*db_, this, "js_cpu_profiler_node");
144 TableBase::TableDeclare<JsCpuProfilerSampleTable>(*db_, this, "js_cpu_profiler_sample");
145 TableBase::TableDeclare<JsConfigTable>(*db_, this, "js_config");
146 }
InitHiperfDB()147 void TraceDataCache::InitHiperfDB()
148 {
149 TableBase::TableDeclare<PerfReportTable>(*db_, this, "perf_report");
150 TableBase::TableDeclare<PerfSampleTable>(*db_, this, "perf_sample");
151 TableBase::TableDeclare<PerfCallChainTable>(*db_, this, "perf_callchain");
152 TableBase::TableDeclare<PerfThreadTable>(*db_, this, "perf_thread");
153 TableBase::TableDeclare<PerfFilesTable>(*db_, this, "perf_files");
154 }
InitMeasureDB()155 void TraceDataCache::InitMeasureDB()
156 {
157 TableBase::TableDeclare<MeasureTable>(*db_, this, "measure");
158 TableBase::TableDeclare<MeasureTable>(*db_, this, "sys_mem_measure");
159 TableBase::TableDeclare<MeasureTable>(*db_, this, "process_measure");
160 TableBase::TableDeclare<CpuMeasureFilterTable>(*db_, this, "cpu_measure_filter");
161 TableBase::TableDeclare<FilterTable>(*db_, this, "measure_filter");
162 TableBase::TableDeclare<ProcessMeasureFilterTable>(*db_, this, "process_measure_filter");
163 TableBase::TableDeclare<ClockEventFilterTable>(*db_, this, "clock_event_filter");
164 TableBase::TableDeclare<ClkEventFilterTable>(*db_, this, "clk_event_filter");
165 }
InitBaseDB()166 void TraceDataCache::InitBaseDB()
167 {
168 TableBase::TableDeclare<ProcessTable>(*db_, this, "process");
169 TableBase::TableDeclare<ThreadTable>(*db_, this, "thread");
170 TableBase::TableDeclare<RangeTable>(*db_, this, "trace_range");
171 TableBase::TableDeclare<DataTypeTable>(*db_, this, "data_type");
172 TableBase::TableDeclare<SpanJoin>(*db_, this, "span_join");
173 TableBase::TableDeclare<SymbolsTable>(*db_, this, "symbols");
174 TableBase::TableDeclare<StatTable>(*db_, this, "stat");
175 TableBase::TableDeclare<ArgsTable>(*db_, this, "args");
176 TableBase::TableDeclare<MetaTable>(*db_, this, "meta");
177 TableBase::TableDeclare<TraceConfigTable>(*db_, this, "trace_config");
178 TableBase::TableDeclare<DataDictTable>(*db_, this, "data_dict");
179 TableBase::TableDeclare<DataSourceClockIdTableTable>(*db_, this, "datasource_clockid");
180 TableBase::TableDeclare<ClockSnapShotTable>(*db_, this, "clock_snapshot");
181 }
InitTemplateDB()182 void TraceDataCache::InitTemplateDB()
183 {
184 // task pool business
185 TableBase::TableDeclare<TaskPoolTable>(*db_, this, "task_pool");
186 // app start up business
187 TableBase::TableDeclare<AppStartupTable>(*db_, this, "app_startup");
188 // so initalize business
189 TableBase::TableDeclare<SoStaticInitalizationTable>(*db_, this, "static_initalize");
190 // animation business
191 TableBase::TableDeclare<AnimationTable>(*db_, this, "animation");
192 TableBase::TableDeclare<DynamicFrameTable>(*db_, this, "dynamic_frame");
193 TableBase::TableDeclare<DeviceInfoTable>(*db_, this, "device_info");
194 }
InitRenderServiceDB()195 void TraceDataCache::InitRenderServiceDB()
196 {
197 TableBase::TableDeclare<FrameSliceTable>(*db_, this, "frame_slice");
198 TableBase::TableDeclare<FrameMapsTable>(*db_, this, "frame_maps");
199 TableBase::TableDeclare<GPUSliceTable>(*db_, this, "gpu_slice");
200 }
InitMemoryDB()201 void TraceDataCache::InitMemoryDB()
202 {
203 TableBase::TableDeclare<SmapsTable>(*db_, this, "smaps");
204 TableBase::TableDeclare<MemoryAshMemTable>(*db_, this, "memory_ashmem");
205 TableBase::TableDeclare<MemoryDmaTable>(*db_, this, "memory_dma");
206 TableBase::TableDeclare<MemoryProcessGpuTable>(*db_, this, "memory_process_gpu");
207 TableBase::TableDeclare<MemoryWindowGpuTable>(*db_, this, "memory_window_gpu");
208 TableBase::TableDeclare<MemoryCpuTable>(*db_, this, "memory_cpu");
209 TableBase::TableDeclare<MemoryProfileTable>(*db_, this, "memory_profile");
210 TableBase::TableDeclare<MemoryRSImageTable>(*db_, this, "memory_rs_image");
211 }
InitHisysEventDB()212 void TraceDataCache::InitHisysEventDB()
213 {
214 TableBase::TableDeclare<SysEventSubkeyTable>(*db_, this, "app_name");
215 TableBase::TableDeclare<SysEventMeasureTable>(*db_, this, "hisys_event_measure");
216 TableBase::TableDeclare<DeviceStateTable>(*db_, this, "device_state");
217 TableBase::TableDeclare<SysEventAllEventTable>(*db_, this, "hisys_all_event");
218 }
InitDB()219 void TraceDataCache::InitDB()
220 {
221 if (dbInited_) {
222 return;
223 }
224 InitBaseDB();
225 InitEbpfDB();
226 InitNativeMemoryDB();
227 InitArkTsDB();
228 InitHiperfDB();
229 InitMeasureDB();
230 InitTemplateDB();
231 InitRenderServiceDB();
232 InitMemoryDB();
233 InitHisysEventDB();
234 TableBase::TableDeclare<RawTable>(*db_, this, "raw");
235 TableBase::TableDeclare<InstantsTable>(*db_, this, "instant");
236 TableBase::TableDeclare<SchedSliceTable>(*db_, this, "sched_slice");
237 TableBase::TableDeclare<ThreadStateTable>(*db_, this, "thread_state");
238 TableBase::TableDeclare<CallStackTable>(*db_, this, "callstack");
239 TableBase::TableDeclare<IrqTable>(*db_, this, "irq");
240 TableBase::TableDeclare<HidumpTable>(*db_, this, "hidump");
241 TableBase::TableDeclare<SystemCallTable>(*db_, this, "syscall");
242 TableBase::TableDeclare<LogTable>(*db_, this, "log");
243 TableBase::TableDeclare<NetworkTable>(*db_, this, "network");
244 TableBase::TableDeclare<SystemEventFilterTable>(*db_, this, "sys_event_filter");
245 TableBase::TableDeclare<DiskIOTable>(*db_, this, "diskio");
246 TableBase::TableDeclare<CpuUsageInfoTable>(*db_, this, "cpu_usage");
247 TableBase::TableDeclare<LiveProcessTable>(*db_, this, "live_process");
248 dbInited_ = true;
249 }
AnimationTraceEnabled() const250 bool TraceDataCache::AnimationTraceEnabled() const
251 {
252 return animationTraceEnabled_;
253 }
UpdateAnimationTraceStatus(bool status)254 void TraceDataCache::UpdateAnimationTraceStatus(bool status)
255 {
256 animationTraceEnabled_ = status;
257 }
TaskPoolTraceEnabled() const258 bool TraceDataCache::TaskPoolTraceEnabled() const
259 {
260 return taskPoolTraceEnabled_;
261 }
UpdateTaskPoolTraceStatus(bool status)262 void TraceDataCache::UpdateTaskPoolTraceStatus(bool status)
263 {
264 taskPoolTraceEnabled_ = status;
265 }
AppStartTraceEnabled() const266 bool TraceDataCache::AppStartTraceEnabled() const
267 {
268 return appStartTraceEnabled_;
269 }
UpdateAppStartTraceStatus(bool status)270 void TraceDataCache::UpdateAppStartTraceStatus(bool status)
271 {
272 appStartTraceEnabled_ = status;
273 }
BinderRunnableTraceEnabled() const274 bool TraceDataCache::BinderRunnableTraceEnabled() const
275 {
276 return binderRunnableTraceEnabled_;
277 }
UpdateBinderRunnableTraceStatus(bool status)278 void TraceDataCache::UpdateBinderRunnableTraceStatus(bool status)
279 {
280 binderRunnableTraceEnabled_ = status;
281 }
HMKernelTraceEnabled() const282 bool TraceDataCache::HMKernelTraceEnabled() const
283 {
284 return HMKernelTraceEnabled_;
285 }
286
UpdateHMKernelTraceStatus(bool status)287 void TraceDataCache::UpdateHMKernelTraceStatus(bool status)
288 {
289 HMKernelTraceEnabled_ = status;
290 }
SplitFileMaxTime()291 uint64_t TraceDataCache::SplitFileMaxTime()
292 {
293 return splitFileMaxTs_;
294 }
SplitFileMinTime()295 uint64_t TraceDataCache::SplitFileMinTime()
296 {
297 return splitFileMinTs_;
298 }
SetSplitFileMaxTime(uint64_t maxTs)299 void TraceDataCache::SetSplitFileMaxTime(uint64_t maxTs)
300 {
301 splitFileMaxTs_ = maxTs;
302 }
SetSplitFileMinTime(uint64_t minTs)303 void TraceDataCache::SetSplitFileMinTime(uint64_t minTs)
304 {
305 splitFileMinTs_ = minTs;
306 }
HookCommProtos()307 std::deque<std::unique_ptr<std::string>> &TraceDataCache::HookCommProtos()
308 {
309 return hookCommProtos_;
310 }
ClearHookCommProtos()311 void TraceDataCache::ClearHookCommProtos()
312 {
313 hookCommProtos_.clear();
314 }
ExportPerfReadableText(const std::string & outputName,TraceDataDB::ResultCallBack resultCallBack)315 int32_t TraceDataCache::ExportPerfReadableText(const std::string &outputName,
316 TraceDataDB::ResultCallBack resultCallBack)
317 {
318 int32_t perfFd = base::OpenFile(outputName, O_CREAT | O_RDWR, TS_PERMISSION_RW);
319 TS_CHECK_TRUE(perfFd != -1, 1, "Failed to create file: %s, err:%s", outputName.c_str(), strerror(errno));
320 std::unique_ptr<int32_t, std::function<void(int32_t *)>> fp(&perfFd, [](int32_t *fp) { close(*fp); });
321 TS_CHECK_TRUE(ftruncate(perfFd, 0) != -1, 1, "Failed to ftruncate file: %s, err:%s", outputName.c_str(),
322 strerror(errno));
323 TS_LOGI("ExportPerfReadableText begin...");
324 std::string perfBufferLine;
325 perfBufferLine.reserve(G_CHUNK_SIZE);
326 for (uint64_t row = 0; row < perfSample_.Size();) {
327 ExportPerfSampleToFile(perfBufferLine, perfFd, outputName, row);
328 TS_CHECK_TRUE(write(perfFd, perfBufferLine.data(), perfBufferLine.size()) != -1, 1,
329 "Failed to write file: %s, err:%s", outputName.c_str(), strerror(errno));
330 perfBufferLine.clear();
331 if (++row != perfSample_.Size() && perfBufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
332 continue;
333 }
334 }
335 TS_LOGI("ExportPerfReadableText end...");
336 return 0;
337 }
ExportPerfSampleToFile(std::string & perfBufferLine,int32_t perfFd,const std::string & outputName,uint64_t row)338 void TraceDataCache::ExportPerfSampleToFile(std::string &perfBufferLine,
339 int32_t perfFd,
340 const std::string &outputName,
341 uint64_t row)
342 {
343 std::string perfTaskName;
344 std::string cpuIdStr = std::to_string(perfSample_.CpuIds()[row]);
345 std::string eventTypeName;
346 auto perfTaskId = perfSample_.Tids()[row];
347 if (perfTaskId == 0) {
348 auto threadDataRow = 0;
349 perfTaskName = GetDataFromDict(GetConstThreadData(threadDataRow).nameIndex_);
350 } else {
351 auto perfThreadTidItor = std::find(perfThread_.Tids().begin(), perfThread_.Tids().end(), perfTaskId);
352 if (perfThreadTidItor != perfThread_.Tids().end()) {
353 auto perfThreadRow = std::distance(perfThread_.Tids().begin(), perfThreadTidItor);
354 perfTaskName = GetDataFromDict(perfThread_.ThreadNames()[perfThreadRow]);
355 }
356 }
357 auto perfReportIdItor =
358 std::find(perfReport_.IdsData().begin(), perfReport_.IdsData().end(), perfSample_.EventTypeIds()[row]);
359 if (perfReportIdItor != perfReport_.IdsData().end()) {
360 auto perfReportRow = std::distance(perfReport_.IdsData().begin(), perfReportIdItor);
361 eventTypeName = GetDataFromDict(perfReport_.Values()[perfReportRow]);
362 }
363 perfBufferLine.append(perfTaskName);
364 perfBufferLine.append(" ").append(std::to_string(perfTaskId));
365 perfBufferLine.append(" [")
366 .append(std::string(CPU_ID_FORMAT_WIDTH - cpuIdStr.size(), '0'))
367 .append(cpuIdStr)
368 .append("]");
369 perfBufferLine.append(" ")
370 .append(base::ConvertTimestampToSecStr(perfSample_.TimeStampData()[row], TIME_PRECISION_SIX))
371 .append(":");
372 perfBufferLine.append(" ").append(std::to_string(perfSample_.EventCounts()[row]));
373 perfBufferLine.append(" ").append(eventTypeName).append(" \r\n");
374 ExportPerfCallChaninText(perfSample_.SampleIds()[row], perfBufferLine);
375 }
ExportPerfCallChaninText(uint32_t callChainId,std::string & bufferLine)376 void TraceDataCache::ExportPerfCallChaninText(uint32_t callChainId, std::string &bufferLine)
377 {
378 std::stack<uint64_t> callChainStackRows;
379 auto perfCallChainItor =
380 std::lower_bound(perfCallChain_.CallChainIds().begin(), perfCallChain_.CallChainIds().end(), callChainId);
381 while (perfCallChainItor != perfCallChain_.CallChainIds().end() && callChainId == *perfCallChainItor) {
382 auto perfCallChainRow = std::distance(perfCallChain_.CallChainIds().begin(), perfCallChainItor);
383 callChainStackRows.emplace(perfCallChainRow);
384 ++perfCallChainItor;
385 }
386 while (!callChainStackRows.empty()) {
387 auto perfCallChainRow = callChainStackRows.top();
388 callChainStackRows.pop();
389 auto formatIp = base::number(perfCallChain_.Ips()[perfCallChainRow], base::INTEGER_RADIX_TYPE_HEX);
390 formatIp = std::string(base::INTEGER_RADIX_TYPE_HEX - formatIp.size(), ' ') + formatIp;
391 std::string filePath("[unknown]");
392 auto curFileId = perfCallChain_.FileIds()[perfCallChainRow];
393 auto perfFileIdItor = std::lower_bound(perfFiles_.FileIds().begin(), perfFiles_.FileIds().end(), curFileId);
394 if (perfFileIdItor != perfFiles_.FileIds().end()) {
395 auto perfFileRow = std::distance(perfFiles_.FileIds().begin(), perfFileIdItor);
396 filePath = GetDataFromDict(perfFiles_.FilePaths()[perfFileRow]);
397 }
398 bufferLine.append("\t").append(formatIp);
399 auto nameStr = GetDataFromDict(perfCallChain_.Names()[perfCallChainRow]);
400 bufferLine.append(" [").append(nameStr).append("]");
401 bufferLine.append(" (").append(filePath).append(")\r\n");
402 }
403 bufferLine.append("\r\n");
404 }
ExportHookReadableText(const std::string & outputName,TraceDataDB::ResultCallBack resultCallBack)405 int32_t TraceDataCache::ExportHookReadableText(const std::string &outputName,
406 TraceDataDB::ResultCallBack resultCallBack)
407 {
408 int32_t hookFd = base::OpenFile(outputName, O_CREAT | O_RDWR, TS_PERMISSION_RW);
409 TS_CHECK_TRUE(hookFd != -1, 1, "Failed to create file: %s, err:%s", outputName.c_str(), strerror(errno));
410 std::unique_ptr<int32_t, std::function<void(int32_t *)>> fp(&hookFd, [](int32_t *fp) { close(*fp); });
411 TS_CHECK_TRUE(ftruncate(hookFd, 0) != -1, 1, "Failed to ftruncate file: %s, err:%s", outputName.c_str(),
412 strerror(errno));
413 TS_LOGI("ExportHookReadableText begin...");
414 std::string hookBufferLine;
415 hookBufferLine.reserve(G_CHUNK_SIZE);
416 ExportHookDataReadableText(hookFd, hookBufferLine);
417 ExportHookStatisticReadableText(hookFd, hookBufferLine);
418 TS_LOGI("ExportHookReadableText end...");
419 return 0;
420 }
ExportHookDataReadableText(int32_t fd,std::string & bufferLine)421 bool TraceDataCache::ExportHookDataReadableText(int32_t fd, std::string &bufferLine)
422 {
423 for (uint64_t row = 0; row < nativeHookData_.Size();) {
424 auto itid = nativeHookData_.InternalTidsData()[row];
425 auto hookTaskId = internalThreadsData_[itid].tid_;
426 auto hookTaskName = GetDataFromDict(internalThreadsData_[itid].nameIndex_);
427 bufferLine.append(hookTaskName);
428 bufferLine.append(" ").append(std::to_string(hookTaskId));
429 bufferLine.append(" ").append("[---]"); // default HookData event cpu id
430 bufferLine.append(" ")
431 .append(base::ConvertTimestampToSecStr(nativeHookData_.TimeStampData()[row], TIME_PRECISION_SIX))
432 .append(":");
433 bufferLine.append(" ").append("1"); // default HookData event event cnt
434 bufferLine.append(" ").append(nativeHookData_.EventTypes()[row]).append(" \r\n");
435 ExportHookCallChaninText(nativeHookData_.CallChainIds()[row], bufferLine);
436 if (++row != nativeHookData_.Size() && bufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
437 continue;
438 }
439 TS_CHECK_TRUE(write(fd, bufferLine.data(), bufferLine.size()) != -1, false,
440 "Failed to write HookData file, err:%s", strerror(errno));
441 bufferLine.clear();
442 }
443 return true;
444 }
ExportHookStatisticReadableText(int32_t fd,std::string & bufferLine)445 bool TraceDataCache::ExportHookStatisticReadableText(int32_t fd, std::string &bufferLine)
446 {
447 std::map<uint32_t, std::string_view> statisticEventTypeMap = {
448 {static_cast<uint32_t>(HookMemoryType::MALLOC), "AllocEvent"},
449 {static_cast<uint32_t>(HookMemoryType::MMAP), "MmapEvent"},
450 {static_cast<uint32_t>(HookMemoryType::FILE_PAGE_MSG), "FilePageEvent"},
451 {static_cast<uint32_t>(HookMemoryType::MEMORY_USING_MSG), "MemoryUsingEvent"}};
452 for (uint64_t row = 0; row < nativeHookStatisticData_.Size();) {
453 auto ipid = nativeHookStatisticData_.Ipids()[row];
454 auto statisticTaskId = internalProcessesData_[ipid].pid_;
455 auto statisticTaskName = internalProcessesData_[ipid].cmdLine_;
456 std::string_view eventType;
457 auto statisticEventTypeItor = statisticEventTypeMap.find(nativeHookStatisticData_.MemoryTypes()[row]);
458 if (statisticEventTypeItor != statisticEventTypeMap.end()) {
459 eventType = statisticEventTypeItor->second;
460 }
461 bufferLine.append(statisticTaskName);
462 bufferLine.append(" ").append(std::to_string(statisticTaskId));
463 bufferLine.append(" ").append("[---]"); // default HookStatistic event cpu id
464 bufferLine.append(" ")
465 .append(base::ConvertTimestampToSecStr(nativeHookStatisticData_.TimeStampData()[row], TIME_PRECISION_SIX))
466 .append(":");
467 bufferLine.append(" ").append("1"); // default HookStatistic event event cnt
468 bufferLine.append(" ").append(eventType).append(" \r\n");
469 ExportHookCallChaninText(nativeHookStatisticData_.CallChainIds()[row], bufferLine);
470 if (++row != nativeHookStatisticData_.Size() && bufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
471 continue;
472 }
473 TS_CHECK_TRUE(write(fd, bufferLine.data(), bufferLine.size()) != -1, false,
474 "Failed to write HookStatistic file, err:%s", strerror(errno));
475 bufferLine.clear();
476 }
477 return true;
478 }
ExportHookCallChaninText(uint32_t callChainId,std::string & bufferLine)479 void TraceDataCache::ExportHookCallChaninText(uint32_t callChainId, std::string &bufferLine)
480 {
481 auto hookFrameCallChainItor = std::lower_bound(nativeHookFrameData_.CallChainIds().begin(),
482 nativeHookFrameData_.CallChainIds().end(), callChainId);
483 while (hookFrameCallChainItor != nativeHookFrameData_.CallChainIds().end() &&
484 callChainId == *hookFrameCallChainItor) {
485 auto hookCallChainRow = std::distance(nativeHookFrameData_.CallChainIds().begin(), hookFrameCallChainItor);
486 auto hookFrameIp = base::number(nativeHookFrameData_.Ips()[hookCallChainRow], base::INTEGER_RADIX_TYPE_HEX);
487 hookFrameIp = std::string(base::INTEGER_RADIX_TYPE_HEX - hookFrameIp.size(), ' ') + hookFrameIp;
488 std::string hookSymName("unknown");
489 std::string hookFilePath("[unknown]");
490 if (nativeHookFrameData_.SymbolNames()[hookCallChainRow] != INVALID_UINT64) {
491 hookSymName = GetDataFromDict(nativeHookFrameData_.SymbolNames()[hookCallChainRow]);
492 }
493 if (nativeHookFrameData_.FilePaths()[hookCallChainRow] != INVALID_UINT64) {
494 hookFilePath = GetDataFromDict(nativeHookFrameData_.FilePaths()[hookCallChainRow]);
495 }
496 bufferLine.append("\t").append(hookFrameIp);
497 bufferLine.append(" [").append(hookSymName).append("]");
498 bufferLine.append(" (").append(hookFilePath).append(")\r\n");
499 ++hookFrameCallChainItor;
500 }
501 bufferLine.append("\r\n");
502 }
ExportEbpfReadableText(const std::string & outputName,TraceDataDB::ResultCallBack resultCallBack)503 int32_t TraceDataCache::ExportEbpfReadableText(const std::string &outputName,
504 TraceDataDB::ResultCallBack resultCallBack)
505 {
506 int32_t ebpfFd = base::OpenFile(outputName, O_CREAT | O_RDWR, TS_PERMISSION_RW);
507 TS_CHECK_TRUE(ebpfFd != -1, 1, "Failed to create file: %s, err:%s", outputName.c_str(), strerror(errno));
508 std::unique_ptr<int32_t, std::function<void(int32_t *)>> fp(&ebpfFd, [](int32_t *fp) { close(*fp); });
509 TS_CHECK_TRUE(ftruncate(ebpfFd, 0) != -1, 1, "Failed to ftruncate file: %s, err:%s", outputName.c_str(),
510 strerror(errno));
511 TS_LOGI("ExportEbpfReadableText begin...");
512 EbpfEventTypeMap ebpfEventTypeMap = {
513 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_MAPS, "MapsEvent"},
514 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_SYMBOL_INFO, "SymbolEvent"},
515 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_FS, "FsEvent"},
516 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_VM, "VmEvent"},
517 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_BIO, "BioEvent"},
518 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_STR, "StrEvent"},
519 {EbpfStdtype::EBPF_DATA_TYPE::ITEM_EVENT_KENEL_SYMBOL_INFO, "KernelSymbolEvent"}};
520 std::string ebpfBufferLine;
521 ebpfBufferLine.reserve(G_CHUNK_SIZE);
522 ExportEbpfFileSystemReadableText(ebpfFd, ebpfBufferLine, ebpfEventTypeMap);
523 ExportEbpfPagedMemReadableText(ebpfFd, ebpfBufferLine, ebpfEventTypeMap);
524 ExportEbpfBIOReadableText(ebpfFd, ebpfBufferLine, ebpfEventTypeMap);
525 TS_LOGI("ExportEbpfReadableText end...");
526 return 0;
527 }
ExportEbpfFileSystemReadableText(int32_t fd,std::string & bufferLine,const EbpfEventTypeMap & ebpfEventTypeMap)528 bool TraceDataCache::ExportEbpfFileSystemReadableText(int32_t fd,
529 std::string &bufferLine,
530 const EbpfEventTypeMap &ebpfEventTypeMap)
531 {
532 for (uint64_t row = 0; row < fileSamplingTableData_.Size();) {
533 auto fileSysTaskId = internalThreadsData_[fileSamplingTableData_.Itids()[row]].tid_;
534 auto fileSysTaskName = GetDataFromDict(internalThreadsData_[fileSamplingTableData_.Itids()[row]].nameIndex_);
535 std::string_view fileSampleEventType;
536 auto ebpfEventTypeItor = ebpfEventTypeMap.find(fileSamplingTableData_.Types()[row]);
537 if (ebpfEventTypeItor != ebpfEventTypeMap.end()) {
538 fileSampleEventType = ebpfEventTypeItor->second;
539 }
540 bufferLine.append(fileSysTaskName);
541 bufferLine.append(" ").append(std::to_string(fileSysTaskId));
542 bufferLine.append(" ").append("[---]"); // default FileSystem event cpu id
543 bufferLine.append(" ")
544 .append(base::ConvertTimestampToSecStr(fileSamplingTableData_.StartTs()[row], TIME_PRECISION_SIX))
545 .append(":");
546 bufferLine.append(" ").append("1"); // default FileSystem event cnt
547 bufferLine.append(" ").append(fileSampleEventType).append(" \r\n");
548 ExportEbpfCallChaninText(fileSamplingTableData_.CallChainIds()[row], bufferLine);
549 if (++row != fileSamplingTableData_.Size() && bufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
550 continue;
551 }
552 TS_CHECK_TRUE(write(fd, bufferLine.data(), bufferLine.size()) != -1, false,
553 "Failed to write FileSystem event file err:%s", strerror(errno));
554 bufferLine.clear();
555 }
556 return true;
557 }
ExportEbpfPagedMemReadableText(int32_t fd,std::string & bufferLine,const EbpfEventTypeMap & ebpfEventTypeMap)558 bool TraceDataCache::ExportEbpfPagedMemReadableText(int32_t fd,
559 std::string &bufferLine,
560 const EbpfEventTypeMap &ebpfEventTypeMap)
561 {
562 for (uint64_t row = 0; row < pagedMemorySampleData_.Size();) {
563 auto pagedMemTaskId = internalThreadsData_[pagedMemorySampleData_.Itids()[row]].tid_;
564 auto pagedMemTaskName = GetDataFromDict(internalThreadsData_[pagedMemorySampleData_.Itids()[row]].nameIndex_);
565 std::string_view pageMemEventType;
566 auto ebpfEventTypeItor = ebpfEventTypeMap.find(pagedMemorySampleData_.Types()[row]);
567 if (ebpfEventTypeItor != ebpfEventTypeMap.end()) {
568 pageMemEventType = ebpfEventTypeItor->second;
569 }
570 bufferLine.append(pagedMemTaskName);
571 bufferLine.append(" ").append(std::to_string(pagedMemTaskId));
572 bufferLine.append(" ").append("[---]"); // default PagedMem event cpu id
573 bufferLine.append(" ")
574 .append(base::ConvertTimestampToSecStr(pagedMemorySampleData_.StartTs()[row], TIME_PRECISION_SIX))
575 .append(":");
576 bufferLine.append(" ").append("1"); // default PagedMem event cnt
577 bufferLine.append(" ").append(pageMemEventType).append(" \r\n");
578 ExportEbpfCallChaninText(pagedMemorySampleData_.CallChainIds()[row], bufferLine);
579 if (++row != pagedMemorySampleData_.Size() && bufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
580 continue;
581 }
582 TS_CHECK_TRUE(write(fd, bufferLine.data(), bufferLine.size()) != -1, false,
583 "Failed to write PagedMem event file err:%s", strerror(errno));
584 bufferLine.clear();
585 }
586 return true;
587 }
ExportEbpfBIOReadableText(int32_t fd,std::string & bufferLine,const EbpfEventTypeMap & ebpfEventTypeMap)588 bool TraceDataCache::ExportEbpfBIOReadableText(int32_t fd,
589 std::string &bufferLine,
590 const EbpfEventTypeMap &ebpfEventTypeMap)
591 {
592 for (uint64_t row = 0; row < bioLatencySampleData_.Size();) {
593 auto bioTaskId = internalThreadsData_[bioLatencySampleData_.Itids()[row]].tid_;
594 auto bioTaskName = GetDataFromDict(internalThreadsData_[bioLatencySampleData_.Itids()[row]].nameIndex_);
595 std::string_view bioEventType;
596 auto ebpfEventTypeItor = ebpfEventTypeMap.find(bioLatencySampleData_.Types()[row]);
597 if (ebpfEventTypeItor != ebpfEventTypeMap.end()) {
598 bioEventType = ebpfEventTypeItor->second;
599 }
600 bufferLine.append(bioTaskName);
601 bufferLine.append(" ").append(std::to_string(bioTaskId));
602 bufferLine.append(" ").append("[---]"); // default BIO event cpu id
603 bufferLine.append(" ")
604 .append(base::ConvertTimestampToSecStr(bioLatencySampleData_.StartTs()[row], TIME_PRECISION_SIX))
605 .append(":");
606 bufferLine.append(" ").append("1"); // default BIO event cnt
607 bufferLine.append(" ").append(bioEventType).append(" \r\n");
608 ExportEbpfCallChaninText(bioLatencySampleData_.CallChainIds()[row], bufferLine);
609 if (++row != bioLatencySampleData_.Size() && bufferLine.size() < FLUSH_CHUNK_THRESHOLD) {
610 continue;
611 }
612 TS_CHECK_TRUE(write(fd, bufferLine.data(), bufferLine.size()) != -1, false,
613 "Failed to write BIO event file err:%s", strerror(errno));
614 bufferLine.clear();
615 }
616 return true;
617 }
ExportEbpfCallChaninText(uint32_t callChainId,std::string & bufferLine)618 void TraceDataCache::ExportEbpfCallChaninText(uint32_t callChainId, std::string &bufferLine)
619 {
620 auto ebpfCallChainItor = std::lower_bound(ebpfCallStackData_.CallChainIds().begin(),
621 ebpfCallStackData_.CallChainIds().end(), callChainId);
622 while (ebpfCallChainItor != ebpfCallStackData_.CallChainIds().end() && callChainId == *ebpfCallChainItor) {
623 auto ebpfCallChainRow = std::distance(ebpfCallStackData_.CallChainIds().begin(), ebpfCallChainItor);
624 auto ebpfFrameIp = GetDataFromDict(ebpfCallStackData_.Ips()[ebpfCallChainRow]).substr(HEX_PREFIX.size());
625 ebpfFrameIp = std::string(base::INTEGER_RADIX_TYPE_HEX - ebpfFrameIp.size(), ' ') + ebpfFrameIp;
626 std::string ebpfSymName("unknown");
627 std::string ebpfFilePath("[unknown]");
628 if (ebpfCallStackData_.SymbolIds()[ebpfCallChainRow] != INVALID_UINT64) {
629 ebpfSymName = GetDataFromDict(ebpfCallStackData_.SymbolIds()[ebpfCallChainRow]);
630 }
631 if (ebpfCallStackData_.FilePathIds()[ebpfCallChainRow] != INVALID_UINT64) {
632 ebpfFilePath = GetDataFromDict(ebpfCallStackData_.FilePathIds()[ebpfCallChainRow]);
633 }
634 bufferLine.append("\t").append(ebpfFrameIp);
635 bufferLine.append(" [").append(ebpfSymName).append("]");
636 bufferLine.append(" (").append(ebpfFilePath).append(")\r\n");
637 ++ebpfCallChainItor;
638 }
639 bufferLine.append("\r\n");
640 }
ClearAllExportedCacheData()641 void TraceDataCache::ClearAllExportedCacheData()
642 {
643 // ftrace plugin
644 argSet_.ClearExportedData();
645 filterData_.ClearExportedData();
646 clkEventFilterData_.ClearExportedData();
647 measureData_.ClearExportedData();
648 clockEventFilterData_.ClearExportedData();
649 processMeasureData_.ClearExportedData();
650 processMeasureFilterData_.ClearExportedData();
651 cpuMeasureData_.ClearExportedData();
652 rawData_.ClearExportedData();
653 instantsData_.ClearExportedData();
654 schedSliceData_.ClearExportedData();
655 irqData_.ClearExportedData();
656 sysMemMeasureData_.ClearExportedData();
657 sysCallData_.ClearExportedData();
658 frameSliceData_.ClearExportedData();
659 frameMapsData_.ClearExportedData();
660 gpuSliceData_.ClearExportedData();
661 }
UpdateAllReadySize()662 void TraceDataCache::UpdateAllReadySize()
663 {
664 // ftrace plugin datacache
665 measureData_.UpdateReadySize(measureData_.Size());
666 processMeasureData_.UpdateReadySize(processMeasureData_.Size());
667 tableToCompletedSize_["measure"] = measureData_.readySize_;
668 tableToCompletedSize_["process_measure"] = processMeasureData_.readySize_;
669 tableToCompletedSize_["frame_slice"] = frameSliceData_.readySize_;
670 tableToCompletedSize_["sched_slice"] = schedSliceData_.readySize_;
671 tableToCompletedSize_["irq"] = irqData_.readySize_;
672
673 argSet_.UpdateReadySize(argSet_.Size());
674 filterData_.UpdateReadySize(filterData_.Size());
675 clkEventFilterData_.UpdateReadySize(clkEventFilterData_.Size());
676 clockEventFilterData_.UpdateReadySize(clockEventFilterData_.Size());
677 processMeasureFilterData_.UpdateReadySize(processMeasureFilterData_.Size());
678 cpuMeasureData_.UpdateReadySize(cpuMeasureData_.Size());
679 rawData_.UpdateReadySize(rawData_.Size());
680
681 instantsData_.UpdateReadySize(instantsData_.Size());
682 sysCallData_.UpdateReadySize(sysCallData_.Size());
683 frameMapsData_.UpdateReadySize(frameMapsData_.Size());
684 gpuSliceData_.UpdateReadySize(gpuSliceData_.Size());
685 }
686 } // namespace TraceStreamer
687 } // namespace SysTuning
688