Restore.cpp 29.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "Restore.hpp"
#include <NdbTCP.h>
19
#include <NdbMem.h>
20 21 22 23 24 25 26
#include <OutputStream.hpp>
#include <Bitmask.hpp>

#include <AttributeHeader.hpp>
#include <trigger_definitions.h>
#include <SimpleProperties.hpp>
#include <signaldata/DictTabInfo.hpp>
27
#include <ndb_limits.h>
28

29 30
#include "../../../../sql/ha_ndbcluster_tables.h"

31 32 33 34 35
Uint16 Twiddle16(Uint16 in); // Byte shift 16-bit data
Uint32 Twiddle32(Uint32 in); // Byte shift 32-bit data
Uint64 Twiddle64(Uint64 in); // Byte shift 64-bit data

bool
36
BackupFile::Twiddle(const AttributeDesc* attr_desc, AttributeData* attr_data, Uint32 arraySize){
unknown's avatar
unknown committed
37
  Uint32 i;
38 39 40 41 42

  if(m_hostByteOrder)
    return true;
  
  if(arraySize == 0){
43
    arraySize = attr_desc->arraySize;
44 45
  }
  
46
  switch(attr_desc->size){
47 48 49 50
  case 8:
    
    return true;
  case 16:
unknown's avatar
unknown committed
51
    for(i = 0; i<arraySize; i++){
52
      attr_data->u_int16_value[i] = Twiddle16(attr_data->u_int16_value[i]);
53 54 55
    }
    return true;
  case 32:
unknown's avatar
unknown committed
56
    for(i = 0; i<arraySize; i++){
57
      attr_data->u_int32_value[i] = Twiddle32(attr_data->u_int32_value[i]);
58 59 60
    }
    return true;
  case 64:
unknown's avatar
unknown committed
61
    for(i = 0; i<arraySize; i++){
62
      attr_data->u_int64_value[i] = Twiddle64(attr_data->u_int64_value[i]);
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    }
    return true;
  default:
    return false;
  } // switch

} // Twiddle

FilteredNdbOut err(* new FileOutputStream(stderr), 0, 0);
FilteredNdbOut info(* new FileOutputStream(stdout), 1, 1);
FilteredNdbOut debug(* new FileOutputStream(stdout), 2, 0);

// To decide in what byte order data is
const Uint32 magicByteOrder = 0x12345678;
const Uint32 swappedMagicByteOrder = 0x78563412;

RestoreMetaData::RestoreMetaData(const char* path, Uint32 nodeId, Uint32 bNo) {
  
  debug << "RestoreMetaData constructor" << endl;
  setCtlFile(nodeId, bNo, path);
}

RestoreMetaData::~RestoreMetaData(){
unknown's avatar
unknown committed
86
  for(Uint32 i= 0; i < allTables.size(); i++)
87 88 89 90
    delete allTables[i];
  allTables.clear();
}

unknown's avatar
unknown committed
91
TableS * 
92
RestoreMetaData::getTable(Uint32 tableId) const {
unknown's avatar
unknown committed
93
  for(Uint32 i= 0; i < allTables.size(); i++)
94 95 96 97 98 99 100 101 102 103 104
    if(allTables[i]->getTableId() == tableId)
      return allTables[i];
  return NULL;
}

Uint32
RestoreMetaData::getStopGCP() const {
  return m_stopGCP;
}

int
105
RestoreMetaData::loadContent() 
106 107
{
  Uint32 noOfTables = readMetaTableList();
108 109 110
  if(noOfTables == 0) {
    return 1;
  }
111
  for(Uint32 i = 0; i<noOfTables; i++){
112
    if(!readMetaTableDesc()){
113 114 115
      return 0;
    }
  }
116 117
  if (! markSysTables())
    return 0;
118 119 120 121 122 123 124 125 126 127
  if(!readGCPEntry())
    return 0;
  return 1;
}

Uint32
RestoreMetaData::readMetaTableList() {
  
  Uint32 sectionInfo[2];
  
unknown's avatar
unknown committed
128 129
  if (buffer_read(&sectionInfo, sizeof(sectionInfo), 1) != 1){
    err << "readMetaTableList read header error" << endl;
130 131 132 133 134 135 136
    return 0;
  }
  sectionInfo[0] = ntohl(sectionInfo[0]);
  sectionInfo[1] = ntohl(sectionInfo[1]);

  const Uint32 tabCount = sectionInfo[1] - 2;

unknown's avatar
unknown committed
137 138 139
  void *tmp;
  if (buffer_get_ptr(&tmp, 4, tabCount) != tabCount){
    err << "readMetaTableList read tabCount error" << endl;
140 141 142 143 144 145 146
    return 0;
  }
  
  return tabCount;
}

