Merged
[Profiling]【feat】device profiling库去除背景线程 #6330
[Profiling]【feat】device profiling库去除背景线程 #6330
Merged
zhengkaiAdd on 11 days ago
Total: 11 files changed+1274-735
@@ -27,6 +27,8 @@ struct AicpuUserProfileBufferInfo;
27 27 
28class DevprofDrvAicpu : public analysis::dvvp::common::singleton::Singleton<DevprofDrvAicpu>,28class DevprofDrvAicpu : public analysis::dvvp::common::singleton::Singleton<DevprofDrvAicpu>,
29 public analysis::dvvp::common::thread::Thread {29 public analysis::dvvp::common::thread::Thread {
30+ static constexpr size_t HOST_MOVE_BUFFER_MAX_CYCLES = 2048;
31+ 
30public:32public:
31 DevprofDrvAicpu();33 DevprofDrvAicpu();
32 ~DevprofDrvAicpu() override;34 ~DevprofDrvAicpu() override;
@@ -47,10 +49,11 @@ public:
47 void DeviceReportStart();49 void DeviceReportStart();
48 void DeviceReportStop();50 void DeviceReportStop();
49 int32_t SendAddtionalInfo();51 int32_t SendAddtionalInfo();
50- void AddStr2IdIntoBuffer(std::string& str);52+ bool AddStr2IdIntoBuffer(std::string& str, bool flushWrite = false);
51 int32_t ReportStr2IdInfoToHost(std::string& dataStr);53 int32_t ReportStr2IdInfoToHost(std::string& dataStr);
52 bool IsSupportHostMove() const { return isSupportHostMove_; }54 bool IsSupportHostMove() const { return isSupportHostMove_; }
53 void SetSupportHostMove(bool support) { isSupportHostMove_ = support; }55 void SetSupportHostMove(bool support) { isSupportHostMove_ = support; }
56+ bool InitAdditionalBuffer();
54 int32_t RecordHostMoveBufferAddresses(const Devprof::AicpuUserProfileBufferInfo* info);57 int32_t RecordHostMoveBufferAddresses(const Devprof::AicpuUserProfileBufferInfo* info);
55 void Release();58 void Release();
56#ifdef __PROF_LLT59#ifdef __PROF_LLT
@@ -63,9 +66,15 @@ protected:
63 66 
64private:67private:
65 int32_t RegisterDrvChannel(uint32_t devId, uint32_t channelId);68 int32_t RegisterDrvChannel(uint32_t devId, uint32_t channelId);
66- void RunHostMoveMode();69+ int32_t WriteDirectlyToHostMoveBuffer(
70+ const MsprofAdditionalInfo* data, uint32_t recordCount, bool flushWrite = false);
71+ bool TryUpdateHostMoveReadIndex(uint32_t maxIdx);
72+ bool TryPublishHostMoveRange(uint32_t maxIdx);
73+ bool EnsureHostMoveCommitState(uint32_t maxIdx);
74+ void FailReservedRange(uint64_t cursor, uint32_t count);
67 void RunNormalMode();75 void RunNormalMode();
68- void FillStr2IdIntoBuffer(std::string& dataStr);76+ bool FillStr2IdIntoBuffer(std::string& dataStr, bool flushWrite = false);
77+ int32_t ReportStr2IdInfoToHostMove(bool flushWrite = false);
69 78 
70#ifdef __PROF_LLT79#ifdef __PROF_LLT
71public:80public:
@@ -73,24 +82,10 @@ public:
73private:82private:
74#endif83#endif
75 void UninitHostMoveBuffer();84 void UninitHostMoveBuffer();
76- int32_t WriteToHostMoveBuffer(const MsprofAdditionalInfo* data, size_t dataSize);
77- int32_t WriteBatchToHostMoveBuffer(const MsprofAdditionalInfo* data, uint32_t recordCount);
78- int32_t DrainBufferToHostMove();
79- 
80- // One step of the host-move drain loop: keep draining, sleep-and-retry, or stop on a fatal error.
81- enum class HostMoveStep : int32_t {
82- OK = 0,
83- RETRY,
84- FATAL,
85- };
86- HostMoveStep AcquireHostMoveFreeSlots(uint32_t& freeSlots);
87- HostMoveStep MoveOneBatchToHostMove(size_t maxBatchRecords, uint32_t freeSlots, uint64_t& totalWriteLen);
88- 
89-private:
90 volatile bool stopped_;85 volatile bool stopped_;
91 // Whether the "host move ring buffer full" event has been logged in the current profiling86 // Whether the "host move ring buffer full" event has been logged in the current profiling
92- // session, so the log is emitted only once instead of flooding on every retry.87+ // session. The relaxed atomic flag prevents data races and unbounded repeated events.
93- bool ringFullLogged_ = false;88+ std::atomic<bool> ringFullLogged_{false};
94 uint32_t devId_;89 uint32_t devId_;
95 uint32_t channelId_;90 uint32_t channelId_;
96 volatile uint64_t profConfig_;91 volatile uint64_t profConfig_;
@@ -100,11 +95,20 @@ private:
100 size_t hostMoveBufferSize_;95 size_t hostMoveBufferSize_;
101 volatile uint32_t* hostMoveWptr_;96 volatile uint32_t* hostMoveWptr_;
102 volatile uint32_t* hostMoveRptr_;97 volatile uint32_t* hostMoveRptr_;
103- std::atomic<uint32_t> hostMoveWriteIndex_;98+ std::atomic<uint64_t> hostMoveReadIndex_{0};
99+ std::atomic<uint64_t> hostMoveWriteIndex_{0};
100+ std::atomic<uint64_t> hostMoveIdleWriteIndex_{0};
101+ std::atomic<uint64_t> hostMoveFailedWriteIndex_{0};
102+ std::atomic<bool> hostMoveAcceptingWrites_{false};
103+ std::atomic<uint32_t> hostMoveActiveWriters_{0};
104+ std::atomic<uint32_t>* hostMoveCommitCounts_ = nullptr;
105+ size_t hostMoveCommitCountSize_ = 0;
106+ std::atomic<uint32_t> hostMoveOverflowDiscardSize_{0};
107+ size_t hostMoveMaxCycles_{HOST_MOVE_BUFFER_MAX_CYCLES};
104 analysis::dvvp::common::queue::BlockBuffer<MsprofAdditionalInfo> aicpuAdditionalBuffer_{};108 analysis::dvvp::common::queue::BlockBuffer<MsprofAdditionalInfo> aicpuAdditionalBuffer_{};
105 MsprofCommandHandle command_;109 MsprofCommandHandle command_;
106 std::map<uint32_t, std::set<ProfCommandHandle>> moduleCallbacks_;110 std::map<uint32_t, std::set<ProfCommandHandle>> moduleCallbacks_;
107 std::mutex aicpuRegisterMutex_;111 std::mutex aicpuRegisterMutex_;
108};112};
109 113 
110-#endif114+#endif
@@ -50,12 +50,12 @@ int32_t PerfExtraTask::Init()
50 }50 }
51 51 
52 if (isInited_) {52 if (isInited_) {
53- MSPROF_LOGE("The PerfExtraTask is inited");53+ MSPROF_LOGE("The PerfExtraTask has already been initialized");
54 return PROFILING_FAILED;54 return PROFILING_FAILED;
55 }55 }
56 56 
57 if (!buf_.Init()) {57 if (!buf_.Init()) {
58- MSPROF_LOGE("Buf init failed");58+ MSPROF_LOGE("Failed to initialize PerfExtraTask buffer, size: %zu bytes", buf_.GetBufferSize());
59 return PROFILING_FAILED;59 return PROFILING_FAILED;
60 }60 }
61 61 
@@ -97,12 +97,12 @@ int32_t ProcTimerHandler::Init()
97 int32_t ret = PROFILING_FAILED;97 int32_t ret = PROFILING_FAILED;
98 do {98 do {
99 if (isInited_) {99 if (isInited_) {
100- MSPROF_LOGE("The Handler is inited");100+ MSPROF_LOGE("The timer handler has already been initialized");
101 break;101 break;
102 }102 }
103 103 
104 if (!buf_.Init()) {104 if (!buf_.Init()) {
105- MSPROF_LOGE("Buf init failed");105+ MSPROF_LOGE("Failed to initialize timer handler buffer, size: %zu bytes", buf_.GetBufferSize());
106 break;106 break;
107 }107 }
108 108 
@@ -267,7 +267,9 @@ void ProcTimerHandler::SendData(CONST_UNSIGNED_CHAR_PTR buf, uint32_t size)
267 }267 }
268 int32_t ret = upLoader_->UploadData(fileChunk);268 int32_t ret = upLoader_->UploadData(fileChunk);
269 if (ret != PROFILING_SUCCESS) {269 if (ret != PROFILING_SUCCESS) {
270- MSPROF_LOGE("[ProcTimerHandler::SendData] Upload Data Failed");270+ MSPROF_LOGE(
271+ "[ProcTimerHandler::SendData] Failed to upload file chunk %s, ret: %d", fileChunk->fileName.c_str(),
272+ ret);
271 }273 }
272 }274 }
273}275}
@@ -1089,8 +1091,10 @@ void NetDevStatsHandler::SendData(uint32_t devId, CONST_UNSIGNED_CHAR_PTR buf, s
1089 fileChunk->extraInfo = Utils::PackDotInfo(jobCtx_->job_id, jobCtx_->dev_id);1091 fileChunk->extraInfo = Utils::PackDotInfo(jobCtx_->job_id, jobCtx_->dev_id);
1090 fileChunk->chunkModule = analysis::dvvp::common::config::FileChunkDataModule::PROFILING_IS_FROM_DEVICE;1092 fileChunk->chunkModule = analysis::dvvp::common::config::FileChunkDataModule::PROFILING_IS_FROM_DEVICE;
1091 1093 
1092- if (upLoader->UploadData(fileChunk) != PROFILING_SUCCESS) {1094+ int32_t ret = upLoader->UploadData(fileChunk);
1093- MSPROF_LOGE("NetDevStatsHandler::SendData Upload Data Failed");1095+ if (ret != PROFILING_SUCCESS) {
1096+ MSPROF_LOGE(
1097+ "NetDevStatsHandler::SendData Failed to upload file chunk %s, ret: %d", fileChunk->fileName.c_str(), ret);
1094 }1098 }
1095}1099}
1096 1100 
@@ -72,13 +72,13 @@ int32_t DeviceTransport::HandlePacket(TLV_REQ_PTR packet, analysis::dvvp::messag
72 72 
73 auto responseMessage = std::dynamic_pointer_cast<analysis::dvvp::proto::Response>(message);73 auto responseMessage = std::dynamic_pointer_cast<analysis::dvvp::proto::Response>(message);
74 if (responseMessage == nullptr) {74 if (responseMessage == nullptr) {
75- MSPROF_LOGE("Device(%s) Not response Message", devIndexIdStr_.c_str());75+ MSPROF_LOGE("Device(%s) did not respond", devIndexIdStr_.c_str());
76 break;76 break;
77 }77 }
78 78 
79 std::string statusStr = responseMessage->message();79 std::string statusStr = responseMessage->message();
80 if (!status.FromString(statusStr)) {80 if (!status.FromString(statusStr)) {
81- MSPROF_LOGE("Device(%s) message from string failed", devIndexIdStr_.c_str());81+ MSPROF_LOGE("Device(%s) failed to parse message from string", devIndexIdStr_.c_str());
82 break;82 break;
83 }83 }
84 FUNRET_CHECK_EXPR_ACTION_LOGW(84 FUNRET_CHECK_EXPR_ACTION_LOGW(
@@ -189,6 +189,7 @@ add_executable(job_wrapper
189 189 
190target_compile_definitions(job_wrapper PRIVATE190target_compile_definitions(job_wrapper PRIVATE
191 C_SEC191 C_SEC
192+ MSPROF_SOURCE_PATH="${MSPROF_SOURCE_DIR}/dvvp"
192)193)
193 194 
194set(libmsprofHeaderDir195set(libmsprofHeaderDir
@@ -9,6 +9,9 @@
9 */9 */
10#include "gtest/gtest.h"10#include "gtest/gtest.h"
11#include "mockcpp/mockcpp.hpp"11#include "mockcpp/mockcpp.hpp"
12+#include <fstream>
13+#include <iterator>
14+#include <string>
12#include <mutex>15#include <mutex>
13#include "thread/thread.h"16#include "thread/thread.h"
14#include "prof_timer.h"17#include "prof_timer.h"
@@ -20,6 +23,15 @@ using namespace analysis::dvvp::common::error;
20using namespace Analysis::Dvvp::JobWrapper;23using namespace Analysis::Dvvp::JobWrapper;
21using namespace Analysis::Dvvp::MsprofErrMgr;24using namespace Analysis::Dvvp::MsprofErrMgr;
22 25 
26+namespace {
27+std::string ReadSourceFile(const std::string& relativePath)
28+{
29+ std::ifstream sourceFile(MSPROF_SOURCE_PATH "/" + relativePath);
30+ EXPECT_TRUE(sourceFile.is_open()) << "Cannot open " << relativePath;
31+ return std::string((std::istreambuf_iterator<char>(sourceFile)), std::istreambuf_iterator<char>());
32+}
33+} // namespace
34+ 
23class PROF_STAT_FILE_HANDLER_TEST : public testing::Test {35class PROF_STAT_FILE_HANDLER_TEST : public testing::Test {
24protected:36protected:
25 virtual void SetUp()37 virtual void SetUp()
@@ -67,6 +79,30 @@ TEST_F(PROF_STAT_FILE_HANDLER_TEST, Init)
67 EXPECT_EQ(PROFILING_SUCCESS, statHandler.Init());79 EXPECT_EQ(PROFILING_SUCCESS, statHandler.Init());
68}80}
69 81 
82+TEST(PROF_LOG_MESSAGE_TEST, Issue416MessagesAreSpecificAndStandard)
83+{
84+ const std::string perfJob = ReadSourceFile("profimpl/collect/job_wrapper/src/prof_perf_job.cpp");
85+ const std::string timer = ReadSourceFile("profimpl/collect/job_wrapper/src/prof_timer.cpp");
86+ const std::string deviceTransport = ReadSourceFile("transport/hdc/device_transport.cpp");
87+ 
88+ EXPECT_EQ(std::string::npos, perfJob.find("The PerfExtraTask is inited"));
89+ EXPECT_NE(std::string::npos, perfJob.find("The PerfExtraTask has already been initialized"));
90+ EXPECT_EQ(std::string::npos, perfJob.find("Buf init failed"));
91+ EXPECT_NE(std::string::npos, perfJob.find("Failed to initialize PerfExtraTask buffer, size: %zu bytes"));
92+ 
93+ EXPECT_EQ(std::string::npos, timer.find("The Handler is inited"));
94+ EXPECT_NE(std::string::npos, timer.find("The timer handler has already been initialized"));
95+ EXPECT_EQ(std::string::npos, timer.find("Buf init failed"));
96+ EXPECT_NE(std::string::npos, timer.find("Failed to initialize timer handler buffer, size: %zu bytes"));
97+ EXPECT_EQ(std::string::npos, timer.find("Upload Data Failed"));
98+ EXPECT_NE(std::string::npos, timer.find("Failed to upload file chunk %s, ret: %d"));
99+ 
100+ EXPECT_EQ(std::string::npos, deviceTransport.find("Device(%s) Not response Message"));
101+ EXPECT_NE(std::string::npos, deviceTransport.find("Device(%s) did not respond"));
102+ EXPECT_EQ(std::string::npos, deviceTransport.find("Device(%s) message from string failed"));
103+ EXPECT_NE(std::string::npos, deviceTransport.find("Device(%s) failed to parse message from string"));
104+}
105+ 
70TEST_F(PROF_STAT_FILE_HANDLER_TEST, UInit)106TEST_F(PROF_STAT_FILE_HANDLER_TEST, UInit)
71{107{
72 GlobalMockObject::verify();108 GlobalMockObject::verify();
@@ -568,6 +568,16 @@ target_compile_options(msprof_utest PRIVATE
568 -Werror568 -Werror
569)569)
570 570 
571+# mockcpp installs a 32-byte AArch64 trampoline at each hooked function entry.
572+# Release optimization can otherwise place adjacent small stubs only 4 or 8 bytes
573+# apart, so hooking one function overwrites the neighboring hook. Align function
574+# entries in this test executable so each mock has enough private entry bytes.
575+if(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64" AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
576+ target_compile_options(msprof_utest PRIVATE
577+ -falign-functions=32
578+ )
579+endif()
580+ 
571target_compile_definitions(msprof_utest PRIVATE581target_compile_definitions(msprof_utest PRIVATE
572 C_SEC582 C_SEC
573 __PROF_LLT583 __PROF_LLT
@@ -11,6 +11,7 @@
11#include <unistd.h>11#include <unistd.h>
12#include <stdio.h>12#include <stdio.h>
13#include <stdarg.h>13#include <stdarg.h>
14+#include <stdlib.h>
14#include <syslog.h>15#include <syslog.h>
15#include <map>16#include <map>
16#include <string>17#include <string>
@@ -22,18 +23,27 @@ const std::map<int, std::string> LOG_LEVEL_INFO = {
22};23};
23 24 
24static std::atomic<int32_t> g_dlogRecordCount{0};25static std::atomic<int32_t> g_dlogRecordCount{0};
26+static std::atomic<int32_t> g_dlogEventCount{0};
27+ 
28+// 设置 UT_DLOG_SILENT=1 时关闭日志格式化与打印,降低外部压测工具复用本二进制时的日志噪声
29+static bool DlogSilent() { return getenv("UT_DLOG_SILENT") != nullptr; }
25 30 
26namespace {31namespace {
27constexpr int LOG_MSG_MAX = 4096;32constexpr int LOG_MSG_MAX = 4096;
28char g_lastDlogRecordMsg[LOG_MSG_MAX] = {0};33char g_lastDlogRecordMsg[LOG_MSG_MAX] = {0};
34+char g_lastDlogEventMsg[LOG_MSG_MAX] = {0};
29} // namespace35} // namespace
30 36 
31void ResetDlogRecordCount() { g_dlogRecordCount.store(0); }37void ResetDlogRecordCount() { g_dlogRecordCount.store(0); }
32int32_t GetDlogRecordCount() { return g_dlogRecordCount.load(); }38int32_t GetDlogRecordCount() { return g_dlogRecordCount.load(); }
39+void ResetDlogEventCount() { g_dlogEventCount.store(0); }
40+int32_t GetDlogEventCount() { return g_dlogEventCount.load(); }
33 41 
34void ResetLastDlogRecordMsg() { g_lastDlogRecordMsg[0] = '\0'; }42void ResetLastDlogRecordMsg() { g_lastDlogRecordMsg[0] = '\0'; }
43+void ResetLastDlogEventMsg() { g_lastDlogEventMsg[0] = '\0'; }
35 44 
36const char* GetLastDlogRecordMsg() { return g_lastDlogRecordMsg; }45const char* GetLastDlogRecordMsg() { return g_lastDlogRecordMsg; }
46+const char* GetLastDlogEventMsg() { return g_lastDlogEventMsg; }
37 47 
38void DlogErrorInner(int moduleId, const char* format, ...)48void DlogErrorInner(int moduleId, const char* format, ...)
39{49{
@@ -97,6 +107,9 @@ void DlogDebugInner(int moduleId, const char* format, ...)
97 107 
98void DlogRecord(int module_id, int level, const char* fmt, ...)108void DlogRecord(int module_id, int level, const char* fmt, ...)
99{109{
110+ if (DlogSilent()) {
111+ return;
112+ }
100 g_dlogRecordCount.fetch_add(1, std::memory_order_relaxed);113 g_dlogRecordCount.fetch_add(1, std::memory_order_relaxed);
101 auto iter = LOG_LEVEL_INFO.find(level);114 auto iter = LOG_LEVEL_INFO.find(level);
102 std::string levelStr;115 std::string levelStr;
@@ -113,6 +126,11 @@ void DlogRecord(int module_id, int level, const char* fmt, ...)
113 if (ret < 0) {126 if (ret < 0) {
114 g_lastDlogRecordMsg[0] = '\0';127 g_lastDlogRecordMsg[0] = '\0';
115 }128 }
129+ // In the non-OSAL build, MSPROF_EVENT maps to dlog_info with RUN_LOG_MASK.
130+ if (level == DLOG_INFO && (static_cast<uint32_t>(module_id) & RUN_LOG_MASK) != 0U) {
131+ g_dlogEventCount.fetch_add(1, std::memory_order_relaxed);
132+ (void)snprintf_s(g_lastDlogEventMsg, sizeof(g_lastDlogEventMsg), sizeof(g_lastDlogEventMsg) - 1U, "%s", buffer);
133+ }
116 printf("[%s][pid:%d]%s", levelStr.c_str(), getpid(), buffer);134 printf("[%s][pid:%d]%s", levelStr.c_str(), getpid(), buffer);
117 va_end(args);135 va_end(args);
118}136}
@@ -131,4 +149,4 @@ void ide_log(int priority, const char* format, ...)
131 va_end(args);149 va_end(args);
132}150}
133 151 
134-int CheckLogLevel(int moduleId, int level) { return 1; }152+int CheckLogLevel(int moduleId, int level) { return DlogSilent() ? 0 : 1; }
@@ -14,8 +14,13 @@
14 14 
15void ResetDlogRecordCount();15void ResetDlogRecordCount();
16int32_t GetDlogRecordCount();16int32_t GetDlogRecordCount();
17+void ResetDlogEventCount();
18+int32_t GetDlogEventCount();
17// capture the last DlogRecord message text so unit tests can assert log content19// capture the last DlogRecord message text so unit tests can assert log content
18const char* GetLastDlogRecordMsg();20const char* GetLastDlogRecordMsg();
19void ResetLastDlogRecordMsg();21void ResetLastDlogRecordMsg();
22+// capture the last run-log event so later warning logs do not hide it in assertions
23+const char* GetLastDlogEventMsg();
24+void ResetLastDlogEventMsg();
20 25 
21-#endif26+#endif