2022-04-28 12:56:53 +00:00
|
|
|
#include <mutex>
|
2021-07-23 22:50:14 +00:00
|
|
|
#include <unistd.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
|
|
|
|
#include <Common/ProfileEvents.h>
|
|
|
|
#include <Common/Exception.h>
|
|
|
|
#include <IO/OpenedFile.h>
|
|
|
|
|
|
|
|
|
|
|
|
namespace ProfileEvents
|
|
|
|
{
|
|
|
|
extern const Event FileOpen;
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
|
|
|
|
|
|
|
namespace ErrorCodes
|
|
|
|
{
|
|
|
|
extern const int FILE_DOESNT_EXIST;
|
|
|
|
extern const int CANNOT_OPEN_FILE;
|
|
|
|
extern const int CANNOT_CLOSE_FILE;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-04-28 12:56:53 +00:00
|
|
|
void OpenedFile::open() const
|
2021-07-23 22:50:14 +00:00
|
|
|
{
|
|
|
|
ProfileEvents::increment(ProfileEvents::FileOpen);
|
|
|
|
|
|
|
|
fd = ::open(file_name.c_str(), (flags == -1 ? 0 : flags) | O_RDONLY | O_CLOEXEC);
|
|
|
|
|
|
|
|
if (-1 == fd)
|
|
|
|
throwFromErrnoWithPath("Cannot open file " + file_name, file_name,
|
|
|
|
errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE);
|
|
|
|
}
|
|
|
|
|
2022-04-28 12:56:53 +00:00
|
|
|
int OpenedFile::getFD() const
|
|
|
|
{
|
|
|
|
std::lock_guard l(mutex);
|
|
|
|
if (fd == -1)
|
|
|
|
open();
|
|
|
|
return fd;
|
|
|
|
}
|
2021-07-23 22:50:14 +00:00
|
|
|
|
|
|
|
std::string OpenedFile::getFileName() const
|
|
|
|
{
|
|
|
|
return file_name;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-04-28 12:56:53 +00:00
|
|
|
OpenedFile::OpenedFile(const std::string & file_name_, int flags_)
|
|
|
|
: file_name(file_name_), flags(flags_)
|
2021-07-23 22:50:14 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
OpenedFile::~OpenedFile()
|
|
|
|
{
|
2022-04-28 12:56:53 +00:00
|
|
|
close(); /// Exceptions will lead to std::terminate and that's Ok.
|
2021-07-23 22:50:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void OpenedFile::close()
|
|
|
|
{
|
2022-04-28 12:56:53 +00:00
|
|
|
std::lock_guard l(mutex);
|
|
|
|
if (fd == -1)
|
|
|
|
return;
|
|
|
|
|
2021-07-23 22:50:14 +00:00
|
|
|
if (0 != ::close(fd))
|
|
|
|
throw Exception("Cannot close file", ErrorCodes::CANNOT_CLOSE_FILE);
|
|
|
|
|
|
|
|
fd = -1;
|
|
|
|
metric_increment.destroy();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|