bool
147
RestoreMetaData::readMetaTableDesc() {
148
  
unknown's avatar
unknown committed
149
  Uint32 sectionInfo[3];
150 151
  
  // Read section header 
unknown's avatar
unknown committed
152 153 154 155 156 157 158
  Uint32 sz = sizeof(sectionInfo) >> 2;
  if (m_fileHeader.NdbVersion < NDBD_ROWID_VERSION)
  {
    sz = 2;
    sectionInfo[2] = htonl(DictTabInfo::UserTable);
  }
  if (buffer_read(&sectionInfo, 4*sz, 1) != 1){
159 160 161 162 163
    err << "readMetaTableDesc read header error" << endl;
    return false;
  } // if
  sectionInfo[0] = ntohl(sectionInfo[0]);
  sectionInfo[1] = ntohl(sectionInfo[1]);
unknown's avatar
unknown committed
164
  sectionInfo[2] = ntohl(sectionInfo[2]);
165 166 167 168
  
  assert(sectionInfo[0] == BackupFormat::TABLE_DESCRIPTION);
  
  // Read dictTabInfo buffer
unknown's avatar
unknown committed
169
  const Uint32 len = (sectionInfo[1] - sz);
unknown's avatar
unknown committed
170 171
  void *ptr;
  if (buffer_get_ptr(&ptr, 4, len) != len){
172 173 174 175
    err << "readMetaTableDesc read error" << endl;
    return false;
  } // if
  
unknown's avatar
unknown committed
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
  int errcode = 0;
  DictObject obj = { sectionInfo[2], 0 };
  switch(obj.m_objType){
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::OrderedIndex:
    return parseTableDescriptor((Uint32*)ptr, len);	     
    break;
  case DictTabInfo::Tablespace:
  {
    NdbDictionary::Tablespace * dst = new NdbDictionary::Tablespace;
    errcode = 
      NdbDictInterface::parseFilegroupInfo(NdbTablespaceImpl::getImpl(* dst), 
					   (Uint32*)ptr, len);
    if (errcode)
      delete dst;
    obj.m_objPtr = dst;
    debug << hex << obj.m_objPtr << " " 
	   << dec << dst->getObjectId() << " " << dst->getName() << endl;
    break;
  }
  case DictTabInfo::LogfileGroup:
  {
    NdbDictionary::LogfileGroup * dst = new NdbDictionary::LogfileGroup;
    errcode = 
      NdbDictInterface::parseFilegroupInfo(NdbLogfileGroupImpl::getImpl(* dst),
					   (Uint32*)ptr, len);
    if (errcode)
      delete dst;
    obj.m_objPtr = dst;
    debug << hex << obj.m_objPtr << " " 
	   << dec << dst->getObjectId() << " " << dst->getName() << endl;
    break;
  }
  case DictTabInfo::Datafile:
  {
    NdbDictionary::Datafile * dst = new NdbDictionary::Datafile;
    errcode = 
      NdbDictInterface::parseFileInfo(NdbDatafileImpl::getImpl(* dst), 
				      (Uint32*)ptr, len);
    if (errcode)
      delete dst;
    obj.m_objPtr = dst;
    debug << hex << obj.m_objPtr << " "
	   << dec << dst->getObjectId() << " " << dst->getPath() << endl;
    break;
  }
  case DictTabInfo::Undofile:
  {
    NdbDictionary::Undofile * dst = new NdbDictionary::Undofile;
    errcode = 
      NdbDictInterface::parseFileInfo(NdbUndofileImpl::getImpl(* dst), 
				      (Uint32*)ptr, len);
    if (errcode)
      delete dst;
    obj.m_objPtr = dst;
    debug << hex << obj.m_objPtr << " " 
	   << dec << dst->getObjectId() << " " << dst->getPath() << endl;
    break;
  }
  default:
    err << "Unsupported table type!! " << sectionInfo[2] << endl;
    return false;
  }
  if (errcode)
  {
    err << "Unable to parse dict info..." 
	<< sectionInfo[2] << " " << errcode << endl;
    return false;
  }

  /**
   * DD objects need to be sorted...
   */
  for(Uint32 i = 0; i<m_objects.size(); i++)
  {
    switch(sectionInfo[2]){
    case DictTabInfo::Tablespace:
      if (DictTabInfo::isFile(m_objects[i].m_objType))
      {
	m_objects.push(obj, i);
	goto end;
      }
      break;
    case DictTabInfo::LogfileGroup:
    {
      if (DictTabInfo::isFile(m_objects[i].m_objType) ||
	  m_objects[i].m_objType == DictTabInfo::Tablespace)
      {
	m_objects.push(obj, i);
	goto end;
      }
      break;
    }
    default:
      m_objects.push_back(obj);
      goto end;
    }
  }
  m_objects.push_back(obj);
  
end:
  return true;
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 321 322 323 324
bool
RestoreMetaData::markSysTables()
{
  Uint32 i;
  for (i = 0; i < getNoOfTables(); i++) {
    TableS* table = allTables[i];
    const char* tableName = table->getTableName();
    if ( // XXX should use type
        strcmp(tableName, "SYSTAB_0") == 0 ||
        strcmp(tableName, "NDB$EVENTS_0") == 0 ||
        strcmp(tableName, "sys/def/SYSTAB_0") == 0 ||
        strcmp(tableName, "sys/def/NDB$EVENTS_0") == 0 ||
        strcmp(tableName, NDB_REP_DB "/def/" NDB_APPLY_TABLE) == 0 ||
        strcmp(tableName, NDB_REP_DB "/def/" NDB_SCHEMA_TABLE)== 0 )
      table->isSysTable = true;
  }
  for (i = 0; i < getNoOfTables(); i++) {
    TableS* blobTable = allTables[i];
    const char* blobTableName = blobTable->getTableName();
    // yet another match blob
    int cnt, id1, id2;
    char buf[256];
    cnt = sscanf(blobTableName, "%[^/]/%[^/]/NDB$BLOB_%d_%d",
                 buf, buf, &id1, &id2);
    if (cnt == 4) {
      Uint32 j;
      for (j = 0; j < getNoOfTables(); j++) {
        TableS* table = allTables[j];
        if (table->getTableId() == id1) {
          if (table->isSysTable)
            blobTable->isSysTable = true;
          break;
        }
      }
      if (j == getNoOfTables()) {
        err << "Restore: Bad primary table id in " << blobTableName << endl;
        return false;
      }
    }
  }
  return true;
}

325 326 327 328 329 330 331 332
bool
RestoreMetaData::readGCPEntry() {

  Uint32 data[4];
  
  BackupFormat::CtlFile::GCPEntry * dst = 
    (BackupFormat::CtlFile::GCPEntry *)&data[0];
  
unknown's avatar
unknown committed
333
  if(buffer_read(dst, 4, 4) != 4){
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    err << "readGCPEntry read error" << endl;
    return false;
  }
  
  dst->SectionType = ntohl(dst->SectionType);
  dst->SectionLength = ntohl(dst->SectionLength);
  
  if(dst->SectionType != BackupFormat::GCP_ENTRY){
    err << "readGCPEntry invalid format" << endl;
    return false;
  }
  
  dst->StartGCP = ntohl(dst->StartGCP);
  dst->StopGCP = ntohl(dst->StopGCP);
  
  m_startGCP = dst->StartGCP;
  m_stopGCP = dst->StopGCP;
  return true;
}

354
TableS::TableS(Uint32 version, NdbTableImpl* tableImpl)
355 356 357 358
  : m_dictTable(tableImpl)
{
  m_dictTable = tableImpl;
  m_noOfNullable = m_nullBitmaskSize = 0;
unknown's avatar
unknown committed
359 360
  m_auto_val_id= ~(Uint32)0;
  m_max_auto_val= 0;
361
  backupVersion = version;
362
  isSysTable = false;
363
  
364
  for (int i = 0; i < tableImpl->getNoOfColumns(); i++)
365 366
    createAttr(tableImpl->getColumn(i));
}
367

unknown's avatar
unknown committed
368 369
TableS::~TableS()
{
unknown's avatar
unknown committed
370
  for (Uint32 i= 0; i < allAttributesDesc.size(); i++)
unknown's avatar
unknown committed
371 372 373
    delete allAttributesDesc[i];
}

374

375 376
// Parse dictTabInfo buffer and pushback to to vector storage 
bool
377 378
RestoreMetaData::parseTableDescriptor(const Uint32 * data, Uint32 len)
{
379 380
  NdbTableImpl* tableImpl = 0;
  int ret = NdbDictInterface::parseTableInfo(&tableImpl, data, len, false);
unknown's avatar
unknown committed
381
  
382 383
  if (ret != 0) {
    err << "parseTableInfo " << " failed" << endl;
384
    return false;
385 386 387 388 389
  }
  if(tableImpl == 0)
    return false;

  debug << "parseTableInfo " << tableImpl->getName() << " done" << endl;
390
  TableS * table = new TableS(m_fileHeader.NdbVersion, tableImpl);
391 392 393 394
  if(table == NULL) {
    return false;
  }

395 396
  debug << "Parsed table id " << table->getTableId() << endl;
  debug << "Parsed table #attr " << table->getNoOfAttributes() << endl;
397 398
  debug << "Parsed table schema version not used " << endl;

399
  debug << "Pushing table " << table->getTableName() << endl;
400
  debug << "   with " << table->getNoOfAttributes() << " attributes" << endl;
unknown's avatar
unknown committed
401
  
402 403 404 405 406 407
  allTables.push_back(table);

  return true;
}

// Constructor
408
RestoreDataIterator::RestoreDataIterator(const RestoreMetaData & md, void (* _free_data_callback)())
unknown's avatar
unknown committed
409
  : BackupFile(_free_data_callback), m_metaData(md)
410 411 412 413 414
{
  debug << "RestoreDataIterator constructor" << endl;
  setDataFile(md, 0);
}

415 416 417 418
TupleS & TupleS::operator=(const TupleS& tuple)
{
  prepareRecord(*tuple.m_currentTable);

unknown's avatar
unknown committed
419
  if (allAttrData)
420 421 422
    memcpy(allAttrData, tuple.allAttrData, getNoOfAttributes()*sizeof(AttributeData));
  
  return *this;
423
}
424 425 426 427
int TupleS::getNoOfAttributes() const {
  if (m_currentTable == 0)
    return 0;
  return m_currentTable->getNoOfAttributes();
428
}
429

unknown's avatar
unknown committed
430
TableS * TupleS::getTable() const {
431
  return m_currentTable;
432
}
433 434 435 436 437 438 439

const AttributeDesc * TupleS::getDesc(int i) const {
  return m_currentTable->allAttributesDesc[i];
}

AttributeData * TupleS::getData(int i) const{
  return &(allAttrData[i]);
440
}
441

442
bool
unknown's avatar
unknown committed
443
TupleS::prepareRecord(TableS & tab){
444
  if (allAttrData) {
unknown's avatar
unknown committed
445 446 447 448 449
    if (getNoOfAttributes() == tab.getNoOfAttributes())
    {
      m_currentTable = &tab;
      return true;
    }
450 451
    delete [] allAttrData;
    m_currentTable= 0;
452
  }
453 454 455 456 457 458
  
  allAttrData = new AttributeData[tab.getNoOfAttributes()];
  if (allAttrData == 0)
    return false;
  
  m_currentTable = &tab;
459

unknown's avatar
unknown committed
460
  return true;
461 462 463 464 465
}

const TupleS *
RestoreDataIterator::getNextTuple(int  & res)
{
466 467
  Uint32  dataLength = 0;
  // Read record length
unknown's avatar
unknown committed
468
  if (buffer_read(&dataLength, sizeof(dataLength), 1) != 1){
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    err << "getNextTuple:Error reading length  of data part" << endl;
    res = -1;
    return NULL;
  } // if
  
  // Convert length from network byte order
  dataLength = ntohl(dataLength);
  const Uint32 dataLenBytes = 4 * dataLength;
  
  if (dataLength == 0) {
    // Zero length for last tuple
    // End of this data fragment
    debug << "End of fragment" << endl;
    res = 0;
    return NULL;
  } // if
485

486
  // Read tuple data
487
  void *_buf_ptr;
unknown's avatar
unknown committed
488
  if (buffer_get_ptr(&_buf_ptr, 1, dataLenBytes) != dataLenBytes) {
489 490 491 492
    err << "getNextTuple:Read error: " << endl;
    res = -1;
    return NULL;
  }
unknown's avatar
unknown committed
493 494 495
 
  //if (m_currentTable->getTableId() >= 2) { for (uint ii=0; ii<dataLenBytes; ii+=4) ndbout << "*" << hex << *(Uint32*)( (char*)_buf_ptr+ii ); ndbout << endl; }

496
  Uint32 *buf_ptr = (Uint32*)_buf_ptr, *ptr = buf_ptr;
497
  ptr += m_currentTable->m_nullBitmaskSize;
unknown's avatar
unknown committed
498
  Uint32 i;
499 500 501 502 503 504 505 506 507 508 509 510
  for(i= 0; i < m_currentTable->m_fixedKeys.size(); i++){
    assert(ptr < buf_ptr + dataLength);
 
    const Uint32 attrId = m_currentTable->m_fixedKeys[i]->attrId;

    AttributeData * attr_data = m_tuple.getData(attrId);
    const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);

    const Uint32 sz = attr_desc->getSizeInWords();

    attr_data->null = false;
    attr_data->void_value = ptr;
unknown's avatar
unknown committed
511
    attr_data->size = 4*sz;
512 513 514 515 516 517 518 519 520

    if(!Twiddle(attr_desc, attr_data))
      {
	res = -1;
	return NULL;
      }
    ptr += sz;
  }

unknown's avatar
unknown committed
521
  for(i = 0; i < m_currentTable->m_fixedAttribs.size(); i++){
522
    assert(ptr < buf_ptr + dataLength);
523 524 525

    const Uint32 attrId = m_currentTable->m_fixedAttribs[i]->attrId;

526 527 528 529
    AttributeData * attr_data = m_tuple.getData(attrId);
    const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);

    const Uint32 sz = attr_desc->getSizeInWords();
530

531 532
    attr_data->null = false;
    attr_data->void_value = ptr;
unknown's avatar
unknown committed
533
    attr_data->size = 4*sz;
534

unknown's avatar
unknown committed
535 536
    //if (m_currentTable->getTableId() >= 2) { ndbout << "fix i=" << i << " off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
    
537
    if(!Twiddle(attr_desc, attr_data))
538 539 540 541 542 543 544 545
      {
	res = -1;
	return NULL;
      }

    ptr += sz;
  }

