summaryrefslogtreecommitdiff
path: root/src/mongo/logger/rotatable_file_writer.cpp
blob: 260e9bb8ec514ce4446ebc9fea91fb2b247a3bfe (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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

/**
 *    Copyright (C) 2018-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/platform/basic.h"

#include "mongo/logger/rotatable_file_writer.h"

#include <boost/filesystem/operations.hpp>
#include <cstdio>
#include <fstream>

#include "mongo/base/string_data.h"
#include "mongo/util/mongoutils/str.h"

namespace mongo {
namespace logger {

namespace {
/**
 * Renames file "oldName" to "newName".
 *
 * Both names are UTF-8 encoded.
 */
int renameFile(const std::string& oldName, const std::string& newName);
}  // namespace

#ifdef _WIN32
namespace {

/**
 * Converts UTF-8 encoded "utf8Str" to std::wstring.
 */
std::wstring utf8ToWide(StringData utf8Str) {
    if (utf8Str.empty())
        return std::wstring();

    // A Windows wchar_t encoding of a unicode codepoint never takes more instances of wchar_t
    // than the UTF-8 encoding takes instances of char.
    std::unique_ptr<wchar_t[]> tempBuffer(new wchar_t[utf8Str.size()]);
    tempBuffer[0] = L'\0';
    int finalSize = MultiByteToWideChar(CP_UTF8,            // Code page
                                        0,                  // Flags
                                        utf8Str.rawData(),  // Input string
                                        utf8Str.size(),     // Count
                                        tempBuffer.get(),   // UTF-16 output buffer
                                        utf8Str.size()      // Buffer size in wide characters
                                        );
    // TODO(schwerin): fassert finalSize > 0?
    return std::wstring(tempBuffer.get(), finalSize);
}


/**
 * Minimal implementation of a std::streambuf for writing to Win32 files via HANDLEs.
 *
 * We require this implementation and the std::ostream subclass below to handle the following:
 * (1) Opening files for shared-delete access, so that open file handles may be renamed.
 * (2) Opening files with non-ASCII characters in their names.
 */
class Win32FileStreambuf : public std::streambuf {
    MONGO_DISALLOW_COPYING(Win32FileStreambuf);

public:
    Win32FileStreambuf();
    virtual ~Win32FileStreambuf();

    bool open(StringData fileName, bool append);
    bool is_open() {
        return _fileHandle != INVALID_HANDLE_VALUE;
    }

private:
    virtual std::streamsize xsputn(const char* s, std::streamsize count);
    virtual int_type overflow(int_type ch = traits_type::eof());

    HANDLE _fileHandle;
};

/**
 * Minimal implementation of a stream to Win32 files.
 */
class Win32FileOStream : public std::ostream {
    MONGO_DISALLOW_COPYING(Win32FileOStream);

public:
    /**
     * Constructs an instance, opening "fileName" in append or truncate mode according to
     * "append".
     */
    Win32FileOStream(const std::string& fileName, bool append) : std::ostream(&_buf), _buf() {
        if (!_buf.open(fileName, append)) {
            setstate(failbit);
        }
    }

