You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

env_posix.cc 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #if !defined(LEVELDB_PLATFORM_WINDOWS)
  5. #include <dirent.h>
  6. #include <errno.h>
  7. #include <fcntl.h>
  8. #include <pthread.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <sys/mman.h>
  13. #include <sys/resource.h>
  14. #include <sys/stat.h>
  15. #include <sys/time.h>
  16. #include <sys/types.h>
  17. #include <time.h>
  18. #include <unistd.h>
  19. #include <deque>
  20. #include <limits>
  21. #include <set>
  22. #include "leveldb/env.h"
  23. #include "leveldb/slice.h"
  24. #include "port/port.h"
  25. #include "util/logging.h"
  26. #include "util/mutexlock.h"
  27. #include "util/posix_logger.h"
  28. #include "util/env_posix_test_helper.h"
  29. namespace leveldb {
  30. namespace {
  31. static int open_read_only_file_limit = -1;
  32. static int mmap_limit = -1;
  33. static Status IOError(const std::string& context, int err_number) {
  34. return Status::IOError(context, strerror(err_number));
  35. }
  36. // Helper class to limit resource usage to avoid exhaustion.
  37. // Currently used to limit read-only file descriptors and mmap file usage
  38. // so that we do not end up running out of file descriptors, virtual memory,
  39. // or running into kernel performance problems for very large databases.
  40. class Limiter {
  41. public:
  42. // Limit maximum number of resources to |n|.
  43. Limiter(intptr_t n) {
  44. SetAllowed(n);
  45. }
  46. // If another resource is available, acquire it and return true.
  47. // Else return false.
  48. bool Acquire() {
  49. if (GetAllowed() <= 0) {
  50. return false;
  51. }
  52. MutexLock l(&mu_);
  53. intptr_t x = GetAllowed();
  54. if (x <= 0) {
  55. return false;
  56. } else {
  57. SetAllowed(x - 1);
  58. return true;
  59. }
  60. }
  61. // Release a resource acquired by a previous call to Acquire() that returned
  62. // true.
  63. void Release() {
  64. MutexLock l(&mu_);
  65. SetAllowed(GetAllowed() + 1);
  66. }
  67. private:
  68. port::Mutex mu_;
  69. port::AtomicPointer allowed_;
  70. intptr_t GetAllowed() const {
  71. return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
  72. }
  73. // REQUIRES: mu_ must be held
  74. void SetAllowed(intptr_t v) {
  75. allowed_.Release_Store(reinterpret_cast<void*>(v));
  76. }
  77. Limiter(const Limiter&);
  78. void operator=(const Limiter&);
  79. };
  80. class PosixSequentialFile: public SequentialFile {
  81. private:
  82. std::string filename_;
  83. FILE* file_;
  84. public:
  85. PosixSequentialFile(const std::string& fname, FILE* f)
  86. : filename_(fname), file_(f) { }
  87. virtual ~PosixSequentialFile() { fclose(file_); }
  88. virtual Status Read(size_t n, Slice* result, char* scratch) {
  89. Status s;
  90. size_t r = fread_unlocked(scratch, 1, n, file_);
  91. *result = Slice(scratch, r);
  92. if (r < n) {
  93. if (feof(file_)) {
  94. // We leave status as ok if we hit the end of the file
  95. } else {
  96. // A partial read with an error: return a non-ok status
  97. s = IOError(filename_, errno);
  98. }
  99. }
  100. return s;
  101. }
  102. virtual Status Skip(uint64_t n) {
  103. if (fseek(file_, n, SEEK_CUR)) {
  104. return IOError(filename_, errno);
  105. }
  106. return Status::OK();
  107. }
  108. virtual std::string GetName() const { return filename_; }
  109. };
  110. // pread() based random-access
  111. class PosixRandomAccessFile: public RandomAccessFile {
  112. private:
  113. std::string filename_;
  114. bool temporary_fd_; // If true, fd_ is -1 and we open on every read.
  115. int fd_;
  116. Limiter* limiter_;
  117. public:
  118. PosixRandomAccessFile(const std::string& fname, int fd, Limiter* limiter)
  119. : filename_(fname), fd_(fd), limiter_(limiter) {
  120. temporary_fd_ = !limiter->Acquire();
  121. if (temporary_fd_) {
  122. // Open file on every access.
  123. close(fd_);
  124. fd_ = -1;
  125. }
  126. }
  127. virtual ~PosixRandomAccessFile() {
  128. if (!temporary_fd_) {
  129. close(fd_);
  130. limiter_->Release();
  131. }
  132. }
  133. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  134. char* scratch) const {
  135. int fd = fd_;
  136. if (temporary_fd_) {
  137. fd = open(filename_.c_str(), O_RDONLY);
  138. if (fd < 0) {
  139. return IOError(filename_, errno);
  140. }
  141. }
  142. Status s;
  143. ssize_t r = pread(fd, scratch, n, static_cast<off_t>(offset));
  144. *result = Slice(scratch, (r < 0) ? 0 : r);
  145. if (r < 0) {
  146. // An error: return a non-ok status
  147. s = IOError(filename_, errno);
  148. }
  149. if (temporary_fd_) {
  150. // Close the temporary file descriptor opened earlier.
  151. close(fd);
  152. }
  153. return s;
  154. }
  155. virtual std::string GetName() const { return filename_; }
  156. };
  157. // mmap() based random-access
  158. class PosixMmapReadableFile: public RandomAccessFile {
  159. private:
  160. std::string filename_;
  161. void* mmapped_region_;
  162. size_t length_;
  163. Limiter* limiter_;
  164. public:
  165. // base[0,length-1] contains the mmapped contents of the file.
  166. PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
  167. Limiter* limiter)
  168. : filename_(fname), mmapped_region_(base), length_(length),
  169. limiter_(limiter) {
  170. }
  171. virtual ~PosixMmapReadableFile() {
  172. munmap(mmapped_region_, length_);
  173. limiter_->Release();
  174. }
  175. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  176. char* scratch) const {
  177. Status s;
  178. if (offset + n > length_) {
  179. *result = Slice();
  180. s = IOError(filename_, EINVAL);
  181. } else {
  182. *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
  183. }
  184. return s;
  185. }
  186. virtual std::string GetName() const { return filename_; }
  187. };
  188. class PosixWritableFile : public WritableFile {
  189. private:
  190. std::string filename_;
  191. FILE* file_;
  192. public:
  193. PosixWritableFile(const std::string& fname, FILE* f)
  194. : filename_(fname), file_(f) { }
  195. ~PosixWritableFile() {
  196. if (file_ != NULL) {
  197. // Ignoring any potential errors
  198. fclose(file_);
  199. }
  200. }
  201. virtual Status Append(const Slice& data) {
  202. size_t r = fwrite_unlocked(data.data(), 1, data.size(), file_);
  203. if (r != data.size()) {
  204. return IOError(filename_, errno);
  205. }
  206. return Status::OK();
  207. }
  208. virtual Status Close() {
  209. Status result;
  210. if (fclose(file_) != 0) {
  211. result = IOError(filename_, errno);
  212. }
  213. file_ = NULL;
  214. return result;
  215. }
  216. virtual Status Flush() {
  217. if (fflush_unlocked(file_) != 0) {
  218. return IOError(filename_, errno);
  219. }
  220. return Status::OK();
  221. }
  222. Status SyncDirIfManifest() {
  223. const char* f = filename_.c_str();
  224. const char* sep = strrchr(f, '/');
  225. Slice basename;
  226. std::string dir;
  227. if (sep == NULL) {
  228. dir = ".";
  229. basename = f;
  230. } else {
  231. dir = std::string(f, sep - f);
  232. basename = sep + 1;
  233. }
  234. Status s;
  235. if (basename.starts_with("MANIFEST")) {
  236. int fd = open(dir.c_str(), O_RDONLY);
  237. if (fd < 0) {
  238. s = IOError(dir, errno);
  239. } else {
  240. if (fsync(fd) < 0 && errno != EINVAL) {
  241. s = IOError(dir, errno);
  242. }
  243. close(fd);
  244. }
  245. }
  246. return s;
  247. }
  248. virtual Status Sync() {
  249. // Ensure new files referred to by the manifest are in the filesystem.
  250. Status s = SyncDirIfManifest();
  251. if (!s.ok()) {
  252. return s;
  253. }
  254. if (fflush_unlocked(file_) != 0 ||
  255. fdatasync(fileno(file_)) != 0) {
  256. s = Status::IOError(filename_, strerror(errno));
  257. }
  258. return s;
  259. }
  260. virtual std::string GetName() const { return filename_; }
  261. };
  262. static int LockOrUnlock(int fd, bool lock) {
  263. errno = 0;
  264. struct flock f;
  265. memset(&f, 0, sizeof(f));
  266. f.l_type = (lock ? F_WRLCK : F_UNLCK);
  267. f.l_whence = SEEK_SET;
  268. f.l_start = 0;
  269. f.l_len = 0; // Lock/unlock entire file
  270. return fcntl(fd, F_SETLK, &f);
  271. }
  272. class PosixFileLock : public FileLock {
  273. public:
  274. int fd_;
  275. std::string name_;
  276. };
  277. // Set of locked files. We keep a separate set instead of just
  278. // relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
  279. // any protection against multiple uses from the same process.
  280. class PosixLockTable {
  281. private:
  282. port::Mutex mu_;
  283. std::set<std::string> locked_files_;
  284. public:
  285. bool Insert(const std::string& fname) {
  286. MutexLock l(&mu_);
  287. return locked_files_.insert(fname).second;
  288. }
  289. void Remove(const std::string& fname) {
  290. MutexLock l(&mu_);
  291. locked_files_.erase(fname);
  292. }
  293. };
  294. class PosixEnv : public Env {
  295. public:
  296. PosixEnv();
  297. virtual ~PosixEnv() {
  298. char msg[] = "Destroying Env::Default()\n";
  299. fwrite(msg, 1, sizeof(msg), stderr);
  300. abort();
  301. }
  302. virtual Status NewSequentialFile(const std::string& fname,
  303. SequentialFile** result) {
  304. FILE* f = fopen(fname.c_str(), "r");
  305. if (f == NULL) {
  306. *result = NULL;
  307. return IOError(fname, errno);
  308. } else {
  309. *result = new PosixSequentialFile(fname, f);
  310. return Status::OK();
  311. }
  312. }
  313. virtual Status NewRandomAccessFile(const std::string& fname,
  314. RandomAccessFile** result) {
  315. *result = NULL;
  316. Status s;
  317. int fd = open(fname.c_str(), O_RDONLY);
  318. if (fd < 0) {
  319. s = IOError(fname, errno);
  320. } else if (mmap_limit_.Acquire()) {
  321. uint64_t size;
  322. s = GetFileSize(fname, &size);
  323. if (s.ok()) {
  324. void* base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
  325. if (base != MAP_FAILED) {
  326. *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
  327. } else {
  328. s = IOError(fname, errno);
  329. }
  330. }
  331. close(fd);
  332. if (!s.ok()) {
  333. mmap_limit_.Release();
  334. }
  335. } else {
  336. *result = new PosixRandomAccessFile(fname, fd, &fd_limit_);
  337. }
  338. return s;
  339. }
  340. virtual Status NewWritableFile(const std::string& fname,
  341. WritableFile** result) {
  342. Status s;
  343. FILE* f = fopen(fname.c_str(), "w");
  344. if (f == NULL) {
  345. *result = NULL;
  346. s = IOError(fname, errno);
  347. } else {
  348. *result = new PosixWritableFile(fname, f);
  349. }
  350. return s;
  351. }
  352. virtual Status NewAppendableFile(const std::string& fname,
  353. WritableFile** result) {
  354. Status s;
  355. FILE* f = fopen(fname.c_str(), "a");
  356. if (f == NULL) {
  357. *result = NULL;
  358. s = IOError(fname, errno);
  359. } else {
  360. *result = new PosixWritableFile(fname, f);
  361. }
  362. return s;
  363. }
  364. virtual bool FileExists(const std::string& fname) {
  365. return access(fname.c_str(), F_OK) == 0;
  366. }
  367. virtual Status GetChildren(const std::string& dir,
  368. std::vector<std::string>* result) {
  369. result->clear();
  370. DIR* d = opendir(dir.c_str());
  371. if (d == NULL) {
  372. return IOError(dir, errno);
  373. }
  374. struct dirent* entry;
  375. while ((entry = readdir(d)) != NULL) {
  376. result->push_back(entry->d_name);
  377. }
  378. closedir(d);
  379. return Status::OK();
  380. }
  381. virtual Status DeleteFile(const std::string& fname) {
  382. Status result;
  383. if (unlink(fname.c_str()) != 0) {
  384. result = IOError(fname, errno);
  385. }
  386. return result;
  387. }
  388. virtual Status CreateDir(const std::string& name) {
  389. Status result;
  390. if (mkdir(name.c_str(), 0755) != 0) {
  391. result = IOError(name, errno);
  392. }
  393. return result;
  394. }
  395. virtual Status DeleteDir(const std::string& name) {
  396. Status result;
  397. if (rmdir(name.c_str()) != 0) {
  398. result = IOError(name, errno);
  399. }
  400. return result;
  401. }
  402. virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
  403. Status s;
  404. struct stat sbuf;
  405. if (stat(fname.c_str(), &sbuf) != 0) {
  406. *size = 0;
  407. s = IOError(fname, errno);
  408. } else {
  409. *size = sbuf.st_size;
  410. }
  411. return s;
  412. }
  413. virtual Status RenameFile(const std::string& src, const std::string& target) {
  414. Status result;
  415. if (rename(src.c_str(), target.c_str()) != 0) {
  416. result = IOError(src, errno);
  417. }
  418. return result;
  419. }
  420. virtual Status LockFile(const std::string& fname, FileLock** lock) {
  421. *lock = NULL;
  422. Status result;
  423. int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
  424. if (fd < 0) {
  425. result = IOError(fname, errno);
  426. } else if (!locks_.Insert(fname)) {
  427. close(fd);
  428. result = Status::IOError("lock " + fname, "already held by process");
  429. } else if (LockOrUnlock(fd, true) == -1) {
  430. result = IOError("lock " + fname, errno);
  431. close(fd);
  432. locks_.Remove(fname);
  433. } else {
  434. PosixFileLock* my_lock = new PosixFileLock;
  435. my_lock->fd_ = fd;
  436. my_lock->name_ = fname;
  437. *lock = my_lock;
  438. }
  439. return result;
  440. }
  441. virtual Status UnlockFile(FileLock* lock) {
  442. PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
  443. Status result;
  444. if (LockOrUnlock(my_lock->fd_, false) == -1) {
  445. result = IOError("unlock", errno);
  446. }
  447. locks_.Remove(my_lock->name_);
  448. close(my_lock->fd_);
  449. delete my_lock;
  450. return result;
  451. }
  452. virtual void Schedule(void (*function)(void*), void* arg);
  453. virtual void StartThread(void (*function)(void* arg), void* arg);
  454. virtual Status GetTestDirectory(std::string* result) {
  455. const char* env = getenv("TEST_TMPDIR");
  456. if (env && env[0] != '\0') {
  457. *result = env;
  458. } else {
  459. char buf[100];
  460. snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
  461. *result = buf;
  462. }
  463. // Directory may already exist
  464. CreateDir(*result);
  465. return Status::OK();
  466. }
  467. static uint64_t gettid() {
  468. pthread_t tid = pthread_self();
  469. uint64_t thread_id = 0;
  470. memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
  471. return thread_id;
  472. }
  473. virtual Status NewLogger(const std::string& fname, Logger** result) {
  474. FILE* f = fopen(fname.c_str(), "w");
  475. if (f == NULL) {
  476. *result = NULL;
  477. return IOError(fname, errno);
  478. } else {
  479. *result = new PosixLogger(f, &PosixEnv::gettid);
  480. return Status::OK();
  481. }
  482. }
  483. virtual uint64_t NowMicros() {
  484. struct timeval tv;
  485. gettimeofday(&tv, NULL);
  486. return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
  487. }
  488. virtual void SleepForMicroseconds(int micros) {
  489. usleep(micros);
  490. }
  491. private:
  492. void PthreadCall(const char* label, int result) {
  493. if (result != 0) {
  494. fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
  495. abort();
  496. }
  497. }
  498. // BGThread() is the body of the background thread
  499. void BGThread();
  500. static void* BGThreadWrapper(void* arg) {
  501. reinterpret_cast<PosixEnv*>(arg)->BGThread();
  502. return NULL;
  503. }
  504. pthread_mutex_t mu_;
  505. pthread_cond_t bgsignal_;
  506. pthread_t bgthread_;
  507. bool started_bgthread_;
  508. // Entry per Schedule() call
  509. struct BGItem { void* arg; void (*function)(void*); };
  510. typedef std::deque<BGItem> BGQueue;
  511. BGQueue queue_;
  512. PosixLockTable locks_;
  513. Limiter mmap_limit_;
  514. Limiter fd_limit_;
  515. };
  516. // Return the maximum number of concurrent mmaps.
  517. static int MaxMmaps() {
  518. if (mmap_limit >= 0) {
  519. return mmap_limit;
  520. }
  521. // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
  522. mmap_limit = sizeof(void*) >= 8 ? 1000 : 0;
  523. return mmap_limit;
  524. }
  525. // Return the maximum number of read-only files to keep open.
  526. static intptr_t MaxOpenFiles() {
  527. if (open_read_only_file_limit >= 0) {
  528. return open_read_only_file_limit;
  529. }
  530. struct rlimit rlim;
  531. if (getrlimit(RLIMIT_NOFILE, &rlim)) {
  532. // getrlimit failed, fallback to hard-coded default.
  533. open_read_only_file_limit = 50;
  534. } else if (rlim.rlim_cur == RLIM_INFINITY) {
  535. open_read_only_file_limit = std::numeric_limits<int>::max();
  536. } else {
  537. // Allow use of 20% of available file descriptors for read-only files.
  538. open_read_only_file_limit = rlim.rlim_cur / 5;
  539. }
  540. return open_read_only_file_limit;
  541. }
  542. PosixEnv::PosixEnv()
  543. : started_bgthread_(false),
  544. mmap_limit_(MaxMmaps()),
  545. fd_limit_(MaxOpenFiles()) {
  546. PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
  547. PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
  548. }
  549. void PosixEnv::Schedule(void (*function)(void*), void* arg) {
  550. PthreadCall("lock", pthread_mutex_lock(&mu_));
  551. // Start background thread if necessary
  552. if (!started_bgthread_) {
  553. started_bgthread_ = true;
  554. PthreadCall(
  555. "create thread",
  556. pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
  557. }
  558. // If the queue is currently empty, the background thread may currently be
  559. // waiting.
  560. if (queue_.empty()) {
  561. PthreadCall("signal", pthread_cond_signal(&bgsignal_));
  562. }
  563. // Add to priority queue
  564. queue_.push_back(BGItem());
  565. queue_.back().function = function;
  566. queue_.back().arg = arg;
  567. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  568. }
  569. void PosixEnv::BGThread() {
  570. while (true) {
  571. // Wait until there is an item that is ready to run
  572. PthreadCall("lock", pthread_mutex_lock(&mu_));
  573. while (queue_.empty()) {
  574. PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
  575. }
  576. void (*function)(void*) = queue_.front().function;
  577. void* arg = queue_.front().arg;
  578. queue_.pop_front();
  579. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  580. (*function)(arg);
  581. }
  582. }
  583. namespace {
  584. struct StartThreadState {
  585. void (*user_function)(void*);
  586. void* arg;
  587. };
  588. }
  589. static void* StartThreadWrapper(void* arg) {
  590. StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
  591. state->user_function(state->arg);
  592. delete state;
  593. return NULL;
  594. }
  595. void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
  596. pthread_t t;
  597. StartThreadState* state = new StartThreadState;
  598. state->user_function = function;
  599. state->arg = arg;
  600. PthreadCall("start thread",
  601. pthread_create(&t, NULL, &StartThreadWrapper, state));
  602. }
  603. } // namespace
  604. static pthread_once_t once = PTHREAD_ONCE_INIT;
  605. static Env* default_env;
  606. static void InitDefaultEnv() { default_env = new PosixEnv; }
  607. void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit) {
  608. assert(default_env == NULL);
  609. open_read_only_file_limit = limit;
  610. }
  611. void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit) {
  612. assert(default_env == NULL);
  613. mmap_limit = limit;
  614. }
  615. Env* Env::Default() {
  616. pthread_once(&once, InitDefaultEnv);
  617. return default_env;
  618. }
  619. } // namespace leveldb
  620. #endif