!1772 更新1.0.3版本;增加GTX与GPU_Counter采集

Merge pull request !1772 from frank-huangran/master
This commit is contained in:
openharmony_ci 2024-08-06 15:46:55 +00:00 committed by Gitee
commit acb10b3b6a
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
22 changed files with 702 additions and 824 deletions

View File

@ -40,7 +40,7 @@ ohos_executable("SP_daemon") {
"Dubai.cpp",
"FPS.cpp",
"GPU.cpp",
"GpuCounter.cpp",
"GPU_Counter.cpp",
"Network.cpp",
"Power.cpp",
"RAM.cpp",
@ -57,6 +57,7 @@ ohos_executable("SP_daemon") {
"parse_start_frame_trace.cpp",
"parse_trace.cpp",
"profiler_fps.cpp",
"sdk_data_recv.cpp",
"smartperf_command.cpp",
"smartperf_main.cpp",
"sp_log.cpp",

View File

@ -0,0 +1,42 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/GPU_Counter.h"
namespace OHOS {
namespace SmartPerf {
std::map<std::string, std::string> GPU_Counter::ItemData()
{
return std::map<std::string, std::string>();
}
void GPU_Counter::StartCollect(GcCollectType type)
{
}
void GPU_Counter::SaveData(std::string path)
{
}
std::vector<std::string> &GPU_Counter::GetGpuCounterData()
{
return gpuCounterData;
}
void GPU_Counter::StopCollect(std::string path)
{
}
}
}

View File

@ -1,365 +0,0 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/GpuCounter.h"
#include <iostream>
#include <fstream>
#include <climits>
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include <chrono>
#include "include/sp_utils.h"
#include "include/sp_log.h"
namespace OHOS {
namespace SmartPerf {
const long long WAIT_EXIT_TIME = 500;
const long long WAIT_RUN_TIME = 200;
const int ERROR_CODE_NEGATIVE_TWO = -2;
const int ERROR_CODE_NEGATIVE_THREE = -3;
const int ERROR_CODE_NEGATIVE_FOUR = -4;
GpuCounter::GpuCounter()
{
originalEP = GetPerm();
LOGI("original execute permissions(%d)", static_cast<int>(originalEP));
}
std::map<std::string, std::string> GpuCounter::ItemData()
{
std::map<std::string, std::string> result;
if (initCheckPath == "/data/local/tmp/" && (gcStatus == GC_START || gcStatus == GC_INIT) && (!initMap.empty())) {
result.insert(initMap.begin(), initMap.end());
initMap.clear();
return result;
}
gcStatus = GC_STOP;
KillCounter();
std::this_thread::sleep_for(std::chrono::microseconds(WAIT_EXIT_TIME));
// After 'kill -9', a CSV file will also be generated
if (SPUtils::FileAccess(constOutSourCVSFile)) {
std::string outStr;
std::string newFileName = constOutDestCVSPrefix + "_" + std::to_string(SPUtils::GetCurTime()) + ".csv";
std::string mvCmd = constMvFile + constOutSourCVSFile + " " + sandBoxPath + newFileName;
LOGI("ItemData new file name(%s)", newFileName.c_str());
if (sandBoxPath != "/data/local/tmp/" && (!isSandBoxWrite)) {
SetPerm(EP_PERMISSIVE);
SPUtils::LoadCmd(mvCmd, outStr);
SetPerm(EP_ENFORCING);
} else {
SPUtils::LoadCmd(mvCmd, outStr);
}
fileList.push_back(newFileName);
}
LOGI("GpuCounter ItemData file size(%u)", fileList.size());
result["gpu_counter"] = "true";
std::string content = "";
for (auto it = fileList.begin(); it != fileList.end(); ++it) {
content += *it;
content += ',';
}
if (!content.empty()) {
content.pop_back();
}
result["info"] = content;
LOGI("GpuCounter ItemData map siez=%u", result.size());
return result;
}
int GpuCounter::CheckResources(const std::string &packageName, std::string &errorInfo)
{
std::string result;
SPUtils::LoadCmd(constWhoami, result);
if (result.empty() || result.find(constUserInfo) == std::string::npos) {
errorInfo = "Non root users";
return ERROR_CODE_NEGATIVE_THREE;
}
result.clear();
SPUtils::LoadCmd(constCheckProductInfo, result);
if (result.empty() || result.find(constProductInfo) == std::string::npos) {
errorInfo = "Non Hisilicon chips";
return ERROR_CODE_NEGATIVE_FOUR;
}
if ((!SPUtils::FileAccess(constV2File)) || (!SPUtils::FileAccess(constExecFile)) ||
(!SPUtils::FileAccess(constConfigFile)) || (!SPUtils::FileAccess(constLibFile))) {
errorInfo = "Missing dependency files such as counters_collector";
return -1;
}
if (packageName.empty()) {
errorInfo = "package name is empty";
return ERROR_CODE_NEGATIVE_TWO;
}
if (packageName == "/data/local/tmp/") {
sandBoxPath = packageName;
} else {
sandBoxPath = constSandBoxPath + packageName + constSandBoxFile;
}
return 0;
}
int GpuCounter::Init(const std::string &packageName, std::map<std::string, std::string> &retMap)
{
int ret = 0;
std::string result;
std::string errorInfo;
Rest();
ret = CheckResources(packageName, errorInfo);
if (ret != 0) {
retMap["gpu_counter"] = "false";
retMap["error"] = errorInfo;
initMap.insert(retMap.begin(), retMap.end());
LOGE("%s", errorInfo.c_str());
return ret;
}
initCheckPath = packageName;
if (access(sandBoxPath.c_str(), W_OK) == 0) {
isSandBoxWrite = true;
}
SPUtils::LoadCmd(constAddPermissionsCounter, result);
ret = Start();
if (ret == 0) {
retMap["gpu_counter"] = "true";
} else {
errorInfo = "counters_collector run failed";
retMap["gpu_counter"] = "false";
retMap["error"] = errorInfo;
LOGE("%s", errorInfo.c_str());
}
initMap.insert(retMap.begin(), retMap.end());
return ret;
}
void GpuCounter::Rest()
{
std::string result;
gcStatus = GC_INIT;
fileList.clear();
startCaptureTime = 0;
KillCounter(); // counters_collector if runing kill
if (SPUtils::FileAccess(constOutSourCVSFile)) {
SPUtils::LoadCmd(constRmCsv, result); // clear history files
}
sandBoxPath = "";
initCheckPath = "";
}
int GpuCounter::Start()
{
int ret = 0;
gcStatus = GC_START;
captureDuration = GetCounterDuration();
LOGI("Start captureDuration(%lld)", captureDuration);
if (captureDuration <= 0) {
captureDuration = constDefaultCaptureDuration;
LOGW("read config duration failed,load default(%lld)", captureDuration);
}
ThreadCapture();
std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_RUN_TIME));
std::vector<std::string> pidList;
GetCounterId(pidList);
if (pidList.empty()) {
LOGE("counters_collector run failed ret(%d)", ret);
return -1;
}
startCaptureTime = SPUtils::GetCurTime();
LOGI("GpuCounter Started ret(%d)", ret);
return ret;
}
void GpuCounter::Check()
{
if (gcStatus != GC_START) {
return;
}
long long diff = 0;
long long nowTime = SPUtils::GetCurTime();
diff = startCaptureTime > nowTime ? (LLONG_MAX - startCaptureTime + nowTime) : (nowTime - startCaptureTime);
if (diff < captureDuration) {
return;
}
LOGI("GpuCounter::Check diff(%lld)", diff);
std::vector<std::string> pidList;
GetCounterId(pidList);
if (!pidList.empty()) { // GPU process did not exit
return;
}
if (SPUtils::FileAccess(constOutSourCVSFile)) {
std::string result;
std::string newFileName = constOutDestCVSPrefix + "_" + std::to_string(nowTime) + ".csv";
std::string mvCmd = constMvFile + constOutSourCVSFile + " " + sandBoxPath + newFileName;
if (sandBoxPath != "/data/local/tmp/" && (!isSandBoxWrite)) {
SetPerm(EP_PERMISSIVE);
SPUtils::LoadCmd(mvCmd, result);
SetPerm(EP_ENFORCING);
} else {
SPUtils::LoadCmd(mvCmd, result);
}
fileList.push_back(newFileName);
LOGI("new file name(%s)", newFileName.c_str());
}
Start();
return;
}
void GpuCounter::GetCounterId(std::vector<std::string> &pidList)
{
std::string result;
pidList.clear();
SPUtils::LoadCmd(constGetCounterId, result);
SPUtils::StrSplit(result, " ", pidList);
return;
}
void GpuCounter::KillCounter()
{
std::vector<std::string> pidList;
std::string result;
GetCounterId(pidList);
for (auto it = pidList.begin(); pidList.end() != it; ++it) {
std::string killStr = constKillProcess + *it;
result.clear();
SPUtils::LoadCmd(killStr, result);
}
return;
}
bool GpuCounter::IsNum(const std::string value)
{
bool isNum = false;
for (size_t i = 0; i < value.length(); i++) {
if (value[i] == ' ') {
continue;
} else if (value[i] >= '0' && value[i] <= '9') {
isNum = true;
break;
} else {
break;
}
}
return isNum;
}
long long GpuCounter::GetCounterDuration()
{
bool startFlag = false;
long long ret = -1;
char realPath[PATH_MAX] = {0x00};
if ((realpath(constConfigFile.c_str(), realPath) == nullptr)) {
std::cout << "" << std::endl;
}
std::ifstream file(realPath);
std::string line;
if (!file.is_open()) {
return -1;
}
while (std::getline(file, line)) {
if (!startFlag) {
if (line.find("collector {") != std::string::npos) {
startFlag = true;
}
continue;
}
if (line.find("duration_ms:") != std::string::npos) {
std::vector<std::string> out;
SPUtils::StrSplit(line, ":", out);
if (out.size() <= 1) {
break;
}
std::string value = out[1];
if (IsNum(value)) {
ret = std::stoll(value);
}
break;
} else if (line.find("}") != std::string::npos) {
startFlag = false;
}
}
file.close();
return ret;
}
int GpuCounter::Capture()
{
return system(constCmd.c_str());
}
std::thread GpuCounter::ThreadCapture()
{
auto th = std::thread([this]() { this->Capture(); });
th.detach();
return th;
}
GpuCounter::ExecutePermissions GpuCounter::GetPerm()
{
ExecutePermissions ep = EP_INVALID;
std::string result;
SPUtils::LoadCmd("getenforce", result);
if (result == "Permissive") {
ep = EP_PERMISSIVE;
} else if (result == "Enforcing") {
ep = EP_ENFORCING;
}
return ep;
}
void GpuCounter::SetPerm(ExecutePermissions code)
{
if (!(code == EP_ENFORCING || code == EP_PERMISSIVE)) {
return;
}
if (originalEP == EP_PERMISSIVE) {
return;
}
std::string result;
std::string cmd = "setenforce " + std::to_string(int(code));
SPUtils::LoadCmd(cmd, result);
return;
}
}
}

