| 44 | |
| 45 | |
| 46 | StatusFile::StatusFile(std::string path_, FillFunction fill) |
| 47 | : path(std::move(path_)) |
| 48 | { |
| 49 | /// If file already exists. NOTE Minor race condition. |
| 50 | if (fs::exists(path)) |
| 51 | { |
| 52 | std::string contents; |
| 53 | { |
| 54 | ReadBufferFromFile in(path, 1024); |
| 55 | LimitReadBuffer limit_in(in, {.read_no_more = 1024}); |
| 56 | readStringUntilEOF(contents, limit_in); |
| 57 | } |
| 58 | |
| 59 | if (!contents.empty()) |
| 60 | LOG_INFO(getLogger("StatusFile"), "Status file {} already exists - unclean restart. Contents:\n{}", path, contents); |
| 61 | else |
| 62 | LOG_INFO(getLogger("StatusFile"), "Status file {} already exists and is empty - probably unclean hardware restart.", path); |
| 63 | } |
| 64 | |
| 65 | fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0666); |
| 66 | |
| 67 | if (-1 == fd) |
| 68 | ErrnoException::throwFromPath(ErrorCodes::CANNOT_OPEN_FILE, path, "Cannot open file {}", path); |
| 69 | |
| 70 | try |
| 71 | { |
| 72 | int flock_ret = flock(fd, LOCK_EX | LOCK_NB); |
| 73 | if (-1 == flock_ret) |
| 74 | { |
| 75 | if (errno == EWOULDBLOCK) |
| 76 | throw Exception(ErrorCodes::CANNOT_OPEN_FILE, "Cannot lock file {}. Another server instance in same directory is already running.", path); |
| 77 | ErrnoException::throwFromPath(ErrorCodes::CANNOT_OPEN_FILE, path, "Cannot lock file {}", path); |
| 78 | } |
| 79 | |
| 80 | if (0 != ftruncate(fd, 0)) |
| 81 | ErrnoException::throwFromPath(ErrorCodes::CANNOT_TRUNCATE_FILE, path, "Cannot ftruncate file {}", path); |
| 82 | |
| 83 | if (0 != lseek(fd, 0, SEEK_SET)) |
| 84 | ErrnoException::throwFromPath(ErrorCodes::CANNOT_SEEK_THROUGH_FILE, path, "Cannot lseek file {}", path); |
| 85 | |
| 86 | /// Write information about current server instance to the file. |
| 87 | WriteBufferFromFileDescriptor out(fd, 1024); |
| 88 | try |
| 89 | { |
| 90 | LOG_INFO(getLogger("StatusFile"), "Writing pid {} to {}", getpid(), path); |
| 91 | fill(out); |
| 92 | out.finalize(); |
| 93 | } |
| 94 | catch (...) |
| 95 | { |
| 96 | out.cancel(); |
| 97 | throw; |
| 98 | } |
| 99 | } |
| 100 | catch (...) |
| 101 | { |
| 102 | [[maybe_unused]] int err = close(fd); |
| 103 | chassert(!err || errno == EINTR); |