Restore.cpp 32.3 KB
Newer Older
1 2 3 4
/* 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
5
   the Free Software Foundation; version 2 of the License.
6 7 8 9 10 11 12 13 14 15 16 17

   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>
18
#include <NdbMem.h>
19 20 21 22 23 24 25
#include <OutputStream.hpp>
#include <Bitmask.hpp>

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

29
#include "../../../../sql/ha_ndbcluster_tables.h"
30
extern NdbRecordPrintFormat g_ndbrecord_print_format;
31

32 33 34 35 36
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
37
BackupFile::Twiddle(const AttributeDesc* attr_desc, AttributeData* attr_data, Uint32 arraySize){
38
  Uint32 i;
39 40 41 42 43

  if(m_hostByteOrder)
    return true;
  
  if(arraySize == 0){
44
    arraySize = attr_desc->arraySize;
45 46
  }
  
47
  switch(attr_desc->size){
48 49 50 51
  case 8:
    
    return true;
  case 16:
52
    for(i = 0; i<arraySize; i++){
53
      attr_data->u_int16_value[i] = Twiddle16(attr_data->u_int16_value[i]);
54 55 56
    }
    return true;
  case 32:
57
    for(i = 0; i<arraySize; i++){
58
      attr_data->u_int32_value[i] = Twiddle32(attr_data->u_int32_value[i]);
59 60 61
    }
    return true;
  case 64:
62
    for(i = 0; i<arraySize; i++){
63 64 65 66 67 68
      // allow unaligned
      char* p = (char*)&attr_data->u_int64_value[i];
      Uint64 x;
      memcpy(&x, p, sizeof(Uint64));
      x = Twiddle64(x);
      memcpy(p, &x, sizeof(Uint64));
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    }
    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(){
92
  for(Uint32 i= 0; i < allTables.size(); i++)
93 94 95 96 97 98
  {
    TableS *table = allTables[i];
    for(Uint32 j= 0; j < table->m_fragmentInfo.size(); j++)
      delete table->m_fragmentInfo[j];
    delete table;
  }
99 100 101
  allTables.clear();
}

102
TableS * 
103
RestoreMetaData::getTable(Uint32 tableId) const {
104
  for(Uint32 i= 0; i < allTables.size(); i++)
105 106 107 108 109 110 111 112 113 114 115
    if(allTables[i]->getTableId() == tableId)
      return allTables[i];
  return NULL;
}

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

int
116
RestoreMetaData::loadContent() 
117 118
{
  Uint32 noOfTables = readMetaTableList();
119 120 121
  if(noOfTables == 0) {
    return 1;
  }
122
  for(Uint32 i = 0; i<noOfTables; i++){
123
    if(!readMetaTableDesc()){
124 125 126
      return 0;
    }
  }
127 128
  if (! markSysTables())
    return 0;
129 130
  if(!readGCPEntry())
    return 0;
131 132 133

  if(!readFragmentInfo())
    return 0;
134 135 136 137 138 139 140 141
  return 1;
}

Uint32
RestoreMetaData::readMetaTableList() {
  
  Uint32 sectionInfo[2];
  
142 143
  if (buffer_read(&sectionInfo, sizeof(sectionInfo), 1) != 1){
    err << "readMetaTableList read header error" << endl;
144 145 146 147 148 149 150
    return 0;
  }
  sectionInfo[0] = ntohl(sectionInfo[0]);
  sectionInfo[1] = ntohl(sectionInfo[1]);

  const Uint32 tabCount = sectionInfo[1] - 2;

151 152 153
  void *tmp;
  if (buffer_get_ptr(&tmp, 4, tabCount) != tabCount){
    err << "readMetaTableList read tabCount error" << endl;
154 155 156 157 158 159 160
    return 0;
  }
  
  return tabCount;
}

bool
161
RestoreMetaData::readMetaTableDesc() {
162
  
163
  Uint32 sectionInfo[3];
164 165
  
  // Read section header 
166 167 168 169 170 171 172
  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){
173 174 175 176 177
    err << "readMetaTableDesc read header error" << endl;
    return false;
  } // if
  sectionInfo[0] = ntohl(sectionInfo[0]);
  sectionInfo[1] = ntohl(sectionInfo[1]);
178
  sectionInfo[2] = ntohl(sectionInfo[2]);
179 180 181 182
  
  assert(sectionInfo[0] == BackupFormat::TABLE_DESCRIPTION);
  
  // Read dictTabInfo buffer
183
  const Uint32 len = (sectionInfo[1] - sz);
184 185
  void *ptr;
  if (buffer_get_ptr(&ptr, 4, len) != len){
186 187 188 189
    err << "readMetaTableDesc read error" << endl;
    return false;
  } // if
  
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
  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;
294 295
}

296 297 298 299 300 301
bool
RestoreMetaData::markSysTables()
{
  Uint32 i;
  for (i = 0; i < getNoOfTables(); i++) {
    TableS* table = allTables[i];
302
    table->m_local_id = i;
303 304 305 306 307 308
    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 ||
309 310 311 312 313
        /*
          The following is for old MySQL versions,
           before we changed the database name of the tables from
           "cluster_replication" -> "cluster" -> "mysql"
        */