unknown's avatar
unknown committed
546
  // init to NULL
unknown's avatar
unknown committed
547
  for(i = 0; i < m_currentTable->m_variableAttribs.size(); i++){
548
    const Uint32 attrId = m_currentTable->m_variableAttribs[i]->attrId;
549

unknown's avatar
unknown committed
550 551 552 553 554 555 556 557 558 559 560 561
    AttributeData * attr_data = m_tuple.getData(attrId);

    attr_data->null = true;
    attr_data->void_value = NULL;
  }

  while (ptr + 2 < buf_ptr + dataLength) {
    typedef BackupFormat::DataFile::VariableData VarData;
    VarData * data = (VarData *)ptr;
    Uint32 sz = ntohl(data->Sz);
    Uint32 attrId = ntohl(data->Id); // column_no

562 563
    AttributeData * attr_data = m_tuple.getData(attrId);
    const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);
564
    
unknown's avatar
unknown committed
565
    // just a reminder - remove when backwards compat implemented
unknown's avatar
unknown committed
566 567
    if(m_currentTable->backupVersion < MAKE_VERSION(5,1,3) && 
       attr_desc->m_column->getNullable()){
568
      const Uint32 ind = attr_desc->m_nullBitIndex;
569
      if(BitmaskImpl::get(m_currentTable->m_nullBitmaskSize, 
570 571 572
			  buf_ptr,ind)){
	attr_data->null = true;
	attr_data->void_value = NULL;
573 574 575
	continue;
      }
    }