View File

@ -16,7 +16,7 @@
├── DDR.cpp # DDR采集代码文件
├── FPS.cpp # FPS采集代码文件
├── GPU.cpp # GPU采集代码文件
├── GpuCounter.cpp # GpuCounter采集代码文件
├── GPU_Counter.cpp # GPU_Counter采集代码文件
├── Network.cpp # 网络上下行速率采集代码文件
├── Power.cpp # 功耗采集代码文件
├── RAM.cpp # 内存采集代码文件

View File

@ -0,0 +1,61 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GPU_COUNTER_H
#define GPU_COUNTER_H
#include "string"
#include "vector"
#include "sp_profiler.h"
#include "thread"
namespace OHOS {
namespace SmartPerf {
class GPU_Counter : public SpProfiler {
public:
enum GcStatus {
GC_INIT = 0,
GC_RUNNING,
};
enum GcCollectType {
GC_START = 0,
GC_RESTART,
};
public:
std::map<std::string, std::string> ItemData() override;
static GPU_Counter &GetInstance()
{
static GPU_Counter instance;
return instance;
}
void StartCollect(GcCollectType type);
void StopCollect(std::string path);
std::vector<std::string> &GetGpuCounterData();
private:
GPU_Counter() {};
GPU_Counter(const GPU_Counter &);
GPU_Counter &operator = (const GPU_Counter &);
GcStatus gcStatus = GC_INIT;
std::vector<std::string> gpuCounterData; //保存 std::vector<OHOS::GameService::GpuPerfInfo> gpuCounter; 的数据
void SaveData(std::string path);
};
};
}
#endif

View File

@ -1,115 +0,0 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GPU_COUNTER_H
#define GPU_COUNTER_H
#include "sp_profiler.h"
#include <string>
#include <vector>
#include <cstdio>
#include <list>
#include <cstdlib>
#include <thread>
namespace OHOS {
namespace SmartPerf {
class GpuCounter : public SpProfiler {
public:
enum GcStatus {
GC_INIT = 0,
GC_START,
GC_STOP,
};
enum ExecutePermissions {
EP_INVALID = -1,
EP_PERMISSIVE = 0,
EP_ENFORCING = 1,
};
public:
std::map<std::string, std::string> ItemData() override;
static GpuCounter &GetInstance()
{
static GpuCounter instance;
return instance;
}
GcStatus GetStatus() const
{
return gcStatus;
}
int Init(const std::string &packageName, std::map<std::string, std::string> &retMap);
void Rest();
// 0 ok-1 run failed
int Start();
void Check();
long long GetCounterDuration();
private:
// 0 succed, -1 dependency file not detected, -2 package name error, -3 non root users, -4 Non Hisilicon chips
int CheckResources(const std::string &packageName, std::string &errorInfo);
void GetCounterId(std::vector<std::string> &pidList);
void KillCounter();
int Capture();
std::thread ThreadCapture();
void SetPerm(ExecutePermissions code);
ExecutePermissions GetPerm();
bool IsNum(const std::string value);
private:
bool isSandBoxWrite = false;
ExecutePermissions originalEP = EP_INVALID;
GcStatus gcStatus = GC_INIT;
long long startCaptureTime = 0;
long long captureDuration = 0;
std::vector<std::string> fileList;
std::string sandBoxPath;
std::string initCheckPath;
std::map<std::string, std::string> initMap;
private:
const long long constDefaultCaptureDuration = 5000; // Unit ms
const std::string constMvFile = "mv -f ";
const std::string constKillProcess = "kill -9 ";
const std::string constGetCounterId = "pidof counters_collector";
const std::string constRmCsv = "rm /data/local/tmp/gpu_counter.csv";
const std::string constAddPermissionsCounter = "chmod 777 /bin/counters_collector";
const std::string constCmd =
"LD_LIBRARY_PATH=/bin/ /bin/counters_collector /bin/config.txt >/dev/null 2>&1";
const std::string constSandBoxFile = "/files/";
const std::string constSandBoxPath = "/data/app/el2/100/base/";
const std::string constOutDestCVSPrefix = "gpu_counter";
const std::string constOutSourCVSFile = "/data/local/tmp/gpu_counter.csv";
const std::string constConfigFile = "/bin/config.txt";
const std::string constExecFile = "/bin/counters_collector";
const std::string constLibFile = "/bin/libGPU_PCM.so";
const std::string constV2File = "/bin/counters_collector_v2.txt";
const std::string constCheckProductInfo = "param get const.product.name";
const std::string constProductInfo = "60";
const std::string constWhoami = "whoami";
const std::string constUserInfo = "root";
private:
GpuCounter();
GpuCounter(const GpuCounter &);
GpuCounter &operator = (const GpuCounter &);
};
}
}
#endif // GPU_COUNTER_H

