Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
#include <cstdio>
#include <sstream>

#include "Alignment/Geners/interface/MultiFileArchive.hh"

#include "Alignment/Geners/interface/ContiguousCatalog.hh"
#include "Alignment/Geners/interface/IOException.hh"
#include "Alignment/Geners/interface/WriteOnlyCatalog.hh"
#include "Alignment/Geners/interface/streamposIO.hh"
#include "Alignment/Geners/interface/uriUtils.hh"

namespace gs {
  MultiFileArchive::MultiFileArchive(const char *basename,
                                     const char *mode,
                                     const char *ann,
                                     const unsigned typicalFileSizeInMB,
                                     const unsigned dataFileBufferSize,
                                     const unsigned catalogFileBufferSize)
      : BinaryArchiveBase(basename, mode),
        filebuf_(nullptr),
        readbuf_(nullptr),
        catabuf_(nullptr),
        annotation_(ann ? std::string(ann) : std::string("")),
        catalogFileName_(AbsArchive::name() + ".gsbmf"),  // binary metafile
        writeFileURI_("/ / / / / / /\\ \\ \\ \\"),
        readFileURI_(writeFileURI_),
        lastpos_(0),
        jumppos_(0),
        maxpos_(std::streamoff(1048576LL * typicalFileSizeInMB)),
        writeFileNumber_(0),
        catalogMergeLevel_(1),
        annotationsMerged_(false),
        streamFlushed_(true) {
    if (!modeValid())
      return;

    try {
      // Get a new buffer for the output stream
      if (dataFileBufferSize)
        filebuf_ = new char[dataFileBufferSize];
      writeStream_.rdbuf()->pubsetbuf(filebuf_, dataFileBufferSize);

      // Get a new buffer for the input stream
      if (dataFileBufferSize)
        readbuf_ = new char[dataFileBufferSize];
      separateReadStream_.rdbuf()->pubsetbuf(readbuf_, dataFileBufferSize);

      // Get a new buffer for the catalog and open the catalog stream.
      // We may have to rewrite the complete catalog, so remove the flag
      // std::ios_base::app from the opening mode.
      if (catalogFileBufferSize)
        catabuf_ = new char[catalogFileBufferSize];
      catStream_.rdbuf()->pubsetbuf(catabuf_, catalogFileBufferSize);
      catStream_.open(catalogFileName_.c_str(), openmode() & ~std::ios_base::app);
      if (!catStream_.is_open())
        throw IOOpeningFailure("gs::MultiFileArchive constructor", catalogFileName_);

      // Can we use a write-only catalog?
      if (openmode() & std::ios_base::in) {
        // Reading is allowed. Have to use in-memory catalog.
        // If the file data already exists, get the catalog in.
        if (isEmptyFile(catStream_))
          setCatalog(new ContiguousCatalog());
        else
          readCatalog<ContiguousCatalog>();
      } else {
        // Yes, we can use a write-only catalog.
        // Is the catalog file empty? If so, write out
        // the stuff needed at the beginning of the file.
        // If not, assume that the necessary stuff is
        // already there. Note that in this case we will
        // not be able to add the annotation.
        if (isEmptyFile(catStream_)) {
          setCatalog(new WriteOnlyCatalog(catStream_));
          writeCatalog();
        } else {
          catStream_.close();
          catStream_.clear();
          catStream_.open(catalogFileName_.c_str(), openmode() | std::ios_base::in);
          if (!catStream_.is_open())
            throw IOOpeningFailure("gs::MultiFileArchive constructor", catalogFileName_);
          readCatalog<WriteOnlyCatalog>();
          catStream_.seekp(0, std::ios_base::end);
        }
      }

      // Open the write stream
      if (openmode() & std::ios_base::out) {
        setupWriteStream();
        const std::streampos pos1 = writeStream_.tellp();
        if (maxpos_ < pos1)
          maxpos_ = pos1;
      }
    } catch (std::exception &e) {
      setCatalog(nullptr);
      releaseBuffers();
      errorStream() << e.what();
    }
  }