unknown's avatar
unknown committed
576 577 578 579 580

    if (m_currentTable->backupVersion < MAKE_VERSION(5,1,3))
    {
      sz *= 4;
    }
581
    
582 583
    attr_data->null = false;
    attr_data->void_value = &data->Data[0];
unknown's avatar
unknown committed
584 585 586
    attr_data->size = sz;

    //if (m_currentTable->getTableId() >= 2) { ndbout << "var off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
587 588 589 590

    /**
     * Compute array size
     */
unknown's avatar
unknown committed
591 592
    const Uint32 arraySize = sz / (attr_desc->size / 8);
    assert(arraySize <= attr_desc->arraySize);
593
    if(!Twiddle(attr_desc, attr_data, attr_desc->arraySize))
594 595 596 597
      {
	res = -1;
	return NULL;
      }
unknown's avatar
unknown committed
598 599
    
    ptr += ((sz + 3) >> 2) + 2;
600 601
  }

unknown's avatar
unknown committed
602 603
  assert(ptr == buf_ptr + dataLength);

604 605
  m_count ++;  
  res = 0;
606
  return &m_tuple;
607 608
} // RestoreDataIterator::getNextTuple

unknown's avatar
unknown committed
609 610 611
BackupFile::BackupFile(void (* _free_data_callback)()) 
  : free_data_callback(_free_data_callback)
{
612 613 614
  m_file = 0;
  m_path[0] = 0;
  m_fileName[0] = 0;
unknown's avatar
unknown committed
615 616 617 618 619

  m_buffer_sz = 64*1024;
  m_buffer = malloc(m_buffer_sz);
  m_buffer_ptr = m_buffer;
  m_buffer_data_left = 0;
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
}