View File

@ -36,9 +36,6 @@ enum class MessageType {
CATCH_TRACE_CONFIG,
CATCH_TRACE_CMD,
SET_DUBAI_DB,
GPU_COUNTER_HB_REQ,
CATCH_GPU_COUNTER, // 请求抓取GPU counter信息
GET_GPU_COUNTER_RESULT, // 获取GPU counter信息
CATCH_NETWORK_TRAFFIC,
GET_NETWORK_TRAFFIC, // 获取网络流量信息
BACK_TO_DESKTOP,
@ -65,9 +62,6 @@ const std::unordered_map<MessageType, std::string> MESSAGE_MAP = {
{ MessageType::CATCH_TRACE_CONFIG, std::string("catch_trace_config") },
{ MessageType::CATCH_TRACE_CMD, std::string("catch_trace_cmd") },
{ MessageType::SET_DUBAI_DB, std::string("set_dubai_db") },
{ MessageType::GPU_COUNTER_HB_REQ, std::string("gpu_counter_hb_req") },
{ MessageType::CATCH_GPU_COUNTER, std::string("catch_gpu_counter") },
{ MessageType::GET_GPU_COUNTER_RESULT, std::string("get_gpu_counter_result") },
{ MessageType::CATCH_NETWORK_TRAFFIC, std::string("catch_network_traffic") },
{ MessageType::GET_NETWORK_TRAFFIC, std::string("get_network_traffic") },
{ MessageType::BACK_TO_DESKTOP, std::string("back_to_desk") },
@ -99,6 +93,7 @@ enum class CommandType {
CT_FTL, //帧间隔限制值单位ms
CT_GC,
CT_NAV,
CT_O,
};
enum class CommandHelp {
HELP,
@ -106,6 +101,7 @@ enum class CommandHelp {
SCREEN,
CLEAR,
SERVER,
EDITORSERVER,
};
const std::unordered_map<std::string, CommandType> COMMAND_MAP = {
@ -131,6 +127,7 @@ const std::unordered_map<std::string, CommandType> COMMAND_MAP = {
{ std::string("-ftl"), CommandType::CT_FTL },
{ std::string("-gc"), CommandType::CT_GC },
{ std::string("-nav"), CommandType::CT_NAV },
{ std::string("-o"), CommandType::CT_O },
};
const std::unordered_map<CommandType, std::string> COMMAND_MAP_REVERSE = {
@ -156,6 +153,7 @@ const std::unordered_map<CommandType, std::string> COMMAND_MAP_REVERSE = {
{ CommandType::CT_FTL, std::string("-ftl") },
{ CommandType::CT_GC, std::string("-gc") },
{ CommandType::CT_NAV, std::string("-nav") },
{ CommandType::CT_O, std::string("-o") },
};
@ -165,6 +163,7 @@ const std::unordered_map<CommandHelp, std::string> COMMAND_HELP_MAP = {
{ CommandHelp::SCREEN, std::string("-screen") },
{ CommandHelp::CLEAR, std::string("-clear") },
{ CommandHelp::SERVER, std::string("-server") },
{ CommandHelp::EDITORSERVER, std::string("-editorServer") },
};
enum class TraceStatus {

View File

@ -0,0 +1,79 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SDK_DATA_RECV_H
#define SDK_DATA_RECV_H
#include <pthread.h>
#include <vector>
#include <string>
#include <arpa/inet.h>
#include "sp_profiler.h"
#include "sp_data.h"
#include <sys/select.h>
namespace OHOS {
namespace SmartPerf {
#define OH_DATA_PORT 12567
#define OH_DATA_PORT_TRY_NUM 3
#define MSG_MAX_LEN 256
#define PARA_NAME_MAX_LEN 16
#define SOCKET_PORT_NUM_PER_TYPE 10
#define OH_SOCKET_MAX 10
typedef struct {
char name[PARA_NAME_MAX_LEN];
int isEvent;
int value;
} ParaStatus;
struct ServerParams {
time_t startTime;
int serverFd;
int pipFd[2];
int receiveFd[OH_SOCKET_MAX];
};
class SdkDataRecv : public SpProfiler {
public:
std::map<std::string, std::string> ItemData() override;
static SdkDataRecv &GetInstance()
{
static SdkDataRecv instance;
return instance;
}
static int CreateOhSocketServer(int basePort);
std::string OhDataReceive(int index, ServerParams &params);
void ServerThread(std::vector<std::string> &dataVec);
void SetRunningState(bool state);
int GetListenFd();
void SetListenFd(int fd);
void RunServerThread(std::vector<std::string> &dataVec, ServerParams &params);
void HandleReceiveFd(std::vector<std::string> &dataVec, int i, ServerParams &params);
void HandleServerFd(ServerParams &params);
void SetUpFdSet(ServerParams &params);
void CleanUpResources(ServerParams &params);
private:
SdkDataRecv() {};
SdkDataRecv(const SdkDataRecv &);
SdkDataRecv &operator = (const SdkDataRecv &);
int listenFd = -1;
int sendSocket = -1;
std::string userTpye = "";
bool collectRunring = false;
int maxFd = 0;
fd_set readFds;
};
}
}
#endif

View File

@ -20,13 +20,14 @@
#include <vector>
#include "common.h"
#include "sp_utils.h"
#include "GPU_Counter.h"
namespace OHOS {
namespace SmartPerf {
class SmartPerfCommand {
public:
const std::string smartPerfExeName = "SP_daemon";
const std::string smartPerfVersion = "1.0.2\n";
const std::string smartPerfVersion = "1.0.3\n";
const std::string smartPerfMsgErr = "error input!\n use command '--help' get more information\n";
const std::string smartPerfMsg = "OpenHarmony performance testing tool SmartPerf command-line version\n"
"Usage: SP_daemon [options] [arguments]\n\n"
@ -83,6 +84,7 @@ public:
std::string pid = "";
// 采集配置项
std::vector<std::string> configs;
GPU_Counter &gpuCounter = GPU_Counter::GetInstance();
};
}
}

View File

@ -22,7 +22,10 @@
#include <map>
#include <mutex>
#include <climits>
#include "parameters.h"
#include "sp_csv_util.h"
#include "sdk_data_recv.h"
#include "GPU_Counter.h"
namespace OHOS {
namespace SmartPerf {
enum class ExceptionMsg {
@ -80,6 +83,12 @@ public:
std::map<std::string, std::string> &dataMap);
void GetItemData(std::map<std::string, std::string> &dataMap);
void WritePath(std::string thisBasePath);
void ConfigDataThread();
void StopSdkRecv();
void StopGpuCounterRecv();
void DeleteSdkVec();
void AsyncGetDataMap(std::function<void(std::string data)> msgTask);
void StopGetInfo();
private:
std::thread ThreadGetHiperf(long long timeStamp);
@ -87,6 +96,8 @@ private:
std::string SetHiperf(const std::string &traceName);
bool CheckCounterId();
void KillHiperfCmd();
void ConfigureSdkData(std::string itConfig);
void RunSdkServer(SdkDataRecv &sdkDataRecv);
private:
TaskInfo curTaskInfo;
@ -99,6 +110,10 @@ private:
const std::string baseOutPath = "/data/local/tmp/smartperf";
long long startCaptuerTime = 0;
int requestId = 1;
bool sdkData = false;
std::thread sdk;
std::vector<std::string> sdkvec;
GPU_Counter &gpuCounter = GPU_Counter::GetInstance();
std::string strOne = R"(hiprofiler_cmd \
-c - \

View File

@ -22,7 +22,6 @@
#include "control_call_cmd.h"
#include "startup_delay.h"
#include "sp_log.h"
#include "GpuCounter.h"
namespace OHOS {
namespace SmartPerf {
class SpThreadSocket {
@ -196,15 +195,7 @@ public:
spSocket.Sendto(retCode);
} else {
std::map<std::string, std::string> data;
if (iterator->first == MessageType::GPU_COUNTER_HB_REQ) {
GpuCounter::GetInstance().Check();
break; // No need to return
} else if (iterator->first == MessageType::CATCH_GPU_COUNTER) {
std::string curPkgName = SplitMsg(recvBuf);
GpuCounter::GetInstance().Init(curPkgName, data);
} else if (iterator->first == MessageType::GET_GPU_COUNTER_RESULT) {
data = profiler->ItemData();
} else if (iterator->first == MessageType::CATCH_NETWORK_TRAFFIC) {
if (iterator->first == MessageType::CATCH_NETWORK_TRAFFIC) {
profiler->ItemData(); // record the collection point for the first time,no need to return
data["network_traffic"] = "true";
} else if (iterator->first == MessageType::GET_NETWORK_TRAFFIC) {

View File

@ -57,6 +57,14 @@ bool LoadFile(const std::string &filePath, std::string &content);
* @return true
* @return false
*/
bool LoadCmdWithLinkBreak(const std::string &cmd, bool isClearLinkBreak, std::string &result);
/**
* @brief
*
* @param path
* @return std::string
*/
bool LoadCmd(const std::string &cmd, std::string &result);
/**
* @brief

View File

@ -15,6 +15,7 @@
#ifndef STARTUP_DELAY_H
#define STARTUP_DELAY_H
#include <thread>
namespace OHOS {
namespace SmartPerf {
class StartUpDelay {
@ -35,6 +36,7 @@ public:
std::string GetPidByPkg(const std::string &curPkgName);
bool GetSpTcp();
bool GetSpClear();
void ClearOldServer();
void InitXY2(const std::string &curAppName, const std::string &fileName, const std::string &appPkgName);
void InitXY(const std::string &curAppName, const std::string &fileName);
std::string pointXY = "0 0";

View File

@ -0,0 +1,246 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sstream>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <string>
#include <regex>
#include <cstdarg>
#include <sys/time.h>
#include <sys/select.h>
#include <netinet/in.h>
#include "include/sp_utils.h"
#include "include/startup_delay.h"
#include "include/sp_log.h"
#include "include/sdk_data_recv.h"
#include "memory_collector.h"
#include "collect_result.h"
#include "include/sp_task.h"
#include "include/sp_utils.h"
#include "securec.h"
namespace OHOS {
namespace SmartPerf {
std::map<std::string, std::string> SdkDataRecv::ItemData()
{
return std::map<std::string, std::string>();
}
int SdkDataRecv::CreateOhSocketServer(int basePort)
{
int i = 0;
int socketFd = 0;
struct sockaddr_in address;
socketFd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (socketFd < 0) {
LOGE("Create socket error.");
return -1;
}
std::fill_n(reinterpret_cast<char*>(&address), sizeof(address), 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
for (i = 0; i < SOCKET_PORT_NUM_PER_TYPE; i++) {
address.sin_port = htons(basePort + i);
if (::bind(socketFd, reinterpret_cast<struct sockaddr *>(&address), sizeof(address)) == 0) {
break;
}
}
if (i >= SOCKET_PORT_NUM_PER_TYPE) {
LOGE("Bind socket error.");
return -1;
}
if (listen(socketFd, OH_SOCKET_MAX) < 0) {
LOGE("Listen socket error.");
close(socketFd);
return -1;
}
LOGD("Listen port %d success, fd is %d", socketFd);
return socketFd;
}
std::string SdkDataRecv::OhDataReceive(int index, ServerParams &params)
{
char receiveBuf[MSG_MAX_LEN];
int readLen = 0;
if ((readLen = read(params.receiveFd[index], receiveBuf, MSG_MAX_LEN)) <= 0) {
close(params.receiveFd[index]);
params.receiveFd[index] = -1;
return "";
}
LOGI("Fd %d,%d, receove %s", index, params.receiveFd[index], receiveBuf);
std::string receiveStr(receiveBuf);
size_t pos = receiveStr.find_first_of('{');
while (pos != std::string::npos) {
receiveStr.erase(pos, 1);
pos = receiveStr.find_first_of('{', pos);
}
pos = receiveStr.find_first_of('}');
while (pos != std::string::npos) {
receiveStr.erase(pos, 1);
pos = receiveStr.find_first_of('}', pos);
}
std::stringstream ss(receiveStr);
std::string item;
std::string source;
std::string timestamp;
std::string eventName;
std::string enable;
std::string value;
while (std::getline(ss, item, ',')) {
std::stringstream itemSS(item);
std::string first;
std::string second;
std::getline(itemSS, first, ':');
std::getline(itemSS, second, ':');
if (first == "src") {
source = second;
} else if (first == "para0") {
eventName = second;
} else if (first == "time") {
timestamp = std::to_string(std::stoll(second) - params.startTime);
} else if (first == "enable") {
enable = second;
} else if (first == "value") {
value = second;
}
}
item = source + "," + timestamp + "," + eventName + "," + enable + "," + value + "\r";
return item;
}
void SdkDataRecv::SetRunningState(bool state)
{
collectRunring = state;
}
void SdkDataRecv::ServerThread(std::vector<std::string> &dataVec)
{
ServerParams params;
for (int i = 0; i < OH_SOCKET_MAX; i++) {
params.receiveFd[i] = -1;
}
params.startTime = SPUtils::GetCurTime();
params.serverFd = CreateOhSocketServer(OH_DATA_PORT);
if (params.serverFd < 0) {
LOGE("Create server failed.");
exit(0);
}
if (pipe(params.pipFd) == -1) {
LOGE("Create service failed.");
exit(0);
}
listenFd = params.pipFd[1];
RunServerThread(dataVec, params);
}
void SdkDataRecv::RunServerThread(std::vector<std::string> &dataVec, ServerParams &params)
{
while (collectRunring) {
SetUpFdSet(params);
if (select(maxFd + 1, &readFds, NULL, NULL, NULL) <= 0) {
continue;
}
for (int i = 0; i < OH_SOCKET_MAX; i++) {
HandleReceiveFd(dataVec, i, params);
}
HandleServerFd(params);
}
CleanUpResources(params);
}
void SdkDataRecv::SetUpFdSet(ServerParams &params)
{
FD_ZERO(&readFds);
FD_SET(params.serverFd, &readFds);
FD_SET(params.pipFd[0], &readFds);
maxFd = std::max(params.serverFd, params.pipFd[0]);
for (int i = 0; i < OH_SOCKET_MAX; i++) {
if (params.receiveFd[i] >= 0) {
FD_SET(params.receiveFd[i], &readFds);
maxFd = std::max(maxFd, params.receiveFd[i]);
}
}
}
void SdkDataRecv::HandleReceiveFd(std::vector<std::string> &dataVec, int i, ServerParams &params)
{
if (params.receiveFd[i] >= 0 && FD_ISSET(params.receiveFd[i], &readFds)) {
std::string data = OhDataReceive(i, params);
dataVec.push_back(data);
}
}
void SdkDataRecv::HandleServerFd(ServerParams &params)
{
if (!FD_ISSET(params.serverFd, &readFds)) {
return;
}
int fd = accept(params.serverFd, NULL, NULL);
if (fd < 0) {
return;
}
for (int i = 0; i < OH_SOCKET_MAX; i++) {
if (params.receiveFd[i] < 0) {
params.receiveFd[i] = fd;
if (fd > maxFd) {
maxFd = fd;
}
break;
}
}
}
void SdkDataRecv::CleanUpResources(ServerParams &params)
{
if (params.serverFd != -1) {
close(params.serverFd);
params.serverFd = -1;
}
if (params.pipFd[0] != -1) {
close(params.pipFd[0]);
params.pipFd[0] = -1;
}
for (int i = 0; i < OH_SOCKET_MAX; i++) {
if (params.receiveFd[i] != -1) {
close(params.receiveFd[i]);
params.receiveFd[i] = -1;
}
}
}
int SdkDataRecv::GetListenFd()
{
return listenFd;
}
void SdkDataRecv::SetListenFd(int fd)
{
listenFd = fd;
}
}
}

View File

@ -84,7 +84,7 @@ void SmartPerfCommand::HelpCommand(CommandHelp type) const
std::cout << smartPerfMsg << std::endl;
}
if (type == CommandHelp::VERSION) {
std::cout << smartPerfVersion << std::endl;
std::cout << "Version: " << smartPerfVersion << std::endl;
}
if (type == CommandHelp::SCREEN) {
std::string result = SPUtils::GetScreen();
@ -94,12 +94,15 @@ void SmartPerfCommand::HelpCommand(CommandHelp type) const
if (type == CommandHelp::CLEAR) {
sd.GetSpClear();
}
if (type == CommandHelp::SERVER) {
if (type == CommandHelp::SERVER || type == CommandHelp::EDITORSERVER) {
sd.ClearOldServer();
std::string pidStr = sd.GetPidByPkg("SP_daemon");
std::string cmdStr = "taskset -p f " + pidStr;
std::string result = "";
SPUtils::LoadCmd(cmdStr, result);
daemon(0, 0);
if (type == CommandHelp::SERVER) {
daemon(0, 0);
}
InitSomething();
SpThreadSocket udpThreadSocket;
SpThreadSocket udpExThreadSocket;
@ -167,23 +170,15 @@ int SmartPerfCommand::GetItemInfo(std::multimap<std::string, std::string, declty
for (size_t j = 0; j < configs.size(); j++) {
std::string curParam = configs[j];
if (curParam.find("-gc") != std::string::npos) {
continue;
}
SpProfiler *profiler = SpProfilerFactory::GetCmdProfilerItem(COMMAND_MAP.at(curParam), true);
if (profiler != nullptr) {
std::map<std::string, std::string> data = profiler->ItemData();
spMap.insert(data.cbegin(), data.cend());
auto cit = data.find("gpu_counter");
if (cit == data.end()) {
continue;
}
if (cit->second == "true") {
rc = 1;
} else {
cit = data.find("error");
errInfo = "gpu_counter error:";
errInfo += (cit != data.end()) ? cit->second : "run failed";
break;
}
}
}
@ -202,10 +197,14 @@ std::string SmartPerfCommand::ExecCommand()
ram.SetFirstFlag();
int rc = 0;
int index = 0;
bool callGpuCounterResult = false;
std::vector<SPData> vmap;
const long long freq = 1000;
num = num + 1;
for (std::string itConfig : configs) {
if (itConfig.find("-gc") != std::string::npos) {
gpuCounter.StartCollect(GPU_Counter::GC_START);
}
}
while (index < num) {
std::multimap<std::string, std::string, decltype(SPUtils::Cmp) *> spMap(SPUtils::Cmp);
long long lastTime = SPUtils::GetCurTime();
@ -213,8 +212,6 @@ std::string SmartPerfCommand::ExecCommand()
rc = GetItemInfo(spMap);
if (rc == -1) {
break;
} else if (rc == 1) {
callGpuCounterResult = true;
}
std::cout << std::endl;
PrintMap(spMap, index);
@ -231,13 +228,8 @@ std::string SmartPerfCommand::ExecCommand()
}
index++;
}
if (callGpuCounterResult) {
const std::map<std::string, std::string> data = GpuCounter::GetInstance().ItemData();
PrintfExecCommand(data);
SPData spdata;
spdata.values.insert(data.begin(), data.end());
vmap.push_back(spdata);
}
std::string outGpuCounterDataPath = "/data/local/tmp/gpu_counter.csv";
gpuCounter.StopCollect(outGpuCounterDataPath);
std::this_thread::sleep_for(std::chrono::milliseconds(freq));
LOGI("SmartPerfCommand::WriteCsv start");
SpCsvUtil::WriteCsv(std::string(outPath.c_str()), vmap);

View File

@ -75,6 +75,7 @@ static bool g_checkCmdParam(std::vector<std::string> &argv, std::string &errorIn
keys.insert("sections");
keys.insert("deviceinfo");
keys.insert("ohtestfps");
keys.insert("editorServer");
for (auto a : OHOS::SmartPerf::COMMAND_MAP) {
keys.insert(a.first.substr(1)); // No prefix required '-'
}

View File

@ -27,11 +27,9 @@
#include "include/sp_profiler_factory.h"
#include "include/Dubai.h"
#include "include/Capture.h"
#include "include/GpuCounter.h"
#include "include/navigation.h"
#include "include/sp_log.h"
namespace OHOS {
namespace SmartPerf {
SpProfiler *SpProfilerFactory::GetProfilerItem(MessageType messageType)
@ -87,11 +85,6 @@ SpProfiler *SpProfilerFactory::GetProfilerItemContinue(MessageType messageType)
case MessageType::SET_DUBAI_DB:
DumpDubaiAndMoveDb();
break;
case MessageType::GPU_COUNTER_HB_REQ:
case MessageType::CATCH_GPU_COUNTER:
case MessageType::GET_GPU_COUNTER_RESULT:
profiler = &GpuCounter::GetInstance();
break;
case MessageType::CATCH_NETWORK_TRAFFIC:
case MessageType::GET_NETWORK_TRAFFIC:
profiler = &Network::GetInstance();
@ -216,17 +209,6 @@ SpProfiler *SpProfilerFactory::GetCmdProfilerItemContinue(CommandType commandTyp
profiler = &Capture::GetInstance();
}
break;
case CommandType::CT_HW:
break;
case CommandType::CT_GC:
if (GpuCounter::GetInstance().GetStatus() == GpuCounter::GC_INIT) {
std::map<std::string, std::string> retMap;
GpuCounter::GetInstance().Init("/data/local/tmp/", retMap);
profiler = &GpuCounter::GetInstance();
} else if (GpuCounter::GetInstance().GetStatus() == GpuCounter::GC_START) {
GpuCounter::GetInstance().Check();
}
break;
default:
break;
}

View File

@ -209,6 +209,11 @@ void SPTask::GetItemData(std::map<std::string, std::string> &dataMap)
std::map<std::string, std::string> captureMap = Capture::GetInstance().ItemData();
dataMap.insert(captureMap.begin(), captureMap.end());
}
if (itConfig.find("-gc") != std::string::npos || itConfig.find("-o") != std::string::npos) {
continue;
}
SpProfiler *profiler = SpProfilerFactory::GetCmdProfilerItem(COMMAND_MAP.at(itConfig), false);
if (profiler != nullptr) {
std::map<std::string, std::string> itemMap = profiler->ItemData();
@ -217,6 +222,104 @@ void SPTask::GetItemData(std::map<std::string, std::string> &dataMap)
}
}
void SPTask::ConfigDataThread()
{
for (std::string itConfig : curTaskInfo.taskConfig) {
if (!sdkData) {
ConfigureSdkData(itConfig);
}
if (itConfig.find("-gc") != std::string::npos) {
gpuCounter.StartCollect(GPU_Counter::GC_START);
}
}
}
void SPTask::ConfigureSdkData(std::string itConfig)
{
if (itConfig.find("-o") != std::string::npos) {
sdkData = true;
OHOS::system::SetParameter("debug.smartperf.sdkdataenable", "1");
SdkDataRecv &sdkDataRecv = SdkDataRecv::GetInstance();
sdkDataRecv.SetRunningState(true);
sdk = std::thread([&sdkDataRecv, this]() { this->RunSdkServer(sdkDataRecv); });
}
}
void SPTask::RunSdkServer(SdkDataRecv &sdkDataRecv)
{
sdkDataRecv.ServerThread(sdkvec);
}
void SPTask::StopSdkRecv()
{
std::string outSdkDataPath = baseOutPath + "/" + curTaskInfo.sessionId + "/sdk_data.csv";
std::ofstream outFile;
outFile.open(outSdkDataPath.c_str(), std::ios::out | std::ios::trunc);
std::mutex mtx;
std::string title = "source,timestamp,eventName,enable,value\r";
outFile << title << std::endl;
mtx.lock();
for (const auto &item : sdkvec) {
outFile << item << std::endl;
}
mtx.unlock();
outFile.close();
OHOS::system::SetParameter("debug.smartperf.sdkdataenable", "0");
sdkData = false;
SdkDataRecv &sdkDataRecv = SdkDataRecv::GetInstance();
sdkDataRecv.SetRunningState(false);
int listenFd = sdkDataRecv.GetListenFd();
if (listenFd != -1) {
close(listenFd);
sdkDataRecv.SetListenFd(-1);
}
if (sdk.joinable()) {
sdk.join();
}
}
void SPTask::DeleteSdkVec()
{
std::string outSdkDataPath = baseOutPath + "/" + curTaskInfo.sessionId + "/sdk_data.csv";
std::ifstream infile(outSdkDataPath.c_str());
if (infile.good()) {
infile.close();
std::remove(outSdkDataPath.c_str());
}
}
void SPTask::AsyncGetDataMap(std::function<void(std::string data)> msgTask)
{
long long lastTime = SPUtils::GetCurTime();
std::lock_guard<std::mutex> lock(mtx);
std::map<std::string, std::string> dataMap;
dataMap.insert(std::pair<std::string, std::string>(std::string("timestamp"), std::to_string(lastTime)));
std::future<std::map<std::string, std::string>> fpsResult = AsyncCollectFps();
std::future<std::map<std::string, std::string>> cpuResult = AsyncCollectCpu();
GetItemData(dataMap);
std::future<std::map<std::string, std::string>> ramResult = AsyncCollectRam();
CheckFutureFps(fpsResult, dataMap);
CheckFutureCpu(cpuResult, dataMap);
CheckFutureRam(ramResult, dataMap);
if (curTaskInfo.stuckInfo.isEffective) {
std::map<std::string, std::string> timeUsedMap = DetectionAndGrab();
if (!timeUsedMap.empty()) {
dataMap.insert(timeUsedMap.begin(), timeUsedMap.end());
}
}
SPData spdata;
spdata.values.insert(dataMap.begin(), dataMap.end());
vmap.push_back(spdata);
msgTask(MapToString(dataMap));
long long nextTime = SPUtils::GetCurTime();
long long costTime = nextTime - lastTime;
long long pTime = 998;
if (costTime < curTaskInfo.freq) {
std::this_thread::sleep_for(std::chrono::milliseconds(pTime - costTime));
}
}
ErrCode SPTask::StartTask(std::function<void(std::string data)> msgTask)
{
LOGI("SPTask::StartTask start ");
@ -232,41 +335,18 @@ ErrCode SPTask::StartTask(std::function<void(std::string data)> msgTask)
SpProfilerFactory::SetProfilerPkg(curTaskInfo.packageName);
}
vmap.clear();
sdkvec.clear();
DeleteSdkVec();
ConfigDataThread();
thread = std::thread([this, msgTask]() {
while (isRunning) {
long long lastTime = SPUtils::GetCurTime();
std::lock_guard<std::mutex> lock(mtx);
std::map<std::string, std::string> dataMap;
dataMap.insert(std::pair<std::string, std::string>(std::string("timestamp"), std::to_string(lastTime)));
std::future<std::map<std::string, std::string>> fpsResult = AsyncCollectFps();
std::future<std::map<std::string, std::string>> cpuResult = AsyncCollectCpu();
GetItemData(dataMap);
std::future<std::map<std::string, std::string>> ramResult = AsyncCollectRam();
CheckFutureFps(fpsResult, dataMap);
CheckFutureCpu(cpuResult, dataMap);
CheckFutureRam(ramResult, dataMap);
if (curTaskInfo.stuckInfo.isEffective) {
std::map<std::string, std::string> timeUsedMap = DetectionAndGrab();
if (!timeUsedMap.empty()) {
dataMap.insert(timeUsedMap.begin(), timeUsedMap.end());
}
}
SPData spdata;
spdata.values.insert(dataMap.begin(), dataMap.end());
vmap.push_back(spdata);
msgTask(MapToString(dataMap));
long long nextTime = SPUtils::GetCurTime();
long long costTime = nextTime - lastTime;
long long pTime = 998;
if (costTime < curTaskInfo.freq) {
std::this_thread::sleep_for(std::chrono::milliseconds(pTime - costTime));
}
AsyncGetDataMap(msgTask);
}
});
LOGI("SPTask::StartTask complete");
return ErrCode::OK;
}
void SPTask::WritePath(std::string thisBasePath)
{
if (!SPUtils::FileAccess(thisBasePath)) {
@ -275,49 +355,64 @@ void SPTask::WritePath(std::string thisBasePath)
}
}
void SPTask::StopTask()
void SPTask::StopGetInfo()
{
bool isTcpMessage = true;
std::string thisBasePath = baseOutPath + "/" + curTaskInfo.sessionId;
WritePath(thisBasePath);
std::string outIndexpath = thisBasePath + "/t_index_info.csv";
long long endTime = SPUtils::GetCurTime();
long long testDuration = (endTime - startTime) / 1000;
std::string screenStr = SPUtils::GetScreen();
size_t pos3 = screenStr.find("=");
std::string refreshrate = screenStr.substr(pos3 + 1);
std::map<std::string, std::string> taskInfoMap = {
{ "sessionId", curTaskInfo.sessionId },
{ "taskId", curTaskInfo.sessionId },
{ "appName", curTaskInfo.packageName },
{ "packageName", curTaskInfo.packageName },
{ "startTime", std::to_string(startTime) },
{ "endTime", std::to_string(endTime) },
{ "testDuration", std::to_string(testDuration) },
{ "taskName", "testtask" },
{ "board", "hw" },
{ "target_fps", refreshrate },
};
std::map<std::string, std::string> deviceInfo = SPUtils::GetDeviceInfo();
std::map<std::string, std::string> cpuInfo = SPUtils::GetCpuInfo(isTcpMessage);
std::map<std::string, std::string> gpuInfo = SPUtils::GetGpuInfo(isTcpMessage);
std::map<std::string, std::string> destMap;
destMap.insert(taskInfoMap.begin(), taskInfoMap.end());
destMap.insert(deviceInfo.begin(), deviceInfo.end());
destMap.insert(cpuInfo.begin(), cpuInfo.end());
destMap.insert(gpuInfo.begin(), gpuInfo.end());
OHOS::SmartPerf::SpCsvUtil::WriteCsvH(destMap);
if (!vmap.empty()) {
vmap.erase(vmap.begin());
}
OHOS::SmartPerf::SpCsvUtil::WriteCsv(outIndexpath, vmap);
}
void SPTask::StopGpuCounterRecv()
{
std::string outGpuCounterDataPath = baseOutPath + "/" + curTaskInfo.sessionId + "/gpu_counter.csv";
gpuCounter.StopCollect(outGpuCounterDataPath);
}
void SPTask::StopTask()
{
LOGI("SPTask::StopTask start");
if (isInit) {
std::string thisBasePath = baseOutPath + "/" + curTaskInfo.sessionId;
WritePath(thisBasePath);
std::string outIndexpath = thisBasePath + "/t_index_info.csv";
long long endTime = SPUtils::GetCurTime();
long long testDuration = (endTime - startTime) / 1000;
std::string screenStr = SPUtils::GetScreen();
size_t pos3 = screenStr.find("=");
std::string refreshrate = screenStr.substr(pos3 + 1);
std::map<std::string, std::string> taskInfoMap = {
{ "sessionId", curTaskInfo.sessionId },
{ "taskId", curTaskInfo.sessionId },
{ "appName", curTaskInfo.packageName },
{ "packageName", curTaskInfo.packageName },
{ "startTime", std::to_string(startTime) },
{ "endTime", std::to_string(endTime) },
{ "testDuration", std::to_string(testDuration) },
{ "taskName", "testtask" },
{ "board", "hw" },
{ "target_fps", refreshrate },
};
std::map<std::string, std::string> deviceInfo = SPUtils::GetDeviceInfo();
std::map<std::string, std::string> cpuInfo = SPUtils::GetCpuInfo(isTcpMessage);
std::map<std::string, std::string> gpuInfo = SPUtils::GetGpuInfo(isTcpMessage);
std::map<std::string, std::string> destMap;
destMap.insert(taskInfoMap.begin(), taskInfoMap.end());
destMap.insert(deviceInfo.begin(), deviceInfo.end());
destMap.insert(cpuInfo.begin(), cpuInfo.end());
destMap.insert(gpuInfo.begin(), gpuInfo.end());
OHOS::SmartPerf::SpCsvUtil::WriteCsvH(destMap);
if (!vmap.empty()) {
vmap.erase(vmap.begin());
StopGetInfo();
if (sdkData) {
StopSdkRecv();
}
OHOS::SmartPerf::SpCsvUtil::WriteCsv(outIndexpath, vmap);
StopGpuCounterRecv();
}
isRunning = false;
isInit = false;
vmap.clear();
sdkvec.clear();
gpuCounter.GetGpuCounterData().clear();
if (thread.joinable()) {
thread.join();
}
@ -402,11 +497,6 @@ bool SPTask::CheckTcpParam(std::string str, std::string &errorInfo)
keys.insert(a.first.substr(1)); // 不需要前面的'-'
}
auto itr = keys.find("gc"); // editor tcp does not support gc
if (keys.end() != itr) {
keys.erase(itr);
}
return SPUtils::VeriyParameter(keys, str, errorInfo);
}

View File

@ -81,7 +81,7 @@ bool SPUtils::LoadFile(const std::string &filePath, std::string &content)
return true;
}
bool SPUtils::LoadCmd(const std::string &cmd, std::string &result)
bool SPUtils::LoadCmdWithLinkBreak(const std::string &cmd, bool isClearLinkBreak, std::string &result)
{
std::string cmdExc = cmd;
FILE *fd = popen(cmdExc.c_str(), "r");
@ -96,11 +96,20 @@ bool SPUtils::LoadCmd(const std::string &cmd, std::string &result)
if (pclose(fd) == -1) {
std::cout << "" << std::endl;
}
// remove '' \n\r
ReplaceString(result);
if (isClearLinkBreak) {
// remove '' \n\r
ReplaceString(result);
}
return ret >= 0 ? true : false;
}
bool SPUtils::LoadCmd(const std::string &cmd, std::string &result)
{
return LoadCmdWithLinkBreak(cmd, true, result);
}
std::string SPUtils::IncludePathDelimiter(const std::string &path)
{
if (!path.empty() && path.back() != '/') {

View File

@ -23,6 +23,8 @@
#include "unistd.h"
#include "include/startup_delay.h"
#include "include/sp_utils.h"
#include "unistd.h"
#include "include/sp_log.h"
namespace OHOS {
namespace SmartPerf {
StartUpDelay::StartUpDelay() {}
@ -135,15 +137,56 @@ bool StartUpDelay::GetSpClear()
std::string str;
SPUtils::LoadCmd("pidof SP_daemon", resultPid);
std::string token;
size_t pos = 0;
while ((pos = resultPid.find(' ')) != std::string::npos) {
token = resultPid.substr(0, pos);
SPUtils::LoadCmd("kill " + token, str);
resultPid.erase(0, pos + 1);
std::string curPid = std::to_string(getpid());
std::stringstream ss(resultPid);
while (ss >> token) {
if (token != curPid) {
SPUtils::LoadCmd("kill " + token, str);
}
}
return false;
}
void StartUpDelay::ClearOldServer()
{
std::string curPid = std::to_string(getpid());
std::string commandServer = "ps -ef | grep -v grep | grep 'SP_daemon -server'";
std::string resultPidServer;
std::string commandEditorServer = "ps -ef | grep -v grep | grep 'SP_daemon -editorServer'";
std::string resultPidEditorServer;
SPUtils::LoadCmdWithLinkBreak(commandServer, false, resultPidServer);
SPUtils::LoadCmdWithLinkBreak(commandEditorServer, false, resultPidEditorServer);
std::istringstream iss(resultPidServer + '\n' + resultPidEditorServer);
std::string resultLine;
std::string killResult;
while (std::getline(iss, resultLine)) {
if (resultLine.empty() || resultLine.find("sh -c") != std::string::npos) {
continue;
}
std::istringstream lineStream(resultLine);
std::string token;
int count = 0;
while (lineStream >> token) {
if (count == 1) {
break;
}
count++;
}
if (token != curPid) {
SPUtils::LoadCmd("kill " + token, killResult);
LOGI("Find old server: %s, killed.", token.c_str());
}
}
}
std::thread StartUpDelay::ThreadGetHisysIds() const
{
auto thGetHisysIds = std::thread([this]() { this->GetHisysIdAndKill(); });

View File

@ -29,7 +29,7 @@ ohos_unittest("sp_daemon_ut") {
"../Dubai.cpp",
"../FPS.cpp",
"../GPU.cpp",
"../GpuCounter.cpp",
"../GPU_Counter.cpp",
"../Network.cpp",
"../Power.cpp",
"../RAM.cpp",
@ -46,7 +46,6 @@ ohos_unittest("sp_daemon_ut") {
"unittest/ddr_test.cpp",
"unittest/dubai_test.cpp",
"unittest/fps_test.cpp",
"unittest/gpu_counter_test.cpp",
"unittest/parse_radar_test.cpp",
"unittest/smartperf_main_test.cpp",
"unittest/sp_daemon_test.cpp",
@ -67,6 +66,7 @@ ohos_unittest("sp_daemon_ut") {
"hilog:libhilog",
"hiview:libucollection_utility",
"image_framework:image_native",
"init:libbegetutil",
"window_manager:libdm",
"window_manager:libwm",
]

View File

@ -1,205 +0,0 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <exception>
#include <iostream>
#include <string>
#include <thread>
#include <gtest/gtest.h>
#include <unistd.h>
#include <cstring>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <functional>
#include "GpuCounter.h"
#include "sp_utils.h"
using namespace testing::ext;
using namespace std;
namespace OHOS {
namespace SmartPerf {
class SPdaemonGpuTest : public testing::Test {
public:
static void SetUpTestCase() {}
static void TearDownTestCase() {}
void SetUp() {}
void TearDown() {}
};
/**
* @tc.name: GpuCounter::Init
* @tc.desc: Test Init
* @tc.type: FUNC
*/
HWTEST_F(SPdaemonGpuTest, Init001, TestSize.Level1)
{
std::string result;
std::string constConfigFile = "/bin/config.txt";
std::string constExecFile = "/bin/counters_collector";
std::string constLibFile = "/bin/libGPU_PCM.so";
std::string constV2File = "/bin/counters_collector_v2.txt";
std::string constCheckProductInfo = "param get const.product.name";
std::string constProductInfo = "60";
std::string constWhoami = "whoami";
std::string constUserInfo = "root";
std::string recvBuf;
std::map<std::string, std::string> data;
int ret = GpuCounter::GetInstance().Init(recvBuf, data);
SPUtils::LoadCmd(constWhoami, result);
if (result.empty() || result.find(constUserInfo) == std::string::npos) {
EXPECT_EQ(ret, -3);
return;
}
SPUtils::LoadCmd(constCheckProductInfo, result);
if (result.empty() || result.find(constProductInfo) == std::string::npos) {
EXPECT_EQ(ret, -4);
return;
}
if ((!SPUtils::FileAccess(constV2File)) || (!SPUtils::FileAccess(constExecFile)) ||
(!SPUtils::FileAccess(constConfigFile)) || (!SPUtils::FileAccess(constLibFile))) {
EXPECT_EQ(ret, -1);
return;
}
EXPECT_EQ(ret, -2);
return;
}
/*
// 002屏蔽GpuCounter.cpp 第35、78-83行进行测试后续测试添加依赖文件文件齐全所以屏蔽该测试
HWTEST_F(SPdaemonGpuTest, Init002, TestSize.Level1)
{
std::string recvBuf;
std::map<std::string, std::string> data;
int ret = GpuCounter::GetInstance().Init(recvBuf, data); // 外部依赖文件不全,返回-1
EXPECT_EQ(ret, -1);
}
// 003屏蔽GpuCounter.cpp 第35、78-83行进行测试
HWTEST_F(SPdaemonTest, Init003, TestSize.Level1)
{
std::string recvBuf = "";
std::map<std::string, std::string> data;
int ret = GpuCounter::GetInstance().Init(recvBuf, data); // recvBuf为空返回-2
EXPECT_EQ(ret, -2);
}
// 004屏蔽GpuCounter.cpp 第35、78-83行进行测试
HWTEST_F(SPdaemonTest, Init004, TestSize.Level1)
{
std::string recvBuf = "ABCDE";
std::map<std::string, std::string> data;
int ret = GpuCounter::GetInstance().Init(recvBuf, data); // 无法访问sandBoxPath路径,返回-3
EXPECT_EQ(ret, -3);
}
// 005屏蔽GpuCounter.cpp 第35、78-83行进行测试
HWTEST_F(SPdaemonTest, Init005, TestSize.Level1)
{
std::string recvBuf = "com.ohos.smartperf1";
std::map<std::string, std::string> data;
int ret = GpuCounter::GetInstance().Init(recvBuf, data);
EXPECT_EQ(ret, -1); // 此处的-1为接口中调用Start所返回的-1
}
*/
/**
* @tc.name: GpuCounter::ItemData
* @tc.desc: Test ItemData
* @tc.type: FUNC
*/
HWTEST_F(SPdaemonGpuTest, ItemData001, TestSize.Level1)
{
bool ret = false;
std::string recvBuf = "catch_gpu_counter";
std::map<std::string, std::string> data;
std::map<std::string, std::string> mapInfo;
GpuCounter::GetInstance().Init(recvBuf, data);
mapInfo = GpuCounter::GetInstance().ItemData();
if (!mapInfo.empty()) {
ret = true;
}
EXPECT_EQ(ret, true);
}
/**
* @tc.name: GpuCounter::GetCounterDuration
* @tc.desc: Test GetCounterDuration
* @tc.type: FUNC
*/
HWTEST_F(SPdaemonGpuTest, GetCounterDuration001, TestSize.Level1)
{
int ret = -1;
std::string fileName = "/bin/config.txt";
bool isExist = SPUtils::FileAccess(fileName);
long long lg = GpuCounter::GetInstance().GetCounterDuration();
if (isExist) {
if (lg >= 0) {
ret = 1;
}
EXPECT_EQ(ret, 1);
} else {
EXPECT_EQ(lg, -1);
}
}
/**
* @tc.name: GpuCounter::Start
* @tc.desc: Test Start
* @tc.type: FUNC
*/
HWTEST_F(SPdaemonGpuTest, Start001, TestSize.Level1)
{
int ret = GpuCounter::GetInstance().Start();
EXPECT_EQ(ret, 0);
}
/**
* @tc.name: GpuCounter::Rest
* @tc.desc: Test Rest
* @tc.type: FUNC
*/
/* HWTEST_F(SPdaemonGpuTest, Rest001, TestSize.Level1)
{
GpuCounter::GetInstance().Rest();
}
*/
/**
* @tc.name: GpuCounter::Check
* @tc.desc: Test Check
* @tc.type: FUNC
*/
HWTEST_F(SPdaemonGpuTest, Check001, TestSize.Level1)
{
std::string recvBuf = "catch_gpu_counter";
std::map<std::string, std::string> data;
GpuCounter::GetInstance().Init(recvBuf, data);
GpuCounter::GetInstance().Check();
}
}
}