  void MultiFileArchive::releaseBuffers() {
    if (writeStream_.is_open())
      writeStream_.close();
    if (separateReadStream_.is_open())
      separateReadStream_.close();
    if (catStream_.is_open())
      catStream_.close();
    catStream_.rdbuf()->pubsetbuf(nullptr, 0);
    writeStream_.rdbuf()->pubsetbuf(nullptr, 0);
    separateReadStream_.rdbuf()->pubsetbuf(nullptr, 0);
    delete[] catabuf_;
    catabuf_ = nullptr;
    delete[] readbuf_;
    readbuf_ = nullptr;
    delete[] filebuf_;
    filebuf_ = nullptr;
  }

  MultiFileArchive::~MultiFileArchive() {
    flush();
    releaseBuffers();
  }

  void MultiFileArchive::writeCatalog() {
    if (isOpen()) {
      if (!annotationsMerged_) {
        if (!annotation_.empty())
          catalogAnnotations_.push_back(annotation_);
        annotationsMerged_ = true;
      }
      const unsigned compress = static_cast<unsigned>(compressionMode());
      if (!writeBinaryCatalog(catStream_, compress, catalogMergeLevel_, catalogAnnotations_, *catalog())) {
        std::ostringstream os;
        os << "In MultiFileArchive::writeCatalog: "
           << "failed to write catalog data to file " << catalogFileName_;
        throw IOWriteFailure(os.str());
      }
    }
  }

  void MultiFileArchive::openWriteStream() {
    assert(openmode() & std::ios_base::out);
    assert(!writeStream_.is_open());
    {
      std::ostringstream os;
      os << AbsArchive::name() << '.' << writeFileNumber_ << ".gsbd";
      writeFileName_ = os.str();
    }
    writeFileURI_ = localFileURI(writeFileName_.c_str());
    openDataFile(writeStream_, writeFileName_.c_str());
  }

  std::ostream &MultiFileArchive::plainOutputStream() {
    if (isOpen()) {
      assert(openmode() & std::ios_base::out);
      if (writeStream_.is_open()) {
        writeStream_.seekp(0, std::ios_base::end);
        lastpos_ = writeStream_.tellp();
        if (lastpos_ > maxpos_) {
          writeStream_.close();
          // Don't have to clear. "openDataFile" will do it.
          // writeStream_.clear();
          ++writeFileNumber_;
        } else if (injectMetadata()) {
          jumppos_ = lastpos_;
          std::streampos catpos(0);
          write_pod(writeStream_, catpos);
          lastpos_ = writeStream_.tellp();
        }
      }
      if (!writeStream_.is_open()) {
        openWriteStream();
        writeStream_.seekp(0, std::ios_base::end);
        if (injectMetadata()) {
          jumppos_ = writeStream_.tellp();
          std::streampos catpos(0);
          write_pod(writeStream_, catpos);
        }
        lastpos_ = writeStream_.tellp();
      }
      streamFlushed_ = false;
    }
    return writeStream_;
  }

  void MultiFileArchive::flush() {
    if (isOpen()) {
      if (!streamFlushed_) {
        writeStream_.flush();
        streamFlushed_ = true;
      }

      if (openmode() & std::ios_base::out) {
        if (dynamic_cast<WriteOnlyCatalog *>(catalog()) == nullptr)
          writeCatalog();
        catStream_.flush();
      }
    }
  }

  void MultiFileArchive::setupWriteStream() {
    if (openmode() & std::ios_base::trunc) {
      bool removed = true;
      for (unsigned i = 0; removed; ++i) {
        std::ostringstream os;
        os << AbsArchive::name() << '.' << i << ".gsbd";
        std::string fname = os.str();
        removed = std::remove(fname.c_str()) == 0;
      }
      writeFileNumber_ = 0;
    } else {
      unsigned long firstNonExistent = 0;
      for (;; ++firstNonExistent) {
        std::ostringstream os;
        os << AbsArchive::name() << '.' << firstNonExistent << ".gsbd";
        std::string fname = os.str();
        std::ifstream f(fname.c_str());
        if (!f)
          break;
      }
      writeFileNumber_ = firstNonExistent ? firstNonExistent - 1UL : 0UL;
    }
    openWriteStream();
  }

