storage.cc 2.4 KB
Newer Older
S
superjom 已提交
1
#include <glog/logging.h>
S
superjom 已提交
2
#include <fstream>
S
superjom 已提交
3 4

#include "visualdl/backend/storage/storage.h"
5
#include "visualdl/backend/utils/filesystem.h"
S
superjom 已提交
6 7 8

namespace visualdl {

9 10
const std::string StorageBase::meta_file_name = "storage.meta";

11 12 13 14 15 16 17 18 19
std::string StorageBase::meta_path() const {
  CHECK(!storage_.dir().empty()) << "storage.dir should be set first";
  return storage_.dir() + "/" + meta_file_name;
}
std::string StorageBase::tablet_path(const std::string &tag) const {
  CHECK(!storage_.dir().empty()) << "storage.dir should be set first";
  return storage_.dir() + "/" + tag;
}

20 21 22 23 24 25
storage::Tablet *MemoryStorage::NewTablet(const std::string &tag,
                                          int num_samples) {
  auto it = tablets_.find(tag);
  if (it == tablets_.end()) {
    // create new tablet
    tablets_[tag] = storage::Tablet();
S
superjom 已提交
26
    tablets_[tag].set_tag(tag);
27 28 29 30 31 32 33 34 35 36 37 38 39
    *storage_.add_tags() = tag;
  } else {
    return &it->second;
  }
  return &tablets_[tag];
}

storage::Tablet *MemoryStorage::tablet(const std::string &tag) {
  auto it = tablets_.find(tag);
  CHECK(it != tablets_.end()) << "tablet tagged as " << tag << " not exists";
  return &it->second;
}

40
// TODO add some checksum to avoid unnecessary saving
41
void MemoryStorage::PersistToDisk() const {
42 43 44 45
  LOG(INFO) << "inside dir " << storage_.dir() << " "
            << (!storage_.dir().empty());
  CHECK(!storage_.dir().empty()) << "storage's dir should be set first";
  LOG(INFO) << "after check dir";
S
superjom 已提交
46 47 48
  VLOG(3) << "persist storage to disk path " << storage_.dir();
  // make a directory if not exist
  fs::TryMkdir(storage_.dir());
49
  // write storage out
50
  fs::SerializeToFile(storage_, meta_path());
51 52 53 54
  // write all the tablets
  for (auto tag : storage_.tags()) {
    auto it = tablets_.find(tag);
    CHECK(it != tablets_.end());
55
    fs::SerializeToFile(it->second, tablet_path(tag));
56 57 58
  }
}

59
// TODO add some checksum to avoid unnecessary loading
60
void MemoryStorage::LoadFromDisk(const std::string &dir) {
S
superjom 已提交
61 62
  VLOG(3) << "load storage from disk path " << dir;
  CHECK(!dir.empty()) << "dir is empty";
63
  storage_.set_dir(dir);
64
  // load storage
65 66
  CHECK(fs::DeSerializeFromFile(&storage_, meta_path()))
      << "parse from " << meta_path() << " failed";
67 68

  // load all the tablets
S
superjom 已提交
69
  for (int i = 0; i < storage_.tags_size(); i++) {
70 71
    auto tag = storage_.tags(i);
    CHECK(fs::DeSerializeFromFile(&tablets_[tag], tablet_path(tag)));
S
superjom 已提交
72 73 74
  }
}

S
superjom 已提交
75
}  // namespace visualdl