314
        strcmp(tableName, "cluster_replication/def/" OLD_NDB_APPLY_TABLE) == 0 ||
315 316
        strcmp(tableName, OLD_NDB_REP_DB "/def/" OLD_NDB_APPLY_TABLE) == 0 ||
        strcmp(tableName, OLD_NDB_REP_DB "/def/" OLD_NDB_SCHEMA_TABLE) == 0 ||
317 318
        strcmp(tableName, NDB_REP_DB "/def/" NDB_APPLY_TABLE) == 0 ||
        strcmp(tableName, NDB_REP_DB "/def/" NDB_SCHEMA_TABLE)== 0 )
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333
      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];
334
        if (table->getTableId() == (Uint32) id1) {
335 336
          if (table->isSysTable)
            blobTable->isSysTable = true;
337
          blobTable->m_main_table = table;
338 339 340 341 342 343 344 345 346 347 348 349
          break;
        }
      }
      if (j == getNoOfTables()) {
        err << "Restore: Bad primary table id in " << blobTableName << endl;
        return false;
      }
    }
  }
  return true;
}

350 351 352 353 354 355 356 357
bool
RestoreMetaData::readGCPEntry() {

  Uint32 data[4];
  
  BackupFormat::CtlFile::GCPEntry * dst = 
    (BackupFormat::CtlFile::GCPEntry *)&data[0];
  
358
  if(buffer_read(dst, 4, 4) != 4){
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    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;
}

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
bool
RestoreMetaData::readFragmentInfo()
{
  BackupFormat::CtlFile::FragmentInfo fragInfo;
  TableS * table = 0;
  Uint32 tableId = RNIL;

  while (buffer_read(&fragInfo, 4, 2) == 2)
  {
    fragInfo.SectionType = ntohl(fragInfo.SectionType);
    fragInfo.SectionLength = ntohl(fragInfo.SectionLength);

    if (fragInfo.SectionType != BackupFormat::FRAGMENT_INFO)
    {
      err << "readFragmentInfo invalid section type: " <<
        fragInfo.SectionType << endl;
      return false;
    }

    if (buffer_read(&fragInfo.TableId, (fragInfo.SectionLength-2)*4, 1) != 1)
    {
      err << "readFragmentInfo invalid section length: " <<
        fragInfo.SectionLength << endl;
      return false;
    }

    fragInfo.TableId = ntohl(fragInfo.TableId);
    if (fragInfo.TableId != tableId)
    {
      tableId = fragInfo.TableId;
      table = getTable(tableId);
    }

    FragmentInfo * tmp = new FragmentInfo;
    tmp->fragmentNo = ntohl(fragInfo.FragmentNo);
    tmp->noOfRecords = ntohl(fragInfo.NoOfRecordsLow) +
      (((Uint64)ntohl(fragInfo.NoOfRecordsHigh)) << 32);
    tmp->filePosLow = ntohl(fragInfo.FilePosLow);
    tmp->filePosHigh = ntohl(fragInfo.FilePosHigh);

    table->m_fragmentInfo.push_back(tmp);
    table->m_noOfRecords += tmp->noOfRecords;
  }
  return true;
}

425
TableS::TableS(Uint32 version, NdbTableImpl* tableImpl)
426 427 428 429
  : m_dictTable(tableImpl)
{
  m_dictTable = tableImpl;
  m_noOfNullable = m_nullBitmaskSize = 0;
430 431
  m_auto_val_id= ~(Uint32)0;
  m_max_auto_val= 0;
432
  m_noOfRecords= 0;
433
  backupVersion = version;
434
  isSysTable = false;
435
  m_main_table = NULL;
436
  
437
  for (int i = 0; i < tableImpl->getNoOfColumns(); i++)
438 439
    createAttr(tableImpl->getColumn(i));
}
440

441 442
TableS::~TableS()
{
443
  for (Uint32 i= 0; i < allAttributesDesc.size(); i++)
444 445 446
    delete allAttributesDesc[i];
}

447

448 449
// Parse dictTabInfo buffer and pushback to to vector storage 
bool
450 451
RestoreMetaData::parseTableDescriptor(const Uint32 * data, Uint32 len)
{
452
  NdbTableImpl* tableImpl = 0;
453 454
  int ret = NdbDictInterface::parseTableInfo(&tableImpl, data, len, false,
                                             m_fileHeader.NdbVersion);
455
  
456 457
  if (ret != 0) {
    err << "parseTableInfo " << " failed" << endl;
458
    return false;
459 460 461 462 463
  }
  if(tableImpl == 0)
    return false;

  debug << "parseTableInfo " << tableImpl->getName() << " done" << endl;
464
  TableS * table = new TableS(m_fileHeader.NdbVersion, tableImpl);
465 466 467 468
  if(table == NULL) {
    return false;
  }

469 470
  debug << "Parsed table id " << table->getTableId() << endl;
  debug << "Parsed table #attr " << table->getNoOfAttributes() << endl;
471 472
  debug << "Parsed table schema version not used " << endl;

473
  debug << "Pushing table " << table->getTableName() << endl;
474
  debug << "   with " << table->getNoOfAttributes() << " attributes" << endl;
joreland@mysql.com's avatar
joreland@mysql.com committed
475
  
476 477 478 479 480 481
  allTables.push_back(table);

  return true;
}

// Constructor
482
RestoreDataIterator::RestoreDataIterator(const RestoreMetaData & md, void (* _free_data_callback)())
483
  : BackupFile(_free_data_callback), m_metaData(md)
484 485 486 487 488
{
  debug << "RestoreDataIterator constructor" << endl;
  setDataFile(md, 0);
}

489 490 491 492
TupleS & TupleS::operator=(const TupleS& tuple)
{
  prepareRecord(*tuple.m_currentTable);

493
  if (allAttrData)
494 495 496
    memcpy(allAttrData, tuple.allAttrData, getNoOfAttributes()*sizeof(AttributeData));
  
  return *this;
497
}
498 499 500 501
int TupleS::getNoOfAttributes() const {
  if (m_currentTable == 0)
    return 0;
  return m_currentTable->getNoOfAttributes();
502
}
503

504
TableS * TupleS::getTable() const {
505
  return m_currentTable;
506
}
507 508 509 510 511 512 513

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

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

516
bool
517
TupleS::prepareRecord(TableS & tab){
518
  if (allAttrData) {
519 520 521 522 523
    if (getNoOfAttributes() == tab.getNoOfAttributes())
    {
      m_currentTable = &tab;
      return true;
    }
524 525
    delete [] allAttrData;
    m_currentTable= 0;
526
  }
527 528 529 530 531 532
  
  allAttrData = new AttributeData[tab.getNoOfAttributes()];
  if (allAttrData == 0)
    return false;
  
  m_currentTable = &tab;
533

534
  return true;
535 536 537 538 539
}

const TupleS *
RestoreDataIterator::getNextTuple(int  & res)
{
540 541
  Uint32  dataLength = 0;
  // Read record length
542
  if (buffer_read(&dataLength, sizeof(dataLength), 1) != 1){
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    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
559

560
  // Read tuple data
561
  void *_buf_ptr;
562
  if (buffer_get_ptr(&_buf_ptr, 1, dataLenBytes) != dataLenBytes) {
563 564 565 566
    err << "getNextTuple:Read error: " << endl;
    res = -1;
    return NULL;
  }
567 568 569
 
  //if (m_currentTable->getTableId() >= 2) { for (uint ii=0; ii<dataLenBytes; ii+=4) ndbout << "*" << hex << *(Uint32*)( (char*)_buf_ptr+ii ); ndbout << endl; }

570
  Uint32 *buf_ptr = (Uint32*)_buf_ptr, *ptr = buf_ptr;
571
  ptr += m_currentTable->m_nullBitmaskSize;
572
  Uint32 i;
573 574 575 576 577 578 579 580 581 582 583 584
  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;
585
    attr_data->size = 4*sz;
586 587 588 589 590 591 592 593 594

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

595
  for(i = 0; i < m_currentTable->m_fixedAttribs.size(); i++){
596
    assert(ptr < buf_ptr + dataLength);
597 598 599

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

600 601 602 603
    AttributeData * attr_data = m_tuple.getData(attrId);
    const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);

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

605 606
    attr_data->null = false;
    attr_data->void_value = ptr;
607
    attr_data->size = 4*sz;
608

609
    //if (m_currentTable->getTableId() >= 2) { ndbout << "fix i=" << i << " off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
610 611 612 613
    if(!m_hostByteOrder
        && attr_desc->m_column->getType() == NdbDictionary::Column::Timestamp)
      attr_data->u_int32_value[0] = Twiddle32(attr_data->u_int32_value[0]);

614
    if(!Twiddle(attr_desc, attr_data))
615 616 617 618 619 620 621 622
      {
	res = -1;
	return NULL;
      }

    ptr += sz;
  }

623
  // init to NULL
624
  for(i = 0; i < m_currentTable->m_variableAttribs.size(); i++){
625
    const Uint32 attrId = m_currentTable->m_variableAttribs[i]->attrId;
626

627 628 629 630 631 632 633 634 635 636 637 638
    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

639 640
    AttributeData * attr_data = m_tuple.getData(attrId);
    const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);
641
    
642
    // just a reminder - remove when backwards compat implemented
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
643 644
    if(m_currentTable->backupVersion < MAKE_VERSION(5,1,3) && 
       attr_desc->m_column->getNullable()){
645
      const Uint32 ind = attr_desc->m_nullBitIndex;
646
      if(BitmaskImpl::get(m_currentTable->m_nullBitmaskSize, 
647 648 649
			  buf_ptr,ind)){
	attr_data->null = true;
	attr_data->void_value = NULL;
650 651 652
	continue;
      }
    }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
653 654 655 656 657

    if (m_currentTable->backupVersion < MAKE_VERSION(5,1,3))
    {
      sz *= 4;
    }
658
    
659 660
    attr_data->null = false;
    attr_data->void_value = &data->Data[0];
661 662 663
    attr_data->size = sz;

    //if (m_currentTable->getTableId() >= 2) { ndbout << "var off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
664 665 666 667

    /**
     * Compute array size
     */
668 669
    const Uint32 arraySize = sz / (attr_desc->size / 8);
    assert(arraySize <= attr_desc->arraySize);
670
    if(!Twiddle(attr_desc, attr_data, attr_desc->arraySize))
671 672 673 674
      {
	res = -1;
	return NULL;
      }
675 676
    
    ptr += ((sz + 3) >> 2) + 2;
677 678
  }

679 680
  assert(ptr == buf_ptr + dataLength);

681 682
  m_count ++;  
  res = 0;
683
  return &m_tuple;
684 685
} // RestoreDataIterator::getNextTuple

