summaryrefslogtreecommitdiff
path: root/src/mongo/logv2/file_rotate_sink.cpp
blob: 4070cd7161092e87c04661d5c4175fe510992691 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 *    Copyright (C) 2020-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/logv2/file_rotate_sink.h"

#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/make_shared.hpp>
#include <fmt/format.h>
#include <fstream>

#include "mongo/logv2/json_formatter.h"
#include "mongo/logv2/log_detail.h"
#include "mongo/logv2/shared_access_fstream.h"
#include "mongo/util/quick_exit.h"
#include "mongo/util/stacktrace.h"
#include "mongo/util/string_map.h"

namespace mongo::logv2 {
namespace {

using namespace fmt::literals;

#if _WIN32
using stream_t = Win32SharedAccessOfstream;
#else
using stream_t = std::ofstream;
#endif

StatusWith<boost::shared_ptr<stream_t>> openFile(const std::string& filename, bool append) {
    std::ios_base::openmode mode = std::ios_base::out;
    bool exists = false;
    if (append) {
        mode |= std::ios_base::app;
        exists = boost::filesystem::exists(filename);
    } else
        mode |= std::ios_base::trunc;
    auto file = boost::make_shared<stream_t>(filename, mode);
    if (file->fail())
        return Status(ErrorCodes::FileNotOpen, fmt::format("Failed to open {}", filename));
    if (append && exists)
        file->put('\n');
    return file;
}
}  // namespace

struct FileRotateSink::Impl {
    Impl(LogTimestampFormat tsFormat) : timestampFormat(tsFormat) {}
    StringMap<boost::shared_ptr<stream_t>> files;
    LogTimestampFormat timestampFormat;
};

FileRotateSink::FileRotateSink(LogTimestampFormat timestampFormat)
    : _impl(std::make_unique<Impl>(timestampFormat)) {}
FileRotateSink::~FileRotateSink() {}

Status FileRotateSink::addFile(const std::string& filename, bool append) {
    auto statusWithFile = openFile(filename, append);
    if (statusWithFile.isOK()) {
        add_stream(statusWithFile.getValue());
        _impl->files[filename] = statusWithFile.getValue();
    }

    return statusWithFile.getStatus().withContext("Can't initialize rotatable log file");
}
void FileRotateSink::removeFile(const std::string& filename) {
    auto it = _impl->files.find(filename);
    if (it != _impl->files.cend()) {
        remove_stream(it->second);
        _impl->files.erase(it);
    }
}

Status FileRotateSink::rotate(bool rename,
                              StringData renameSuffix,
                              std::function<void(Status)> onMinorError) {
    for (auto& file : _impl->files) {
        const std::string& filename = file.first;
        if (rename) {
            std::string renameTarget = filename + renameSuffix;

            auto targetExists = [&]() -> StatusWith<bool> {
                try {
                    return boost::filesystem::exists(renameTarget);
                } catch (const boost::exception&) {
                    return exceptionToStatus();
                }
            }();

            if (!targetExists.isOK()) {
                return Status(ErrorCodes::FileRenameFailed, targetExists.getStatus().reason())
                    .withContext("Cannot verify whether destination already exists: {}"_format(
                        renameTarget));
            }

            if (targetExists.getValue()) {
                if (onMinorError) {
                    onMinorError({ErrorCodes::FileRenameFailed,
                                  "Target already exists during log rotation. Skipping this file. "
                                  "target={}, file={}"_format(renameTarget, filename)});
                }
                continue;
            }

            boost::system::error_code ec;
            boost::filesystem::rename(filename, renameTarget, ec);
            if (ec) {
                if (ec == boost::system::errc::no_such_file_or_directory) {
                    if (onMinorError)
                        onMinorError(
                            {ErrorCodes::FileRenameFailed,
                             "Source file was missing during log rotation. Creating a new one. "
                             "file={}"_format(filename)});
                } else {
                    return Status(ErrorCodes::FileRenameFailed,
                                  "Failed to rename {} to {}: {}"_format(
                                      filename, renameTarget, ec.message()));
                }
            }
        }

        auto newFile = openFile(filename, false);
        if (newFile.isOK()) {
            invariant(file.second);
            remove_stream(file.second);
            file.second->close();
            file.second = newFile.getValue();
            add_stream(file.second);
        }
        return newFile.getStatus();
    }

    return Status::OK();
}

void FileRotateSink::consume(const boost::log::record_view& rec,
                             const string_type& formatted_string) {
    auto isFailed = [](const auto& file) { return file.second->fail(); };
    boost::log::sinks::text_ostream_backend::consume(rec, formatted_string);
    if (std::any_of(_impl->files.begin(), _impl->files.end(), isFailed)) {
        try {
            auto failedBegin =
                boost::make_filter_iterator(isFailed, _impl->files.begin(), _impl->files.end());
            auto failedEnd =
                boost::make_filter_iterator(isFailed, _impl->files.end(), _impl->files.end());

            auto getFilename = [](const auto& file) -> const auto& {
                return file.first;
            };
            auto begin = boost::make_transform_iterator(failedBegin, getFilename);
            auto end = boost::make_transform_iterator(failedEnd, getFilename);
            auto sequence = logv2::seqLog(begin, end);

            DynamicAttributes attrs;
            attrs.add("files", sequence);

            fmt::memory_buffer buffer;
            JSONFormatter(nullptr, _impl->timestampFormat)
                .format(buffer,
                        LogSeverity::Severe(),
                        LogComponent::kControl,
                        Date_t::now(),
                        4522200,
                        getThreadName(),
                        "Writing to log file failed, aborting application",
                        TypeErasedAttributeStorage(attrs),
                        LogTag::kNone,
                        nullptr /* tenantID */,
                        LogTruncation::Disabled);
            // Commented out log line below to get validation of the log id with the errorcodes
            // linter LOGV2(4522200, "Writing to log file failed, aborting application");
            std::cerr << StringData(buffer.data(), buffer.size()) << std::endl;
        } catch (const std::exception& ex) {
            std::cerr << "Caught std::exception of type " << demangleName(typeid(ex)) << ": "
                      << ex.what() << std::endl;
        } catch (const boost::exception& ex) {
            std::cerr << "Caught boost::exception of type " << demangleName(typeid(ex)) << ": "
                      << boost::diagnostic_information(ex) << std::endl;
        } catch (...) {
            std::cerr << "Caught unidentified exception" << std::endl;
        }

        printStackTrace(std::cerr);
        quickExitWithoutLogging(EXIT_FAILURE);
    }
}

}  // namespace mongo::logv2