• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <iostream>
16 #include <thread>
17 #include <string>
18 #include <climits>
19 #include "include/sp_task.h"
20 #include "include/sp_profiler_factory.h"
21 #include "include/sp_utils.h"
22 #include "include/FPS.h"
23 #include "include/RAM.h"
24 #include "include/CPU.h"
25 #include "include/Capture.h"
26 #include "include/startup_delay.h"
27 #include "include/sp_log.h"
28 #include "ByTrace.h"
29 #include <cstdio>
30 #include <ios>
31 #include <vector>
32 #include <fstream>
33 #include <sstream>
34 #include <regex>
35 #include "unistd.h"
36 #include <future>
37 #include "include/common.h"
38 
39 namespace OHOS {
40 namespace SmartPerf {
41 const long long RM_0 = 0;
42 const long long RM_5000 = 5000;
43 const long long RM_1000 = 1000;
44 const long long RM_1000000 = 1000000;
45 const long long END_WAITING_TIME = 8; // End waiting time,unit seconds
46 // init::-SESSIONID 12345678 -INTERVAL 1000 -PKG ohos.samples.ecg -c -g -t -p -f -r -fl 30
ParseToTask(std::string command,TaskInfo & taskInfo)47 static ExceptionMsg ParseToTask(std::string command, TaskInfo &taskInfo)
48 {
49     std::vector<std::string> args;
50     size_t pos = 0;
51     while ((pos = command.find(" ")) != std::string::npos) {
52         args.push_back(command.substr(0, pos));
53         command.erase(0, pos + 1);
54     }
55     args.push_back(command);
56     StuckNotification snf;
57     snf.isEffective = false;
58     std::string sessionId;
59     long long interval = 1000;
60     std::string pkg;
61     bool isFPS = false;
62     std::vector<std::string> configs;
63     for (size_t i = 0; i < args.size(); i++) {
64         if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_SESSIONID)) {
65             sessionId = args[++i];
66         } else if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_INTERVAL)) {
67             interval = SPUtilesTye::StringToSometype<long long>(args[++i]);
68         } else if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_PKG)) {
69             pkg = args[++i];
70         } else if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_FL)) { // 获取用户fps的值,并赋给snf.   CT_FL
71             snf.fps = SPUtilesTye::StringToSometype<int>(args[++i]);
72             snf.isEffective = true;
73         } else if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_FTL)) { // 获取frameTime的值      CT_FTL
74             snf.frameTime = SPUtilesTye::StringToSometype<int>(args[++i]);
75             snf.isEffective = true;
76         } else {
77             if (args[i] == COMMAND_MAP_REVERSE.at(CommandType::CT_F)) { // 判断用户设置是否有-f
78                 isFPS = true;
79             }
80             if (COMMAND_MAP.end() != COMMAND_MAP.find(args[i])) {
81                 configs.push_back(args[i]);
82             }
83         }
84     }
85     if (snf.isEffective && (!isFPS)) {
86         return ExceptionMsg::TASK_CONFIG_NULL;
87     }
88     if (sessionId.empty()) {
89         LOGE("ExceptionMsg ParseToTask sessoin id is null");
90         return ExceptionMsg::SESSION_ID_NULL;
91     } else if (configs.size() == 0) {
92         LOGE("ExceptionMsg ParseToTask configs size is 0");
93         return ExceptionMsg::TASK_CONFIG_NULL;
94     }
95     taskInfo = { sessionId, pkg, configs, interval, snf };
96     return ExceptionMsg::NO_ERR;
97 }
98 
MapToString(std::map<std::string,std::string> myMap)99 static std::string MapToString(std::map<std::string, std::string> myMap)
100 {
101     // 将Map转换为字符串
102     std::string str = "{ ";
103     for (auto it = myMap.begin(); it != myMap.end(); ++it) {
104         str += "\"" + it->first + "\": " + it->second + ", ";
105     }
106     const int subLen = 2;
107     str.erase(str.end() - subLen, str.end());
108     str += " }";
109     return str;
110 }
111 
InitTask(const std::string & recvStr)112 ErrCode SPTask::InitTask(const std::string &recvStr)
113 {
114     std::string result = "";
115     std::string hiprofiler = CMD_COMMAND_MAP.at(CmdCommand::HIPROFILER);
116     SPUtils::LoadCmd(hiprofiler, result);
117     result.clear();
118     std::string perf = CMD_COMMAND_MAP.at(CmdCommand::PERF);
119     SPUtils::LoadCmd(perf, result);
120     std::cout << recvStr << std::endl;
121     ExceptionMsg exMsg = ParseToTask(recvStr, curTaskInfo);
122     if (exMsg == ExceptionMsg::NO_ERR) {
123         FPS &fps = FPS::GetInstance();
124         fps.isGameApp = SPUtils::GetIsGameApp(curTaskInfo.packageName);
125         fps.firstDump = true;
126         isInit = true;
127         return ErrCode::OK;
128     }
129 
130     std::string errInfo = EXCEPTION_MSG_MAP.at(exMsg);
131     LOGE("SPTask::InitTask error(%s)", errInfo.c_str());
132     return ErrCode::FAILED;
133 }
134 
AsyncCollectRam()135 std::future<std::map<std::string, std::string>> SPTask::AsyncCollectRam()
136 {
137     std::promise<std::map<std::string, std::string>> p;
138     std::future<std::map<std::string, std::string>> futureResult;
139     for (std::string ramConfig : curTaskInfo.taskConfig) {
140         if (ramConfig.find("-r") != std::string::npos) {
141             futureResult = p.get_future();
142             std::thread([p = std::move(p)]() mutable {
143                 p.set_value(RAM::GetInstance().ItemData());
144             }).detach();
145         }
146     }
147     return futureResult;
148 }
149 
AsyncCollectCpu()150 std::future<std::map<std::string, std::string>> SPTask::AsyncCollectCpu()
151 {
152     std::promise<std::map<std::string, std::string>> p;
153     std::future<std::map<std::string, std::string>> futureResult;
154     for (std::string cpuConfig : curTaskInfo.taskConfig) {
155         if (cpuConfig.find("-c") != std::string::npos) {
156             futureResult = p.get_future();
157             std::thread([p = std::move(p)]() mutable {
158                 p.set_value(CPU::GetInstance().ItemData());
159             }).detach();
160         }
161     }
162     return futureResult;
163 }
164 
AsyncCollectFps()165 std::future<std::map<std::string, std::string>> SPTask::AsyncCollectFps()
166 {
167     std::promise<std::map<std::string, std::string>> p;
168     std::future<std::map<std::string, std::string>> futureResult;
169     for (std::string fpsConfig : curTaskInfo.taskConfig) {
170         if (fpsConfig.find("-f") != std::string::npos) {
171             futureResult = p.get_future();
172             std::thread([p = std::move(p)]() mutable {
173                 p.set_value(FPS::GetInstance().ItemData());
174             }).detach();
175         }
176     }
177     return futureResult;
178 }
179 
CheckFutureRam(std::future<std::map<std::string,std::string>> & ramResult,std::map<std::string,std::string> & dataMap)180 void SPTask::CheckFutureRam(std::future<std::map<std::string, std::string>> &ramResult,
181     std::map<std::string, std::string> &dataMap)
182 {
183     if (ramResult.valid()) {
184         std::map<std::string, std::string> result = ramResult.get();
185         dataMap.insert(result.begin(), result.end());
186     }
187 }
188 
CheckFutureCpu(std::future<std::map<std::string,std::string>> & cpuResult,std::map<std::string,std::string> & dataMap)189 void SPTask::CheckFutureCpu(std::future<std::map<std::string, std::string>> &cpuResult,
190     std::map<std::string, std::string> &dataMap)
191 {
192     if (cpuResult.valid()) {
193         std::map<std::string, std::string> result = cpuResult.get();
194         dataMap.insert(result.begin(), result.end());
195     }
196 }
197 
CheckFutureFps(std::future<std::map<std::string,std::string>> & fpsResult,std::map<std::string,std::string> & dataMap)198 void SPTask::CheckFutureFps(std::future<std::map<std::string, std::string>> &fpsResult,
199     std::map<std::string, std::string> &dataMap)
200 {
201     if (fpsResult.valid()) {
202         std::map<std::string, std::string> result = fpsResult.get();
203         dataMap.insert(result.begin(), result.end());
204     }
205 }
206 
GetItemData(std::map<std::string,std::string> & dataMap)207 void SPTask::GetItemData(std::map<std::string, std::string> &dataMap)
208 {
209     for (std::string itConfig : curTaskInfo.taskConfig) {
210         if (itConfig.find("-snapshot") != std::string::npos && screenshotFlag) {
211             Capture::GetInstance().SocketMessage();
212             std::map<std::string, std::string> captureMap = Capture::GetInstance().ItemData();
213             dataMap.insert(captureMap.begin(), captureMap.end());
214         }
215 
216         if (itConfig.find("-gc") != std::string::npos ||
217             itConfig.find("-o") != std::string::npos ||
218             itConfig.find("-lockfreq") != std::string::npos) {
219             continue;
220         }
221 
222         SpProfiler *profiler = SpProfilerFactory::GetCmdProfilerItem(COMMAND_MAP.at(itConfig), false);
223         if (profiler != nullptr) {
224             std::map<std::string, std::string> itemMap = profiler->ItemData();
225             dataMap.insert(itemMap.begin(), itemMap.end());
226         }
227     }
228 }
229 
ConfigDataThread()230 void SPTask::ConfigDataThread()
231 {
232     for (std::string itConfig : curTaskInfo.taskConfig) {
233         if (!sdkData) {
234             ConfigureSdkData(itConfig);
235         }
236 
237         if (itConfig.find("-gc") != std::string::npos) {
238             gpuCounter.StartCollect(GpuCounter::GC_START);
239         }
240 
241         if (itConfig.find("-lockfreq") != std::string::npos) {
242             lockFreq.SetIsCollecting(true);
243             lockFreqThread = std::thread([this]() { this->lockFreq.LockingThread(); });
244         }
245     }
246 }
247 
ConfigureSdkData(std::string itConfig)248 void SPTask::ConfigureSdkData(std::string itConfig)
249 {
250     if (itConfig.find("-o") != std::string::npos) {
251         sdkData = true;
252         OHOS::system::SetParameter("debug.smartperf.sdkdataenable", "1");
253         SdkDataRecv &sdkDataRecv = SdkDataRecv::GetInstance();
254         sdkDataRecv.SetRunningState(true);
255         sdk = std::thread([&sdkDataRecv, this]() { this->RunSdkServer(sdkDataRecv); });
256     }
257 }
258 
RunSdkServer(SdkDataRecv & sdkDataRecv)259 void SPTask::RunSdkServer(SdkDataRecv &sdkDataRecv)
260 {
261     sdkDataRecv.ServerThread(sdkvec);
262 }
263 
ResetSdkParam()264 void SPTask::ResetSdkParam()
265 {
266     OHOS::system::SetParameter("debug.smartperf.sdkdataenable", "0");
267     sdkData = false;
268     SdkDataRecv &sdkDataRecv = SdkDataRecv::GetInstance();
269     sdkDataRecv.SetRunningState(false);
270     int listenFd = sdkDataRecv.GetListenFd();
271     if (listenFd != -1) {
272         close(listenFd);
273         sdkDataRecv.SetListenFd(-1);
274     }
275     if (sdk.joinable()) {
276         sdk.join();
277     }
278 };
279 
StopSdkRecv()280 void SPTask::StopSdkRecv()
281 {
282     if (!sdkData || sdkvec.size() <= 0) {
283         return;
284     }
285 
286     std::string outSdkDataDir = baseOutPath + "/" + curTaskInfo.sessionId;
287     char outSdkDataDirChar[PATH_MAX] = {0x00};
288     if (realpath(outSdkDataDir.c_str(), outSdkDataDirChar) == nullptr) {
289         LOGE("data dir %s is nullptr", outSdkDataDir.c_str());
290         return;
291     }
292     std::string outSdkDataPath = std::string(outSdkDataDirChar) + "/sdk_data.csv";
293     sdkDataMtx.lock();
294     std::ofstream outFile;
295     outFile.open(outSdkDataPath.c_str(), std::ios::out | std::ios::trunc);
296     if (!outFile.is_open()) {
297         LOGE("data %s open failed", outSdkDataPath.c_str());
298         return;
299     }
300     std::string title = "source,timestamp,eventName,enable,value\r";
301     outFile << title << std::endl;
302     for (const auto &item : sdkvec) {
303         outFile << item << std::endl;
304     }
305     outFile.close();
306     sdkDataMtx.unlock();
307 }
308 
InitDataFile()309 void SPTask::InitDataFile()
310 {
311     vmap.clear();
312     sdkvec.clear();
313     gpuCounter.GetGpuCounterSaveReportData().clear();
314     SdkDataRecv::GetInstance().SetStartRecordTime();
315     startTime = SPUtils::GetCurTime();
316     std::vector<std::string> files = {
317         "sdk_data.csv",
318         "gpu_counter.csv",
319         "t_general_info.csv",
320         "t_index_info.csv",
321     };
322     std::string fileDir = baseOutPath + "/" + curTaskInfo.sessionId;
323 
324     for (const auto &file: files) {
325         std::string filePath = fileDir + "/" + file;
326         char filePathChar[PATH_MAX] = {0x00};
327         if ((realpath(filePath.c_str(), filePathChar) == nullptr)) {
328             LOGE("%s is not exist, init finish.", filePath.c_str());
329             continue;
330         }
331         std::remove(filePathChar);
332     }
333 }
334 
AsyncGetDataMap(std::function<void (std::string data)> msgTask)335 void SPTask::AsyncGetDataMap(std::function<void(std::string data)> msgTask)
336 {
337     long long lastTime = SPUtils::GetCurTime();
338     asyncDataMtx.lock();
339     std::map<std::string, std::string> dataMap;
340     if (!curTaskInfo.packageName.empty()) {
341         std::string processId = "";
342         OHOS::SmartPerf::StartUpDelay sp;
343         processId = sp.GetPidByPkg(curTaskInfo.packageName);
344         SpProfilerFactory::SetProfilerPidByPkg(processId);
345     }
346     dataMap.insert(std::pair<std::string, std::string>(std::string("timestamp"), std::to_string(lastTime)));
347     std::future<std::map<std::string, std::string>> fpsResult = AsyncCollectFps();
348     std::future<std::map<std::string, std::string>> cpuResult = AsyncCollectCpu();
349     GetItemData(dataMap);
350     std::future<std::map<std::string, std::string>> ramResult = AsyncCollectRam();
351     CheckFutureFps(fpsResult, dataMap);
352     CheckFutureCpu(cpuResult, dataMap);
353     CheckFutureRam(ramResult, dataMap);
354     if (curTaskInfo.stuckInfo.isEffective && recordTrace) {
355         std::map<std::string, std::string> timeUsedMap = DetectionAndGrab();
356         if (!timeUsedMap.empty()) {
357             dataMap.insert(timeUsedMap.begin(), timeUsedMap.end());
358         }
359     }
360     SPData spdata;
361     spdata.values.insert(dataMap.begin(), dataMap.end());
362     if (GetRecordState()) {
363         vmap.push_back(spdata);
364     }
365     gpuCounter.GetGpuRealtimeData(dataMap);
366     SdkDataRecv::GetInstance().GetSdkDataRealtimeData(dataMap);
367     msgTask(MapToString(dataMap));
368     nextTime = SPUtils::GetCurTime();
369     long long costTime = nextTime - lastTime;
370     long long pTime = 998;
371     if (costTime < curTaskInfo.freq) {
372         std::this_thread::sleep_for(std::chrono::milliseconds(pTime - costTime));
373     }
374     asyncDataMtx.unlock();
375 }
376 
StartTask(std::function<void (std::string data)> msgTask)377 ErrCode SPTask::StartTask(std::function<void(std::string data)> msgTask)
378 {
379     RAM &ram = RAM::GetInstance();
380     ram.SetFirstFlag();
381     if (!isInit) {
382         LOGE("SPTask::StartTask initialization failed");
383         return ErrCode::FAILED;
384     }
385     isRunning = true;
386     realTimeStart = SPUtils::GetCurTime();
387     if (!curTaskInfo.packageName.empty()) {
388         SpProfilerFactory::SetProfilerPkg(curTaskInfo.packageName);
389     }
390     InitDataFile();
391     ConfigDataThread();
392     thread = std::thread([this, msgTask]() {
393         while (isRunning) {
394             AsyncGetDataMap(msgTask);
395         }
396     });
397     return ErrCode::OK;
398 }
399 
CreatPath(std::string path)400 void SPTask::CreatPath(std::string path)
401 {
402     if (!SPUtils::FileAccess(path)) {
403         std::string cmdResult;
404         std::string creatPath = CMD_COMMAND_MAP.at(CmdCommand::CREAT_DIR) + path;
405         SPUtils::LoadCmd(creatPath, cmdResult);
406     }
407 }
408 
StopGetInfo()409 void SPTask::StopGetInfo()
410 {
411     bool isTcpMessage = true;
412     CreatPath(baseOutPath);
413     std::string thisBasePath = baseOutPath + "/" + curTaskInfo.sessionId;
414     CreatPath(thisBasePath);
415     std::string outIndexpath = thisBasePath + "/t_index_info.csv";
416     long long endTime = SPUtils::GetCurTime();
417     long long testDuration = (endTime - startTime) / 1000;
418     const std::string gpuDataVersion = "1.1";
419     std::string screenStr = SPUtils::GetScreen();
420     size_t pos3 = screenStr.find("=");
421     std::string refreshrate = screenStr.substr(pos3 + 1);
422     std::map<std::string, std::string> taskInfoMap = {
423         { "sessionId", curTaskInfo.sessionId },
424         { "taskId", curTaskInfo.sessionId },
425         { "appName", curTaskInfo.packageName },
426         { "packageName", curTaskInfo.packageName },
427         { "startTime", std::to_string(startTime) },
428         { "endTime", std::to_string(endTime) },
429         { "testDuration", std::to_string(testDuration) },
430         { "taskName", "testtask" },
431         { "board", "hw" },
432         { "target_fps", refreshrate },
433         { "gpuDataVersion", gpuDataVersion },
434         { "battery_change", std::to_string(battaryEnd - battaryStart) },
435     };
436     std::map<std::string, std::string> deviceInfo = SPUtils::GetDeviceInfo();
437     std::map<std::string, std::string> cpuInfo = SPUtils::GetCpuInfo(isTcpMessage);
438     std::map<std::string, std::string> gpuInfo = SPUtils::GetGpuInfo(isTcpMessage);
439     std::map<std::string, std::string> destMap;
440     destMap.insert(taskInfoMap.begin(), taskInfoMap.end());
441     destMap.insert(deviceInfo.begin(), deviceInfo.end());
442     destMap.insert(cpuInfo.begin(), cpuInfo.end());
443     destMap.insert(gpuInfo.begin(), gpuInfo.end());
444     OHOS::SmartPerf::SpCsvUtil::WriteCsvH(destMap);
445     if (!vmap.empty()) {
446         vmap.erase(vmap.begin());
447     }
448     OHOS::SmartPerf::SpCsvUtil::WriteCsv(outIndexpath, vmap);
449 }
StopGpuCounterRecv()450 void SPTask::StopGpuCounterRecv()
451 {
452     std::string outGpuCounterDataPath = baseOutPath + "/" + curTaskInfo.sessionId;
453 
454     if (GetRecordState()) {
455         gpuCounter.GetInstance().SaveData(outGpuCounterDataPath);
456     }
457 }
StopTask()458 ErrCode SPTask::StopTask()
459 {
460     if (GetRecordState()) {
461         StopGetInfo();
462         StopSdkRecv();
463         StopGpuCounterRecv();
464 
465         vmap.clear();
466         sdkvec.clear();
467         gpuCounter.GetGpuCounterData().clear();
468         recordState = false;
469         screenshotFlag = false;
470     }
471 
472     ResetSdkParam();
473     gpuCounter.StopCollect();
474     lockFreq.SetIsCollecting(false);
475     if (lockFreqThread.joinable()) {
476         lockFreqThread.join();
477     }
478 
479     isRunning = false;
480     isInit = false;
481     realTimeStart = 0;
482 
483     if (thread.joinable()) {
484         thread.join();
485     }
486     SpProfilerFactory::editorFlag = false;
487     return ErrCode::OK;
488 }
489 
DetectionAndGrab()490 std::map<std::string, std::string> SPTask::DetectionAndGrab()
491 {
492     std::map<std::string, std::string> templateMap;
493     if (!curTaskInfo.stuckInfo.isEffective) {
494         return templateMap;
495     }
496 
497     FpsCurrentFpsTime fcf = FPS::GetInstance().GetFpsCurrentFpsTime();
498     long long nowTime = SPUtils::GetCurTime();
499     long long curframeTime = fcf.currentFpsTime / RM_1000000; // Convert to milliseconds
500     LOGD("Start capture time: %lld", startCaptuerTime);
501 
502     if (startCaptuerTime > 0) {
503         long long diff =
504             startCaptuerTime > nowTime ? (LLONG_MAX - startCaptuerTime + nowTime) : (nowTime - startCaptuerTime);
505         if (diff > RM_5000 && (!CheckCounterId())) {
506             startCaptuerTime = RM_0;
507         }
508     }
509 
510     if (curTaskInfo.stuckInfo.fps > fcf.fps || curTaskInfo.stuckInfo.frameTime < curframeTime) {
511         if (startCaptuerTime == 0) {
512             startCaptuerTime = nowTime;
513             LOGD("ThreadGetHiperf::%ld", startCaptuerTime);
514             ThreadGetHiperf(startCaptuerTime);
515         }
516     }
517     templateMap["fpsWarn"] = std::to_string(fcf.fps);
518     templateMap["FrameTimeWarn"] = std::to_string(fcf.currentFpsTime);
519     templateMap["TraceTime"] = std::to_string(startCaptuerTime);
520     return templateMap;
521 }
522 
CheckCounterId()523 bool SPTask::CheckCounterId()
524 {
525     std::string result;
526     std::string hiprofilerCmd = CMD_COMMAND_MAP.at(CmdCommand::HIPROFILER_CMD);
527     SPUtils::LoadCmd(hiprofilerCmd, result);
528     if (result.empty()) {
529         return false;
530     }
531 
532     if (result.find("-k") != std::string::npos) {
533         return true;
534     }
535 
536     return false;
537 }
ThreadGetHiperf(long long timeStamp)538 std::thread SPTask::ThreadGetHiperf(long long timeStamp)
539 {
540     auto thGetTrace = [this, timeStamp]() { this->GetHiperf(std::to_string(timeStamp)); };
541     std::thread spThread(thGetTrace);
542     spThread.detach();
543     return spThread;
544 }
545 
GetHiperf(const std::string & traceName)546 void SPTask::GetHiperf(const std::string &traceName)
547 {
548     std::string result;
549     std::string tmp = SetHiperf(traceName);
550     std::cout << tmp << std::endl;
551     SPUtils::LoadCmd(tmp, result);
552     LOGD("hiprofiler exec (%s), hiprofiler exec trace name(%s), hiprofiler exec end (%s)",
553         tmp.c_str(), traceName.c_str(), result.c_str());
554 }
555 
556 
CheckTcpParam(std::string str,std::string & errorInfo)557 bool SPTask::CheckTcpParam(std::string str, std::string &errorInfo)
558 {
559     std::set<std::string> keys;
560     for (auto a : COMMAND_MAP) {
561         keys.insert(a.first.substr(1)); // 不需要前面的'-'
562     }
563 
564     return SPUtils::VeriyParameter(keys, str, errorInfo);
565 }
566 
KillHiperfCmd()567 void SPTask::KillHiperfCmd()
568 {
569     long long now = 0;
570     long long runTime = 0;
571     std::string killCmd = CMD_COMMAND_MAP.at(CmdCommand::KILL_CMD) + "-9 ";
572     std::string result;
573     std::vector<std::string> out;
574 
575     if (startCaptuerTime <= 0) {
576         return;
577     }
578 
579     now = SPUtils::GetCurTime();
580     runTime = now > startCaptuerTime ? now - startCaptuerTime : LLONG_MAX - startCaptuerTime + now;
581     runTime = runTime / RM_1000; // Convert to seconds
582 
583     LOGD("Preparing to exit run time(%lld)", runTime);
584     do {
585         out.clear();
586         std::string hiprofilerPid = CMD_COMMAND_MAP.at(CmdCommand::HIPROFILER_PID);
587         SPUtils::LoadCmd(hiprofilerPid, result);
588         SPUtils::StrSplit(result, " ", out);
589         if (out.empty()) {
590             break;
591         }
592 
593         sleep(1);
594     } while (END_WAITING_TIME - runTime++ > 0);
595 
596     out.clear();
597     std::string hiprofilerPid = CMD_COMMAND_MAP.at(CmdCommand::HIPROFILER_PID);
598     SPUtils::LoadCmd(hiprofilerPid, result);
599     SPUtils::StrSplit(result, " ", out);
600     LOGD("pidof hiprofiker_cmd size(%d)", out.size());
601     for (auto it = out.begin(); out.end() != it; ++it) {
602         result.clear();
603         SPUtils::LoadCmd(killCmd + (*it), result);
604     }
605 
606     return;
607 }
608 
SetHiperf(const std::string & traceName)609 std::string SPTask::SetHiperf(const std::string &traceName)
610 {
611     std::string hiPrefix = "hiprofiler_";
612     std::string dataPrefix = "perf_";
613     requestId++;
614     std::string trtmp = strOne + hiPrefix + traceName + strTwo + "\n" + strThree + std::to_string(requestId) + "\n" +
615         strFour + "\n" + strFive + hiPrefix + traceName + strSix + "\n" + strNine + strEleven + "\n" + strSeven +
616         dataPrefix + traceName + strEight + strTen + "\n" + conFig;
617     return trtmp;
618 }
619 
GetRecordState()620 bool SPTask::GetRecordState()
621 {
622     return recordState;
623 }
GetCurrentBattary()624 int SPTask::GetCurrentBattary()
625 {
626     std::string content;
627     const std::string  cmd = "hidumper -s 3302 -a -i | grep capacity";
628     SPUtils::LoadCmd(cmd, content);
629     content = content.substr(content.find(':') + 1);
630     if (content == "") {
631         return 0;
632     }
633     return SPUtilesTye::StringToSometype<int>(content);
634 }
StartRecord()635 ErrCode SPTask::StartRecord()
636 {
637     LOGD("SPTask StartRecord");
638     battaryStart = GetCurrentBattary();
639     startTime = SPUtils::GetCurTime();
640     while (startTime > nextTime) {
641         std::this_thread::sleep_for(std::chrono::milliseconds(1));
642     }
643     InitDataFile();
644     screenshotFlag = true;
645     recordState = true;
646     recordTrace = true;
647     return ErrCode::OK;
648 }
649 
StopRecord()650 ErrCode SPTask::StopRecord()
651 {
652     LOGD("SPTask StopRecord");
653     battaryEnd = GetCurrentBattary();
654     long long stopRecordTime = SPUtils::GetCurTime();
655     while (stopRecordTime > nextTime) {
656         std::this_thread::sleep_for(std::chrono::milliseconds(1));
657     }
658     screenshotFlag = false;
659     recordState = false;
660     recordTrace = false;
661     std::string outGpuCounterDataPath = baseOutPath + "/" + curTaskInfo.sessionId;
662 
663     if (isInit) {
664         StopGetInfo();
665         if (sdkData) {
666             StopSdkRecv();
667         }
668         gpuCounter.GetInstance().SaveData(outGpuCounterDataPath);
669     }
670 
671     vmap.clear();
672     sdkvec.clear();
673     gpuCounter.GetGpuCounterData().clear();
674     Capture::GetInstance().SetCollectionNum();
675     KillHiperfCmd();
676 
677     return ErrCode::OK;
678 }
GetRealStartTime() const679 time_t SPTask::GetRealStartTime() const
680 {
681     return realTimeStart;
682 }
SetTcpToken(std::string token)683 void SPTask::SetTcpToken(std::string token)
684 {
685     tcpToken = token;
686 }
GetTcpToken()687 std::string SPTask::GetTcpToken()
688 {
689     return tcpToken;
690 }
691 }
692 }
693