686 687 688
BackupFile::BackupFile(void (* _free_data_callback)()) 
  : free_data_callback(_free_data_callback)
{
689 690 691
  m_file = 0;
  m_path[0] = 0;
  m_fileName[0] = 0;
692 693 694 695 696

  m_buffer_sz = 64*1024;
  m_buffer = malloc(m_buffer_sz);
  m_buffer_ptr = m_buffer;
  m_buffer_data_left = 0;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
}

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;
}

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
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);
733
  }
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

  *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;
765 766 767 768 769 770 771 772 773
}

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);
774
  BaseString::snprintf(name, sz, "BACKUP-%d.%d.ctl", backupId, nodeId);  
775 776 777 778 779 780 781 782 783 784
  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);
785
  BaseString::snprintf(name, sz, "BACKUP-%d-%d.%d.Data", 
786 787 788 789 790 791 792 793 794 795 796
	   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);
797
  BaseString::snprintf(name, sz, "BACKUP-%d.%d.log", 
798 799 800 801 802 803 804 805 806
	   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] == '/'){
807
      BaseString::snprintf(m_path, sz, "%s", p);
808
    } else {
809
      BaseString::snprintf(m_path, sz, "%s%s", p, "/");
810 811 812 813 814
    }
  } else {
    m_path[0] = 0;
  }