    virtual ~Win32FileOStream() {}

private:
    Win32FileStreambuf _buf;
};

Win32FileStreambuf::Win32FileStreambuf() : _fileHandle(INVALID_HANDLE_VALUE) {}
Win32FileStreambuf::~Win32FileStreambuf() {
    if (is_open()) {
        CloseHandle(_fileHandle);  // TODO(schwerin): Should we check for failure?
    }
}

bool Win32FileStreambuf::open(StringData fileName, bool append) {
    _fileHandle = CreateFileW(utf8ToWide(fileName).c_str(),         // lpFileName
                              GENERIC_WRITE,                        // dwDesiredAccess
                              FILE_SHARE_DELETE | FILE_SHARE_READ,  // dwShareMode
                              NULL,                                 // lpSecurityAttributes
                              OPEN_ALWAYS,                          // dwCreationDisposition
                              FILE_ATTRIBUTE_NORMAL,                // dwFlagsAndAttributes
                              NULL                                  // hTemplateFile
                              );


    if (INVALID_HANDLE_VALUE == _fileHandle)
        return false;

    LARGE_INTEGER zero;
    zero.QuadPart = 0LL;

    if (append) {
        if (SetFilePointerEx(_fileHandle, zero, NULL, FILE_END)) {
            return true;
        }
    } else {
        if (SetFilePointerEx(_fileHandle, zero, NULL, FILE_BEGIN) && SetEndOfFile(_fileHandle)) {
            return true;
        }
    }
    // TODO(schwerin): Record error info?
    CloseHandle(_fileHandle);
    return false;
}

// Called when strings are written to ostream
std::streamsize Win32FileStreambuf::xsputn(const char* s, std::streamsize count) {
    DWORD totalBytesWritten = 0;

    while (count > totalBytesWritten) {
        DWORD bytesWritten;
        if (!WriteFile(_fileHandle, s, count - totalBytesWritten, &bytesWritten, NULL)) {
            break;
        }

        totalBytesWritten += bytesWritten;
    }

    return totalBytesWritten;
}

// Overflow is called for single character writes to the ostream
Win32FileStreambuf::int_type Win32FileStreambuf::overflow(int_type ch) {
    if (ch == traits_type::eof())
        return ~ch;  // Returning traits_type::eof() => failure, anything else => success.
    char toPut = static_cast<char>(ch);
    if (1 == xsputn(&toPut, 1))
        return ch;
    return traits_type::eof();
}

}  // namespace
#endif

RotatableFileWriter::RotatableFileWriter() : _stream(nullptr) {}

RotatableFileWriter::Use::Use(RotatableFileWriter* writer)
    : _writer(writer), _lock(writer->_mutex) {}

Status RotatableFileWriter::Use::setFileName(const std::string& name, bool append) {
    _writer->_fileName = name;
    return _openFileStream(append);
}

Status RotatableFileWriter::Use::rotate(bool renameOnRotate, const std::string& renameTarget) {
    if (_writer->_stream) {
        _writer->_stream->flush();

        if (renameOnRotate) {
            try {
                if (boost::filesystem::exists(renameTarget)) {
                    return Status(
                        ErrorCodes::FileRenameFailed,
                        mongoutils::str::stream() << "Renaming file " << _writer->_fileName
                                                  << " to "
                                                  << renameTarget
                                                  << " failed; destination already exists");
                }
            } catch (const std::exception& e) {
                return Status(
                    ErrorCodes::FileRenameFailed,
                    mongoutils::str::stream() << "Renaming file " << _writer->_fileName << " to "
                                              << renameTarget
                                              << " failed; Cannot verify whether destination "
                                                 "already exists: "
                                              << e.what());
            }

            boost::system::error_code ec;
            boost::filesystem::rename(_writer->_fileName, renameTarget, ec);
            if (ec) {
                return Status(ErrorCodes::FileRenameFailed,
                              mongoutils::str::stream() << "Failed  to rename \""
                                                        << _writer->_fileName
                                                        << "\" to \""
                                                        << renameTarget
                                                        << "\": "
                                                        << ec.message());
                // TODO(schwerin): Make errnoWithDescription() available in the logger library, and
                // use it here.
            }
        }
    }
    return _openFileStream(false);
}

Status RotatableFileWriter::Use::status() {
    if (!_writer->_stream) {
        return Status(ErrorCodes::FileNotOpen,
                      mongoutils::str::stream() << "File \"" << _writer->_fileName
                                                << "\" not open");
    }
    if (_writer->_stream->fail()) {
        return Status(ErrorCodes::FileStreamFailed,
                      mongoutils::str::stream() << "File \"" << _writer->_fileName
                                                << "\" in failed state");
    }
    return Status::OK();
}

Status RotatableFileWriter::Use::_openFileStream(bool append) {
    using std::swap;

#ifdef _WIN32
    std::unique_ptr<std::ostream> newStream(new Win32FileOStream(_writer->_fileName, append));
#else
    std::ios::openmode mode = std::ios::out;
    if (append) {
        mode |= std::ios::app;
    } else {
        mode |= std::ios::trunc;
    }
    std::unique_ptr<std::ostream> newStream(new std::ofstream(_writer->_fileName.c_str(), mode));
#endif

    if (newStream->fail()) {
        return Status(ErrorCodes::FileNotOpen, "Failed to open \"" + _writer->_fileName + "\"");
    }
    swap(_writer->_stream, newStream);
    return status();
}

}  // namespace logger
}  // namespace mongo