OmniSciDB  471d68cefb
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
FileBuffer.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
24 
25 #include <future>
26 #include <map>
27 #include <thread>
28 #include <utility> // std::pair
29 
31 #include "Shared/File.h"
32 #include "Shared/checked_alloc.h"
33 
34 using namespace std;
35 
36 namespace File_Namespace {
37 
38 FileBuffer::FileBuffer(FileMgr* fm,
39  const size_t pageSize,
40  const ChunkKey& chunkKey,
41  const size_t initialSize)
42  : AbstractBuffer(fm->getDeviceId())
43  , fm_(fm)
44  , metadataPages_(METADATA_PAGE_SIZE)
45  , pageSize_(pageSize)
46  , chunkKey_(chunkKey) {
47  // Create a new FileBuffer
48  CHECK(fm_);
52  //@todo reintroduce initialSize - need to develop easy way of
53  // differentiating these pre-allocated pages from "written-to" pages
54  /*
55  if (initalSize > 0) {
56  // should expand to initialSize bytes
57  size_t initialNumPages = (initalSize + pageSize_ -1) / pageSize_;
58  int32_t epoch = fm_->epoch();
59  for (size_t pageNum = 0; pageNum < initialNumPages; ++pageNum) {
60  Page page = addNewMultiPage(epoch);
61  writeHeader(page,pageNum,epoch);
62  }
63  }
64  */
65 }
66 
68  const size_t pageSize,
69  const ChunkKey& chunkKey,
70  const SQLTypeInfo sqlType,
71  const size_t initialSize)
72  : AbstractBuffer(fm->getDeviceId(), sqlType)
73  , fm_(fm)
74  , metadataPages_(METADATA_PAGE_SIZE)
75  , pageSize_(pageSize)
76  , chunkKey_(chunkKey) {
77  CHECK(fm_);
80 }
81 
83  /* const size_t pageSize,*/ const ChunkKey& chunkKey,
84  const std::vector<HeaderInfo>::const_iterator& headerStartIt,
85  const std::vector<HeaderInfo>::const_iterator& headerEndIt)
86  : AbstractBuffer(fm->getDeviceId())
87  , fm_(fm)
88  , metadataPages_(METADATA_PAGE_SIZE)
89  , pageSize_(0)
90  , chunkKey_(chunkKey) {
91  // We are being assigned an existing FileBuffer on disk
92 
93  CHECK(fm_);
95  int32_t lastPageId = -1;
96  int32_t curPageId = 0;
97  for (auto vecIt = headerStartIt; vecIt != headerEndIt; ++vecIt) {
98  curPageId = vecIt->pageId;
99 
100  // We only want to read last metadata page
101  if (curPageId == -1) { // stats page
102  metadataPages_.push(vecIt->page, vecIt->versionEpoch);
103  } else {
104  if (curPageId != lastPageId) {
105  // protect from bad data on disk, and give diagnostics
106  if (fm->failOnReadError()) {
107  if (curPageId != lastPageId + 1) {
108  LOG(FATAL) << "Failure reading DB file " << show_chunk(chunkKey)
109  << " Current page " << curPageId << " last page " << lastPageId
110  << " epoch " << vecIt->versionEpoch;
111  }
112  }
113  if (lastPageId == -1) { // If we are on first real page
115  }
116  MultiPage multiPage(pageSize_);
117  multiPages_.push_back(multiPage);
118  lastPageId = curPageId;
119  }
120  multiPages_.back().push(vecIt->page, vecIt->versionEpoch);
121  }
122  }
123  if (curPageId == -1) { // meaning there was only a metadata page
125  }
126 }
127 
129  // need to free pages
130  // NOP
131 }
132 
133 void FileBuffer::reserve(const size_t numBytes) {
134  size_t numPagesRequested = (numBytes + pageSize_ - 1) / pageSize_;
135  size_t numCurrentPages = multiPages_.size();
136  auto epoch = getFileMgrEpoch();
137  for (size_t pageNum = numCurrentPages; pageNum < numPagesRequested; ++pageNum) {
138  Page page = addNewMultiPage(epoch);
139  writeHeader(page, pageNum, epoch);
140  }
141 }
142 
144  // 3 * sizeof(int32_t) is for headerSize, for pageId and versionEpoch
145  // sizeof(size_t) is for chunkSize
146  reservedHeaderSize_ = (chunkKey_.size() + 3) * sizeof(int32_t);
147  size_t headerMod = reservedHeaderSize_ % headerBufferOffset_;
148  if (headerMod > 0) {
150  }
151 }
152 
153 void FileBuffer::freePage(const Page& page) {
154  freePage(page, false);
155 }
156 
157 void FileBuffer::freePage(const Page& page, const bool isRolloff) {
158  FileInfo* fileInfo = fm_->getFileInfoForFileId(page.fileId);
159  fileInfo->freePage(page.pageNum, isRolloff, getFileMgrEpoch());
160 }
161 
163  size_t num_pages_freed = metadataPages_.pageVersions.size();
164  for (auto metaPageIt = metadataPages_.pageVersions.begin();
165  metaPageIt != metadataPages_.pageVersions.end();
166  ++metaPageIt) {
167  freePage(metaPageIt->page, false /* isRolloff */);
168  }
169  while (metadataPages_.pageVersions.size() > 0) {
171  }
172  return num_pages_freed;
173 }
174 
176  size_t num_pages_freed = multiPages_.size();
177  for (auto multiPageIt = multiPages_.begin(); multiPageIt != multiPages_.end();
178  ++multiPageIt) {
179  for (auto pageIt = multiPageIt->pageVersions.begin();
180  pageIt != multiPageIt->pageVersions.end();
181  ++pageIt) {
182  freePage(pageIt->page, false /* isRolloff */);
183  }
184  }
185  multiPages_.clear();
186  return num_pages_freed;
187 }
188 
190  return freeMetadataPages() + freeChunkPages();
191 }
192 
194  const int32_t targetEpoch,
195  const int32_t currentEpoch) {
196  std::vector<EpochedPage> epochedPagesToFree =
197  multiPage.freePagesBeforeEpoch(targetEpoch, currentEpoch);
198  for (const auto& epochedPageToFree : epochedPagesToFree) {
199  freePage(epochedPageToFree.page, true /* isRolloff */);
200  }
201 }
202 
203 void FileBuffer::freePagesBeforeEpoch(const int32_t targetEpoch) {
204  // This method is only safe to be called within a checkpoint, after the sync and epoch
205  // increment where a failure at any point32_t in the process would lead to a safe
206  // rollback
207  auto currentEpoch = getFileMgrEpoch();
208  CHECK_LE(targetEpoch, currentEpoch);
209  freePagesBeforeEpochForMultiPage(metadataPages_, targetEpoch, currentEpoch);
210  for (auto& multiPage : multiPages_) {
211  freePagesBeforeEpochForMultiPage(multiPage, targetEpoch, currentEpoch);
212  }
213 
214  // Check if all buffer pages can be freed
215  if (size_ == 0) {
216  size_t max_historical_buffer_size{0};
217  for (auto& epoch_page : metadataPages_.pageVersions) {
218  // Create buffer that is used to get the buffer size at the epoch version
219  FileBuffer buffer{fm_, pageSize_, chunkKey_};
220  buffer.readMetadata(epoch_page.page);
221  max_historical_buffer_size = std::max(max_historical_buffer_size, buffer.size());
222  }
223 
224  // Free all chunk pages, if none of the old chunk versions has any data
225  if (max_historical_buffer_size == 0) {
226  freeChunkPages();
227  }
228  }
229 }
230 
231 struct readThreadDS {
232  FileMgr* t_fm; // ptr to FileMgr
233  size_t t_startPage; // start page for the thread
234  size_t t_endPage; // last page for the thread
235  int8_t* t_curPtr; // pointer to the current location of the target for the thread
236  size_t t_bytesLeft; // number of bytes to be read in the thread
237  size_t t_startPageOffset; // offset - used for the first page of the buffer
238  bool t_isFirstPage; // true - for first page of the buffer, false - otherwise
239  std::vector<MultiPage> multiPages; // MultiPages of the FileBuffer passed to the thread
240 };
241 
242 static size_t readForThread(FileBuffer* fileBuffer, const readThreadDS threadDS) {
243  size_t startPage = threadDS.t_startPage; // start reading at startPage, including it
244  size_t endPage = threadDS.t_endPage; // stop reading at endPage, not including it
245  int8_t* curPtr = threadDS.t_curPtr;
246  size_t bytesLeft = threadDS.t_bytesLeft;
247  size_t totalBytesRead = 0;
248  bool isFirstPage = threadDS.t_isFirstPage;
249 
250  // Traverse the logical pages
251  for (size_t pageNum = startPage; pageNum < endPage; ++pageNum) {
252  CHECK(threadDS.multiPages[pageNum].pageSize == fileBuffer->pageSize());
253  Page page = threadDS.multiPages[pageNum].current().page;
254 
255  FileInfo* fileInfo = threadDS.t_fm->getFileInfoForFileId(page.fileId);
256  CHECK(fileInfo);
257 
258  // Read the page into the destination (dst) buffer at its
259  // current (cur) location
260  size_t bytesRead = 0;
261  if (isFirstPage) {
262  bytesRead = fileInfo->read(
263  page.pageNum * fileBuffer->pageSize() + threadDS.t_startPageOffset +
264  fileBuffer->reservedHeaderSize(),
265  min(fileBuffer->pageDataSize() - threadDS.t_startPageOffset, bytesLeft),
266  curPtr);
267  isFirstPage = false;
268  } else {
269  bytesRead = fileInfo->read(
270  page.pageNum * fileBuffer->pageSize() + fileBuffer->reservedHeaderSize(),
271  min(fileBuffer->pageDataSize(), bytesLeft),
272  curPtr);
273  }
274  curPtr += bytesRead;
275  bytesLeft -= bytesRead;
276  totalBytesRead += bytesRead;
277  }
278  CHECK(bytesLeft == 0);
279 
280  return (totalBytesRead);
281 }
282 
283 void FileBuffer::read(int8_t* const dst,
284  const size_t numBytes,
285  const size_t offset,
286  const MemoryLevel dstBufferType,
287  const int32_t deviceId) {
288  if (dstBufferType != CPU_LEVEL) {
289  LOG(FATAL) << "Unsupported Buffer type";
290  }
291 
292  // variable declarations
293  size_t startPage = offset / pageDataSize_;
294  size_t startPageOffset = offset % pageDataSize_;
295  size_t numPagesToRead =
296  (numBytes + startPageOffset + pageDataSize_ - 1) / pageDataSize_;
297  /*
298  if (startPage + numPagesToRead > multiPages_.size()) {
299  cout << "Start page: " << startPage << endl;
300  cout << "Num pages to read: " << numPagesToRead << endl;
301  cout << "Num multipages: " << multiPages_.size() << endl;
302  cout << "Offset: " << offset << endl;
303  cout << "Num bytes: " << numBytes << endl;
304  }
305  */
306 
307  CHECK(startPage + numPagesToRead <= multiPages_.size());
308 
309  size_t numPagesPerThread = 0;
310  size_t numBytesCurrent = numBytes; // total number of bytes still to be read
311  size_t bytesRead = 0; // total number of bytes already being read
312  size_t bytesLeftForThread = 0; // number of bytes to be read in the thread
313  size_t numExtraPages = 0; // extra pages to be assigned one per thread as needed
314  size_t numThreads = fm_->getNumReaderThreads();
315  std::vector<readThreadDS>
316  threadDSArr; // array of threadDS, needed to avoid racing conditions
317 
318  if (numPagesToRead > numThreads) {
319  numPagesPerThread = numPagesToRead / numThreads;
320  numExtraPages = numPagesToRead - (numThreads * numPagesPerThread);
321  } else {
322  numThreads = numPagesToRead;
323  numPagesPerThread = 1;
324  }
325 
326  /* set threadDS for the first thread */
327  readThreadDS threadDS;
328  threadDS.t_fm = fm_;
329  threadDS.t_startPage = offset / pageDataSize_;
330  if (numExtraPages > 0) {
331  threadDS.t_endPage = threadDS.t_startPage + numPagesPerThread + 1;
332  numExtraPages--;
333  } else {
334  threadDS.t_endPage = threadDS.t_startPage + numPagesPerThread;
335  }
336  threadDS.t_curPtr = dst;
337  threadDS.t_startPageOffset = offset % pageDataSize_;
338  threadDS.t_isFirstPage = true;
339 
340  bytesLeftForThread = min(((threadDS.t_endPage - threadDS.t_startPage) * pageDataSize_ -
341  threadDS.t_startPageOffset),
342  numBytesCurrent);
343  threadDS.t_bytesLeft = bytesLeftForThread;
344  threadDS.multiPages = getMultiPage();
345 
346  if (numThreads == 1) {
347  bytesRead += readForThread(this, threadDS);
348  } else {
349  std::vector<std::future<size_t>> threads;
350 
351  for (size_t i = 0; i < numThreads; i++) {
352  threadDSArr.push_back(threadDS);
353  threads.push_back(
354  std::async(std::launch::async, readForThread, this, threadDSArr[i]));
355 
356  // calculate elements of threadDS
357  threadDS.t_fm = fm_;
358  threadDS.t_isFirstPage = false;
359  threadDS.t_curPtr += bytesLeftForThread;
360  threadDS.t_startPage +=
361  threadDS.t_endPage -
362  threadDS.t_startPage; // based on # of pages read on previous iteration
363  if (numExtraPages > 0) {
364  threadDS.t_endPage = threadDS.t_startPage + numPagesPerThread + 1;
365  numExtraPages--;
366  } else {
367  threadDS.t_endPage = threadDS.t_startPage + numPagesPerThread;
368  }
369  numBytesCurrent -= bytesLeftForThread;
370  bytesLeftForThread = min(
371  ((threadDS.t_endPage - threadDS.t_startPage) * pageDataSize_), numBytesCurrent);
372  threadDS.t_bytesLeft = bytesLeftForThread;
373  threadDS.multiPages = getMultiPage();
374  }
375 
376  for (auto& p : threads) {
377  p.wait();
378  }
379  for (auto& p : threads) {
380  bytesRead += p.get();
381  }
382  }
383  CHECK(bytesRead == numBytes);
384 }
385 
387  Page& destPage,
388  const size_t numBytes,
389  const size_t offset) {
390  // FILE *srcFile = fm_->files_[srcPage.fileId]->f;
391  // FILE *destFile = fm_->files_[destPage.fileId]->f;
392  CHECK_LE(offset + numBytes, pageDataSize_);
393  FileInfo* srcFileInfo = fm_->getFileInfoForFileId(srcPage.fileId);
394  FileInfo* destFileInfo = fm_->getFileInfoForFileId(destPage.fileId);
395 
396  int8_t* buffer = reinterpret_cast<int8_t*>(checked_malloc(numBytes));
397  size_t bytesRead = srcFileInfo->read(
398  srcPage.pageNum * pageSize_ + offset + reservedHeaderSize_, numBytes, buffer);
399  CHECK(bytesRead == numBytes);
400  size_t bytesWritten = destFileInfo->write(
401  destPage.pageNum * pageSize_ + offset + reservedHeaderSize_, numBytes, buffer);
402  CHECK(bytesWritten == numBytes);
403  free(buffer);
404 }
405 
406 Page FileBuffer::addNewMultiPage(const int32_t epoch) {
407  Page page = fm_->requestFreePage(pageSize_, false);
408  MultiPage multiPage(pageSize_);
409  multiPage.push(page, epoch);
410  multiPages_.emplace_back(multiPage);
411  return page;
412 }
413 
415  const int32_t pageId,
416  const int32_t epoch,
417  const bool writeMetadata) {
418  int32_t intHeaderSize = chunkKey_.size() + 3; // does not include chunkSize
419  vector<int32_t> header(intHeaderSize);
420  // in addition to chunkkey we need size of header, pageId, version
421  header[0] =
422  (intHeaderSize - 1) * sizeof(int32_t); // don't need to include size of headerSize
423  // value - sizeof(size_t) is for chunkSize
424  std::copy(chunkKey_.begin(), chunkKey_.end(), header.begin() + 1);
425  header[intHeaderSize - 2] = pageId;
426  header[intHeaderSize - 1] = epoch;
427  FileInfo* fileInfo = fm_->getFileInfoForFileId(page.fileId);
428  size_t pageSize = writeMetadata ? METADATA_PAGE_SIZE : pageSize_;
429  fileInfo->write(
430  page.pageNum * pageSize, (intHeaderSize) * sizeof(int32_t), (int8_t*)&header[0]);
431 }
432 
433 void FileBuffer::readMetadata(const Page& page) {
434  FILE* f = fm_->getFileForFileId(page.fileId);
435  fseek(f, page.pageNum * METADATA_PAGE_SIZE + reservedHeaderSize_, SEEK_SET);
436  fread((int8_t*)&pageSize_, sizeof(size_t), 1, f);
437  fread((int8_t*)&size_, sizeof(size_t), 1, f);
438  vector<int32_t> typeData(
439  NUM_METADATA); // assumes we will encode hasEncoder, bufferType,
440  // encodingType, encodingBits all as int
441  fread((int8_t*)&(typeData[0]), sizeof(int32_t), typeData.size(), f);
442  int32_t version = typeData[0];
443  CHECK(version == METADATA_VERSION); // add backward compatibility code here
444  bool has_encoder = static_cast<bool>(typeData[1]);
445  if (has_encoder) {
446  sql_type_.set_type(static_cast<SQLTypes>(typeData[2]));
447  sql_type_.set_subtype(static_cast<SQLTypes>(typeData[3]));
448  sql_type_.set_dimension(typeData[4]);
449  sql_type_.set_scale(typeData[5]);
450  sql_type_.set_notnull(static_cast<bool>(typeData[6]));
451  sql_type_.set_compression(static_cast<EncodingType>(typeData[7]));
452  sql_type_.set_comp_param(typeData[8]);
453  sql_type_.set_size(typeData[9]);
455  encoder_->readMetadata(f);
456  }
457 }
458 
459 void FileBuffer::writeMetadata(const int32_t epoch) {
460  // Right now stats page is size_ (in bytes), bufferType, encodingType,
461  // encodingDataType, numElements
463  writeHeader(page, -1, epoch, true);
464  FILE* f = fm_->getFileForFileId(page.fileId);
465  fseek(f, page.pageNum * METADATA_PAGE_SIZE + reservedHeaderSize_, SEEK_SET);
466  fwrite((int8_t*)&pageSize_, sizeof(size_t), 1, f);
467  fwrite((int8_t*)&size_, sizeof(size_t), 1, f);
468  vector<int32_t> typeData(
469  NUM_METADATA); // assumes we will encode hasEncoder, bufferType,
470  // encodingType, encodingBits all as int32_t
471  typeData[0] = METADATA_VERSION;
472  typeData[1] = static_cast<int32_t>(hasEncoder());
473  if (hasEncoder()) {
474  typeData[2] = static_cast<int32_t>(sql_type_.get_type());
475  typeData[3] = static_cast<int32_t>(sql_type_.get_subtype());
476  typeData[4] = sql_type_.get_dimension();
477  typeData[5] = sql_type_.get_scale();
478  typeData[6] = static_cast<int32_t>(sql_type_.get_notnull());
479  typeData[7] = static_cast<int32_t>(sql_type_.get_compression());
480  typeData[8] = sql_type_.get_comp_param();
481  typeData[9] = sql_type_.get_size();
482  }
483  fwrite((int8_t*)&(typeData[0]), sizeof(int32_t), typeData.size(), f);
484  if (hasEncoder()) { // redundant
485  encoder_->writeMetadata(f);
486  }
487  metadataPages_.push(page, epoch);
488 }
489 
490 void FileBuffer::append(int8_t* src,
491  const size_t numBytes,
492  const MemoryLevel srcBufferType,
493  const int32_t deviceId) {
494  setAppended();
495 
496  size_t startPage = size_ / pageDataSize_;
497  size_t startPageOffset = size_ % pageDataSize_;
498  size_t numPagesToWrite =
499  (numBytes + startPageOffset + pageDataSize_ - 1) / pageDataSize_;
500  size_t bytesLeft = numBytes;
501  int8_t* curPtr = src; // a pointer to the current location in dst being written to
502  size_t initialNumPages = multiPages_.size();
503  size_ = size_ + numBytes;
504  auto epoch = getFileMgrEpoch();
505  for (size_t pageNum = startPage; pageNum < startPage + numPagesToWrite; ++pageNum) {
506  Page page;
507  if (pageNum >= initialNumPages) {
508  page = addNewMultiPage(epoch);
509  writeHeader(page, pageNum, epoch);
510  } else {
511  // we already have a new page at current
512  // epoch for this page - just grab this page
513  page = multiPages_[pageNum].current().page;
514  }
515  CHECK(page.fileId >= 0); // make sure page was initialized
516  FileInfo* fileInfo = fm_->getFileInfoForFileId(page.fileId);
517  size_t bytesWritten;
518  if (pageNum == startPage) {
519  bytesWritten = fileInfo->write(
520  page.pageNum * pageSize_ + startPageOffset + reservedHeaderSize_,
521  min(pageDataSize_ - startPageOffset, bytesLeft),
522  curPtr);
523  } else {
524  bytesWritten = fileInfo->write(page.pageNum * pageSize_ + reservedHeaderSize_,
525  min(pageDataSize_, bytesLeft),
526  curPtr);
527  }
528  curPtr += bytesWritten;
529  bytesLeft -= bytesWritten;
530  }
531  CHECK(bytesLeft == 0);
532 }
533 
534 void FileBuffer::write(int8_t* src,
535  const size_t numBytes,
536  const size_t offset,
537  const MemoryLevel srcBufferType,
538  const int32_t deviceId) {
539  CHECK(srcBufferType == CPU_LEVEL) << "Unsupported Buffer type";
540 
541  bool tempIsAppended = false;
542  setDirty();
543  if (offset < size_) {
544  setUpdated();
545  }
546  if (offset + numBytes > size_) {
547  tempIsAppended = true; // because is_appended_ could have already been true - to
548  // avoid rewriting header
549  setAppended();
550  size_ = offset + numBytes;
551  }
552 
553  size_t startPage = offset / pageDataSize_;
554  size_t startPageOffset = offset % pageDataSize_;
555  size_t numPagesToWrite =
556  (numBytes + startPageOffset + pageDataSize_ - 1) / pageDataSize_;
557  size_t bytesLeft = numBytes;
558  int8_t* curPtr = src; // a pointer to the current location in dst being written to
559  size_t initialNumPages = multiPages_.size();
560  auto epoch = getFileMgrEpoch();
561 
562  if (startPage >
563  initialNumPages) { // means there is a gap we need to allocate pages for
564  for (size_t pageNum = initialNumPages; pageNum < startPage; ++pageNum) {
565  Page page = addNewMultiPage(epoch);
566  writeHeader(page, pageNum, epoch);
567  }
568  }
569  for (size_t pageNum = startPage; pageNum < startPage + numPagesToWrite; ++pageNum) {
570  Page page;
571  if (pageNum >= initialNumPages) {
572  page = addNewMultiPage(epoch);
573  writeHeader(page, pageNum, epoch);
574  } else if (multiPages_[pageNum].current().epoch <
575  epoch) { // need to create new page b/c this current one lags epoch and we
576  // can't overwrite it also need to copy if we are on first or
577  // last page
578  Page lastPage = multiPages_[pageNum].current().page;
579  page = fm_->requestFreePage(pageSize_, false);
580  multiPages_[pageNum].push(page, epoch);
581  if (pageNum == startPage && startPageOffset > 0) {
582  // copyPage takes care of header offset so don't worry
583  // about it
584  copyPage(lastPage, page, startPageOffset, 0);
585  }
586  if (pageNum == (startPage + numPagesToWrite - 1) &&
587  bytesLeft > 0) { // bytesLeft should always > 0
588  copyPage(lastPage,
589  page,
590  pageDataSize_ - bytesLeft,
591  bytesLeft); // these would be empty if we're appending but we won't
592  // worry about it right now
593  }
594  writeHeader(page, pageNum, epoch);
595  } else {
596  // we already have a new page at current
597  // epoch for this page - just grab this page
598  page = multiPages_[pageNum].current().page;
599  }
600  CHECK(page.fileId >= 0); // make sure page was initialized
601  FileInfo* fileInfo = fm_->getFileInfoForFileId(page.fileId);
602  size_t bytesWritten;
603  if (pageNum == startPage) {
604  bytesWritten = fileInfo->write(
605  page.pageNum * pageSize_ + startPageOffset + reservedHeaderSize_,
606  min(pageDataSize_ - startPageOffset, bytesLeft),
607  curPtr);
608  } else {
609  bytesWritten = fileInfo->write(page.pageNum * pageSize_ + reservedHeaderSize_,
610  min(pageDataSize_, bytesLeft),
611  curPtr);
612  }
613  curPtr += bytesWritten;
614  bytesLeft -= bytesWritten;
615  if (tempIsAppended && pageNum == startPage + numPagesToWrite - 1) { // if last page
616  //@todo below can lead to undefined - we're overwriting num
617  // bytes valid at checkpoint
618  writeHeader(page, 0, multiPages_[0].current().epoch, true);
619  }
620  }
621  CHECK(bytesLeft == 0);
622 }
623 
625  auto [db_id, tb_id] = get_table_prefix(chunkKey_);
626  return fm_->epoch(db_id, tb_id);
627 }
628 
629 std::string FileBuffer::dump() const {
630  std::stringstream ss;
631  ss << "chunk_key = " << show_chunk(chunkKey_) << "\n";
632  ss << "has_encoder = " << (hasEncoder() ? "true\n" : "false\n");
633  ss << "size_ = " << size_ << "\n";
634  return ss.str();
635 }
636 
638  CHECK(metadataPages_.current().page.fileId != -1); // was initialized
641 }
642 
644  // Detect the case where a page is missing by comparing the amount of pages read
645  // with the metadata size.
646  return ((size() + pageDataSize_ - 1) / pageDataSize_ != multiPages_.size());
647 }
648 
650  size_t total_size = 0;
651  for (const auto& multi_page : multiPages_) {
652  total_size += multi_page.pageVersions.size();
653  }
654  return total_size;
655 }
656 
657 } // namespace File_Namespace
virtual std::vector< MultiPage > getMultiPage() const
Returns vector of MultiPages in the FileBuffer.
Definition: FileBuffer.h:148
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:330
void set_compression(EncodingType c)
Definition: sqltypes.h:429
void set_size(int s)
Definition: sqltypes.h:427
virtual int32_t epoch(int32_t db_id, int32_t tb_id) const
Returns current value of epoch - should be one greater than recorded at last checkpoint. Because FileMgr only contains buffers from one table we can just return the FileMgr&#39;s epoch instead of finding a table-specific epoch.
Definition: FileMgr.h:271
#define METADATA_PAGE_SIZE
Definition: FileBuffer.h:37
std::vector< int > ChunkKey
Definition: types.h:37
size_t write(const size_t offset, const size_t size, const int8_t *buf)
Definition: FileInfo.cpp:60
void freePagesBeforeEpochForMultiPage(MultiPage &multiPage, const int32_t targetEpoch, const int32_t currentEpoch)
Definition: FileBuffer.cpp:193
HOST DEVICE int get_size() const
Definition: sqltypes.h:339
virtual Page requestFreePage(size_t pagesize, const bool isMetadata)
Definition: FileMgr.cpp:851
void freePagesBeforeEpoch(const int32_t targetEpoch)
Definition: FileBuffer.cpp:203
static size_t readForThread(FileBuffer *fileBuffer, const readThreadDS threadDS)
Definition: FileBuffer.cpp:242
A logical page (Page) belongs to a file on disk.
Definition: Page.h:46
void pop()
Purges the oldest Page.
Definition: Page.h:110
#define LOG(tag)
Definition: Logger.h:203
size_t numChunkPages() const
Definition: FileBuffer.cpp:649
Page addNewMultiPage(const int32_t epoch)
Definition: FileBuffer.cpp:406
HOST DEVICE int get_scale() const
Definition: sqltypes.h:334
void writeMetadata(const int32_t epoch)
Definition: FileBuffer.cpp:459
void write(int8_t *src, const size_t numBytes, const size_t offset=0, const MemoryLevel srcMemoryLevel=CPU_LEVEL, const int32_t deviceId=-1) override
Writes the contents of source (src) into new versions of the affected logical pages.
Definition: FileBuffer.cpp:534
HOST DEVICE void set_subtype(SQLTypes st)
Definition: sqltypes.h:420
std::vector< MultiPage > multiPages_
Definition: FileBuffer.h:194
std::vector< MultiPage > multiPages
Definition: FileBuffer.cpp:239
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:329
Represents/provides access to contiguous data stored in the file system.
Definition: FileBuffer.h:58
#define CHECK_GT(x, y)
Definition: Logger.h:221
void initEncoder(const SQLTypeInfo &tmp_sql_type)
std::string show_chunk(const ChunkKey &key)
Definition: types.h:86
void freePage(int32_t pageId, const bool isRolloff, int32_t epoch)
Definition: FileInfo.cpp:178
std::deque< EpochedPage > pageVersions
Definition: Page.h:81
future< Result > async(Fn &&fn, Args &&...args)
void * checked_malloc(const size_t size)
Definition: checked_alloc.h:45
DEVICE auto copy(ARGS &&...args)
Definition: gpu_enabled.h:51
int32_t fileId
Definition: Page.h:47
size_t pageSize() const override
Returns the size in bytes of each page in the FileBuffer.
Definition: FileBuffer.h:138
void set_scale(int s)
Definition: sqltypes.h:424
std::string dump() const
Definition: FileBuffer.cpp:629
FILE * getFileForFileId(const int32_t fileId)
Returns FILE pointer associated with requested fileId.
Definition: FileMgr.cpp:964
An AbstractBuffer is a unit of data management for a data manager.
size_t pageNum
unique identifier of the owning file
Definition: Page.h:48
void append(int8_t *src, const size_t numBytes, const MemoryLevel srcMemoryLevel=CPU_LEVEL, const int32_t deviceId=-1) override
Definition: FileBuffer.cpp:490
void set_comp_param(int p)
Definition: sqltypes.h:430
string version
Definition: setup.in.py:73
void writeHeader(Page &page, const int32_t pageId, const int32_t epoch, const bool writeMetadata=false)
Write header writes header at top of page in format.
Definition: FileBuffer.cpp:414
virtual size_t reservedHeaderSize() const
Definition: FileBuffer.h:145
#define CHECK_LE(x, y)
Definition: Logger.h:220
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:337
#define NUM_METADATA
Definition: FileBuffer.h:35
void set_dimension(int d)
Definition: sqltypes.h:421
void push(const Page &page, const int epoch)
Pushes a new page with epoch value.
Definition: Page.h:102
~FileBuffer() override
Destructor.
Definition: FileBuffer.cpp:128
size_t read(const size_t offset, const size_t size, int8_t *buf)
Definition: FileInfo.cpp:66
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:331
virtual bool failOnReadError() const
True if a read error should cause a fatal error.
Definition: FileMgr.h:359
std::unique_ptr< Encoder > encoder_
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:338
FileBuffer(FileMgr *fm, const size_t pageSize, const ChunkKey &chunkKey, const size_t initialSize=0)
Constructs a FileBuffer object.
Definition: FileBuffer.cpp:38
std::pair< int, int > get_table_prefix(const ChunkKey &key)
Definition: types.h:58
void set_notnull(bool n)
Definition: sqltypes.h:426
#define CHECK(condition)
Definition: Logger.h:209
char * f
void reserve(const size_t numBytes) override
Definition: FileBuffer.cpp:133
FileInfo * getFileInfoForFileId(const int32_t fileId) const
Definition: FileMgr.h:218
std::vector< EpochedPage > freePagesBeforeEpoch(const int32_t target_epoch, const int32_t current_epoch)
Definition: Page.h:117
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:336
void read(int8_t *const dst, const size_t numBytes=0, const size_t offset=0, const MemoryLevel dstMemoryLevel=CPU_LEVEL, const int32_t deviceId=-1) override
Definition: FileBuffer.cpp:283
void readMetadata(const Page &page)
Definition: FileBuffer.cpp:433
void copyPage(Page &srcPage, Page &destPage, const size_t numBytes, const size_t offset=0)
Definition: FileBuffer.cpp:386
EpochedPage current() const
Returns a reference to the most recent version of the page.
Definition: Page.h:94
virtual size_t pageDataSize() const
Returns the size in bytes of the data portion of each page in the FileBuffer.
Definition: FileBuffer.h:141
#define METADATA_VERSION
Definition: FileBuffer.h:36
The MultiPage stores versions of the same logical page in a deque.
Definition: Page.h:79
A selection of helper methods for File I/O.
size_t getNumReaderThreads()
Returns number of threads defined by parameter num-reader-threads which should be used during initial...
Definition: FileMgr.h:306
void freePage(const Page &page)
Definition: FileBuffer.cpp:153
bool isMissingPages() const
Definition: FileBuffer.cpp:643
static constexpr size_t headerBufferOffset_
Definition: FileBuffer.h:166
HOST DEVICE void set_type(SQLTypes t)
Definition: sqltypes.h:419