void LogRotation tarFile int idx std string oldestFile for idx std str

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void LogRotation::tarFile() {
int idx = 0;
std::string oldestFile;
for (;; ++idx) {
std::string tarPath = fmt::sprintf("%s.tar.xz.%d", logPath_.c_str(), idx);
if (access(tarPath.c_str(), F_OK) == -1) {
auto dpkgCmd = fmt::sprintf("tar -cJf %s %s", tarPath.c_str(),
logPath_.c_str());
int ret = system(dpkgCmd.c_str());
if (ret < 0) {
writeLog(Error, "Can't tar logs");
}
break;
}
if (idx == fileNamelimit_) { // Заменяем самый первый созданный архив
std::string tarArchive = fmt::sprintf("%s.tar.xz.%d", logPath_.c_str(), 0);
struct stat result;
time_t minTime = time(NULL);
if (stat(tarArchive.c_str(), &result) == 0) {
minTime = result.st_mtime;
oldestFile = tarArchive;
}
for (int i = 1; i <= fileNamelimit_; ++i) {
tarArchive = fmt::sprintf("%s.tar.xz.%d", logPath_.c_str(), i);
if (stat(tarArchive.c_str(), &result) == 0) {
auto mod_time = result.st_mtime;
if (mod_time < minTime) {
oldestFile = tarArchive;
}
}
}
remove(oldestFile.c_str());
auto dpkgCmd = fmt::sprintf("tar -cJf %s %s", oldestFile.c_str(),
logPath_.c_str());
int ret = system(dpkgCmd.c_str());
if (ret < 0) {
writeLog(Error, "Can't tar logs");
}
break;
}
}
}