BackupFile::~BackupFile(){
  if(m_file != 0)
    fclose(m_file);
  if(m_buffer != 0)
    free(m_buffer);
}

bool
BackupFile::openFile(){
  if(m_file != NULL){
    fclose(m_file);
    m_file = 0;
  }
  
  m_file = fopen(m_fileName, "r");
  return m_file != 0;
}

unknown's avatar
unknown committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
Uint32 BackupFile::buffer_get_ptr_ahead(void **p_buf_ptr, Uint32 size, Uint32 nmemb)
{
  Uint32 sz = size*nmemb;
  if (sz > m_buffer_data_left) {

    if (free_data_callback)
      (*free_data_callback)();

    memcpy(m_buffer, m_buffer_ptr, m_buffer_data_left);

    size_t r = fread(((char *)m_buffer) + m_buffer_data_left, 1, m_buffer_sz - m_buffer_data_left, m_file);
    m_buffer_data_left += r;
    m_buffer_ptr = m_buffer;

    if (sz > m_buffer_data_left)
      sz = size * (m_buffer_data_left / size);
656
  }
unknown's avatar
unknown committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

  *p_buf_ptr = m_buffer_ptr;

  return sz/size;
}
Uint32 BackupFile::buffer_get_ptr(void **p_buf_ptr, Uint32 size, Uint32 nmemb)
{
  Uint32 r = buffer_get_ptr_ahead(p_buf_ptr, size, nmemb);

  m_buffer_ptr = ((char*)m_buffer_ptr)+(r*size);
  m_buffer_data_left -= (r*size);

  return r;
}

Uint32 BackupFile::buffer_read_ahead(void *ptr, Uint32 size, Uint32 nmemb)
{
  void *buf_ptr;
  Uint32 r = buffer_get_ptr_ahead(&buf_ptr, size, nmemb);
  memcpy(ptr, buf_ptr, r*size);

  return r;
}

Uint32 BackupFile::buffer_read(void *ptr, Uint32 size, Uint32 nmemb)
{
  void *buf_ptr;
  Uint32 r = buffer_get_ptr(&buf_ptr, size, nmemb);
  memcpy(ptr, buf_ptr, r*size);

  return r;
688 689 690 691 692 693 694 695 696
}

void
BackupFile::setCtlFile(Uint32 nodeId, Uint32 backupId, const char * path){
  m_nodeId = nodeId;
  m_expectedFileHeader.BackupId = backupId;
  m_expectedFileHeader.FileType = BackupFormat::CTL_FILE;

  char name[PATH_MAX]; const Uint32 sz = sizeof(name);
697
  BaseString::snprintf(name, sz, "BACKUP-%d.%d.ctl", backupId, nodeId);  
698 699 700 701 702 703 704 705 706 707
  setName(path, name);
}

void
BackupFile::setDataFile(const BackupFile & bf, Uint32 no){
  m_nodeId = bf.m_nodeId;
  m_expectedFileHeader = bf.m_fileHeader;
  m_expectedFileHeader.FileType = BackupFormat::DATA_FILE;
  
  char name[PATH_MAX]; const Uint32 sz = sizeof(name);
708
  BaseString::snprintf(name, sz, "BACKUP-%d-%d.%d.Data", 
709 710 711 712 713 714 715 716 717 718 719
	   m_expectedFileHeader.BackupId, no, m_nodeId);
  setName(bf.m_path, name);
}

void
BackupFile::setLogFile(const BackupFile & bf, Uint32 no){
  m_nodeId = bf.m_nodeId;
  m_expectedFileHeader = bf.m_fileHeader;
  m_expectedFileHeader.FileType = BackupFormat::LOG_FILE;
  
  char name[PATH_MAX]; const Uint32 sz = sizeof(name);
720
  BaseString::snprintf(name, sz, "BACKUP-%d.%d.log", 
721 722 723 724 725 726 727 728 729
	   m_expectedFileHeader.BackupId, m_nodeId);
  setName(bf.m_path, name);
}

void
BackupFile::setName(const char * p, const char * n){
  const Uint32 sz = sizeof(m_path);
  if(p != 0 && strlen(p) > 0){
    if(p[strlen(p)-1] == '/'){
730
      BaseString::snprintf(m_path, sz, "%s", p);
731
    } else {
732
      BaseString::snprintf(m_path, sz, "%s%s", p, "/");
733 734 735 736 737
    }
  } else {
    m_path[0] = 0;
  }

738
  BaseString::snprintf(m_fileName, sizeof(m_fileName), "%s%s", m_path, n);
739 740 741 742 743 744 745 746 747
  debug << "Filename = " << m_fileName << endl;
}

