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