815
  BaseString::snprintf(m_fileName, sizeof(m_fileName), "%s%s", m_path, n);
816 817 818 819 820 821 822 823 824
  debug << "Filename = " << m_fileName << endl;
}

bool
BackupFile::readHeader(){
  if(!openFile()){
    return false;
  }
  
825
  if(buffer_read(&m_fileHeader, sizeof(m_fileHeader), 1) != 1){
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    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;
}

873
bool RestoreDataIterator::readFragmentHeader(int & ret, Uint32 *fragmentId)
874 875 876 877 878
{
  BackupFormat::DataFile::FragmentHeader Header;
  
  debug << "RestoreDataIterator::getNextFragment" << endl;
  
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
  while (1)
  {
    /* read first part of header */
    if (buffer_read(&Header, 8, 1) != 1)
    {
      ret = 0;
      return false;
    } // if

    /* skip if EMPTY_ENTRY */
    Header.SectionType  = ntohl(Header.SectionType);
    Header.SectionLength  = ntohl(Header.SectionLength);
    if (Header.SectionType == BackupFormat::EMPTY_ENTRY)
    {
      void *tmp;
      buffer_get_ptr(&tmp, Header.SectionLength*4-8, 1);
      continue;
    }
    break;
  }
  /* read rest of header */
  if (buffer_read(((char*)&Header)+8, sizeof(Header)-8, 1) != 1)
  {
902 903
    ret = 0;
    return false;
904
  }
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
  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;
  }
  
921 922 923 924 925 926
  if(!m_tuple.prepareRecord(*m_currentTable))
  {
    ret =-1;
    return false;
  }

927
  info.setLevel(254);
928
  info << "_____________________________________________________" << endl
929
       << "Processing data in table: " << m_currentTable->getTableName() 
930 931 932 933 934
       << "(" << Header.TableId << ") fragment " 
       << Header.FragmentNo << endl;
  
  m_count = 0;
  ret = 0;
935
  *fragmentId = Header.FragmentNo;
936 937 938 939 940 941 942 943
  return true;
} // RestoreDataIterator::getNextFragment


