小组成员:谢瑞阳、徐翔宇
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

605 рядки
15 KiB

Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 роки тому
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 роки тому
  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. #include <dirent.h>
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <sys/mman.h>
  12. #include <sys/stat.h>
  13. #include <sys/time.h>
  14. #include <sys/types.h>
  15. #include <time.h>
  16. #include <unistd.h>
  17. #include <deque>
  18. #include <set>
  19. #include "leveldb/env.h"
  20. #include "leveldb/slice.h"
  21. #include "port/port.h"
  22. #include "util/logging.h"
  23. #include "util/mutexlock.h"
  24. #include "util/posix_logger.h"
  25. namespace leveldb {
  26. namespace {
  27. static Status IOError(const std::string& context, int err_number) {
  28. return Status::IOError(context, strerror(err_number));
  29. }
  30. class PosixSequentialFile: public SequentialFile {
  31. private:
  32. std::string filename_;
  33. FILE* file_;
  34. public:
  35. PosixSequentialFile(const std::string& fname, FILE* f)
  36. : filename_(fname), file_(f) { }
  37. virtual ~PosixSequentialFile() { fclose(file_); }
  38. virtual Status Read(size_t n, Slice* result, char* scratch) {
  39. Status s;
  40. size_t r = fread_unlocked(scratch, 1, n, file_);
  41. *result = Slice(scratch, r);
  42. if (r < n) {
  43. if (feof(file_)) {
  44. // We leave status as ok if we hit the end of the file
  45. } else {
  46. // A partial read with an error: return a non-ok status
  47. s = IOError(filename_, errno);
  48. }
  49. }
  50. return s;
  51. }
  52. virtual Status Skip(uint64_t n) {
  53. if (fseek(file_, n, SEEK_CUR)) {
  54. return IOError(filename_, errno);
  55. }
  56. return Status::OK();
  57. }
  58. };
  59. // pread() based random-access
  60. class PosixRandomAccessFile: public RandomAccessFile {
  61. private:
  62. std::string filename_;
  63. int fd_;
  64. public:
  65. PosixRandomAccessFile(const std::string& fname, int fd)
  66. : filename_(fname), fd_(fd) { }
  67. virtual ~PosixRandomAccessFile() { close(fd_); }
  68. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  69. char* scratch) const {
  70. Status s;
  71. ssize_t r = pread(fd_, scratch, n, static_cast<off_t>(offset));
  72. *result = Slice(scratch, (r < 0) ? 0 : r);
  73. if (r < 0) {
  74. // An error: return a non-ok status
  75. s = IOError(filename_, errno);
  76. }
  77. return s;
  78. }
  79. };
  80. // Helper class to limit mmap file usage so that we do not end up
  81. // running out virtual memory or running into kernel performance
  82. // problems for very large databases.
  83. class MmapLimiter {
  84. public:
  85. // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
  86. MmapLimiter() {
  87. SetAllowed(sizeof(void*) >= 8 ? 1000 : 0);
  88. }
  89. // If another mmap slot is available, acquire it and return true.
  90. // Else return false.
  91. bool Acquire() {
  92. if (GetAllowed() <= 0) {
  93. return false;
  94. }
  95. MutexLock l(&mu_);
  96. intptr_t x = GetAllowed();
  97. if (x <= 0) {
  98. return false;
  99. } else {
  100. SetAllowed(x - 1);
  101. return true;
  102. }
  103. }
  104. // Release a slot acquired by a previous call to Acquire() that returned true.
  105. void Release() {
  106. MutexLock l(&mu_);
  107. SetAllowed(GetAllowed() + 1);
  108. }
  109. private:
  110. port::Mutex mu_;
  111. port::AtomicPointer allowed_;
  112. intptr_t GetAllowed() const {
  113. return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
  114. }
  115. // REQUIRES: mu_ must be held
  116. void SetAllowed(intptr_t v) {
  117. allowed_.Release_Store(reinterpret_cast<void*>(v));
  118. }
  119. MmapLimiter(const MmapLimiter&);
  120. void operator=(const MmapLimiter&);
  121. };
  122. // mmap() based random-access
  123. class PosixMmapReadableFile: public RandomAccessFile {
  124. private:
  125. std::string filename_;
  126. void* mmapped_region_;
  127. size_t length_;
  128. MmapLimiter* limiter_;
  129. public:
  130. // base[0,length-1] contains the mmapped contents of the file.
  131. PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
  132. MmapLimiter* limiter)
  133. : filename_(fname), mmapped_region_(base), length_(length),
  134. limiter_(limiter) {
  135. }
  136. virtual ~PosixMmapReadableFile() {
  137. munmap(mmapped_region_, length_);
  138. limiter_->Release();
  139. }
  140. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  141. char* scratch) const {
  142. Status s;
  143. if (offset + n > length_) {
  144. *result = Slice();
  145. s = IOError(filename_, EINVAL);
  146. } else {
  147. *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
  148. }
  149. return s;
  150. }
  151. };
  152. class PosixWritableFile : public WritableFile {
  153. private:
  154. std::string filename_;
  155. FILE* file_;
  156. public:
  157. PosixWritableFile(const std::string& fname, FILE* f)
  158. : filename_(fname), file_(f) { }
  159. ~PosixWritableFile() {
  160. if (file_ != NULL) {
  161. // Ignoring any potential errors
  162. fclose(file_);
  163. }
  164. }
  165. virtual Status Append(const Slice& data) {
  166. size_t r = fwrite_unlocked(data.data(), 1, data.size(), file_);
  167. if (r != data.size()) {
  168. return IOError(filename_, errno);
  169. }
  170. return Status::OK();
  171. }
  172. virtual Status Close() {
  173. Status result;
  174. if (fclose(file_) != 0) {
  175. result = IOError(filename_, errno);
  176. }
  177. file_ = NULL;
  178. return result;
  179. }
  180. virtual Status Flush() {
  181. if (fflush_unlocked(file_) != 0) {
  182. return IOError(filename_, errno);
  183. }
  184. return Status::OK();
  185. }
  186. Status SyncDirIfManifest() {
  187. const char* f = filename_.c_str();
  188. const char* sep = strrchr(f, '/');
  189. Slice basename;
  190. std::string dir;
  191. if (sep == NULL) {
  192. dir = ".";
  193. basename = f;
  194. } else {
  195. dir = std::string(f, sep - f);
  196. basename = sep + 1;
  197. }
  198. Status s;
  199. if (basename.starts_with("MANIFEST")) {
  200. int fd = open(dir.c_str(), O_RDONLY);
  201. if (fd < 0) {
  202. s = IOError(dir, errno);
  203. } else {
  204. if (fsync(fd) < 0) {
  205. s = IOError(dir, errno);
  206. }
  207. close(fd);
  208. }
  209. }
  210. return s;
  211. }
  212. virtual Status Sync() {
  213. // Ensure new files referred to by the manifest are in the filesystem.
  214. Status s = SyncDirIfManifest();
  215. if (!s.ok()) {
  216. return s;
  217. }
  218. if (fflush_unlocked(file_) != 0 ||
  219. fdatasync(fileno(file_)) != 0) {
  220. s = Status::IOError(filename_, strerror(errno));
  221. }
  222. return s;
  223. }
  224. };
  225. static int LockOrUnlock(int fd, bool lock) {
  226. errno = 0;
  227. struct flock f;
  228. memset(&f, 0, sizeof(f));
  229. f.l_type = (lock ? F_WRLCK : F_UNLCK);
  230. f.l_whence = SEEK_SET;
  231. f.l_start = 0;
  232. f.l_len = 0; // Lock/unlock entire file
  233. return fcntl(fd, F_SETLK, &f);
  234. }
  235. class PosixFileLock : public FileLock {
  236. public:
  237. int fd_;
  238. std::string name_;
  239. };
  240. // Set of locked files. We keep a separate set instead of just
  241. // relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
  242. // any protection against multiple uses from the same process.
  243. class PosixLockTable {
  244. private:
  245. port::Mutex mu_;
  246. std::set<std::string> locked_files_;
  247. public:
  248. bool Insert(const std::string& fname) {
  249. MutexLock l(&mu_);
  250. return locked_files_.insert(fname).second;
  251. }
  252. void Remove(const std::string& fname) {
  253. MutexLock l(&mu_);
  254. locked_files_.erase(fname);
  255. }
  256. };
  257. class PosixEnv : public Env {
  258. public:
  259. PosixEnv();
  260. virtual ~PosixEnv() {
  261. char msg[] = "Destroying Env::Default()\n";
  262. fwrite(msg, 1, sizeof(msg), stderr);
  263. abort();
  264. }
  265. virtual Status NewSequentialFile(const std::string& fname,
  266. SequentialFile** result) {
  267. FILE* f = fopen(fname.c_str(), "r");
  268. if (f == NULL) {
  269. *result = NULL;
  270. return IOError(fname, errno);
  271. } else {
  272. *result = new PosixSequentialFile(fname, f);
  273. return Status::OK();
  274. }
  275. }
  276. virtual Status NewRandomAccessFile(const std::string& fname,
  277. RandomAccessFile** result) {
  278. *result = NULL;
  279. Status s;
  280. int fd = open(fname.c_str(), O_RDONLY);
  281. if (fd < 0) {
  282. s = IOError(fname, errno);
  283. } else if (mmap_limit_.Acquire()) {
  284. uint64_t size;
  285. s = GetFileSize(fname, &size);
  286. if (s.ok()) {
  287. void* base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
  288. if (base != MAP_FAILED) {
  289. *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
  290. } else {
  291. s = IOError(fname, errno);
  292. }
  293. }
  294. close(fd);
  295. if (!s.ok()) {
  296. mmap_limit_.Release();
  297. }
  298. } else {
  299. *result = new PosixRandomAccessFile(fname, fd);
  300. }
  301. return s;
  302. }
  303. virtual Status NewWritableFile(const std::string& fname,
  304. WritableFile** result) {
  305. Status s;
  306. FILE* f = fopen(fname.c_str(), "w");
  307. if (f == NULL) {
  308. *result = NULL;
  309. s = IOError(fname, errno);
  310. } else {
  311. *result = new PosixWritableFile(fname, f);
  312. }
  313. return s;
  314. }
  315. virtual bool FileExists(const std::string& fname) {
  316. return access(fname.c_str(), F_OK) == 0;
  317. }
  318. virtual Status GetChildren(const std::string& dir,
  319. std::vector<std::string>* result) {
  320. result->clear();
  321. DIR* d = opendir(dir.c_str());
  322. if (d == NULL) {
  323. return IOError(dir, errno);
  324. }
  325. struct dirent* entry;
  326. while ((entry = readdir(d)) != NULL) {
  327. result->push_back(entry->d_name);
  328. }
  329. closedir(d);
  330. return Status::OK();
  331. }
  332. virtual Status DeleteFile(const std::string& fname) {
  333. Status result;
  334. if (unlink(fname.c_str()) != 0) {
  335. result = IOError(fname, errno);
  336. }
  337. return result;
  338. }
  339. virtual Status CreateDir(const std::string& name) {
  340. Status result;
  341. if (mkdir(name.c_str(), 0755) != 0) {
  342. result = IOError(name, errno);
  343. }
  344. return result;
  345. }
  346. virtual Status DeleteDir(const std::string& name) {
  347. Status result;
  348. if (rmdir(name.c_str()) != 0) {
  349. result = IOError(name, errno);
  350. }
  351. return result;
  352. }
  353. virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
  354. Status s;
  355. struct stat sbuf;
  356. if (stat(fname.c_str(), &sbuf) != 0) {
  357. *size = 0;
  358. s = IOError(fname, errno);
  359. } else {
  360. *size = sbuf.st_size;
  361. }
  362. return s;
  363. }
  364. virtual Status RenameFile(const std::string& src, const std::string& target) {
  365. Status result;
  366. if (rename(src.c_str(), target.c_str()) != 0) {
  367. result = IOError(src, errno);
  368. }
  369. return result;
  370. }
  371. virtual Status LockFile(const std::string& fname, FileLock** lock) {
  372. *lock = NULL;
  373. Status result;
  374. int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
  375. if (fd < 0) {
  376. result = IOError(fname, errno);
  377. } else if (!locks_.Insert(fname)) {
  378. close(fd);
  379. result = Status::IOError("lock " + fname, "already held by process");
  380. } else if (LockOrUnlock(fd, true) == -1) {
  381. result = IOError("lock " + fname, errno);
  382. close(fd);
  383. locks_.Remove(fname);
  384. } else {
  385. PosixFileLock* my_lock = new PosixFileLock;
  386. my_lock->fd_ = fd;
  387. my_lock->name_ = fname;
  388. *lock = my_lock;
  389. }
  390. return result;
  391. }
  392. virtual Status UnlockFile(FileLock* lock) {
  393. PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
  394. Status result;
  395. if (LockOrUnlock(my_lock->fd_, false) == -1) {
  396. result = IOError("unlock", errno);
  397. }
  398. locks_.Remove(my_lock->name_);
  399. close(my_lock->fd_);
  400. delete my_lock;
  401. return result;
  402. }
  403. virtual void Schedule(void (*function)(void*), void* arg);
  404. virtual void StartThread(void (*function)(void* arg), void* arg);
  405. virtual Status GetTestDirectory(std::string* result) {
  406. const char* env = getenv("TEST_TMPDIR");
  407. if (env && env[0] != '\0') {
  408. *result = env;
  409. } else {
  410. char buf[100];
  411. snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
  412. *result = buf;
  413. }
  414. // Directory may already exist
  415. CreateDir(*result);
  416. return Status::OK();
  417. }
  418. static uint64_t gettid() {
  419. pthread_t tid = pthread_self();
  420. uint64_t thread_id = 0;
  421. memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
  422. return thread_id;
  423. }
  424. virtual Status NewLogger(const std::string& fname, Logger** result) {
  425. FILE* f = fopen(fname.c_str(), "w");
  426. if (f == NULL) {
  427. *result = NULL;
  428. return IOError(fname, errno);
  429. } else {
  430. *result = new PosixLogger(f, &PosixEnv::gettid);
  431. return Status::OK();
  432. }
  433. }
  434. virtual uint64_t NowMicros() {
  435. struct timeval tv;
  436. gettimeofday(&tv, NULL);
  437. return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
  438. }
  439. virtual void SleepForMicroseconds(int micros) {
  440. usleep(micros);
  441. }
  442. private:
  443. void PthreadCall(const char* label, int result) {
  444. if (result != 0) {
  445. fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
  446. abort();
  447. }
  448. }
  449. // BGThread() is the body of the background thread
  450. void BGThread();
  451. static void* BGThreadWrapper(void* arg) {
  452. reinterpret_cast<PosixEnv*>(arg)->BGThread();
  453. return NULL;
  454. }
  455. pthread_mutex_t mu_;
  456. pthread_cond_t bgsignal_;
  457. pthread_t bgthread_;
  458. bool started_bgthread_;
  459. // Entry per Schedule() call
  460. struct BGItem { void* arg; void (*function)(void*); };
  461. typedef std::deque<BGItem> BGQueue;
  462. BGQueue queue_;
  463. PosixLockTable locks_;
  464. MmapLimiter mmap_limit_;
  465. };
  466. PosixEnv::PosixEnv() : started_bgthread_(false) {
  467. PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
  468. PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
  469. }
  470. void PosixEnv::Schedule(void (*function)(void*), void* arg) {
  471. PthreadCall("lock", pthread_mutex_lock(&mu_));
  472. // Start background thread if necessary
  473. if (!started_bgthread_) {
  474. started_bgthread_ = true;
  475. PthreadCall(
  476. "create thread",
  477. pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
  478. }
  479. // If the queue is currently empty, the background thread may currently be
  480. // waiting.
  481. if (queue_.empty()) {
  482. PthreadCall("signal", pthread_cond_signal(&bgsignal_));
  483. }
  484. // Add to priority queue
  485. queue_.push_back(BGItem());
  486. queue_.back().function = function;
  487. queue_.back().arg = arg;
  488. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  489. }
  490. void PosixEnv::BGThread() {
  491. while (true) {
  492. // Wait until there is an item that is ready to run
  493. PthreadCall("lock", pthread_mutex_lock(&mu_));
  494. while (queue_.empty()) {
  495. PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
  496. }
  497. void (*function)(void*) = queue_.front().function;
  498. void* arg = queue_.front().arg;
  499. queue_.pop_front();
  500. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  501. (*function)(arg);
  502. }
  503. }
  504. namespace {
  505. struct StartThreadState {
  506. void (*user_function)(void*);
  507. void* arg;
  508. };
  509. }
  510. static void* StartThreadWrapper(void* arg) {
  511. StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
  512. state->user_function(state->arg);
  513. delete state;
  514. return NULL;
  515. }
  516. void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
  517. pthread_t t;
  518. StartThreadState* state = new StartThreadState;
  519. state->user_function = function;
  520. state->arg = arg;
  521. PthreadCall("start thread",
  522. pthread_create(&t, NULL, &StartThreadWrapper, state));
  523. }
  524. } // namespace
  525. static pthread_once_t once = PTHREAD_ONCE_INIT;
  526. static Env* default_env;
  527. static void InitDefaultEnv() { default_env = new PosixEnv; }
  528. Env* Env::Default() {
  529. pthread_once(&once, InitDefaultEnv);
  530. return default_env;
  531. }
  532. } // namespace leveldb