bool
BackupFile::readHeader(){
  if(!openFile()){
    return false;
  }
  
unknown's avatar
unknown committed
748
  if(buffer_read(&m_fileHeader, sizeof(m_fileHeader), 1) != 1){
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    err << "readDataFileHeader: Error reading header" << endl;
    return false;
  }
  
  // Convert from network to host byte order for platform compatibility
  m_fileHeader.NdbVersion  = ntohl(m_fileHeader.NdbVersion);
  m_fileHeader.SectionType = ntohl(m_fileHeader.SectionType);
  m_fileHeader.SectionLength = ntohl(m_fileHeader.SectionLength);
  m_fileHeader.FileType = ntohl(m_fileHeader.FileType);
  m_fileHeader.BackupId = ntohl(m_fileHeader.BackupId);
  m_fileHeader.BackupKey_0 = ntohl(m_fileHeader.BackupKey_0);
  m_fileHeader.BackupKey_1 = ntohl(m_fileHeader.BackupKey_1);

  debug << "FileHeader: " << m_fileHeader.Magic << " " <<
    m_fileHeader.NdbVersion << " " <<
    m_fileHeader.SectionType << " " <<
    m_fileHeader.SectionLength << " " <<
    m_fileHeader.FileType << " " <<
    m_fileHeader.BackupId << " " <<
    m_fileHeader.BackupKey_0 << " " <<
    m_fileHeader.BackupKey_1 << " " <<
    m_fileHeader.ByteOrder << endl;
  
  debug << "ByteOrder is " << m_fileHeader.ByteOrder << endl;
  debug << "magicByteOrder is " << magicByteOrder << endl;
  
  if (m_fileHeader.FileType != m_expectedFileHeader.FileType){
    abort();
  }
  
  // Check for BackupFormat::FileHeader::ByteOrder if swapping is needed
  if (m_fileHeader.ByteOrder == magicByteOrder) {
    m_hostByteOrder = true;
  } else if (m_fileHeader.ByteOrder == swappedMagicByteOrder){
    m_hostByteOrder = false;
  } else {
    abort();
  }
  
  return true;
} // BackupFile::readHeader

bool
BackupFile::validateFooter(){
  return true;
}

796
bool RestoreDataIterator::readFragmentHeader(int & ret, Uint32 *fragmentId)
797 798 799 800 801
{
  BackupFormat::DataFile::FragmentHeader Header;
  
  debug << "RestoreDataIterator::getNextFragment" << endl;
  
unknown's avatar
unknown committed
802
  if (buffer_read(&Header, sizeof(Header), 1) != 1){
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    ret = 0;
    return false;
  } // if
  
  Header.SectionType  = ntohl(Header.SectionType);
  Header.SectionLength  = ntohl(Header.SectionLength);
  Header.TableId  = ntohl(Header.TableId);
  Header.FragmentNo  = ntohl(Header.FragmentNo);
  Header.ChecksumType  = ntohl(Header.ChecksumType);
  
  debug << "FragmentHeader: " << Header.SectionType 
	<< " " << Header.SectionLength 
	<< " " << Header.TableId 
	<< " " << Header.FragmentNo 
	<< " " << Header.ChecksumType << endl;
  
  m_currentTable = m_metaData.getTable(Header.TableId);
  if(m_currentTable == 0){
    ret = -1;
    return false;
  }
  
825 826 827 828 829 830
  if(!m_tuple.prepareRecord(*m_currentTable))
  {
    ret =-1;
    return false;
  }

831
  info << "_____________________________________________________" << endl
unknown's avatar
unknown committed
832
       << "Processing data in table: " << m_currentTable->getTableName() 
833 834 835 836 837
       << "(" << Header.TableId << ") fragment " 
       << Header.FragmentNo << endl;
  
  m_count = 0;
  ret = 0;
838
  *fragmentId = Header.FragmentNo;
839 840 841 842 843 844 845 846
  return true;
} // RestoreDataIterator::getNextFragment


bool
RestoreDataIterator::validateFragmentFooter() {
  BackupFormat::DataFile::FragmentFooter footer;
  
unknown's avatar
unknown committed
847
  if (buffer_read(&footer, sizeof(footer), 1) != 1){
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    err << "getFragmentFooter:Error reading fragment footer" << endl;
    return false;
  } 
  
  // TODO: Handle footer, nothing yet
  footer.SectionType  = ntohl(footer.SectionType);
  footer.SectionLength  = ntohl(footer.SectionLength);
  footer.TableId  = ntohl(footer.TableId);
  footer.FragmentNo  = ntohl(footer.FragmentNo);
  footer.NoOfRecords  = ntohl(footer.NoOfRecords);
  footer.Checksum  = ntohl(footer.Checksum);

  assert(m_count == footer.NoOfRecords);
  
  return true;
} // RestoreDataIterator::getFragmentFooter

865 866
AttributeDesc::AttributeDesc(NdbDictionary::Column *c)
  : m_column(c)
867
{
unknown's avatar
unknown committed
868 869
  size = 8*NdbColumnImpl::getImpl(* c).m_attrSize;
  arraySize = NdbColumnImpl::getImpl(* c).m_arraySize;
870
}
871