bool
RestoreDataIterator::validateFragmentFooter() {
  BackupFormat::DataFile::FragmentFooter footer;
  
944
  if (buffer_read(&footer, sizeof(footer), 1) != 1){
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    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

962 963
AttributeDesc::AttributeDesc(NdbDictionary::Column *c)
  : m_column(c)
964
{
joreland@mysql.com's avatar
joreland@mysql.com committed
965 966
  size = 8*NdbColumnImpl::getImpl(* c).m_attrSize;
  arraySize = NdbColumnImpl::getImpl(* c).m_arraySize;
967
}
968

969 970 971
void TableS::createAttr(NdbDictionary::Column *column)
{
  AttributeDesc * d = new AttributeDesc(column);
972 973 974 975
  if(d == NULL) {
    ndbout_c("Restore: Failed to allocate memory");
    abort();
  }
976
  d->attrId = allAttributesDesc.size();
977 978
  allAttributesDesc.push_back(d);

979 980 981
  if (d->m_column->getAutoIncrement())
    m_auto_val_id= d->attrId;

982 983 984 985 986 987
  if(d->m_column->getPrimaryKey() && backupVersion <= MAKE_VERSION(4,1,7))
  {
    m_fixedKeys.push_back(d);
    return;
  }
  
988 989
  if (d->m_column->getArrayType() == NDB_ARRAYTYPE_FIXED &&
      ! d->m_column->getNullable())
990
  {
991 992 993
    m_fixedAttribs.push_back(d);
    return;
  }
994

995
  // just a reminder - does not solve backwards compat
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
996
  if (backupVersion < MAKE_VERSION(5,1,3))
997 998 999 1000 1001
  {
    d->m_nullBitIndex = m_noOfNullable; 
    m_noOfNullable++;
    m_nullBitmaskSize = (m_noOfNullable + 31) / 32;
  }
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  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;
joreland@mysql.com's avatar
joreland@mysql.com committed
1052
  m_last_gci = 0;
1053 1054 1055
}

const LogEntry *
1056
RestoreLogIterator::getNextLogEntry(int & res) {
1057 1058
  // Read record length
  const Uint32 stopGCP = m_metaData.getStopGCP();
1059 1060 1061 1062 1063
  Uint32 tableId;
  Uint32 triggerEvent;
  Uint32 frag_id;
  Uint32 *attr_data;
  Uint32 attr_data_len;
1064
  do {
1065 1066
    Uint32 len;
    Uint32 *logEntryPtr;
1067 1068 1069
    if (buffer_read_ahead(&len, sizeof(Uint32), 1) != 1){
      res= -1;
      return 0;
1070
    }
1071
    len= ntohl(len);
1072

1073
    Uint32 data_len = sizeof(Uint32) + len*4;
1074
    if (buffer_get_ptr((void **)(&logEntryPtr), 1, data_len) != data_len) {
1075 1076
      res= -2;
      return 0;
1077 1078 1079
    }
    
    if(len == 0){
1080
      res= 0;
1081 1082
      return 0;
    }
1083 1084

    if (unlikely(m_metaData.getFileHeader().NdbVersion < NDBD_FRAGID_VERSION))
1085 1086 1087 1088 1089 1090 1091 1092
    {
      /*
        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.
      */
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      typedef BackupFormat::LogFile::LogEntry_no_fragid LogE_no_fragid;
      LogE_no_fragid * logE_no_fragid= (LogE_no_fragid *)logEntryPtr;
      tableId= ntohl(logE_no_fragid->TableId);
      triggerEvent= ntohl(logE_no_fragid->TriggerEvent);
      frag_id= 0;
      attr_data= &logE_no_fragid->Data[0];
      attr_data_len= len - ((offsetof(LogE_no_fragid, Data) >> 2) - 1);
    }
    else /* normal case */
    {
      typedef BackupFormat::LogFile::LogEntry LogE;
      LogE * logE= (LogE *)logEntryPtr;
      tableId= ntohl(logE->TableId);
      triggerEvent= ntohl(logE->TriggerEvent);
      frag_id= ntohl(logE->FragId);
      attr_data= &logE->Data[0];
      attr_data_len= len - ((offsetof(LogE, Data) >> 2) - 1);
1110
    }
1111
    
1112 1113 1114
    const bool hasGcp= (triggerEvent & 0x10000) != 0;
    triggerEvent &= 0xFFFF;

1115
    if(hasGcp){
1116 1117 1118
      // last attr_data is gci info
      attr_data_len--;
      m_last_gci = ntohl(*(attr_data + attr_data_len));
1119
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
1120
  } while(m_last_gci > stopGCP + 1);
1121 1122 1123

  m_logEntry.m_table = m_metaData.getTable(tableId);
  switch(triggerEvent){
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  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;
1139
  m_logEntry.clear();
1140

1141 1142
  AttributeHeader * ah = (AttributeHeader *)attr_data;
  AttributeHeader *end = (AttributeHeader *)(attr_data + attr_data_len);
1143
  AttributeS *  attr;
1144
  m_logEntry.m_frag_id = frag_id;
1145
  while(ah < end){
1146
    attr= m_logEntry.add_attr();
1147 1148 1149
    if(attr == NULL) {
      ndbout_c("Restore: Failed to allocate memory");
      res = -1;
1150
      return 0;
1151
    }
1152

1153 1154 1155
    if(unlikely(!m_hostByteOrder))
      *(Uint32*)ah = Twiddle32(*(Uint32*)ah);

1156 1157 1158 1159 1160
    attr->Desc = (* tab)[ah->getAttributeId()];
    assert(attr->Desc != 0);

    const Uint32 sz = ah->getDataSize();
    if(sz == 0){
1161 1162
      attr->Data.null = true;
      attr->Data.void_value = NULL;
1163
    } else {
1164 1165
      attr->Data.null = false;
      attr->Data.void_value = ah->getDataPtr();
1166 1167
    }
    
1168
    Twiddle(attr->Desc, &(attr->Data));
1169 1170 1171
    
    ah = ah->getNext();
  }
1172

1173 1174 1175 1176
  m_count ++;
  res = 0;
  return &m_logEntry;
}
1177 1178 1179

NdbOut &
operator<<(NdbOut& ndbout, const AttributeS& attr){
1180
  const AttributeData & data = attr.Data;
1181 1182 1183 1184
  const AttributeDesc & desc = *(attr.Desc);

  if (data.null)
  {
1185
    ndbout << g_ndbrecord_print_format.null_string;
1186 1187 1188
    return ndbout;
  }
  
jonas@eel.(none)'s avatar
ndb  
jonas@eel.(none) committed
1189
  NdbRecAttr tmprec(0);
1190
  tmprec.setup(desc.m_column, 0);
1191
  tmprec.receive_data((Uint32*)data.void_value, data.size);
1192
  ndbrecattr_print_formatted(ndbout, tmprec, g_ndbrecord_print_format);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

  return ndbout;
}

// Print tuple data
NdbOut& 
operator<<(NdbOut& ndbout, const TupleS& tuple)
{
  for (int i = 0; i < tuple.getNoOfAttributes(); i++) 
  {
1203 1204
    if (i > 0)
      ndbout << g_ndbrecord_print_format.fields_terminated_by;
1205 1206
    AttributeData * attr_data = tuple.getData(i);
    const AttributeDesc * attr_desc = tuple.getDesc(i);
1207
    const AttributeS attr = {attr_desc, *attr_data};
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    debug << i << " " << attr_desc->m_column->getName();
    ndbout << attr;
  } // 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)" ;
  }
  
1233
  for (Uint32 i= 0; i < logE.size();i++) 
1234
  {
1235
    const AttributeS * attr = logE[i];
1236 1237
    ndbout << attr->Desc->m_column->getName() << "=";
    ndbout << (* attr);
1238
    if (i < (logE.size() - 1))
1239 1240 1241 1242 1243
      ndbout << ", ";
  }
  return ndbout;
}

joreland@mysql.com's avatar
joreland@mysql.com committed
1244
#include <NDBT.hpp>
1245 1246 1247

NdbOut & 
operator<<(NdbOut& ndbout, const TableS & table){
joreland@mysql.com's avatar
joreland@mysql.com committed
1248 1249
  
  ndbout << (* (NDBT_Table*)table.m_dictTable) << endl;
1250 1251
  return ndbout;
}
1252 1253 1254 1255

template class Vector<TableS*>;
template class Vector<AttributeS*>;
template class Vector<AttributeDesc*>;
1256
template class Vector<FragmentInfo*>;
1257
template class Vector<DictObject>;