| 36 | } |
| 37 | |
| 38 | bool Disk::LoadStorage(std::function<void (int64_t, Disk*, BlockMeta)> callback) { |
| 39 | MutexLock lock(&mu_); |
| 40 | int64_t start_load_time = common::timer::get_micros(); |
| 41 | leveldb::Options options; |
| 42 | options.create_if_missing = true; |
| 43 | leveldb::Status s = leveldb::DB::Open(options, path_ + "meta/", &metadb_); |
| 44 | if (!s.ok()) { |
| 45 | LOG(WARNING, "Load blocks fail: %s", s.ToString().c_str()); |
| 46 | return false; |
| 47 | } |
| 48 | |
| 49 | std::string version_key(8, '\0'); |
| 50 | version_key.append("version"); |
| 51 | std::string version_str; |
| 52 | s = metadb_->Get(leveldb::ReadOptions(), version_key, &version_str); |
| 53 | if (s.ok() && version_str.size() == 8) { |
| 54 | namespace_version_ = *(reinterpret_cast<int64_t*>(&version_str[0])); |
| 55 | LOG(INFO, "Load namespace %ld", namespace_version_); |
| 56 | } |
| 57 | int block_num = 0; |
| 58 | leveldb::Iterator* it = metadb_->NewIterator(leveldb::ReadOptions()); |
| 59 | for (it->Seek(version_key+'\0'); it->Valid(); it->Next()) { |
| 60 | int64_t block_id = 0; |
| 61 | if (1 != sscanf(it->key().data(), "%ld", &block_id)) { |
| 62 | LOG(WARNING, "Unknown key: %s\n", it->key().ToString().c_str()); |
| 63 | delete it; |
| 64 | return false; |
| 65 | } |
| 66 | BlockMeta meta; |
| 67 | if (!meta.ParseFromArray(it->value().data(), it->value().size())) { |
| 68 | LOG(INFO, "Parse meta for #%ld failed", block_id); |
| 69 | assert(0); // TODO: fault tolerant |
| 70 | } |
| 71 | // TODO: do not need store_path in meta any more |
| 72 | std::string file_path = meta.store_path() + Block::BuildFilePath(block_id); |
| 73 | if (meta.version() < 0) { |
| 74 | LOG(INFO, "Incomplete block #%ld V%ld %ld, drop it", |
| 75 | block_id, meta.version(), meta.block_size()); |
| 76 | metadb_->Delete(leveldb::WriteOptions(), it->key()); |
| 77 | remove(file_path.c_str()); |
| 78 | continue; |
| 79 | } else { |
| 80 | struct stat st; |
| 81 | if (stat(file_path.c_str(), &st) || |
| 82 | st.st_size != meta.block_size() || |
| 83 | access(file_path.c_str(), R_OK)) { |
| 84 | LOG(WARNING, "Corrupted block #%ld V%ld size %ld path %s can't access: %s'", |
| 85 | block_id, meta.version(), meta.block_size(), file_path.c_str(), |
| 86 | strerror(errno)); |
| 87 | metadb_->Delete(leveldb::WriteOptions(), it->key()); |
| 88 | remove(file_path.c_str()); |
| 89 | continue; |
| 90 | } else { |
| 91 | LOG(DEBUG, "Load #%ld V%ld size %ld path %s", |
| 92 | block_id, meta.version(), meta.block_size(), file_path.c_str()); |
| 93 | } |
| 94 | } |
| 95 | callback(block_id, this, meta); |