  std::istream &MultiFileArchive::plainInputStream(const unsigned long long id,
                                                   unsigned *compressionCode,
                                                   unsigned long long *length) {
    std::fstream *readStream = &writeStream_;
    if (isOpen()) {
      assert(openmode() & std::ios_base::in);
      if (!id)
        throw gs::IOInvalidArgument("In gs::MultiFileArchive::plainInputStream: invalid item id");

      // If we have a write stream, and if the archive
      // has one file only, we should be able to retrieve
      // stream position quickly
      std::streampos pos(0);
      if ((openmode() & std::ios_base::out) && writeFileNumber_ == 0UL) {
        if (!catalog()->retrieveStreampos(id, compressionCode, length, &pos)) {
          std::ostringstream os;
          os << "In gs::MultiFileArchive::plainInputStream: "
             << "failed to locate item with id " << id << "in the catalog stored in file " << catalogFileName_;
          throw gs::IOInvalidArgument(os.str());
        }
      } else {
        // Here, we have to do a full catalog search
        std::shared_ptr<const CatalogEntry> sptr = catalog()->retrieveEntry(id);
        const CatalogEntry *pe = sptr.get();
        if (!pe) {
          std::ostringstream os;
          os << "In gs::MultiFileArchive::plainInputStream: "
             << "failed to locate item with id " << id << "in the catalog stored in file " << catalogFileName_;
          throw gs::IOInvalidArgument(os.str());
        }
        pos = pe->location().streamPosition();
        if (pe->location().URI() != writeFileURI_) {
          updateReadStream(pe->location().URI());
          readStream = &separateReadStream_;
        }
        *compressionCode = pe->compressionCode();
        *length = pe->itemLength();
      }

      // Flush the write stream if it will be used for reading
      if (readStream == &writeStream_) {
        assert(writeStream_.is_open());
        if (!streamFlushed_) {
          writeStream_.flush();
          streamFlushed_ = true;
        }
      }

      readStream->seekg(pos);
    }
    return *readStream;
  }

  void MultiFileArchive::updateReadStream(const std::string &uri) {
    if (uri == readFileURI_)
      return;

    assert(openmode() & std::ios_base::in);
    if (separateReadStream_.is_open()) {
      separateReadStream_.close();
      separateReadStream_.clear();
    }

    // We need to get the name of the local file from the URI.
    // We will assume that it belongs to the archive we are
    // working with right now.
    readFileName_ = joinDir1WithName2(AbsArchive::name().c_str(), uri.c_str());
    separateReadStream_.open(readFileName_.c_str(), std::ios_base::binary | std::ios_base::in);
    if (!separateReadStream_.is_open())
      throw IOOpeningFailure("gs::MultiFileArchive::updateReadStream", readFileName_);
    readFileURI_ = uri;
  }

  unsigned long long MultiFileArchive::addToCatalog(const AbsRecord &record,
                                                    const unsigned compressionCode,
                                                    const unsigned long long itemLength) {
    unsigned long long id = 0;
    if (isOpen()) {
      id = catalog()->makeEntry(record, compressionCode, itemLength, ItemLocation(lastpos_, writeFileURI_.c_str()));
      if (id && injectMetadata()) {
        const CatalogEntry *entry = catalog()->lastEntryMade();
        assert(entry);
        writeStream_.seekp(0, std::ios_base::end);
        std::streampos now = writeStream_.tellp();
        if (entry->write(writeStream_)) {
          writeStream_.seekp(jumppos_);
          write_pod(writeStream_, now);
          writeStream_.seekp(0, std::ios_base::end);
        } else
          id = 0;
      }
    }
    return id;
  }
}  // namespace gs