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
16#ifndef _HILOG_PERSISTER_ROTATOR_H
17#define _HILOG_PERSISTER_ROTATOR_H
18#include <fstream>
19#include <string>
20#include <zlib.h>
21#include <hilog_common.h>
22#include <log_utils.h>
23
24#include "log_filter.h"
25
26namespace OHOS {
27namespace HiviewDFX {
28#define FILE_PATH_MAX_LEN 100
29static constexpr const char* AUXILLARY_PERSISTER_PREFIX = "persisterInfo_";
30
31using LogPersistStartMsg = struct {
32    uint16_t compressAlg;
33    char filePath[FILE_PATH_MAX_LEN];
34    uint32_t fileSize;
35    uint32_t fileNum;
36    uint32_t jobId;
37    LogFilter filter;
38} __attribute__((__packed__));
39
40using PersistRecoveryInfo = struct {
41    uint32_t index;
42    LogPersistStartMsg msg;
43} __attribute__((__packed__));
44
45class LogPersisterRotator {
46public:
47    LogPersisterRotator(const std::string& path, uint32_t id, uint32_t maxFiles, const std::string& suffix = "");
48    ~LogPersisterRotator();
49    int Init(const PersistRecoveryInfo& info, bool restore = false);
50    int Input(const char *buf, uint32_t length);
51    void FinishInput();
52
53    void SetFileIndex(uint32_t index, bool forceRotate);
54
55private:
56    void RemoveOldFile();
57    bool IsOldFile(const std::string& logName, const int index);
58    int OpenInfoFile();
59    void UpdateRotateNumber();
60    void WriteRecoveryInfo();
61    int SetInfo(const LogPersistStartMsg& pMsg, uint16_t logType, uint8_t logLevel);
62
63    void CreateLogFile();
64    void Rotate();
65
66    uint32_t m_maxLogFileNum = 0;
67    std::string m_logsPath;
68    std::string m_fileNameSuffix;
69    std::string m_currentLogFileName;
70    uint32_t m_currentLogFileIdx = 0;
71    std::fstream m_currentLogOutput;
72
73    uint32_t m_id = 0;
74    std::fstream m_infoFile;
75    std::string m_infoFilePath;
76    PersistRecoveryInfo m_info = {0};
77
78    bool m_needRotate = false;
79};
80} // namespace HiviewDFX
81} // namespace OHOS
82#endif
83