ClickHouse/src/IO/MMappedFile.cpp

79 lines
1.4 KiB
C++
Raw Normal View History

2021-03-26 20:51:46 +00:00
#include <unistd.h>
2021-03-26 23:22:51 +00:00
#include <fcntl.h>
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
#include <Common/ProfileEvents.h>
2021-03-26 20:51:46 +00:00
#include <Common/formatReadable.h>
#include <Common/Exception.h>
2021-03-28 19:24:28 +00:00
#include <IO/MMappedFile.h>
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
namespace ProfileEvents
{
extern const Event FileOpen;
}
2021-03-26 20:51:46 +00:00
namespace DB
{
namespace ErrorCodes
{
2021-03-26 23:22:51 +00:00
extern const int FILE_DOESNT_EXIST;
extern const int CANNOT_OPEN_FILE;
extern const int CANNOT_CLOSE_FILE;
2021-03-26 20:51:46 +00:00
}
2021-03-28 19:24:28 +00:00
void MMappedFile::open()
2021-03-26 20:51:46 +00:00
{
2021-03-26 23:22:51 +00:00
ProfileEvents::increment(ProfileEvents::FileOpen);
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
fd = ::open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
if (-1 == fd)
throwFromErrnoWithPath("Cannot open file " + file_name, file_name,
errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE);
2021-03-26 20:51:46 +00:00
}
2021-03-28 19:24:28 +00:00
std::string MMappedFile::getFileName() const
2021-03-26 20:51:46 +00:00
{
2021-03-26 23:22:51 +00:00
return file_name;
2021-03-26 20:51:46 +00:00
}
2021-03-28 19:24:28 +00:00
MMappedFile::MMappedFile(const std::string & file_name_, size_t offset_, size_t length_)
2021-03-26 23:22:51 +00:00
: file_name(file_name_)
2021-03-26 20:51:46 +00:00
{
2021-03-26 23:22:51 +00:00
open();
set(fd, offset_, length_);
2021-03-26 20:51:46 +00:00
}
2021-03-26 23:22:51 +00:00
2021-03-28 19:24:28 +00:00
MMappedFile::MMappedFile(const std::string & file_name_, size_t offset_)
2021-03-26 23:22:51 +00:00
: file_name(file_name_)
2021-03-26 20:51:46 +00:00
{
2021-03-26 23:22:51 +00:00
open();
set(fd, offset_);
}
2021-03-26 20:51:46 +00:00
2021-03-28 19:24:28 +00:00
MMappedFile::~MMappedFile()
2021-03-26 23:22:51 +00:00
{
if (fd != -1)
close(); /// Exceptions will lead to std::terminate and that's Ok.
2021-03-26 20:51:46 +00:00
}
2021-03-28 19:24:28 +00:00
void MMappedFile::close()
2021-03-26 23:22:51 +00:00
{
finish();
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
if (0 != ::close(fd))
throw Exception("Cannot close file", ErrorCodes::CANNOT_CLOSE_FILE);
2021-03-26 20:51:46 +00:00
2021-03-26 23:22:51 +00:00
fd = -1;
metric_increment.destroy();
2021-03-26 20:51:46 +00:00
}
}