• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 <cstdlib>
16 #include <ctime>
17 #include <dirent.h>
18 #include <fstream>
19 #include <fcntl.h>
20 #include <iostream>
21 #include <memory>
22 #include <string>
23 #include <sys/time.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <vector>
28 #include "collect_item_result.h"
29 #include "collect_parameter.h"
30 #include "hitrace_dump.h"
31 #include "hilog/log.h"
32 #include "xcollect_service.h"
33 
34 using namespace std;
35 using namespace OHOS::HiviewDFX::Hitrace;
36 namespace OHOS {
37 namespace HiviewDFX {
38 namespace {
39 constexpr HiLogLabel LABEL = { LOG_CORE, 0xD002D10, "HiView-xcollect_service" };
40 }
41 class TraceService  {
42 public:
TraceService()43     TraceService()
44     {
45         const std::vector<std::string> tagGroups = {"scene_performance"};
46         if (OpenTrace(tagGroups) != TraceErrorCode::SUCCESS) {
47             HiLog::Error(LABEL, "OpenTrace fail.");
48         }
49         HiLog::Info(LABEL, "OpenTrace success.");
50     }
51 };
52 
53 TraceService g_traceService;
54 
55 class DefCollectCallback : public CollectCallback {
56 public:
Handle(std::shared_ptr<CollectItemResult> dara,bool isFinish)57     virtual void Handle(std::shared_ptr<CollectItemResult> dara, bool isFinish)
58     {}
59 };
60 
XcollectService(std::shared_ptr<CollectParameter> collectParameter)61 XcollectService::XcollectService(std::shared_ptr<CollectParameter> collectParameter)
62     : collectParameter_(collectParameter), callback_(std::make_shared<DefCollectCallback>())
63 {}
64 
XcollectService(std::shared_ptr<CollectParameter> collectParameter,std::shared_ptr<CollectCallback> callback)65 XcollectService::XcollectService(std::shared_ptr<CollectParameter> collectParameter,
66     std::shared_ptr<CollectCallback> callback) : collectParameter_(collectParameter), callback_(callback)
67 {
68     if (callback_ == nullptr) {
69         callback_ = std::make_shared<DefCollectCallback>();
70     }
71 }
72 
~XcollectService()73 XcollectService::~XcollectService()
74 {}
75 
StartCollect()76 void XcollectService::StartCollect()
77 {
78     for (auto it = collectParameter_->items_.begin(); it != collectParameter_->items_.end(); it++) {
79         if (it->rfind("/hitrace/")==0) {
80             CollectHiTrace(*it);
81         }
82     }
83 }
84 
85 namespace {
86 std::vector<std::pair<std::string, uint64_t>> g_traceDirTable;
CopyTmpFile(const std::string & src,const std::string & dest)87 bool CopyTmpFile(const std::string &src, const std::string &dest)
88 {
89     char srcPath[PATH_MAX + 1] = {0x00};
90     if (strlen(src.c_str()) > PATH_MAX || realpath(src.c_str(), srcPath) == nullptr) {
91         return false;
92     }
93     int srcFd = open(srcPath, O_RDONLY | O_NONBLOCK);
94     if (srcFd < 0) {
95         close(srcFd);
96         HiLog::Error(LABEL, "CopyFile: open %{public}s failed.", srcPath);
97         return false;
98     }
99 
100     char destPath[PATH_MAX + 1] = {0x00};
101     if (strlen(dest.c_str()) > PATH_MAX || realpath(dest.c_str(), destPath) == nullptr) {
102         return false;
103     }
104     int destFd = open(destPath, O_WRONLY | O_CREAT, FILE_RIGHT_READ);
105     if (destFd < 0) {
106         close(srcFd);
107         HiLog::Error(LABEL, "CopyFile: open %{public}s failed.", destPath);
108         return false;
109     }
110 
111     const int bufferSize = 4096;
112     char* buffer = (char*)calloc(bufferSize * sizeof(char), sizeof(char));
113     if (buffer == nullptr) {
114         HiLog::Error(LABEL, "CopyFile: calloc failed.");
115         close(srcFd);
116         close(destFd);
117         return false;
118     }
119     do {
120         ssize_t len = read(srcFd, buffer, bufferSize);
121         if (len <= 0) {
122             break;
123         }
124         write(destFd, buffer, len);
125     } while (true);
126     close(destFd);
127     close(srcFd);
128     return true;
129 }
130 
RemoveDir(const std::string & dirName)131 void RemoveDir(const std::string &dirName)
132 {
133     if (access(dirName.c_str(), F_OK) != 0) {
134         return;
135     }
136     const std::string alignStr = "/data/log/hitrace/";
137     if (dirName.compare(0, alignStr.size(), alignStr) != 0) {
138         return;
139     }
140     DIR *dirPtr = opendir(dirName.c_str());
141     if (!dirPtr) {
142         return;
143     }
144     struct dirent *ptr;
145     const int normalFileType = 8;
146     while ((ptr = readdir(dirPtr)) != nullptr) {
147         std::string subFile = dirName + "/" + ptr->d_name;
148         if (ptr->d_type == normalFileType) {
149             if (remove(subFile.c_str()) != 0) {
150                 HiLog::Error(LABEL, "error|RemoveDir: delete %{public}s failed.", subFile.c_str());
151             }
152         }
153     }
154     if (rmdir(dirName.c_str()) != 0) {
155         HiLog::Error(LABEL, "error|RemoveDir: delete %{public}s failed.", dirName.c_str());
156     }
157 }
158 } // namespace
159 
DumpTraceToDir()160 std::string XcollectService::DumpTraceToDir()
161 {
162     TraceRetInfo ret = DumpTrace();
163     if (ret.errorCode != TraceErrorCode::SUCCESS) {
164         HiLog::Error(LABEL, "error|DumpTrace: failed to dump trace, error code (%{public}d).", ret.errorCode);
165         return "";
166     }
167     const std::string defaultParentDir = "/data/log/hitrace/";
168     const std::string logDir = "/data/log/";
169     if (access(defaultParentDir.c_str(), F_OK) != 0) {
170         if (access(logDir.c_str(), F_OK) != 0) {
171             mkdir(logDir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRWXG | S_IRWXO);
172         }
173         mkdir(defaultParentDir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IROTH);
174     }
175     struct timeval now = {0, 0};
176     gettimeofday(&now, nullptr);
177     uint64_t nowSec = now.tv_sec;
178     uint64_t nowUsec = now.tv_usec;
179     const std::string outDir = defaultParentDir + "trace_" + std::to_string(nowSec) + "_" + std::to_string(nowUsec);
180     mkdir(outDir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IROTH);
181     g_traceDirTable.push_back({outDir, nowSec});
182 
183     for (auto trace : ret.outputFiles) {
184         size_t pos = trace.rfind('/');
185         if (pos == std::string::npos) {
186             HiLog::Error(LABEL, "error|DumpTraceToDir Error: copy to this dir failed.");
187             return "";
188         }
189         std::string dst = outDir + trace.substr(pos);
190         CopyTmpFile(trace, dst);
191     }
192     const uint64_t agingTime = 30 * 60;
193     for (auto iter = g_traceDirTable.begin(); iter != g_traceDirTable.end();) {
194         if (nowSec - iter->second >= agingTime) {
195             RemoveDir(iter->first);
196             HiLog::Info(LABEL, "Info|RemoveDir: delete old %{public}s dir success.", iter->first.c_str());
197             iter = g_traceDirTable.erase(iter);
198             continue;
199         }
200         iter++;
201     }
202     return outDir;
203 }
204 
CollectHiTrace(const std::string & item)205 void XcollectService::CollectHiTrace(const std::string &item)
206 {
207     if (item == "/hitrace/client/dump") {
208         std::string outTraceDir = DumpTraceToDir();
209         std::shared_ptr<CollectItemResult> collectItem = std::make_shared<CollectItemResult>();
210         collectItem->SetCollectItemValue(item, outTraceDir);
211         callback_->Handle(collectItem, true);
212         return;
213     }
214 
215     if (item == "/hitrace/cmd/open") {
216         std::string args = "tags::sched clockType:boot bufferSize:1024 overwrite:1";
217         if (CloseTrace() != TraceErrorCode::SUCCESS) {
218             HiLog::Error(LABEL, "CloseTrace failed");
219         }
220         if (OpenTrace(args) != TraceErrorCode::SUCCESS) {
221             HiLog::Error(LABEL, "OpenTrace failed");
222         }
223         return;
224     }
225 
226     if (item == "/hitrace/cmd/traceon") {
227         if (DumpTraceOn() != TraceErrorCode::SUCCESS) {
228             HiLog::Error(LABEL, "traceon failed");
229         }
230         return;
231     }
232 
233     if (item == "/hitrace/cmd/traceoff") {
234         TraceRetInfo ret = DumpTraceOff();
235         if (ret.errorCode != TraceErrorCode::SUCCESS) {
236             HiLog::Error(LABEL, "traceoff failed");
237         }
238         return;
239     }
240 
241     if (item == "/hitrace/cmd/close") {
242         const std::vector<std::string> tagGroups = {"scene_performance"};
243         if (CloseTrace() != TraceErrorCode::SUCCESS) {
244             HiLog::Error(LABEL, "CloseTrace failed");
245         }
246         if (OpenTrace(tagGroups) != TraceErrorCode::SUCCESS) {
247             HiLog::Error(LABEL, "OpenTrace failed");
248         }
249         return;
250     }
251 }
252 } // namespace HiviewDFX
253 } // namespace OHOS
254