872 873 874
void TableS::createAttr(NdbDictionary::Column *column)
{
  AttributeDesc * d = new AttributeDesc(column);
875 876 877 878
  if(d == NULL) {
    ndbout_c("Restore: Failed to allocate memory");
    abort();
  }
879
  d->attrId = allAttributesDesc.size();
880 881
  allAttributesDesc.push_back(d);

unknown's avatar
unknown committed
882 883 884
  if (d->m_column->getAutoIncrement())
    m_auto_val_id= d->attrId;

885 886 887 888 889 890
  if(d->m_column->getPrimaryKey() && backupVersion <= MAKE_VERSION(4,1,7))
  {
    m_fixedKeys.push_back(d);
    return;
  }
  
unknown's avatar
unknown committed
891 892
  if (d->m_column->getArrayType() == NDB_ARRAYTYPE_FIXED &&
      ! d->m_column->getNullable())
893
  {
894 895 896
    m_fixedAttribs.push_back(d);
    return;
  }
897

unknown's avatar
unknown committed
898
  // just a reminder - does not solve backwards compat
unknown's avatar
unknown committed
899
  if (backupVersion < MAKE_VERSION(5,1,3))
unknown's avatar
unknown committed
900 901 902 903 904
  {
    d->m_nullBitIndex = m_noOfNullable; 
    m_noOfNullable++;
    m_nullBitmaskSize = (m_noOfNullable + 31) / 32;
  }
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
  m_variableAttribs.push_back(d);
} // TableS::createAttr

Uint16 Twiddle16(Uint16 in)
{
  Uint16 retVal = 0;

  retVal = ((in & 0xFF00) >> 8) |
    ((in & 0x00FF) << 8);

  return(retVal);
} // Twiddle16

Uint32 Twiddle32(Uint32 in)
{
  Uint32 retVal = 0;

  retVal = ((in & 0x000000FF) << 24) | 
    ((in & 0x0000FF00) << 8)  |
    ((in & 0x00FF0000) >> 8)  |
    ((in & 0xFF000000) >> 24);
  
  return(retVal);
} // Twiddle32

Uint64 Twiddle64(Uint64 in)
{
  Uint64 retVal = 0;

  retVal = 
    ((in & (Uint64)0x00000000000000FFLL) << 56) | 
    ((in & (Uint64)0x000000000000FF00LL) << 40) | 
    ((in & (Uint64)0x0000000000FF0000LL) << 24) | 
    ((in & (Uint64)0x00000000FF000000LL) << 8) | 
    ((in & (Uint64)0x000000FF00000000LL) >> 8) | 
    ((in & (Uint64)0x0000FF0000000000LL) >> 24) | 
    ((in & (Uint64)0x00FF000000000000LL) >> 40) | 
    ((in & (Uint64)0xFF00000000000000LL) >> 56);

  return(retVal);
} // Twiddle64


RestoreLogIterator::RestoreLogIterator(const RestoreMetaData & md)
  : m_metaData(md) 
{
  debug << "RestoreLog constructor" << endl;
  setLogFile(md, 0);

  m_count = 0;
unknown's avatar
unknown committed
955
  m_last_gci = 0;
956 957 958
}

const LogEntry *
959
RestoreLogIterator::getNextLogEntry(int & res, bool *alloc_flag) {
960 961 962
  // Read record length
  typedef BackupFormat::LogFile::LogEntry LogE;

unknown's avatar
unknown committed
963 964
  LogE * logE= 0;
  Uint32 len= ~0;
965 966
  const Uint32 stopGCP = m_metaData.getStopGCP();
  do {
unknown's avatar
unknown committed
967 968 969
    if (buffer_read_ahead(&len, sizeof(Uint32), 1) != 1){
      res= -1;
      return 0;
970
    }
unknown's avatar
unknown committed
971
    len= ntohl(len);
972

unknown's avatar
unknown committed
973 974 975 976
    Uint32 data_len = sizeof(Uint32) + len*4;
    if (buffer_get_ptr((void **)(&logE), 1, data_len) != data_len) {
      res= -2;
      return 0;
977 978 979
    }
    
    if(len == 0){
unknown's avatar
unknown committed
980
      res= 0;
981 982
      return 0;
    }
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    if (m_metaData.getFileHeader().NdbVersion < NDBD_FRAGID_VERSION)
    {
      /*
        FragId was introduced in LogEntry in version
        5.1.6
        We set FragId to 0 in older versions (these versions
        do not support restore of user defined partitioned
        tables.
      */
      int i;
      LogE *tmpLogE = (LogE*)NdbMem_Allocate(data_len + 4);
      if (!tmpLogE)
      {
        res = -2;
        return 0;
      }
      tmpLogE->Length = logE->Length;
      tmpLogE->TableId = logE->TableId;
      tmpLogE->TriggerEvent = logE->TriggerEvent;
      tmpLogE->FragId = 0;
      for (i = 0; i < len - 3; i++)
        tmpLogE->Data[i] = logE->Data[i-1];
      *alloc_flag= true;
    }
unknown's avatar
unknown committed
1007 1008
    logE->TableId= ntohl(logE->TableId);
    logE->TriggerEvent= ntohl(logE->TriggerEvent);
1009
    
unknown's avatar
unknown committed
1010
    const bool hasGcp= (logE->TriggerEvent & 0x10000) != 0;
1011 1012 1013 1014
    logE->TriggerEvent &= 0xFFFF;
    
    if(hasGcp){
      len--;
unknown's avatar
unknown committed
1015
      m_last_gci = ntohl(logE->Data[len-2]);
1016
    }
unknown's avatar
unknown committed
1017 1018
  } while(m_last_gci > stopGCP + 1);
  
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
  m_logEntry.m_table = m_metaData.getTable(logE->TableId);
  switch(logE->TriggerEvent){
  case TriggerEvent::TE_INSERT:
    m_logEntry.m_type = LogEntry::LE_INSERT;
    break;
  case TriggerEvent::TE_UPDATE:
    m_logEntry.m_type = LogEntry::LE_UPDATE;
    break;
  case TriggerEvent::TE_DELETE:
    m_logEntry.m_type = LogEntry::LE_DELETE;
    break;
  default:
    res = -1;
    return NULL;
  }

  const TableS * tab = m_logEntry.m_table;
unknown's avatar
unknown committed
1036
  m_logEntry.clear();
1037 1038 1039 1040

  AttributeHeader * ah = (AttributeHeader *)&logE->Data[0];
  AttributeHeader *end = (AttributeHeader *)&logE->Data[len - 2];
  AttributeS *  attr;
1041
  m_logEntry.m_frag_id = ntohl(logE->FragId);
1042
  while(ah < end){
unknown's avatar
unknown committed
1043
    attr= m_logEntry.add_attr();
1044 1045 1046
    if(attr == NULL) {
      ndbout_c("Restore: Failed to allocate memory");
      res = -1;
unknown's avatar
unknown committed
1047
      return 0;
1048
    }
unknown's avatar
unknown committed
1049

1050 1051 1052 1053 1054
    attr->Desc = (* tab)[ah->getAttributeId()];
    assert(attr->Desc != 0);

    const Uint32 sz = ah->getDataSize();
    if(sz == 0){
unknown's avatar
unknown committed
1055 1056
      attr->Data.null = true;
      attr->Data.void_value = NULL;
1057
    } else {
unknown's avatar
unknown committed
1058 1059
      attr->Data.null = false;
      attr->Data.void_value = ah->getDataPtr();
1060 1061
    }
    
unknown's avatar
unknown committed
1062
    Twiddle(attr->Desc, &(attr->Data));
1063 1064 1065
    
    ah = ah->getNext();
  }
unknown's avatar
unknown committed
1066

1067 1068 1069 1070
  m_count ++;
  res = 0;
  return &m_logEntry;
}
1071 1072 1073

