小组成员:姚凯文(kevinyao0901),姜嘉琪
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

506 linhas
18 KiB

há 3 semanas
há 3 semanas
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)
há 10 anos
há 3 semanas
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)
há 10 anos
  1. # LevelDB TTL 实验报告
  2. > StuName:姚凯文
  3. >
  4. > StuID:10224507041
  5. ## 实验背景及要求:
  6. **TTL(Time To Live)**,即生存时间,是指数据在存储系统中的有效期。设置TTL可以使得过期的数据自动失效,减少存储空间占用,提高系统性能。
  7. **为什么需要TTL功能:**
  8. - **数据自动过期**:无需手动删除过期数据,简化数据管理。
  9. - **节省存储空间**:定期清理无效数据,优化资源利用。
  10. - **提高性能**:减少无效数据的干扰,提升读写效率。
  11. **要求:**
  12. - 在LevelDB中实现键值对的TTL功能,使得过期的数据在**读取时自动失效**,并在适当的时候**被合并清理**。
  13. - 修改LevelDB的源码,实现对TTL的支持,包括数据的写入、读取和过期数据的清理。
  14. - 编写测试用例,验证TTL功能的正确性和稳定性。
  15. ## 设计思路
  16. 在本次实验中,为了给 LevelDB 增加 TTL(Time-to-Live)功能,我的设计思路主要围绕以下几个方面:
  17. 1. **TTL 数据存储设计**:通过在每个 key-value 对中引入过期时间字段,使每条数据都能记录其有效期。为了实现这一点,需要在数据写入时自动附加 TTL 值,并在读取数据时检查该 key 是否过期。设计中决定将 TTL 时间戳和数据一起存储,使其在写入或读取时简单易行。
  18. 2. **过期数据的判断与清理**:在数据查询过程中加入检查机制,确保返回的数据都是未过期的。特别是在 `DBImpl::Get`、`MemTable::Get` 等方法中加入过期判断逻辑。对于过期的数据,在读取时会返回“未找到”状态。在定期清理方面,手动触发合并和删除机制,通过手动调用 `CompactRange` 来清理过期数据,以避免占用存储空间。
  19. 3. **手动合并策略**:为了在特定时间点清理过期数据,本次实验中禁用了 LevelDB 的自动合并机制。在所有数据写入完成后,通过手动调用 `db->CompactRange(nullptr, nullptr);` 触发合并,以删除过期的数据文件。这样设计的目的是为确保在批量写入后清理过期数据,减少额外开销。
  20. 计划在以上设计的基础上实现levelDB的TTL 功能,使得在 LevelDB 中可以较为高效地处理过期数据,并且在性能和存储空间之间取得平衡。
  21. ## 实现过程:
  22. 1. **数据格式调整**:为每条数据附加过期时间戳,将时间戳和实际数据一起存储在 value 中。
  23. - 新增 `AppendExpirationTime` 函数:将 TTL 过期时间戳作为小端序添加到 value 的前部。
  24. - 新增 `ParseExpirationTime` 函数:解析出附加在 value 前部的过期时间戳。
  25. - 新增 `ParseActualValue` 函数:提取并返回去掉过期时间戳的实际数据值。
  26. ```
  27. //TTL ToDo : add func for TTL Put
  28. void AppendExpirationTime(std::string* value, uint64_t expiration_time) {
  29. // 直接将小端序的过期时间戳(64位整数)附加到值的前面
  30. value->append(reinterpret_cast<const char*>(&expiration_time), sizeof(expiration_time));
  31. }
  32. uint64_t GetCurrentTime() {
  33. // 返回当前的Unix时间戳
  34. return static_cast<uint64_t>(time(nullptr));
  35. }
  36. // 解析过期时间戳
  37. uint64_t ParseExpirationTime(const std::string& value) {
  38. // 假设过期时间戳在值的前 8 字节
  39. assert(value.size() >= sizeof(uint64_t));
  40. uint64_t expiration_time;
  41. memcpy(&expiration_time, value.data(), sizeof(uint64_t));
  42. return expiration_time; // 直接返回小端序的值
  43. }
  44. // 解析出实际的值(去掉前面的过期时间戳部分)
  45. std::string ParseActualValue(const std::string& value) {
  46. // 去掉前 8 字节(存储过期时间戳),返回实际值
  47. return value.substr(sizeof(uint64_t));
  48. }
  49. //finish modify
  50. ```
  51. 2. **支持 TTL 的 `Put` 方法**:扩展 `DBImpl::Put``DB::Put` 方法,使其支持指定 TTL。
  52. - 计算当前时间加上 TTL 作为到期时间。
  53. - 将到期时间添加到 value 前部,然后将完整的键值对写入数据库。
  54. ```
  55. // TTL ToDo: add DBImpl for Put
  56. // 新增支持TTL的Put方法
  57. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val, uint64_t ttl) {
  58. return DB::Put(o, key, val, ttl);
  59. }
  60. //TTL ToDo: add a func for TTL Put
  61. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value, uint64_t ttl) {
  62. // 获取当前时间并计算过期时间戳
  63. uint64_t expiration_time = GetCurrentTime() + ttl;
  64. // 将过期时间戳和值一起存储(假设值前面附加过期时间戳)
  65. std::string new_value;
  66. AppendExpirationTime(&new_value, expiration_time);
  67. new_value.append(value.data(), value.size());
  68. // 构造 WriteBatch,并将键值对加入到批处理中
  69. WriteBatch batch;
  70. batch.Put(key, new_value);
  71. // 执行写操作
  72. return Write(opt, &batch);
  73. }
  74. //finish modify
  75. ```
  76. 3. **数据清理策略**:在合并过程中清理过期数据。
  77. - 修改 `Status DBImpl::DoCompactionWork(CompactionState* compact)`:在合并过程中检查每个键的过期时间,若已过期则将其标记为 `drop` 丢弃,不再写入下一层级。
  78. - 添加过期键值对的计数器 `dropped_keys_count` 以跟踪被丢弃的条目数量。
  79. ```
  80. Status DBImpl::DoCompactionWork(CompactionState* compact){
  81. //...
  82. // TTL ToDo: add expiration time check
  83. // 检查是否为目标键
  84. if (key == target_key) {
  85. // 输出调试信息
  86. Log(options_.info_log, "Found target key during compaction: %s\n", key.ToString().c_str());
  87. }
  88. Slice value = input->value();
  89. if (value.size() >= sizeof(uint64_t)) {
  90. const char* ptr = value.data();
  91. uint64_t expiration_time = DecodeFixed64(ptr);
  92. uint64_t current_time = env_->NowMicros() / 1000000;
  93. if (current_time > expiration_time) {
  94. drop = true; // 过期的键值对,标记为丢弃
  95. dropped_keys_count ++; // 初始化计数器
  96. }else{
  97. bool flag = current_time > expiration_time;
  98. }
  99. }else{
  100. bool bs = value.size() >= sizeof(uint64_t);
  101. }
  102. //...
  103. }
  104. ```
  105. 4. **数据读取时的 TTL 检查**:扩展 `DBImpl::Get`,在读取时判断数据是否过期。
  106. - 对获取到的 value 调用 `ParseExpirationTime` 提取出过期时间。
  107. - 若当前时间已超过过期时间,则返回 `NotFound`,否则解析实际数据并返回。
  108. ```
  109. Status DBImpl::Get(const ReadOptions& options, const Slice& key,
  110. std::string* value) {
  111. //...
  112. // TTL ToDo : add check for TTL
  113. // 如果从 memtable、imm 或 sstable 获取到了数据,则需要检查TTL
  114. if (s.ok()) {
  115. // 从 value 中解析出过期时间戳(假设值存储格式为:[过期时间戳][实际值])
  116. uint64_t expiration_time = ParseExpirationTime(*value);
  117. uint64_t current_time = GetCurrentTime();
  118. // 如果当前时间已经超过过期时间,则认为数据过期,返回 NotFound
  119. if (current_time >= expiration_time) {
  120. s = Status::NotFound(Slice());
  121. } else {
  122. // 数据未过期,解析出实际的值
  123. *value = ParseActualValue(*value);
  124. }
  125. }
  126. // //finish modify//...
  127. }
  128. ```
  129. **所有修改的相关代码均标有`TTL ToDo`标签**,方便查看这样就实现了目标设计,使当前LevelDB 可以支持 TTL 功能,即能够在指定时间后自动删除过期的数据。完成了实验要求。
  130. ## 相关测试:
  131. 在原先测试脚本的基础上,为了更好的测试目标TTL设计,我在原先脚本的基础上进行了部分修改,包括但不限于修改随机种子,即使关闭数据库,添加调试信息等
  132. ```
  133. #include "gtest/gtest.h"
  134. #include "leveldb/env.h"
  135. #include "leveldb/db.h"
  136. #include <unordered_set>
  137. using namespace leveldb;
  138. constexpr int value_size = 2048;
  139. constexpr int data_size = 128 << 20;
  140. //--------------------------------------------------------------
  141. void PrintAllKeys(DB *db) {
  142. // 创建一个读选项对象
  143. ReadOptions readOptions;
  144. int LeftKeyCount = 0;
  145. // 创建迭代器
  146. std::unique_ptr<Iterator> it(db->NewIterator(readOptions));
  147. int cnt = 20;
  148. // 遍历所有键
  149. for (it->SeekToFirst(); it->Valid()&&cnt; it->Next()) {
  150. std::string key = it->key().ToString();
  151. std::string value = it->value().ToString();
  152. std::cout << "Key: " << key << std::endl;
  153. LeftKeyCount++;
  154. cnt--;
  155. }
  156. // 检查迭代器的有效性
  157. if (!it->status().ok()) {
  158. std::cerr << "Error iterating through keys: " << it->status().ToString() << std::endl;
  159. }
  160. std::cerr << "Key hasn't been deleted: " << LeftKeyCount << std::endl;
  161. }
  162. //------------------------------------------------------------------
  163. Status OpenDB(std::string dbName, DB **db) {
  164. Options options;
  165. options.create_if_missing = true;
  166. return DB::Open(options, dbName, db);
  167. }
  168. void InsertData(DB *db, uint64_t ttl/* second */) {
  169. WriteOptions writeOptions;
  170. int key_num = data_size / value_size;
  171. srand(42);
  172. // 用于存储成功写入的唯一键
  173. std::unordered_set<std::string> unique_keys;
  174. for (int i = 0; i < key_num; i++) {
  175. std::string key;
  176. do {
  177. int key_ = rand() % key_num + 1;
  178. key = std::to_string(key_);
  179. } while (unique_keys.find(key) != unique_keys.end()); // 检查是否已存在
  180. std::string value(value_size, 'a');
  181. // 判断 key 是否在范围内
  182. if (key >= "-" && key < "A") {
  183. //std::cout << "Key: " << key << " is within the range (-, A)" << std::endl;
  184. } else {
  185. std::cout << "Key: " << key << " is outside the range (-, A)" << std::endl;
  186. return;
  187. }
  188. Status status = db->Put(writeOptions, key, value, ttl);
  189. if (!status.ok()) {
  190. // 输出失败的状态信息并退出循环
  191. std::cerr << "Failed to write key: " << key
  192. << ", Status: " << status.ToString() << std::endl;
  193. } else {
  194. unique_keys.insert(key); // 插入集合中,如果已经存在则不会重复插入
  195. }
  196. }
  197. Iterator* iter = db->NewIterator(ReadOptions());
  198. iter->SeekToFirst();
  199. std::cout << "Data base First key: " << iter->key().ToString() << std::endl;
  200. iter->SeekToLast();
  201. std::cout << "Data base last key: " << iter->key().ToString() << std::endl;
  202. delete iter;
  203. // 打印成功写入的唯一键的数量
  204. std::cout << "Total unique keys successfully written: " << unique_keys.size() << std::endl;
  205. }
  206. void GetData(DB *db, int size = (1 << 30)) {
  207. ReadOptions readOptions;
  208. int key_num = data_size / value_size;
  209. // 点查
  210. srand(42);
  211. for (int i = 0; i < 100; i++) {
  212. int key_ = rand() % key_num+1;
  213. std::string key = std::to_string(key_);
  214. std::string value;
  215. db->Get(readOptions, key, &value);
  216. }
  217. Iterator* iter = db->NewIterator(ReadOptions());
  218. iter->SeekToFirst();
  219. std::cout << "Data base First key: " << iter->key().ToString() << std::endl;
  220. int cnt = 0;
  221. while (iter->Valid())
  222. {
  223. cnt++;
  224. iter->Next();
  225. }
  226. std::cout << "Total key cnt: " << cnt << "\n";
  227. delete iter;
  228. }
  229. TEST(TestTTL, ReadTTL) {
  230. DB *db;
  231. if(OpenDB("testdb", &db).ok() == false) {
  232. std::cerr << "open db failed" << std::endl;
  233. abort();
  234. }
  235. uint64_t ttl = 20;
  236. InsertData(db, ttl);
  237. ReadOptions readOptions;
  238. Status status;
  239. int key_num = data_size / value_size;
  240. srand(42);
  241. for (int i = 0; i < 100; i++) {
  242. int key_ = rand() % key_num+1;
  243. std::string key = std::to_string(key_);
  244. std::string value;
  245. status = db->Get(readOptions, key, &value);
  246. // 检查 status 并打印出失败的状态信息
  247. if (!status.ok()) {
  248. std::cerr << "Key: " << key << ", Status: " << status.ToString() << std::endl;
  249. }
  250. ASSERT_TRUE(status.ok());
  251. }
  252. Env::Default()->SleepForMicroseconds(ttl * 1000000);
  253. srand(42);
  254. for (int i = 0; i < 100; i++) {
  255. int key_ = rand() % key_num+1;
  256. std::string key = std::to_string(key_);
  257. std::string value;
  258. status = db->Get(readOptions, key, &value);
  259. // 检查 status 并打印出失败的状态信息
  260. if (status.ok()) {
  261. std::cerr << "Key: " << key << ", Status: " << status.ToString() << std::endl;
  262. }
  263. ASSERT_FALSE(status.ok());
  264. }
  265. delete db;
  266. }
  267. TEST(TestTTL, CompactionTTL) {
  268. DB *db;
  269. leveldb::Options options;
  270. // options.write_buffer_size = 1024*1024*1024;
  271. // options.max_file_size = 1024*1024*1024;
  272. leveldb::DestroyDB("testdb", options);
  273. if(OpenDB("testdb", &db).ok() == false) {
  274. std::cerr << "open db failed" << std::endl;
  275. abort();
  276. }
  277. uint64_t ttl = 20;
  278. leveldb::Range ranges[1];
  279. ranges[0] = leveldb::Range("-", "A");
  280. uint64_t sizes[1];
  281. db->GetApproximateSizes(ranges, 1, sizes);
  282. ASSERT_EQ(sizes[0], 0);
  283. InsertData(db, ttl);
  284. //leveldb::Range ranges[1];
  285. ranges[0] = leveldb::Range("-", "A");
  286. //uint64_t sizes[1];
  287. db->GetApproximateSizes(ranges, 1, sizes);
  288. ASSERT_GT(sizes[0], 0);
  289. ttl += 10;
  290. Env::Default()->SleepForMicroseconds(ttl * 1000000);
  291. std::cout << "Start drop\n";
  292. db->CompactRange(nullptr, nullptr);
  293. ranges[0] = leveldb::Range("-", "A");
  294. db->GetApproximateSizes(ranges, 1, sizes);
  295. PrintAllKeys(db);
  296. ASSERT_EQ(sizes[0], 0);
  297. delete db;
  298. }
  299. int main(int argc, char** argv) {
  300. srand(42);
  301. // All tests currently run with the same read-only file limits.
  302. testing::InitGoogleTest(&argc, argv);
  303. return RUN_ALL_TESTS();
  304. }
  305. ```
  306. 修改后的测试脚本主要分为以下几个部分:
  307. 1. **InsertData函数**
  308. - 通过随机生成键值对并将其写入数据库,测试数据库的写入操作。
  309. - 添加一个 TTL(time-to-live)时间,并确保键值在TTL时间到期后会被删除。
  310. - `unique_keys`集合用于存储唯一键,确保写入的数据没有重复键。
  311. 2. **GetData函数**
  312. - 通过随机键读取数据,检查点查功能。
  313. - 使用迭代器统计并打印当前数据库中的总键数。
  314. 3. **PrintAllKeys函数**(调试信息):
  315. - 迭代数据库中的所有键,并打印出部分键信息。
  316. - 用于检查在过期和压缩操作后是否仍然存在未删除的键。
  317. 4. **TestTTL ReadTTL测试**
  318. - 测试数据库中的TTL功能是否正确。
  319. - 首先插入数据,然后在TTL时间到期前读取,确保数据存在。
  320. - 然后,等待TTL时间到期后再次读取数据,确保数据已经过期并被删除。
  321. 5. **TestTTL CompactionTTL测试**
  322. - 测试压缩过程中TTL数据的清理功能。
  323. - 插入数据后,利用`GetApproximateSizes`函数获取数据大小。
  324. - 等待TTL过期后,调用`CompactRange`函数手动触发压缩。
  325. - 再次使用`GetApproximateSizes`检查数据库大小,确保过期数据已被清理。
  326. 通过这个脚本,能够全面验证LevelDB的TTL功能和压缩清理机制。
  327. **运行结果截图:**
  328. ![](.\png\result.png)
  329. ## 实验中遇到的相关问题:
  330. 1.脚本中的随机种子问题:
  331. *问题描述:*
  332. 初始脚本中使用的随机生成key可能有重复,导致没有完整的65536个数据,存在重复写入,get时也随机生成的话有大概率会生成没有写入过的key从而导致abort。
  333. *解决方案:*
  334. 在与TA交流后,确认了该问题存在,在将随机种子改为统一的之后修复了这个问题。随后TA在水杉上对源码进行了修改。
  335. 2.大小端问题
  336. *问题描述*:
  337. 在存储和解析TTL时间戳时,需要确保数据在不同系统架构上能正确读取。不同架构可能使用不同的字节序(小端或大端),因此直接存储时间戳会导致在不同平台上读取错误。
  338. *解决方案:*
  339. 为了解决这个问题,我选择将小端序作为时间戳存储格式。这一选择基于以下几点:
  340. 1. **兼容性**:大多数现代硬件(包括我的实验环境)默认使用小端序,因此直接采用小端序可以避免额外的转换开销。
  341. 2. **跨平台一致性**:即使在大端系统上,通过明确指定小端序可以确保数据格式在不同平台上保持一致。
  342. 3. **简化操作**:在存储和读取TTL时间戳时,我采用了 `reinterpret_cast``memcpy` 方法直接对数据进行小端序读写,避免了复杂的转换逻辑。
  343. 3.Compaction自动合并问题
  344. *问题描述:*
  345. 手动合并可能无法保证合并所有数据,导致无法完全丢弃过期数据。leveldb的自动合并可能提前把一些数据合并为有序,而CompactRange(nullptr, nullptr)函数只会合并剩下没完全有序的数据。
  346. *解决方案:*
  347. 通过修改函数中的判断条件在决定数据向下一层的迁移方式时禁用`DBImpl::BackgroundCall()`中的`TrivialMove`方法,迫使所有数据进入`DoCompactionWork()`,并且适当调整`Option.h`中level0的大小,减少自动合并的次数,同时针对levelDB中在满足条件时将level0中文件自动迁移到level2的这类特殊优化,由于其会干扰`DBImpl::CompactRange`正常合并,所以在`DBImpl::CompactRange`中将遍历扩大一层以覆盖所有文件。
  348. ```
  349. for (int level = 0; level <= max_level_with_files; level++) {
  350. TEST_CompactRange(level, begin, end);
  351. }
  352. ```