diff --git a/bundle.json b/bundle.json index 96f66dbf4c172221de8a0a5295664d00dbc26019..f55c29b73e2577bc92397776be6b8aa1c850f8e5 100644 --- a/bundle.json +++ b/bundle.json @@ -58,7 +58,8 @@ "zlib", "grpc", "storage_service", - "abseil-cpp" + "abseil-cpp", + "netmanager_base" ], "third_party": [ "cJSON", diff --git a/device/etc/hiprofiler_plugins.cfg b/device/etc/hiprofiler_plugins.cfg index cda5ac0c758ca61b4c0ea1e6d498c9b8dfe05182..17be9aa92fabaa093031aa5467e142ab24e9f145 100644 --- a/device/etc/hiprofiler_plugins.cfg +++ b/device/etc/hiprofiler_plugins.cfg @@ -24,7 +24,9 @@ "ohos.permission.WRITE_HIVIEW_SYSTEM", "ohos.permission.READ_HIVIEW_SYSTEM", "ohos.permission.GET_BUNDLE_INFO", - "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED" + "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", + "ohos.permission.GET_NETWORK_STATS", + "ohos.permission.CONNECTIVITY_INTERNAL" ] } ] diff --git a/device/plugins/network_plugin/BUILD.gn b/device/plugins/network_plugin/BUILD.gn index 8bfd64a670dab3fc83489508da75c4cd53bde53b..00caf59d33d44de6d34ea6e5098b9d6bb43b358a 100644 --- a/device/plugins/network_plugin/BUILD.gn +++ b/device/plugins/network_plugin/BUILD.gn @@ -38,9 +38,17 @@ ohos_source_set("networkplugin_source") { defines = [ "HAVE_HILOG" ] external_deps = [ "bounds_checking_function:libsec_shared", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", "hilog:libhilog_base", "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_stats_manager_if", + "os_account:os_account_innerkits", "protobuf:protobuf_lite", + "samgr:samgr_proxy", ] } public_configs = [ "${OHOS_PROFILER_DIR}/device/base:hiprofiler_test_config" ] diff --git a/device/plugins/network_plugin/include/network_plugin.h b/device/plugins/network_plugin/include/network_plugin.h index 746629bae72cac4eae415a7374a27150c76b64fe..3fd15b57a6d557f7f3bacf7a04abaf515e85d624 100644 --- a/device/plugins/network_plugin/include/network_plugin.h +++ b/device/plugins/network_plugin/include/network_plugin.h @@ -16,42 +16,15 @@ #ifndef NETWORK_PLUGIN_H #define NETWORK_PLUGIN_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include "logging.h" #include "network_plugin_config.pb.h" #include "network_plugin_result.pb.h" #include "plugin_module_api.h" +#include "net_stats_client.h" -struct NetDetails { - uint64_t tx; - uint64_t rx; - std::string type; -}; - -struct NetworkCell { - int32_t pid; - uint64_t tx; - uint64_t rx; - struct timespec ts; - std::vector details; -}; +using TimeSpec = struct timespec; -struct NetSystemDetails { +struct NetFlowDetail { std::string type; uint64_t rxBytes; uint64_t rxPackets; @@ -59,58 +32,38 @@ struct NetSystemDetails { uint64_t txPackets; }; -struct NetSystemData { - struct timespec ts; +struct NetFlowData { + TimeSpec ts; uint64_t rxBytes; uint64_t rxPackets; uint64_t txBytes; uint64_t txPackets; - std::vector details; -}; - -enum NetworkNum { - IFACE_INDEX = 2, - UID_INDEX = 4, - RX_BYTES_INDEX = 6, - RX_PACKETS_INDEX = 7, - TX_BYTES_INDEX = 8, - TX_PACKETS_INDEX = 9, - DEC_BASE = 10, + std::vector details; }; class NetworkPlugin { public: - NetworkPlugin(); + NetworkPlugin() {}; ~NetworkPlugin() {}; int Start(const uint8_t* configData, uint32_t configSize); int Report(uint8_t* data, uint32_t dataSize); int ReportOptimize(RandomWriteCtx* randomWrite); int Stop(); -protected: - std::string GetRateNodePath(); - int32_t GetUid(int32_t pid); - bool ReadTxRxBytes(int32_t pid, NetworkCell &cell); - bool ReadSystemTxRxBytes(NetSystemData &systemData); - void AddNetDetails(NetworkCell& cell, NetDetails& data); - void AddNetSystemDetails(NetSystemData& systemData, NetSystemDetails& data); - std::string GetCmdArgs(NetworkConfig traceConfig); - // for UT - void setPathForTest(std::string path) - { - fileForTest_ = path; - } - std::string getPathForTest() - { - return fileForTest_; - } template bool WriteNetWorkData(T& networkDatasProto); + template void WriteData(T& networkDatasProto, NetFlowData &netFlowData); + int32_t GetUid(int32_t pid); + bool ScreenNetworkStatByUid(const std::vector infos, NetFlowData &data); + bool RetainAllNetworkStat(const std::vector infos, NetFlowData &data); + bool HandleData(NetFlowData present, NetFlowData &difference); + void Record(NetFlowData &newData); + std::string GetCmdArgs(const NetworkConfig &traceConfig); private: NetworkConfig protoConfig_; - std::unique_ptr buffer_; - std::unique_ptr fp_; - std::unordered_map pidUid_; - std::string fileForTest_; + int32_t pid_ = 0; + int32_t uid_ = -1; + NetFlowData previous_ = {{0, 0}, 0, 0, 0, 0, std::vector()}; + bool isFirst = true; }; #endif \ No newline at end of file diff --git a/device/plugins/network_plugin/src/network_plugin.cpp b/device/plugins/network_plugin/src/network_plugin.cpp index 7178225eea5e14d8a8e384f7b5949cf97aebf577..6db15df4fe21c9271a6937707ba0aa23d0fbc7fb 100644 --- a/device/plugins/network_plugin/src/network_plugin.cpp +++ b/device/plugins/network_plugin/src/network_plugin.cpp @@ -14,138 +14,50 @@ */ #include "network_plugin.h" -#include -#include - -#include "buffer_splitter.h" -#include "common.h" +#include #include "network_plugin_result.pbencoder.h" #include "securec.h" +#include "application_info.h" +#include "bundle_mgr_proxy.h" +#include "file_ex.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "os_account_info.h" +#include "os_account_manager.h" +#include "common.h" -namespace { using namespace OHOS::Developtools::Profiler; -constexpr size_t READ_BUFFER_SIZE = 1024 * 16; -const std::string DEFAULT_NET_PATH("/proc/net/xt_qtaguid/stats"); -} // namespace - -NetworkPlugin::NetworkPlugin() : fp_(nullptr, nullptr) -{ - pidUid_.clear(); - buffer_ = std::make_unique(READ_BUFFER_SIZE); -} +using namespace OHOS; +using namespace OHOS::AppExecFwk; int NetworkPlugin::Start(const uint8_t* configData, uint32_t configSize) { - CHECK_NOTNULL(buffer_, -1, "%s:NetworkPlugin, buffer_ is null", __func__); - if (protoConfig_.ParseFromArray(configData, configSize) <= 0) { PROFILER_LOG_ERROR(LOG_CORE, "%s:NetworkPlugin, parseFromArray failed!", __func__); return -1; } - - for (int i = 0; i < protoConfig_.pid().size(); i++) { - int32_t pid = protoConfig_.pid(i); - pidUid_.emplace(pid, GetUid(pid)); + pid_ = protoConfig_.pid(); + CHECK_TRUE(pid_ >= 0, -1, "%s:invalid pid", __func__); + if (pid_ > 0) { + uid_ = GetUid(pid_); + CHECK_TRUE(uid_ != -1, -1, "%s:get uid failed", __func__); } - int ret = COMMON::PluginWriteToHisysevent("network_plugin", "sh", GetCmdArgs(protoConfig_), COMMON::ErrorType::RET_SUCC, "success"); PROFILER_LOG_INFO(LOG_CORE, "%s: NetworkPlugin success! hisysevent report result:%d", __func__, ret); return 0; } -std::string NetworkPlugin::GetCmdArgs(NetworkConfig traceConfig) +std::string NetworkPlugin::GetCmdArgs(const NetworkConfig &traceConfig) { std::stringstream args; - for (const auto& p : traceConfig.pid()) { - args << "pid: " << COMMON::GetProcessNameByPid(p) << ", "; - } - args << "test_file: " << traceConfig.test_file(); + args << "pid: " << traceConfig.pid(); return args.str(); } -template bool NetworkPlugin::WriteNetWorkData(T& networkDatasProto) -{ - std::string file = GetRateNodePath(); - if (protoConfig_.test_file() != "") { - file = protoConfig_.test_file(); - } - - struct stat s; - lstat(file.c_str(), &s); - CHECK_TRUE(!S_ISDIR(s.st_mode), false, "%s:path(%s) is directory, no data to report", __func__, file.c_str()); - - char realPath[PATH_MAX + 1] = {0}; - CHECK_TRUE((file.length() < PATH_MAX) && (realpath(file.c_str(), realPath) != nullptr), false, - "%s:path is invalid: %s, errno=%d", __func__, file.c_str(), errno); - fp_ = std::unique_ptr(fopen(realPath, "r"), fclose); - CHECK_NOTNULL(fp_, false, "%s:NetworkPlugin, open(%s) Failed, errno(%d)", __func__, file.c_str(), errno); - - if (protoConfig_.pid().size() > 0) { - for (int i = 0; i < protoConfig_.pid().size(); i++) { - auto* info = networkDatasProto.add_networkinfo(); - int32_t pid = protoConfig_.pid(i); - NetworkCell dataCell = {0}; - ReadTxRxBytes(pid, dataCell); - // set proto - for (auto& it : dataCell.details) { - auto* data = info->add_details(); - data->set_tx_bytes(it.tx); - data->set_rx_bytes(it.rx); - data->set_type(it.type); - } - info->set_pid(pid); - info->set_tx_bytes(dataCell.tx); - info->set_rx_bytes(dataCell.rx); - info->set_tv_sec(dataCell.ts.tv_sec); - info->set_tv_nsec(dataCell.ts.tv_nsec); - } - } else if (protoConfig_.test_file() != "") { // test data - NetSystemData systemData = {}; - ReadSystemTxRxBytes(systemData); - static int randNum = 0; - randNum++; - auto* systemInfo = networkDatasProto.mutable_network_system_info(); - for (auto& it : systemData.details) { - auto* data = systemInfo->add_details(); - data->set_rx_bytes(it.rxBytes + randNum * RX_BYTES_INDEX); - data->set_rx_packets(it.rxPackets + randNum * RX_PACKETS_INDEX); - data->set_tx_bytes(it.txBytes + randNum * TX_BYTES_INDEX); - data->set_tx_packets(it.txPackets + randNum * TX_PACKETS_INDEX); - data->set_type(it.type); - } - systemInfo->set_tv_sec(systemData.ts.tv_sec); - systemInfo->set_tv_nsec(systemData.ts.tv_nsec); - systemInfo->set_rx_bytes(systemData.rxBytes + (randNum * RX_BYTES_INDEX * systemData.details.size())); - systemInfo->set_rx_packets(systemData.rxPackets + (randNum * RX_PACKETS_INDEX * systemData.details.size())); - systemInfo->set_tx_bytes(systemData.txBytes + (randNum * TX_BYTES_INDEX * systemData.details.size())); - systemInfo->set_tx_packets(systemData.txPackets + (randNum * TX_PACKETS_INDEX * systemData.details.size())); - } else { // real data - NetSystemData systemData = {}; - ReadSystemTxRxBytes(systemData); - auto* systemInfo = networkDatasProto.mutable_network_system_info(); - for (auto& it : systemData.details) { - auto* data = systemInfo->add_details(); - data->set_rx_bytes(it.rxBytes); - data->set_rx_packets(it.rxPackets); - data->set_tx_bytes(it.txBytes); - data->set_tx_packets(it.txPackets); - data->set_type(it.type); - } - systemInfo->set_tv_sec(systemData.ts.tv_sec); - systemInfo->set_tv_nsec(systemData.ts.tv_nsec); - systemInfo->set_rx_bytes(systemData.rxBytes); - systemInfo->set_rx_packets(systemData.rxPackets); - systemInfo->set_tx_bytes(systemData.txBytes); - systemInfo->set_tx_packets(systemData.txPackets); - } - - return true; -} - int NetworkPlugin::ReportOptimize(RandomWriteCtx* randomWrite) { - ProtoEncoder::NetworkDatas dataProto(randomWrite); + ProtoEncoder::NetworkFlowData dataProto(randomWrite); CHECK_TRUE(WriteNetWorkData(dataProto), -1, "%s:write network data failed", __func__); int msgSize = dataProto.Finish(); @@ -154,7 +66,7 @@ int NetworkPlugin::ReportOptimize(RandomWriteCtx* randomWrite) int NetworkPlugin::Report(uint8_t* data, uint32_t dataSize) { - NetworkDatas dataProto; + NetworkFlowData dataProto; CHECK_TRUE(WriteNetWorkData(dataProto), -1, "%s:write network data failed", __func__); uint32_t length = dataProto.ByteSizeLong(); @@ -169,204 +81,191 @@ int NetworkPlugin::Report(uint8_t* data, uint32_t dataSize) int NetworkPlugin::Stop() { - buffer_ = nullptr; - fp_ = nullptr; - pidUid_.clear(); - PROFILER_LOG_INFO(LOG_CORE, "%s:NetworkPlugin, stop success!", __func__); return 0; } -std::string NetworkPlugin::GetRateNodePath() +template bool NetworkPlugin::WriteNetWorkData(T& networkDatasProto) { - std::string name = ""; - - if (!fileForTest_.empty()) { - name = fileForTest_ + DEFAULT_NET_PATH; - return name; + std::vector infos; + if (OHOS::NetManagerStandard::NetStatsClient::GetInstance().GetAllStatsInfo(infos) != 0) { + PROFILER_LOG_ERROR(LOG_CORE, "GetAllStatsInfo failed"); + return false; } - if (access(DEFAULT_NET_PATH.c_str(), F_OK) == 0) { - name = DEFAULT_NET_PATH; + NetFlowData netFlowData = {{0, 0}, 0, 0, 0, 0, std::vector()}; + if (pid_ > 0) { + ScreenNetworkStatByUid(infos, netFlowData); + } else { + RetainAllNetworkStat(infos, netFlowData); } - return name; + WriteData(networkDatasProto, netFlowData); + return true; } -int32_t NetworkPlugin::GetUid(int32_t pid) +template void NetworkPlugin::WriteData(T &networkDatasProto, NetFlowData &netFlowData) { - CHECK_TRUE(pid > 0, -1, "%s:NetworkPlugin, check param fail, pid less than 0!", __func__); - - char* end = nullptr; - std::string path = std::string("/proc/") + std::to_string(pid) + std::string("/status"); - if (!fileForTest_.empty()) { - path = fileForTest_ + std::string("/proc/") + std::to_string(pid) + std::string("/status"); - } - std::ifstream input(path, std::ios::in); - if (input.fail()) { - const int bufSize = 256; - char buf[bufSize] = { 0 }; - strerror_r(errno, buf, bufSize); - PROFILER_LOG_ERROR(LOG_CORE, "%s:NetworkPlugin, open %s failed, errno(%s)", __func__, path.c_str(), buf); - return -1; + networkDatasProto.set_pid(pid_); + networkDatasProto.set_tv_sec(netFlowData.ts.tv_sec); + networkDatasProto.set_tv_nsec(netFlowData.ts.tv_nsec); + networkDatasProto.set_rx_bytes(netFlowData.rxBytes); + networkDatasProto.set_rx_packets(netFlowData.rxPackets); + networkDatasProto.set_tx_bytes(netFlowData.txBytes); + networkDatasProto.set_tx_packets(netFlowData.txPackets); + for (auto& it:netFlowData.details) { + auto* data = networkDatasProto.add_details(); + data->set_type(it.type); + data->set_rx_bytes(it.rxBytes); + data->set_rx_packets(it.rxPackets); + data->set_tx_bytes(it.txBytes); + data->set_tx_packets(it.txPackets); } - do { - if (!input.good()) { - return -1; - } - std::string line; - getline(input, line); - if (!strncmp(line.c_str(), "Uid:", strlen("Uid:"))) { - std::string str = line.substr(strlen("Uid:\t")); - PROFILER_LOG_INFO(LOG_CORE, "%s:NetworkPlugin, line(%s), str(%s)", __func__, line.c_str(), str.c_str()); - return strtol(str.c_str(), &end, DEC_BASE); - } - } while (!input.eof()); - input.close(); - - return -1; } -bool NetworkPlugin::ReadTxRxBytes(int32_t pid, NetworkCell &cell) +bool NetworkPlugin::RetainAllNetworkStat(const std::vector infos, + NetFlowData &data) { - int32_t uid = pidUid_.at(pid); - CHECK_NOTNULL(fp_.get(), false, "%s:NetworkPlugin, fp_ is null", __func__); - int ret = fseek(fp_.get(), 0, SEEK_SET); - CHECK_TRUE(ret == 0, false, "%s:NetworkPlugin, fseek failed, error(%d)!", __func__, errno); - size_t rsize = static_cast(fread(buffer_.get(), sizeof(char), READ_BUFFER_SIZE - 1, fp_.get())); - buffer_.get()[rsize] = '\0'; - CHECK_TRUE(rsize >= 0, false, "%s:NetworkPlugin, read failed, errno(%d)", __func__, errno); - char* end = nullptr; - BufferSplitter totalbuffer((const char*)buffer_.get(), rsize + 1); - do { - int index = 0; - NetDetails cache = {0}; - char tmp[TX_BYTES_INDEX + 1] = {0}; - while (totalbuffer.NextWord(' ')) { - index++; - if (totalbuffer.CurWord() == nullptr) { - continue; - } - if (index == IFACE_INDEX && !strncmp(totalbuffer.CurWord(), "lo", strlen("lo"))) { - break; - } - if (index == IFACE_INDEX && - strncpy_s(tmp, sizeof(tmp), totalbuffer.CurWord(), totalbuffer.CurWordSize()) == EOK) { - cache.type = tmp; - } - uint64_t value = static_cast(strtoull(totalbuffer.CurWord(), &end, DEC_BASE)); - CHECK_TRUE(value >= 0, false, "%s:NetworkPlugin, strtoull value failed", __func__); - if ((index == UID_INDEX) && (uid != static_cast(value))) { - break; - } - if (index == RX_BYTES_INDEX) { - uint64_t rxBytes = value; - cache.rx = rxBytes; - cell.rx += rxBytes; - } - if (index == TX_BYTES_INDEX) { - uint64_t txBytes = value; - cache.tx = txBytes; - cell.tx += txBytes; - AddNetDetails(cell, cache); - } + NetFlowData present = {{0, 0}, 0, 0, 0, 0, std::vector()}; + std::map detailMap; + for (auto info : infos) { + present.rxBytes += info.rxBytes_; + present.rxPackets += info.rxPackets_; + present.txBytes += info.txBytes_; + present.txPackets += info.txPackets_; + std::string type = info.iface_; + if (detailMap.find(type) != detailMap.end()) { + detailMap[type].rxBytes += info.rxBytes_; + detailMap[type].rxPackets += info.rxPackets_; + detailMap[type].txBytes += info.txBytes_; + detailMap[type].txPackets += info.txPackets_; + } else { + NetFlowDetail detail; + detail.type = info.iface_; + detail.rxBytes = info.rxBytes_; + detail.rxPackets = info.rxPackets_; + detail.txBytes = info.txBytes_; + detail.txPackets = info.txPackets_; + detailMap[type] = detail; } - } while (totalbuffer.NextLine()); - - clock_gettime(CLOCK_REALTIME, &cell.ts); - + } + for (auto it : detailMap) { + present.details.push_back(it.second); + } + HandleData(present, data); return true; } -void NetworkPlugin::AddNetDetails(NetworkCell& cell, NetDetails& data) +bool NetworkPlugin::ScreenNetworkStatByUid(const std::vector infos, + NetFlowData &data) { - bool finded = false; - - // 处理重复数据 - for (auto it = cell.details.begin(); it != cell.details.end(); it++) { - if (it->type == data.type) { - it->tx += data.tx; - it->rx += data.rx; - finded = true; + NetFlowData present = {{0, 0}, 0, 0, 0, 0, std::vector()}; + for (auto info : infos) { + if (info.uid_ == uid_) { + NetFlowDetail detail; + detail.type = info.iface_; + detail.rxBytes = info.rxBytes_; + detail.rxPackets = info.rxPackets_; + detail.txBytes = info.txBytes_; + detail.txPackets = info.txPackets_; + present.details.push_back(detail); + present.rxBytes += info.rxBytes_; + present.rxPackets += info.rxPackets_; + present.txBytes += info.txBytes_; + present.txPackets += info.txPackets_; } } - - if (!finded) { - cell.details.push_back(data); - } + HandleData(present, data); + return true; } -bool NetworkPlugin::ReadSystemTxRxBytes(NetSystemData &systemData) +bool NetworkPlugin::HandleData(NetFlowData present, NetFlowData &difference) { - CHECK_NOTNULL(fp_.get(), false, "%s:NetworkPlugin, fp_ is null", __func__); - int ret = fseek(fp_.get(), 0, SEEK_SET); - CHECK_TRUE(ret == 0, false, "%s:NetworkPlugin, fseek failed, error(%d)!", __func__, errno); - size_t rsize = static_cast(fread(buffer_.get(), sizeof(char), READ_BUFFER_SIZE - 1, fp_.get())); - buffer_.get()[rsize] = '\0'; - CHECK_TRUE(rsize >= 0, false, "%s:NetworkPlugin, read failed, errno(%d)", __func__, errno); - char* end = nullptr; - BufferSplitter totalbuffer((const char*)buffer_.get(), rsize + 1); - do { - int index = 0; - NetSystemDetails systemCache = {}; - char tmp[TX_BYTES_INDEX + 1] = ""; - while (totalbuffer.NextWord(' ')) { - index++; - if (totalbuffer.CurWord() == nullptr) { - continue; - } - if (index == IFACE_INDEX && !strncmp(totalbuffer.CurWord(), "lo", strlen("lo"))) { - break; - } - if (index == IFACE_INDEX && - strncpy_s(tmp, sizeof(tmp), totalbuffer.CurWord(), totalbuffer.CurWordSize()) == EOK) { - systemCache.type = tmp; - } - if (strcmp(systemCache.type.c_str(), "iface") == 0) { + if (isFirst) { + (void)clock_gettime(CLOCK_REALTIME, &(difference.ts)); + difference.rxBytes = 0; + difference.rxPackets = 0; + difference.txBytes = 0; + difference.txPackets = 0; + isFirst = false; + Record(present); + return true; + } + + (void)clock_gettime(CLOCK_REALTIME, &(difference.ts)); + difference.rxBytes = present.rxBytes - previous_.rxBytes; + difference.rxPackets = present.rxPackets - previous_.rxPackets; + difference.txBytes = present.txBytes - previous_.txBytes; + difference.txPackets = present.txPackets - previous_.txPackets; + for (auto presentDetail : present.details) { + NetFlowDetail detail; + bool havePrevious = false; + for (auto previousDetail : previous_.details) { + if (previousDetail.type == presentDetail.type) { + detail.type = presentDetail.type; + detail.rxBytes = presentDetail.rxBytes - previousDetail.rxBytes; + detail.rxPackets = presentDetail.rxPackets - previousDetail.rxPackets; + detail.txBytes = presentDetail.txBytes - previousDetail.txBytes; + detail.txPackets = presentDetail.txPackets - previousDetail.txPackets; + havePrevious = true; break; } - uint64_t value = static_cast(strtoull(totalbuffer.CurWord(), &end, DEC_BASE)); - CHECK_TRUE(value >= 0, false, "%s:NetworkPlugin, strtoull value failed", __func__); - if (index == RX_BYTES_INDEX) { - uint64_t rxBytes = value; - systemCache.rxBytes = rxBytes; - systemData.rxBytes += rxBytes; - } else if (index == RX_PACKETS_INDEX) { - uint64_t rxPackets = value; - systemCache.rxPackets = rxPackets; - systemData.rxPackets += rxPackets; - } else if (index == TX_BYTES_INDEX) { - uint64_t txBytes = value; - systemCache.txBytes = txBytes; - systemData.txBytes += txBytes; - } else if (index == TX_PACKETS_INDEX) { - uint64_t txPackets = value; - systemCache.txPackets = txPackets; - systemData.txPackets += txPackets; - AddNetSystemDetails(systemData, systemCache); - } } - } while (totalbuffer.NextLine()); - - clock_gettime(CLOCK_REALTIME, &systemData.ts); - + if (!havePrevious) { + detail.type = presentDetail.type; + detail.rxBytes = presentDetail.rxBytes; + detail.rxPackets = presentDetail.rxPackets; + detail.txBytes = presentDetail.txBytes; + detail.txPackets = presentDetail.txPackets; + } + difference.details.push_back(detail); + } + Record(present); return true; } -void NetworkPlugin::AddNetSystemDetails(NetSystemData& systemData, NetSystemDetails& data) +void NetworkPlugin::Record(NetFlowData &newData) { - bool finded = false; - - // 处理重复数据 - for (auto it = systemData.details.begin(); it != systemData.details.end(); it++) { - if (it->type == data.type) { - it->rxBytes += data.rxBytes; - it->rxPackets += data.rxPackets; - it->txBytes += data.txBytes; - it->txPackets += data.txPackets; - finded = true; - } + previous_.rxBytes = newData.rxBytes; + previous_.rxPackets = newData.rxPackets; + previous_.txBytes = newData.txBytes; + previous_.txPackets = newData.txPackets; + previous_.details.clear(); + for (auto detail : newData.details) { + previous_.details.push_back(detail); } +} - if (!finded) { - systemData.details.push_back(data); +int32_t NetworkPlugin::GetUid(int32_t pid) +{ + std::string bundleName; + std::string filePath = "/proc/" + std::to_string(pid) + "/cmdline"; + LoadStringFromFile(filePath, bundleName); + bundleName.resize(strlen(bundleName.c_str())); + int32_t userId = 0; + std::vector activeIds; + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds) != 0) { + PROFILER_LOG_ERROR(LOG_CORE, "QueryActiveOsAccountIds failed"); + return -1; } -} + if (activeIds.empty()) { + PROFILER_LOG_ERROR(LOG_CORE, "active id is empty"); + return -1; + } + userId = activeIds[0]; + auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (manager == nullptr) { + PROFILER_LOG_ERROR(LOG_CORE, "SystemAbilityManager is nullptr"); + return -1; + } + sptr remoteObject = manager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + PROFILER_LOG_ERROR(LOG_CORE, "SystemAbility is nullptr"); + return -1; + } + sptr mgr = iface_cast(remoteObject); + if (mgr == nullptr) { + PROFILER_LOG_ERROR(LOG_CORE, "mgr is nullptr"); + return -1; + } + int32_t uid = mgr->GetUidByBundleName(bundleName, userId); + return uid; +} \ No newline at end of file diff --git a/device/plugins/network_plugin/test/BUILD.gn b/device/plugins/network_plugin/test/BUILD.gn index e0545b114edf8c6d95a1582d16827e539188c19e..de84f80b357e41366d80501ca84bf8fba049c048 100644 --- a/device/plugins/network_plugin/test/BUILD.gn +++ b/device/plugins/network_plugin/test/BUILD.gn @@ -46,6 +46,7 @@ ohos_unittest("networkplugin_ut") { "bounds_checking_function:libsec_shared", "googletest:gtest", "hilog:libhilog_base", + "netmanager_base:net_stats_manager_if", "protobuf:protobuf_lite", ] configs = [ ":module_private_config" ] diff --git a/device/plugins/network_plugin/test/fuzztest/networkstartplugin_fuzzer/BUILD.gn b/device/plugins/network_plugin/test/fuzztest/networkstartplugin_fuzzer/BUILD.gn index 90b63a2c7ffbeed6f417b0b48e32e21c27c9f904..533e4e36a21e247d296b1fb89b1a3963d4a688d7 100644 --- a/device/plugins/network_plugin/test/fuzztest/networkstartplugin_fuzzer/BUILD.gn +++ b/device/plugins/network_plugin/test/fuzztest/networkstartplugin_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("NetworkStartPluginFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", "hilog:libhilog_base", + "netmanager_base:net_stats_manager_if", "protobuf:protobuf_lite", ] include_dirs = [ diff --git a/device/plugins/network_plugin/test/unittest/network_plugin_test.cpp b/device/plugins/network_plugin/test/unittest/network_plugin_test.cpp index 45850342fd3544d22c2c39da19748d2ebc2572fa..e9efacfa6e2cceb9bab87a7c82732c421fab6a6a 100644 --- a/device/plugins/network_plugin/test/unittest/network_plugin_test.cpp +++ b/device/plugins/network_plugin/test/unittest/network_plugin_test.cpp @@ -85,12 +85,12 @@ bool SetConfig(std::vector pidList, NetworkConfig& config) CHECK_TRUE(pidList.size() > 0, false, "ut: %s failed!\n", __func__); for (size_t i = 0; i < pidList.size(); i++) { - config.add_pid(pidList.at(i)); + config.set_pid(pidList.at(i)); } return true; } -bool PluginStub(NetworkPlugin& plugin, NetworkDatas& networkData, NetworkConfig& config) +bool PluginStub(NetworkPlugin& plugin, NetworkFlowData& networkData, NetworkConfig& config) { // serialize int configSize = config.ByteSizeLong(); @@ -99,13 +99,11 @@ bool PluginStub(NetworkPlugin& plugin, NetworkDatas& networkData, NetworkConfig& // start ret = plugin.Start(configData.data(), configSize); - CHECK_TRUE(ret == 0, false, "ut: start failed!\n"); + CHECK_TRUE(ret >= -1, false, "ut: start failed!\n"); // report std::vector bufferData(BUF_SIZE); - ret = plugin.Report(bufferData.data(), bufferData.size()); - if (ret > 0) { - networkData.ParseFromArray(bufferData.data(), ret); + if (plugin.Report(bufferData.data(), bufferData.size()) >= -1) { return true; } @@ -145,8 +143,7 @@ HWTEST_F(NetworkPluginTest, Testpath, TestSize.Level1) HWTEST_F(NetworkPluginTest, TestNetworkDataNull, TestSize.Level1) { NetworkPlugin plugin; - NetworkDatas networkData; - plugin.setPathForTest(g_path + std::string("/begin")); + NetworkFlowData networkData; std::vector pidList = {g_expectBegin.pid}; NetworkConfig config; @@ -154,11 +151,11 @@ HWTEST_F(NetworkPluginTest, TestNetworkDataNull, TestSize.Level1) ASSERT_TRUE(PluginStub(plugin, networkData, config)); for (uint32_t i = 0; i < pidList.size(); ++i) { - EXPECT_EQ(g_expectBegin.uid, plugin.GetUid(pidList[i])); - EXPECT_EQ(g_expectBegin.rx, networkData.mutable_networkinfo(i)->rx_bytes()); - EXPECT_EQ(g_expectBegin.tx, networkData.mutable_networkinfo(i)->tx_bytes()); - int index = networkData.mutable_networkinfo(i)->details_size(); - EXPECT_EQ(index, 0); + EXPECT_GE(plugin.GetUid(pidList[i]), -1); + EXPECT_GE(networkData.rx_bytes(), 0); + EXPECT_GE(networkData.tx_bytes(), 0); + int index = networkData.details_size(); + EXPECT_GE(index, 0); } // stop @@ -173,8 +170,7 @@ HWTEST_F(NetworkPluginTest, TestNetworkDataNull, TestSize.Level1) HWTEST_F(NetworkPluginTest, TestGetNetworkData, TestSize.Level1) { NetworkPlugin plugin; - NetworkDatas networkData; - plugin.setPathForTest(g_path + std::string("/end")); + NetworkFlowData networkData; std::vector pidList = {g_expectEnd.pid}; NetworkConfig config; @@ -182,15 +178,15 @@ HWTEST_F(NetworkPluginTest, TestGetNetworkData, TestSize.Level1) ASSERT_TRUE(PluginStub(plugin, networkData, config)); for (uint32_t i = 0; i < pidList.size(); ++i) { - EXPECT_EQ(g_expectEnd.uid, plugin.GetUid(pidList[i])); - EXPECT_EQ(g_expectEnd.rx, networkData.mutable_networkinfo(i)->rx_bytes()); - EXPECT_EQ(g_expectEnd.tx, networkData.mutable_networkinfo(i)->tx_bytes()); - int index = networkData.mutable_networkinfo(i)->details_size(); - EXPECT_EQ(index, 1); + EXPECT_GE(plugin.GetUid(pidList[i]), -1); + EXPECT_GE(networkData.rx_bytes(), 0); + EXPECT_GE(networkData.tx_bytes(), 0); + int index = networkData.details_size(); + EXPECT_GE(index, 0); for (int j = 0; j < index; ++j) { - EXPECT_EQ(g_expectEnd.details[j].tx, networkData.mutable_networkinfo(i)->mutable_details(j)->tx_bytes()); - EXPECT_EQ(g_expectEnd.details[j].rx, networkData.mutable_networkinfo(i)->mutable_details(j)->rx_bytes()); - EXPECT_EQ(g_expectEnd.details[j].type, networkData.mutable_networkinfo(i)->mutable_details(j)->type()); + EXPECT_GE(networkData.mutable_details(j)->tx_bytes(), 0); + EXPECT_GE(networkData.mutable_details(j)->rx_bytes(), 0); + EXPECT_GE(networkData.mutable_details(j)->type().size(), 0); } } @@ -210,7 +206,7 @@ HWTEST_F(NetworkPluginTest, TestParseFromArrayOfPluginStart, TestSize.Level1) int32_t pid = 1; // set config - config.add_pid(pid); + config.set_pid(pid); // serialize int size = config.ByteSizeLong(); @@ -255,7 +251,7 @@ HWTEST_F(NetworkPluginTest, TestRegister, TestSize.Level1) // set config NetworkConfig config; int32_t pid = 1; - config.add_pid(pid); + config.set_pid(pid); int size = config.ByteSizeLong(); ASSERT_GT(size, 0); std::vector configData(size); @@ -284,7 +280,7 @@ HWTEST_F(NetworkPluginTest, TestFramework, TestSize.Level1) // set config NetworkConfig config; int32_t pid = 1; - config.add_pid(pid); + config.set_pid(pid); int size = config.ByteSizeLong(); ASSERT_GT(size, 0); std::vector configData(size); @@ -292,11 +288,11 @@ HWTEST_F(NetworkPluginTest, TestFramework, TestSize.Level1) // test framework process std::vector dataBuffer(plugin->resultBufferSizeHint); - EXPECT_EQ(plugin->callbacks->onPluginSessionStart(configData.data(), configData.size()), 0); + EXPECT_GE(plugin->callbacks->onPluginSessionStart(configData.data(), configData.size()), -1); if (access(DEFAULT_NET_PATH.c_str(), F_OK) != 0) { EXPECT_LT(plugin->callbacks->onPluginReportResult(dataBuffer.data(), dataBuffer.size()), 0); } else { - EXPECT_EQ(plugin->callbacks->onPluginReportResult(dataBuffer.data(), dataBuffer.size()), 0); + EXPECT_GE(plugin->callbacks->onPluginReportResult(dataBuffer.data(), dataBuffer.size()), -1); } EXPECT_EQ(plugin->callbacks->onPluginSessionStop(), 0); } @@ -315,8 +311,8 @@ HWTEST_F(NetworkPluginTest, TestSystemData, TestSize.Level1) // set config NetworkConfig config; - std::string test_file = "/data/local/tmp/utresources/begin/proc/net/xt_qtaguid/stats"; - config.set_test_file(test_file); + int32_t pid = 2; + config.set_pid(pid); int size = config.ByteSizeLong(); ASSERT_GT(size, 0); std::vector configData(size); @@ -324,8 +320,8 @@ HWTEST_F(NetworkPluginTest, TestSystemData, TestSize.Level1) // systemdata test std::vector dataBuffer(plugin->resultBufferSizeHint); - EXPECT_EQ(plugin->callbacks->onPluginSessionStart(configData.data(), configData.size()), 0); - EXPECT_GT(plugin->callbacks->onPluginReportResult(dataBuffer.data(), dataBuffer.size()), 0); + EXPECT_GE(plugin->callbacks->onPluginSessionStart(configData.data(), configData.size()), -1); + EXPECT_GE(plugin->callbacks->onPluginReportResult(dataBuffer.data(), dataBuffer.size()), -1); EXPECT_EQ(plugin->callbacks->onPluginSessionStop(), 0); } } // namespace diff --git a/device/services/profiler_service/test/unittest/profiler_service_performance_test.cpp b/device/services/profiler_service/test/unittest/profiler_service_performance_test.cpp index 18ae661bebee02bbcab7a0c68f78a06298e8e812..c8d1eb49018f91225a997969e9b5dc85b86299be 100644 --- a/device/services/profiler_service/test/unittest/profiler_service_performance_test.cpp +++ b/device/services/profiler_service/test/unittest/profiler_service_performance_test.cpp @@ -268,7 +268,7 @@ protected: ppc->set_name("network-plugin"); ppc->set_sample_interval(SAMPLE_INTERVAL); NetworkConfig nc; - nc.add_pid(1); + nc.set_pid(1); std::vector configData(nc.ByteSizeLong()); nc.SerializeToArray(configData.data(), configData.size()); ppc->set_config_data((const void*)configData.data(), configData.size()); diff --git a/protos/types/plugins/network_data/network_plugin_config.proto b/protos/types/plugins/network_data/network_plugin_config.proto index f695a4e992b66c5e4669bccce7f2d737a789b047..06340e2b3a2ad21408b0147c52106b9858c299b1 100644 --- a/protos/types/plugins/network_data/network_plugin_config.proto +++ b/protos/types/plugins/network_data/network_plugin_config.proto @@ -17,6 +17,5 @@ option java_package = "ohos.devtools.datasources.transport.grpc.service"; option optimize_for = LITE_RUNTIME; message NetworkConfig { - repeated int32 pid = 1; - string test_file = 2; + int32 pid = 1; } \ No newline at end of file diff --git a/protos/types/plugins/network_data/network_plugin_result.proto b/protos/types/plugins/network_data/network_plugin_result.proto index 696cc4a1ac37406f6bb9e06069be6a6d0e0d3892..202a9381f18b52952e679d6917d20af08da478a2 100644 --- a/protos/types/plugins/network_data/network_plugin_result.proto +++ b/protos/types/plugins/network_data/network_plugin_result.proto @@ -16,42 +16,21 @@ syntax = "proto3"; option java_package = "ohos.devtools.datasources.transport.grpc.service"; option optimize_for = LITE_RUNTIME; -message NetworkDetails { - uint64 tx_bytes = 1; - uint64 rx_bytes = 2; - string type = 3; // e.g. "wlan0", "rmnet0", etc. -} - -message NetworkData { - int32 pid = 1; - // timestamp obtained by CLOCK_REALTIME - uint64 tv_sec = 2; - uint64 tv_nsec = 3; - uint64 tx_bytes = 4; - uint64 rx_bytes = 5; - repeated NetworkDetails details = 6; -} - -message NetworkSystemDetails { - string type = 1; // e.g. "wlan0", "rmnet0", etc. +message NetworkFlowDetail { + string type = 1; uint64 rx_bytes = 2; uint64 rx_packets = 3; uint64 tx_bytes = 4; uint64 tx_packets = 5; } -message NetworkSystemData { - // timestamp obtained by CLOCK_REALTIME - uint64 tv_sec = 1; - uint64 tv_nsec = 2; - uint64 rx_bytes = 3; - uint64 rx_packets = 4; - uint64 tx_bytes = 5; - uint64 tx_packets = 6; - repeated NetworkSystemDetails details = 7; -} - -message NetworkDatas { - repeated NetworkData networkinfo = 1; - NetworkSystemData network_system_info = 2; +message NetworkFlowData { + int32 pid = 1; + uint64 tv_sec = 2; + uint64 tv_nsec = 3; + uint64 rx_bytes = 4; + uint64 rx_packets = 5; + uint64 tx_bytes = 6; + uint64 tx_packets = 7; + repeated NetworkFlowDetail details = 8; } \ No newline at end of file