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