NdbOut &
operator<<(NdbOut& ndbout, const AttributeS& attr){
unknown's avatar
unknown committed
1074
  const AttributeData & data = attr.Data;
1075 1076 1077 1078 1079 1080 1081 1082
  const AttributeDesc & desc = *(attr.Desc);

  if (data.null)
  {
    ndbout << "<NULL>";
    return ndbout;
  }
  
unknown's avatar
ndb  
unknown committed
1083
  NdbRecAttr tmprec(0);
1084
  tmprec.setup(desc.m_column, (char *)data.void_value);
unknown's avatar
unknown committed
1085
  tmprec.receive_data((Uint32*)data.void_value, data.size);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
  ndbout << tmprec;

  return ndbout;
}

// Print tuple data
NdbOut& 
operator<<(NdbOut& ndbout, const TupleS& tuple)
{
  ndbout << tuple.getTable()->getTableName() << "; ";
  for (int i = 0; i < tuple.getNoOfAttributes(); i++) 
  {
    AttributeData * attr_data = tuple.getData(i);
    const AttributeDesc * attr_desc = tuple.getDesc(i);
unknown's avatar
unknown committed
1100
    const AttributeS attr = {attr_desc, *attr_data};
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    debug << i << " " << attr_desc->m_column->getName();
    ndbout << attr;
    
    if (i != (tuple.getNoOfAttributes() - 1))
      ndbout << delimiter << " ";
  } // for
  return ndbout;
}

// Print tuple data
NdbOut& 
operator<<(NdbOut& ndbout, const LogEntry& logE)
{
  switch(logE.m_type)
  {
  case LogEntry::LE_INSERT:
    ndbout << "INSERT " << logE.m_table->getTableName() << " ";
    break;
  case LogEntry::LE_DELETE:
    ndbout << "DELETE " << logE.m_table->getTableName() << " ";
    break;
  case LogEntry::LE_UPDATE:
    ndbout << "UPDATE " << logE.m_table->getTableName() << " ";
    break;
  default:
    ndbout << "Unknown log entry type (not insert, delete or update)" ;
  }
  
unknown's avatar
unknown committed
1129
  for (Uint32 i= 0; i < logE.size();i++) 
1130
  {
unknown's avatar
unknown committed
1131
    const AttributeS * attr = logE[i];
1132 1133
    ndbout << attr->Desc->m_column->getName() << "=";
    ndbout << (* attr);
unknown's avatar
unknown committed
1134
    if (i < (logE.size() - 1))
1135 1136 1137 1138 1139
      ndbout << ", ";
  }
  return ndbout;
}

unknown's avatar
unknown committed
1140
#include <NDBT.hpp>
1141 1142 1143

NdbOut & 
operator<<(NdbOut& ndbout, const TableS & table){
unknown's avatar
unknown committed
1144 1145
  
  ndbout << (* (NDBT_Table*)table.m_dictTable) << endl;
1146 1147
  return ndbout;
}
unknown's avatar
unknown committed
1148 1149 1150 1151

template class Vector<TableS*>;
template class Vector<AttributeS*>;
template class Vector<AttributeDesc*>;
unknown's avatar
unknown committed
1152
template class Vector<DictObject>;