consumer_restore.cpp 41.5 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

   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 */

16
#include <NDBT_ReturnCodes.h>
17
#include "consumer_restore.hpp"
18
#include <my_sys.h>
19 20
#include <NdbSleep.h>

21 22
extern my_bool opt_core;

23 24 25 26
extern FilteredNdbOut err;
extern FilteredNdbOut info;
extern FilteredNdbOut debug;

27
static void callback(int, NdbTransaction*, void*);
28 29
static Uint32 get_part_id(const NdbDictionary::Table *table,
                          Uint32 hash_value);
30

31
extern const char * g_connect_string;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
32 33
extern BaseString g_options;

34 35 36 37 38
bool
BackupRestore::init()
{
  release();

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
39
  if (!m_restore && !m_restore_meta && !m_restore_epoch)
40 41
    return true;

42
  m_cluster_connection = new Ndb_cluster_connection(g_connect_string);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
43
  m_cluster_connection->set_name(g_options.c_str());
44 45
  if(m_cluster_connection->connect(12, 5, 1) != 0)
  {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
46
    return false;
47 48 49
  }

  m_ndb = new Ndb(m_cluster_connection);
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

  if (m_ndb == NULL)
    return false;
  
  m_ndb->init(1024);
  if (m_ndb->waitUntilReady(30) != 0)
  {
    err << "Failed to connect to ndb!!" << endl;
    return false;
  }
  info << "Connected to ndb!!" << endl;

  m_callback = new restore_callback_t[m_parallelism];

  if (m_callback == 0)
  {
    err << "Failed to allocate callback structs" << endl;
    return false;
  }

  m_free_callback= m_callback;
  for (Uint32 i= 0; i < m_parallelism; i++) {
    m_callback[i].restore= this;
    m_callback[i].connection= 0;
    if (i > 0)
      m_callback[i-1].next= &(m_callback[i]);
  }
  m_callback[m_parallelism-1].next = 0;

  return true;
}

void BackupRestore::release()
{
  if (m_ndb)
  {
    delete m_ndb;
    m_ndb= 0;
  }

  if (m_callback)
  {
    delete [] m_callback;
    m_callback= 0;
  }
95 96 97 98 99 100

  if (m_cluster_connection)
  {
    delete m_cluster_connection;
    m_cluster_connection= 0;
  }
101 102 103 104 105 106 107
}

BackupRestore::~BackupRestore()
{
  release();
}

joreland@mysql.com's avatar
joreland@mysql.com committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
static
int 
match_blob(const char * name){
  int cnt, id1, id2;
  char buf[256];
  if((cnt = sscanf(name, "%[^/]/%[^/]/NDB$BLOB_%d_%d", buf, buf, &id1, &id2)) == 4){
    return id1;
  }
  
  return -1;
}

const NdbDictionary::Table*
BackupRestore::get_table(const NdbDictionary::Table* tab){
  if(m_cache.m_old_table == tab)
    return m_cache.m_new_table;
  m_cache.m_old_table = tab;

  int cnt, id1, id2;
127 128 129 130 131 132 133 134 135 136 137
  char db[256], schema[256];
  if((cnt = sscanf(tab->getName(), "%[^/]/%[^/]/NDB$BLOB_%d_%d", 
		   db, schema, &id1, &id2)) == 4){
    m_ndb->setDatabaseName(db);
    m_ndb->setSchemaName(schema);
    
    BaseString::snprintf(db, sizeof(db), "NDB$BLOB_%d_%d", 
			 m_new_tables[id1]->getTableId(), id2);
    
    m_cache.m_new_table = m_ndb->getDictionary()->getTable(db);
    
joreland@mysql.com's avatar
joreland@mysql.com committed
138 139 140
  } else {
    m_cache.m_new_table = m_new_tables[tab->getTableId()];
  }
141
  assert(m_cache.m_new_table);
joreland@mysql.com's avatar
joreland@mysql.com committed
142 143 144
  return m_cache.m_new_table;
}

145 146 147 148 149
bool
BackupRestore::finalize_table(const TableS & table){
  bool ret= true;
  if (!m_restore && !m_restore_meta)
    return ret;
150 151 152 153 154
  if (!table.have_auto_inc())
    return ret;

  Uint64 max_val= table.get_max_auto_val();
  do
155
  {
156
    Uint64 auto_val = ~(Uint64)0;
157
    int r= m_ndb->readAutoIncrementValue(get_table(table.m_dictTable), auto_val);
158 159 160 161 162 163 164
    if (r == -1 && m_ndb->getNdbError().status == NdbError::TemporaryError)
    {
      NdbSleep_MilliSleep(50);
      continue; // retry
    }
    else if (r == -1 && m_ndb->getNdbError().code != 626)
    {
165
      ret= false;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    }
    else if ((r == -1 && m_ndb->getNdbError().code == 626) ||
             max_val+1 > auto_val || auto_val == ~(Uint64)0)
    {
      r= m_ndb->setAutoIncrementValue(get_table(table.m_dictTable),
                                      max_val+1, false);
      if (r == -1 &&
            m_ndb->getNdbError().status == NdbError::TemporaryError)
      {
        NdbSleep_MilliSleep(50);
        continue; // retry
      }
      ret = (r == 0);
    }
    return (ret);
  } while (1);
182 183
}

184

185
#ifdef NOT_USED
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
static bool default_nodegroups(NdbDictionary::Table *table)
{
  Uint16 *node_groups = (Uint16*)table->getFragmentData();
  Uint32 no_parts = table->getFragmentDataLen() >> 1;
  Uint32 i;

  if (node_groups[0] != 0)
    return false; 
  for (i = 1; i < no_parts; i++) 
  {
    if (node_groups[i] != UNDEF_NODEGROUP)
      return false;
  }
  return true;
}
201
#endif
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 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 425 426


static Uint32 get_no_fragments(Uint64 max_rows, Uint32 no_nodes)
{
  Uint32 i = 0;
  Uint32 acc_row_size = 27;
  Uint32 acc_fragment_size = 512*1024*1024;
  Uint32 no_parts= (max_rows*acc_row_size)/acc_fragment_size + 1;
  Uint32 reported_parts = no_nodes; 
  while (reported_parts < no_parts && ++i < 4 &&
         (reported_parts + no_parts) < MAX_NDB_PARTITIONS)
    reported_parts+= no_nodes;
  if (reported_parts < no_parts)
  {
    err << "Table will be restored but will not be able to handle the maximum";
    err << " amount of rows as requested" << endl;
  }
  return reported_parts;
}


static void set_default_nodegroups(NdbDictionary::Table *table)
{
  Uint32 no_parts = table->getFragmentCount();
  Uint16 node_group[MAX_NDB_PARTITIONS];
  Uint32 i;

  node_group[0] = 0;
  for (i = 1; i < no_parts; i++)
  {
    node_group[i] = UNDEF_NODEGROUP;
  }
  table->setFragmentData((const void*)node_group, 2 * no_parts);
}

Uint32 BackupRestore::map_ng(Uint32 ng)
{
  NODE_GROUP_MAP *ng_map = m_nodegroup_map;

  if (ng == UNDEF_NODEGROUP ||
      ng_map[ng].map_array[0] == UNDEF_NODEGROUP)
  {
    return ng;
  }
  else
  {
    Uint32 new_ng;
    Uint32 curr_inx = ng_map[ng].curr_index;
    Uint32 new_curr_inx = curr_inx + 1;

    assert(ng < MAX_NDB_PARTITIONS);
    assert(curr_inx < MAX_MAPS_PER_NODE_GROUP);
    assert(new_curr_inx < MAX_MAPS_PER_NODE_GROUP);

    if (new_curr_inx >= MAX_MAPS_PER_NODE_GROUP)
      new_curr_inx = 0;
    else if (ng_map[ng].map_array[new_curr_inx] == UNDEF_NODEGROUP)
      new_curr_inx = 0;
    new_ng = ng_map[ng].map_array[curr_inx];
    ng_map[ng].curr_index = new_curr_inx;
    return new_ng;
  }
}


bool BackupRestore::map_nodegroups(Uint16 *ng_array, Uint32 no_parts)
{
  Uint32 i;
  bool mapped = FALSE;
  DBUG_ENTER("map_nodegroups");

  assert(no_parts < MAX_NDB_PARTITIONS);
  for (i = 0; i < no_parts; i++)
  {
    Uint32 ng;
    ng = map_ng((Uint32)ng_array[i]);
    if (ng != ng_array[i])
      mapped = TRUE;
    ng_array[i] = ng;
  }
  DBUG_RETURN(mapped);
}


static void copy_byte(const char **data, char **new_data, uint *len)
{
  **new_data = **data;
  (*data)++;
  (*new_data)++;
  (*len)++;
}


bool BackupRestore::search_replace(char *search_str, char **new_data,
                                   const char **data, const char *end_data,
                                   uint *new_data_len)
{
  uint search_str_len = strlen(search_str);
  uint inx = 0;
  bool in_delimiters = FALSE;
  bool escape_char = FALSE;
  char start_delimiter = 0;
  DBUG_ENTER("search_replace");

  do
  {
    char c = **data;
    copy_byte(data, new_data, new_data_len);
    if (escape_char)
    {
      escape_char = FALSE;
    }
    else if (in_delimiters)
    {
      if (c == start_delimiter)
        in_delimiters = FALSE;
    }
    else if (c == '\'' || c == '\"')
    {
      in_delimiters = TRUE;
      start_delimiter = c;
    }
    else if (c == '\\')
    {
      escape_char = TRUE;
    }
    else if (c == search_str[inx])
    {
      inx++;
      if (inx == search_str_len)
      {
        bool found = FALSE;
        uint number = 0;
        while (*data != end_data)
        {
          if (isdigit(**data))
          {
            found = TRUE;
            number = (10 * number) + (**data);
            if (number > MAX_NDB_NODES)
              break;
          }
          else if (found)
          {
            /*
               After long and tedious preparations we have actually found
               a node group identifier to convert. We'll use the mapping
               table created for node groups and then insert the new number
               instead of the old number.
            */
            uint temp = map_ng(number);
            int no_digits = 0;
            char digits[10];
            while (temp != 0)
            {
              digits[no_digits] = temp % 10;
              no_digits++;
              temp/=10;
            }
            for (no_digits--; no_digits >= 0; no_digits--)
            {
              **new_data = digits[no_digits];
              *new_data_len+=1;
            }
            DBUG_RETURN(FALSE); 
          }
          else
            break;
          (*data)++;
        }
        DBUG_RETURN(TRUE);
      }
    }
    else
      inx = 0;
  } while (*data < end_data);
  DBUG_RETURN(FALSE);
}

bool BackupRestore::map_in_frm(char *new_data, const char *data,
                                       uint data_len, uint *new_data_len)
{
  const char *end_data= data + data_len;
  const char *end_part_data;
  const char *part_data;
  char *extra_ptr;
  uint start_key_definition_len = uint2korr(data + 6);
  uint key_definition_len = uint4korr(data + 47);
  uint part_info_len;
  DBUG_ENTER("map_in_frm");

  if (data_len < 4096) goto error;
  extra_ptr = (char*)data + start_key_definition_len + key_definition_len;
  if ((int)data_len < ((extra_ptr - data) + 2)) goto error;
  extra_ptr = extra_ptr + 2 + uint2korr(extra_ptr);
  if ((int)data_len < ((extra_ptr - data) + 2)) goto error;
  extra_ptr = extra_ptr + 2 + uint2korr(extra_ptr);
  if ((int)data_len < ((extra_ptr - data) + 4)) goto error;
  part_info_len = uint4korr(extra_ptr);
  part_data = extra_ptr + 4;
  if ((int)data_len < ((part_data + part_info_len) - data)) goto error;
 
  do
  {
    copy_byte(&data, &new_data, new_data_len);
  } while (data < part_data);
  end_part_data = part_data + part_info_len;
  do
  {
    if (search_replace((char*)" NODEGROUP = ", &new_data, &data,
                       end_part_data, new_data_len))
      goto error;
  } while (data != end_part_data);
  do
  {
    copy_byte(&data, &new_data, new_data_len);
  } while (data < end_data);
  DBUG_RETURN(FALSE);
error:
  DBUG_RETURN(TRUE);
}


bool BackupRestore::translate_frm(NdbDictionary::Table *table)
{
427
  uchar *pack_data, *data, *new_pack_data;
428
  char *new_data;
429 430
  uint new_data_len;
  size_t data_len, new_pack_len;
431 432 433
  uint no_parts, extra_growth;
  DBUG_ENTER("translate_frm");

434
  pack_data = (uchar*) table->getFrmData();
435 436 437 438 439 440 441 442 443 444 445
  no_parts = table->getFragmentCount();
  /*
    Add max 4 characters per partition to handle worst case
    of mapping from single digit to 5-digit number.
    Fairly future-proof, ok up to 99999 node groups.
  */
  extra_growth = no_parts * 4;
  if (unpackfrm(&data, &data_len, pack_data))
  {
    DBUG_RETURN(TRUE);
  }
446
  if ((new_data = (char*) my_malloc(data_len + extra_growth, MYF(0))))
447 448 449 450 451 452 453 454
  {
    DBUG_RETURN(TRUE);
  }
  if (map_in_frm(new_data, (const char*)data, data_len, &new_data_len))
  {
    my_free(new_data, MYF(0));
    DBUG_RETURN(TRUE);
  }
455
  if (packfrm((uchar*) new_data, new_data_len,
456 457 458 459 460 461 462 463 464
              &new_pack_data, &new_pack_len))
  {
    my_free(new_data, MYF(0));
    DBUG_RETURN(TRUE);
  }
  table->setFrm(new_pack_data, new_pack_len);
  DBUG_RETURN(FALSE);
}

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
#include <signaldata/DictTabInfo.hpp>

bool
BackupRestore::object(Uint32 type, const void * ptr)
{
  if (!m_restore_meta)
    return true;
  
  NdbDictionary::Dictionary* dict = m_ndb->getDictionary();
  switch(type){
  case DictTabInfo::Tablespace:
  {
    NdbDictionary::Tablespace old(*(NdbDictionary::Tablespace*)ptr);

    Uint32 id = old.getObjectId();

    if (!m_no_restore_disk)
    {
      NdbDictionary::LogfileGroup * lg = m_logfilegroups[old.getDefaultLogfileGroupId()];
      old.setDefaultLogfileGroup(* lg);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
485
      info << "Creating tablespace: " << old.getName() << "..." << flush;
486 487 488 489
      int ret = dict->createTablespace(old);
      if (ret)
      {
	NdbError errobj= dict->getNdbError();
490 491
	info << "FAILED" << endl;
        err << "Create tablespace failed: " << old.getName() << ": " << errobj << endl;
492 493
	return false;
      }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
494
      info << "done" << endl;
495 496 497 498
    }
    
    NdbDictionary::Tablespace curr = dict->getTablespace(old.getName());
    NdbError errobj = dict->getNdbError();
499
    if ((int) errobj.classification == (int) ndberror_cl_none)
500 501 502 503
    {
      NdbDictionary::Tablespace* currptr = new NdbDictionary::Tablespace(curr);
      NdbDictionary::Tablespace * null = 0;
      m_tablespaces.set(currptr, id, null);
504
      debug << "Retreived tablespace: " << currptr->getName() 
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
	    << " oldid: " << id << " newid: " << currptr->getObjectId() 
	    << " " << (void*)currptr << endl;
      return true;
    }
    
    err << "Failed to retrieve tablespace \"" << old.getName() << "\": "
	<< errobj << endl;
    
    return false;
    break;
  }
  case DictTabInfo::LogfileGroup:
  {
    NdbDictionary::LogfileGroup old(*(NdbDictionary::LogfileGroup*)ptr);
    
    Uint32 id = old.getObjectId();
    
    if (!m_no_restore_disk)
    {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
524
      info << "Creating logfile group: " << old.getName() << "..." << flush;
525 526 527 528
      int ret = dict->createLogfileGroup(old);
      if (ret)
      {
	NdbError errobj= dict->getNdbError();
529 530
	info << "FAILED" << endl;
        err << "Create logfile group failed: " << old.getName() << ": " << errobj << endl;
531 532
	return false;
      }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
533
      info << "done" << endl;
534 535 536 537
    }
    
    NdbDictionary::LogfileGroup curr = dict->getLogfileGroup(old.getName());
    NdbError errobj = dict->getNdbError();
538
    if ((int) errobj.classification == (int) ndberror_cl_none)
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    {
      NdbDictionary::LogfileGroup* currptr = 
	new NdbDictionary::LogfileGroup(curr);
      NdbDictionary::LogfileGroup * null = 0;
      m_logfilegroups.set(currptr, id, null);
      debug << "Retreived logfile group: " << currptr->getName() 
	    << " oldid: " << id << " newid: " << currptr->getObjectId() 
	    << " " << (void*)currptr << endl;
      return true;
    }
    
    err << "Failed to retrieve logfile group \"" << old.getName() << "\": "
	<< errobj << endl;
    
    return false;
    break;
  }
  case DictTabInfo::Datafile:
  {
    if (!m_no_restore_disk)
    {
      NdbDictionary::Datafile old(*(NdbDictionary::Datafile*)ptr);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
561 562 563
      NdbDictionary::ObjectId objid;
      old.getTablespaceId(&objid);
      NdbDictionary::Tablespace * ts = m_tablespaces[objid.getObjectId()];
564
      debug << "Connecting datafile " << old.getPath() 
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
565
	    << " to tablespace: oldid: " << objid.getObjectId()
566 567
	    << " newid: " << ts->getObjectId() << endl;
      old.setTablespace(* ts);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
568
      info << "Creating datafile \"" << old.getPath() << "\"..." << flush;
569 570
      if (dict->createDatafile(old))
      {
571 572 573
	NdbError errobj= dict->getNdbError();
	info << "FAILED" << endl;
        err << "Create datafile failed: " << old.getPath() << ": " << errobj << endl;
574 575
	return false;
      }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
576
      info << "done" << endl;
577 578 579 580 581 582 583 584 585
    }
    return true;
    break;
  }
  case DictTabInfo::Undofile:
  {
    if (!m_no_restore_disk)
    {
      NdbDictionary::Undofile old(*(NdbDictionary::Undofile*)ptr);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
586 587 588
      NdbDictionary::ObjectId objid;
      old.getLogfileGroupId(&objid);
      NdbDictionary::LogfileGroup * lg = m_logfilegroups[objid.getObjectId()];
589
      debug << "Connecting undofile " << old.getPath() 
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
590
	    << " to logfile group: oldid: " << objid.getObjectId()
591 592 593
	    << " newid: " << lg->getObjectId() 
	    << " " << (void*)lg << endl;
      old.setLogfileGroup(* lg);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
594
      info << "Creating undofile \"" << old.getPath() << "\"..." << flush;
595 596
      if (dict->createUndofile(old))
      {
597 598 599
	NdbError errobj= dict->getNdbError();
	info << "FAILED" << endl;
        err << "Create undofile failed: " << old.getPath() << ": " << errobj << endl;
600 601
	return false;
      }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
602
      info << "done" << endl;
603 604 605 606 607 608 609 610
    }
    return true;
    break;
  }
  }
  return true;
}

611 612 613 614 615
bool
BackupRestore::has_temp_error(){
  return m_temp_error;
}

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
616 617 618 619 620 621 622
bool
BackupRestore::update_apply_status(const RestoreMetaData &metaData)
{
  if (!m_restore_epoch)
    return true;

  bool result= false;
623
  unsigned apply_table_format= 0;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
624 625 626 627 628 629 630 631 632 633 634 635

  m_ndb->setDatabaseName(NDB_REP_DB);
  m_ndb->setSchemaName("def");

  NdbDictionary::Dictionary *dict= m_ndb->getDictionary();
  const NdbDictionary::Table *ndbtab= dict->getTable(Ndb_apply_table);
  if (!ndbtab)
  {
    err << Ndb_apply_table << ": "
	<< dict->getNdbError() << endl;
    return false;
  }
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  if
    (ndbtab->getColumn(0)->getType() == NdbDictionary::Column::Unsigned &&
     ndbtab->getColumn(1)->getType() == NdbDictionary::Column::Bigunsigned)
  {
    if (ndbtab->getNoOfColumns() == 2)
    {
      apply_table_format= 1;
    }
    else if
      (ndbtab->getColumn(2)->getType() == NdbDictionary::Column::Varchar &&
       ndbtab->getColumn(3)->getType() == NdbDictionary::Column::Bigunsigned &&
       ndbtab->getColumn(4)->getType() == NdbDictionary::Column::Bigunsigned)
    {
      apply_table_format= 2;
    }
  }
  if (apply_table_format == 0)
  {
    err << Ndb_apply_table << " has wrong format\n";
    return false;
  }

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
658 659
  Uint32 server_id= 0;
  Uint64 epoch= metaData.getStopGCP();
660 661 662
  Uint64 zero= 0;
  char empty_string[1];
  empty_string[0]= 0;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  NdbTransaction * trans= m_ndb->startTransaction();
  if (!trans)
  {
    err << Ndb_apply_table << ": "
	<< m_ndb->getNdbError() << endl;
    return false;
  }
  NdbOperation * op= trans->getNdbOperation(ndbtab);
  if (!op)
  {
    err << Ndb_apply_table << ": "
	<< trans->getNdbError() << endl;
    goto err;
  }
  if (op->writeTuple() ||
      op->equal(0u, (const char *)&server_id, sizeof(server_id)) ||
      op->setValue(1u, (const char *)&epoch, sizeof(epoch)))
  {
    err << Ndb_apply_table << ": "
	<< op->getNdbError() << endl;
    goto err;
  }
685 686 687 688 689 690 691
  if ((apply_table_format == 2) &&
      (op->setValue(2u, (const char *)&empty_string, 1) ||
       op->setValue(3u, (const char *)&zero, sizeof(zero)) ||
       op->setValue(4u, (const char *)&zero, sizeof(zero))))
  {
    err << Ndb_apply_table << ": "
	<< op->getNdbError() << endl;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705
    goto err;
  }
  if (trans->execute(NdbTransaction::Commit))
  {
    err << Ndb_apply_table << ": "
	<< trans->getNdbError() << endl;
    goto err;
  }
  result= true;
err:
  m_ndb->closeTransaction(trans);
  return result;
}

706
bool
707 708 709 710 711
BackupRestore::table_equal(const TableS &tableS)
{
  if (!m_restore)
    return true;

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 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 765
  const char *tablename = tableS.getTableName();

  if(tableS.m_dictTable == NULL){
    ndbout<<"Table %s has no m_dictTable " << tablename << endl;
    return false;
  }
  /**
   * Ignore blob tables
   */
  if(match_blob(tablename) >= 0)
    return true;

  const NdbTableImpl & tmptab = NdbTableImpl::getImpl(* tableS.m_dictTable);
  if ((int) tmptab.m_indexType != (int) NdbDictionary::Index::Undefined){
    return true;
  }

  BaseString tmp(tablename);
  Vector<BaseString> split;
  if(tmp.split(split, "/") != 3){
    err << "Invalid table name format " << tablename << endl;
    return false;
  }

  m_ndb->setDatabaseName(split[0].c_str());
  m_ndb->setSchemaName(split[1].c_str());

  NdbDictionary::Dictionary* dict = m_ndb->getDictionary();  
  const NdbDictionary::Table* tab = dict->getTable(split[2].c_str());
  if(tab == 0){
    err << "Unable to find table: " << split[2].c_str() << endl;
    return false;
  }

  if(tab->getNoOfColumns() != tableS.m_dictTable->getNoOfColumns())
  {
    ndbout_c("m_columns.size %d != %d",tab->getNoOfColumns(),
                       tableS.m_dictTable->getNoOfColumns());
    return false;
  }

 for(int i = 0; i<tab->getNoOfColumns(); i++)
  {
    if(!tab->getColumn(i)->equal(*(tableS.m_dictTable->getColumn(i))))
    {
      ndbout_c("m_columns %s != %s",tab->getColumn(i)->getName(),
                tableS.m_dictTable->getColumn(i)->getName());
      return false;
    }
  }

  return true;
}

766 767
bool
BackupRestore::createSystable(const TableS & tables){
768 769
  if (!m_restore && !m_restore_meta && !m_restore_epoch)
    return true;
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
  const char *tablename = tables.getTableName();

  if( strcmp(tablename, NDB_REP_DB "/def/" NDB_APPLY_TABLE) != 0 &&
      strcmp(tablename, NDB_REP_DB "/def/" NDB_SCHEMA_TABLE) != 0 )
  {
    return true;
  }

  BaseString tmp(tablename);
  Vector<BaseString> split;
  if(tmp.split(split, "/") != 3){
    err << "Invalid table name format " << tablename << endl;
    return false;
  }

  m_ndb->setDatabaseName(split[0].c_str());
  m_ndb->setSchemaName(split[1].c_str());

  NdbDictionary::Dictionary* dict = m_ndb->getDictionary();
  if( dict->getTable(split[2].c_str()) != NULL ){
    return true;
  }
  return table(tables);
}

795 796
bool
BackupRestore::table(const TableS & table){
joreland@mysql.com's avatar
joreland@mysql.com committed
797
  if (!m_restore && !m_restore_meta)
798
    return true;
799

joreland@mysql.com's avatar
joreland@mysql.com committed
800
  const char * name = table.getTableName();
801
 
joreland@mysql.com's avatar
joreland@mysql.com committed
802 803 804 805 806
  /**
   * Ignore blob tables
   */
  if(match_blob(name) >= 0)
    return true;
807 808
  
  const NdbTableImpl & tmptab = NdbTableImpl::getImpl(* table.m_dictTable);
809
  if ((int) tmptab.m_indexType != (int) NdbDictionary::Index::Undefined){
810 811 812 813
    m_indexes.push_back(table.m_dictTable);
    return true;
  }
  
joreland@mysql.com's avatar
joreland@mysql.com committed
814 815 816
  BaseString tmp(name);
  Vector<BaseString> split;
  if(tmp.split(split, "/") != 3){
817
    err << "Invalid table name format `" << name << "`" << endl;
joreland@mysql.com's avatar
joreland@mysql.com committed
818 819 820 821 822 823
    return false;
  }

  m_ndb->setDatabaseName(split[0].c_str());
  m_ndb->setSchemaName(split[1].c_str());
  
824
  NdbDictionary::Dictionary* dict = m_ndb->getDictionary();
825 826
  if(m_restore_meta)
  {
joreland@mysql.com's avatar
joreland@mysql.com committed
827 828 829
    NdbDictionary::Table copy(*table.m_dictTable);

    copy.setName(split[2].c_str());
830 831
    Uint32 id;
    if (copy.getTablespace(&id))
832 833
    {
      debug << "Connecting " << name << " to tablespace oldid: " << id << flush;
834
      NdbDictionary::Tablespace* ts = m_tablespaces[id];
835 836 837 838
      debug << " newid: " << ts->getObjectId() << endl;
      copy.setTablespace(* ts);
    }
    
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
    if (copy.getDefaultNoPartitionsFlag())
    {
      /*
        Table was defined with default number of partitions. We can restore
        it with whatever is the default in this cluster.
        We use the max_rows parameter in calculating the default number.
      */
      Uint32 no_nodes = m_cluster_connection->no_db_nodes();
      copy.setFragmentCount(get_no_fragments(copy.getMaxRows(),
                            no_nodes));
      set_default_nodegroups(&copy);
    }
    else
    {
      /*
        Table was defined with specific number of partitions. It should be
        restored with the same number of partitions. It will either be
        restored in the same node groups as when backup was taken or by
        using a node group map supplied to the ndb_restore program.
      */
      Uint16 *ng_array = (Uint16*)copy.getFragmentData();
      Uint16 no_parts = copy.getFragmentCount();
      if (map_nodegroups(ng_array, no_parts))
      {
        if (translate_frm(&copy))
        {
          err << "Create table " << table.getTableName() << " failed: ";
          err << "Translate frm error" << endl;
          return false;
        }
      }
      copy.setFragmentData((const void *)ng_array, no_parts << 1);
    }

873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    /**
     * Force of varpart was introduced in 5.1.18, telco 6.1.7 and 6.2.1
     * Since default from mysqld is to add force of varpart (disable with
     * ROW_FORMAT=FIXED) we force varpart onto tables when they are restored
     * from backups taken with older versions. This will be wrong if
     * ROW_FORMAT=FIXED was used on original table, however the likelyhood of
     * this is low, since ROW_FORMAT= was a NOOP in older versions.
     */

    if (table.getBackupVersion() < MAKE_VERSION(5,1,18))
      copy.setForceVarPart(true);
    else if (getMajor(table.getBackupVersion()) == 6 &&
             (table.getBackupVersion() < MAKE_VERSION(6,1,7) ||
              table.getBackupVersion() == MAKE_VERSION(6,2,0)))
      copy.setForceVarPart(true);

889 890 891 892 893 894 895 896 897
    /*
      update min and max rows to reflect the table, this to
      ensure that memory is allocated properly in the ndb kernel
    */
    copy.setMinRows(table.getNoOfRecords());
    if (table.getNoOfRecords() > copy.getMaxRows())
    {
      copy.setMaxRows(table.getNoOfRecords());
    }
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    
    NdbTableImpl &tableImpl = NdbTableImpl::getImpl(copy);
    if (table.getBackupVersion() < MAKE_VERSION(5,1,0) && !m_no_upgrade){
      for(int i= 0; i < copy.getNoOfColumns(); i++)
      {
        NdbDictionary::Column::Type t = copy.getColumn(i)->getType();

        if (t == NdbDictionary::Column::Varchar ||
          t == NdbDictionary::Column::Varbinary)
          tableImpl.getColumn(i)->setArrayType(NdbDictionary::Column::ArrayTypeShortVar);
        if (t == NdbDictionary::Column::Longvarchar ||
          t == NdbDictionary::Column::Longvarbinary)
          tableImpl.getColumn(i)->setArrayType(NdbDictionary::Column::ArrayTypeMediumVar);
      }
    }
913

joreland@mysql.com's avatar
joreland@mysql.com committed
914 915
    if (dict->createTable(copy) == -1) 
    {
916
      err << "Create table `" << table.getTableName() << "` failed: "
917 918 919 920 921 922 923 924 925 926 927 928 929 930
          << dict->getNdbError() << endl;
      if (dict->getNdbError().code == 771)
      {
        /*
          The user on the cluster where the backup was created had specified
          specific node groups for partitions. Some of these node groups
          didn't exist on this cluster. We will warn the user of this and
          inform him of his option.
        */
        err << "The node groups defined in the table didn't exist in this";
        err << " cluster." << endl << "There is an option to use the";
        err << " the parameter ndb-nodegroup-map to define a mapping from";
        err << endl << "the old nodegroups to new nodegroups" << endl; 
      }
joreland@mysql.com's avatar
joreland@mysql.com committed
931 932
      return false;
    }
933 934
    info << "Successfully restored table `"
         << table.getTableName() << "`" << endl;
joreland@mysql.com's avatar
joreland@mysql.com committed
935 936 937 938
  }  
  
  const NdbDictionary::Table* tab = dict->getTable(split[2].c_str());
  if(tab == 0){
939
    err << "Unable to find table: `" << split[2].c_str() << "`" << endl;
940 941
    return false;
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
  if(m_restore_meta)
  {
    if (tab->getFrmData())
    {
      // a MySQL Server table is restored, thus an event should be created
      BaseString event_name("REPL$");
      event_name.append(split[0].c_str());
      event_name.append("/");
      event_name.append(split[2].c_str());

      NdbDictionary::Event my_event(event_name.c_str());
      my_event.setTable(*tab);
      my_event.addTableEvent(NdbDictionary::Event::TE_ALL);

      // add all columns to the event
957
      bool has_blobs = false;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
958 959 960
      for(int a= 0; a < tab->getNoOfColumns(); a++)
      {
	my_event.addEventColumn(a);
961 962 963 964
        NdbDictionary::Column::Type t = tab->getColumn(a)->getType();
        if (t == NdbDictionary::Column::Blob ||
            t == NdbDictionary::Column::Text)
          has_blobs = true;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
965
      }
966 967
      if (has_blobs)
        my_event.mergeEvents(true);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

      while ( dict->createEvent(my_event) ) // Add event to database
      {
	if (dict->getNdbError().classification == NdbError::SchemaObjectExists)
	{
	  info << "Event for table " << table.getTableName()
	       << " already exists, removing.\n";
	  if (!dict->dropEvent(my_event.getName()))
	    continue;
	}
	err << "Create table event for " << table.getTableName() << " failed: "
	    << dict->getNdbError() << endl;
	dict->dropTable(split[2].c_str());
	return false;
      }
      info << "Successfully restored table event " << event_name << endl ;
    }
985
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
986 987 988
  const NdbDictionary::Table* null = 0;
  m_new_tables.fill(table.m_dictTable->getTableId(), null);
  m_new_tables[table.m_dictTable->getTableId()] = tab;
989 990 991
  return true;
}

992 993 994 995 996 997 998
bool
BackupRestore::endOfTables(){
  if(!m_restore_meta)
    return true;

  NdbDictionary::Dictionary* dict = m_ndb->getDictionary();
  for(size_t i = 0; i<m_indexes.size(); i++){
999
    NdbTableImpl & indtab = NdbTableImpl::getImpl(* m_indexes[i]);
1000 1001

    Vector<BaseString> split;
1002 1003 1004 1005 1006 1007 1008 1009
    {
      BaseString tmp(indtab.m_primaryTable.c_str());
      if (tmp.split(split, "/") != 3)
      {
        err << "Invalid table name format `" << indtab.m_primaryTable.c_str()
            << "`" << endl;
        return false;
      }
1010 1011 1012 1013 1014 1015 1016
    }
    
    m_ndb->setDatabaseName(split[0].c_str());
    m_ndb->setSchemaName(split[1].c_str());
    
    const NdbDictionary::Table * prim = dict->getTable(split[2].c_str());
    if(prim == 0){
1017 1018 1019
      err << "Unable to find base table `" << split[2].c_str() 
	  << "` for index `"
	  << indtab.getName() << "`" << endl;
1020 1021 1022 1023
      return false;
    }
    NdbTableImpl& base = NdbTableImpl::getImpl(*prim);
    NdbIndexImpl* idx;
1024 1025 1026 1027 1028 1029 1030 1031
    Vector<BaseString> split_idx;
    {
      BaseString tmp(indtab.getName());
      if (tmp.split(split_idx, "/") != 4)
      {
        err << "Invalid index name format `" << indtab.getName() << "`" << endl;
        return false;
      }
1032 1033 1034
    }
    if(NdbDictInterface::create_index_obj_from_table(&idx, &indtab, &base))
    {
1035 1036
      err << "Failed to create index `" << split_idx[3]
	  << "` on " << split[2].c_str() << endl;
1037 1038
	return false;
    }
1039
    idx->setName(split_idx[3].c_str());
1040 1041 1042
    if(dict->createIndex(* idx) != 0)
    {
      delete idx;
1043 1044
      err << "Failed to create index `" << split_idx[3].c_str()
	  << "` on `" << split[2].c_str() << "`" << endl
1045 1046 1047 1048 1049
	  << dict->getNdbError() << endl;

      return false;
    }
    delete idx;
1050 1051
    info << "Successfully created index `" << split_idx[3].c_str()
	 << "` on `" << split[2].c_str() << "`" << endl;
1052 1053 1054 1055
  }
  return true;
}

1056
void BackupRestore::tuple(const TupleS & tup, Uint32 fragmentId)
1057 1058 1059 1060
{
  if (!m_restore) 
    return;

1061 1062 1063 1064 1065 1066 1067 1068
  while (m_free_callback == 0)
  {
    assert(m_transactions == m_parallelism);
    // send-poll all transactions
    // close transaction is done in callback
    m_ndb->sendPollNdb(3000, 1);
  }
  
1069
  restore_callback_t * cb = m_free_callback;
1070
  
1071 1072
  if (cb == 0)
    assert(false);
1073
  
1074 1075
  m_free_callback = cb->next;
  cb->retries = 0;
1076
  cb->fragId = fragmentId;
1077
  cb->tup = tup; // must do copy!
1078 1079 1080 1081 1082 1083
  tuple_a(cb);

}

void BackupRestore::tuple_a(restore_callback_t *cb)
{
1084
  Uint32 partition_id = cb->fragId;
1085 1086 1087 1088 1089 1090 1091 1092
  while (cb->retries < 10) 
  {
    /**
     * start transactions
     */
    cb->connection = m_ndb->startTransaction();
    if (cb->connection == NULL) 
    {
1093 1094 1095
      if (errorHandler(cb)) 
      {
	m_ndb->sendPollNdb(3000, 1);
1096
	continue;
1097
      }
1098
      err << "Cannot start transaction" << endl;
1099 1100 1101
      exitHandler();
    } // if
    
1102
    const TupleS &tup = cb->tup;
joreland@mysql.com's avatar
joreland@mysql.com committed
1103 1104 1105
    const NdbDictionary::Table * table = get_table(tup.getTable()->m_dictTable);

    NdbOperation * op = cb->connection->getNdbOperation(table);
1106 1107 1108 1109 1110
    
    if (op == NULL) 
    {
      if (errorHandler(cb)) 
	continue;
1111
      err << "Cannot get operation: " << cb->connection->getNdbError() << endl;
1112 1113 1114 1115 1116 1117 1118
      exitHandler();
    } // if
    
    if (op->writeTuple() == -1) 
    {
      if (errorHandler(cb))
	continue;
1119
      err << "Error defining op: " << cb->connection->getNdbError() << endl;
1120 1121
      exitHandler();
    } // if
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

    if (table->getFragmentType() == NdbDictionary::Object::UserDefined)
    {
      if (table->getDefaultNoPartitionsFlag())
      {
        /*
          This can only happen for HASH partitioning with
          user defined hash function where user hasn't
          specified the number of partitions and we
          have to calculate it. We use the hash value
          stored in the record to calculate the partition
          to use.
        */
        int i = tup.getNoOfAttributes() - 1;
	const AttributeData  *attr_data = tup.getData(i);
        Uint32 hash_value =  *attr_data->u_int32_value;
        op->setPartitionId(get_part_id(table, hash_value));
      }
      else
      {
        /*
          Either RANGE or LIST (with or without subparts)
          OR HASH partitioning with user defined hash
          function but with fixed set of partitions.
        */
        op->setPartitionId(partition_id);
      }
    }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    int ret = 0;
    for (int j = 0; j < 2; j++)
    {
      for (int i = 0; i < tup.getNoOfAttributes(); i++) 
      {
	const AttributeDesc * attr_desc = tup.getDesc(i);
	const AttributeData * attr_data = tup.getData(i);
	int size = attr_desc->size;
	int arraySize = attr_desc->arraySize;
	char * dataPtr = attr_data->string_value;
1160 1161
	Uint32 length = 0;
       
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        if (!attr_data->null)
        {
          const unsigned char * src = (const unsigned char *)dataPtr;
          switch(attr_desc->m_column->getType()){
          case NdbDictionary::Column::Varchar:
          case NdbDictionary::Column::Varbinary:
            length = src[0] + 1;
            break;
          case NdbDictionary::Column::Longvarchar:
          case NdbDictionary::Column::Longvarbinary:
            length = src[0] + (src[1] << 8) + 2;
            break;
          default:
            length = attr_data->size;
            break;
          }
1178
        }
1179
	if (j == 0 && tup.getTable()->have_auto_inc(i))
1180
	  tup.getTable()->update_max_auto_val(dataPtr,size*arraySize);
1181
	
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	if (attr_desc->m_column->getPrimaryKey())
	{
	  if (j == 1) continue;
	  ret = op->equal(i, dataPtr, length);
	}
	else
	{
	  if (j == 0) continue;
	  if (attr_data->null) 
	    ret = op->setValue(i, NULL, 0);
	  else
	    ret = op->setValue(i, dataPtr, length);
	}
	if (ret < 0) {
joreland@mysql.com's avatar
joreland@mysql.com committed
1196 1197
	  ndbout_c("Column: %d type %d %d %d %d",i,
		   attr_desc->m_column->getType(),
1198
		   size, arraySize, length);
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	  break;
	}
      }
      if (ret < 0)
	break;
    }
    if (ret < 0)
    {
      if (errorHandler(cb)) 
	continue;
1209
      err << "Error defining op: " << cb->connection->getNdbError() << endl;
1210 1211 1212 1213
      exitHandler();
    }

    // Prepare transaction (the transaction is NOT yet sent to NDB)
1214 1215
    cb->connection->executeAsynchPrepare(NdbTransaction::Commit,
					 &callback, cb);
1216 1217 1218
    m_transactions++;
    return;
  }
1219 1220 1221
  err << "Retried transaction " << cb->retries << " times.\nLast error"
      << m_ndb->getNdbError(cb->error_code) << endl
      << "...Unable to recover from errors. Exiting..." << endl;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
  exitHandler();
}

void BackupRestore::cback(int result, restore_callback_t *cb)
{
  m_transactions--;

  if (result < 0)
  {
    /**
     * Error. temporary or permanent?
     */
    if (errorHandler(cb))
      tuple_a(cb); // retry
    else
    {
      err << "Restore: Failed to restore data due to a unrecoverable error. Exiting..." << endl;
      exitHandler();
    }
  }
1242
  else
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
  {
    /**
     * OK! close transaction
     */
    m_ndb->closeTransaction(cb->connection);
    cb->connection= 0;
    cb->next= m_free_callback;
    m_free_callback= cb;
    m_dataCount++;
  }
}

/**
 * returns true if is recoverable,
 * Error handling based on hugo
 *  false if it is an  error that generates an abort.
 */
bool BackupRestore::errorHandler(restore_callback_t *cb) 
{
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
  NdbError error;
  if(cb->connection)
  {
    error= cb->connection->getNdbError();
    m_ndb->closeTransaction(cb->connection);
    cb->connection= 0;
  }
  else
  {
    error= m_ndb->getNdbError();
  } 
1273 1274 1275

  Uint32 sleepTime = 100 + cb->retries * 300;
  
1276
  cb->retries++;
1277 1278
  cb->error_code = error.code;

1279 1280 1281
  switch(error.status)
  {
  case NdbError::Success:
1282
    err << "Success error: " << error << endl;
1283 1284 1285
    return false;
    // ERROR!
    
1286
  case NdbError::TemporaryError:
1287
    err << "Temporary error: " << error << endl;
1288
    m_temp_error = true;
1289
    NdbSleep_MilliSleep(sleepTime);
1290 1291 1292 1293
    return true;
    // RETRY
    
  case NdbError::UnknownResult:
1294
    err << "Unknown: " << error << endl;
1295 1296 1297 1298 1299 1300
    return false;
    // ERROR!
    
  default:
  case NdbError::PermanentError:
    //ERROR
1301
    err << "Permanent: " << error << endl;
1302 1303
    return false;
  }
1304
  err << "No error status" << endl;
1305 1306 1307 1308 1309 1310
  return false;
}

void BackupRestore::exitHandler() 
{
  release();
1311 1312 1313 1314 1315
  NDBT_ProgramExit(NDBT_FAILED);
  if (opt_core)
    abort();
  else
    exit(NDBT_FAILED);
1316 1317 1318 1319 1320 1321 1322 1323 1324
}


void
BackupRestore::tuple_free()
{
  if (!m_restore)
    return;

1325 1326 1327 1328
  // Poll all transactions
  while (m_transactions)
  {
    m_ndb->sendPollNdb(3000);
1329
  }
1330 1331 1332 1333 1334 1335 1336 1337
}

void
BackupRestore::endOfTuples()
{
  tuple_free();
}

1338
#ifdef NOT_USED
1339 1340 1341 1342 1343 1344 1345 1346
static bool use_part_id(const NdbDictionary::Table *table)
{
  if (table->getDefaultNoPartitionsFlag() &&
      (table->getFragmentType() == NdbDictionary::Object::UserDefined))
    return false;
  else
    return true;
}
1347
#endif
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368

static Uint32 get_part_id(const NdbDictionary::Table *table,
                          Uint32 hash_value)
{
  Uint32 no_frags = table->getFragmentCount();
  
  if (table->getLinearFlag())
  {
    Uint32 part_id;
    Uint32 mask = 1;
    while (no_frags > mask) mask <<= 1;
    mask--;
    part_id = hash_value & mask;
    if (part_id >= no_frags)
      part_id = hash_value & (mask >> 1);
    return part_id;
  }
  else
    return (hash_value % no_frags);
}

1369 1370 1371 1372 1373 1374
void
BackupRestore::logEntry(const LogEntry & tup)
{
  if (!m_restore)
    return;

1375
  NdbTransaction * trans = m_ndb->startTransaction();
1376 1377
  if (trans == NULL) 
  {
Staale Smedseng's avatar
Staale Smedseng committed
1378
    // TODO: handle the error
1379
    err << "Cannot start transaction" << endl;
1380
    exitHandler();
1381 1382
  } // if
  
joreland@mysql.com's avatar
joreland@mysql.com committed
1383 1384
  const NdbDictionary::Table * table = get_table(tup.m_table->m_dictTable);
  NdbOperation * op = trans->getNdbOperation(table);
1385 1386 1387
  if (op == NULL) 
  {
    err << "Cannot get operation: " << trans->getNdbError() << endl;
1388
    exitHandler();
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
  } // if
  
  int check = 0;
  switch(tup.m_type)
  {
  case LogEntry::LE_INSERT:
    check = op->insertTuple();
    break;
  case LogEntry::LE_UPDATE:
    check = op->updateTuple();
    break;
  case LogEntry::LE_DELETE:
    check = op->deleteTuple();
    break;
  default:
    err << "Log entry has wrong operation type."
	   << " Exiting...";
1406
    exitHandler();
1407
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
1408 1409 1410 1411

  if (check != 0) 
  {
    err << "Error defining op: " << trans->getNdbError() << endl;
1412
    exitHandler();
joreland@mysql.com's avatar
joreland@mysql.com committed
1413
  } // if
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

  if (table->getFragmentType() == NdbDictionary::Object::UserDefined)
  {
    if (table->getDefaultNoPartitionsFlag())
    {
      const AttributeS * attr = tup[tup.size()-1];
      Uint32 hash_value = *(Uint32*)attr->Data.string_value;
      op->setPartitionId(get_part_id(table, hash_value));
    }
    else
      op->setPartitionId(tup.m_frag_id);
  }

joreland@mysql.com's avatar
joreland@mysql.com committed
1427
  Bitmask<4096> keys;
1428
  for (Uint32 i= 0; i < tup.size(); i++) 
1429
  {
1430
    const AttributeS * attr = tup[i];
1431 1432
    int size = attr->Desc->size;
    int arraySize = attr->Desc->arraySize;
1433
    const char * dataPtr = attr->Data.string_value;
1434
    
1435
    if (tup.m_table->have_auto_inc(attr->Desc->attrId))
1436
      tup.m_table->update_max_auto_val(dataPtr,size*arraySize);
1437

1438
    const Uint32 length = (size / 8) * arraySize;
1439
    if (attr->Desc->m_column->getPrimaryKey())
joreland@mysql.com's avatar
joreland@mysql.com committed
1440 1441 1442 1443 1444 1445 1446
    {
      if(!keys.get(attr->Desc->attrId))
      {
	keys.set(attr->Desc->attrId);
	check= op->equal(attr->Desc->attrId, dataPtr, length);
      }
    }
1447
    else
joreland@mysql.com's avatar
joreland@mysql.com committed
1448 1449 1450 1451 1452
      check= op->setValue(attr->Desc->attrId, dataPtr, length);
    
    if (check != 0) 
    {
      err << "Error defining op: " << trans->getNdbError() << endl;
1453
      exitHandler();
joreland@mysql.com's avatar
joreland@mysql.com committed
1454
    } // if
1455 1456
  }
  
1457
  const int ret = trans->execute(NdbTransaction::Commit);
1458 1459
  if (ret != 0)
  {
1460 1461 1462
    // Both insert update and delete can fail during log running
    // and it's ok
    // TODO: check that the error is either tuple exists or tuple does not exist?
joreland@mysql.com's avatar
joreland@mysql.com committed
1463 1464
    bool ok= false;
    NdbError errobj= trans->getNdbError();
1465 1466 1467
    switch(tup.m_type)
    {
    case LogEntry::LE_INSERT:
joreland@mysql.com's avatar
joreland@mysql.com committed
1468 1469 1470
      if(errobj.status == NdbError::PermanentError &&
	 errobj.classification == NdbError::ConstraintViolation)
	ok= true;
1471 1472 1473
      break;
    case LogEntry::LE_UPDATE:
    case LogEntry::LE_DELETE:
joreland@mysql.com's avatar
joreland@mysql.com committed
1474 1475 1476
      if(errobj.status == NdbError::PermanentError &&
	 errobj.classification == NdbError::NoDataFound)
	ok= true;
1477 1478
      break;
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
1479
    if (!ok)
1480
    {
joreland@mysql.com's avatar
joreland@mysql.com committed
1481
      err << "execute failed: " << errobj << endl;
1482
      exitHandler();
1483
    }
1484 1485 1486 1487 1488 1489 1490 1491 1492
  }
  
  m_ndb->closeTransaction(trans);
  m_logCount++;
}

void
BackupRestore::endOfLogEntrys()
{
1493 1494 1495 1496 1497
  if (!m_restore)
    return;

  info << "Restored " << m_dataCount << " tuples and "
       << m_logCount << " log entries" << endl;
1498 1499 1500 1501 1502 1503 1504
}

/*
 *   callback : This is called when the transaction is polled
 *              
 *   (This function must have three arguments: 
 *   - The result of the transaction, 
1505
 *   - The NdbTransaction object, and 
1506 1507 1508 1509
 *   - A pointer to an arbitrary object.)
 */

static void
1510
callback(int result, NdbTransaction* trans, void* aObject)
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
{
  restore_callback_t *cb = (restore_callback_t *)aObject;
  (cb->restore)->cback(result, cb);
}

#if 0 // old tuple impl
void
BackupRestore::tuple(const TupleS & tup)
{
  if (!m_restore)
    return;
  while (1) 
  {
1524
    NdbTransaction * trans = m_ndb->startTransaction();
1525 1526
    if (trans == NULL) 
    {
Staale Smedseng's avatar
Staale Smedseng committed
1527
      // TODO: handle the error
1528
      ndbout << "Cannot start transaction" << endl;
1529
      exitHandler();
1530 1531 1532 1533 1534 1535 1536 1537
    } // if
    
    const TableS * table = tup.getTable();
    NdbOperation * op = trans->getNdbOperation(table->getTableName());
    if (op == NULL) 
    {
      ndbout << "Cannot get operation: ";
      ndbout << trans->getNdbError() << endl;
1538
      exitHandler();
1539 1540 1541 1542 1543 1544 1545
    } // if
    
    // TODO: check return value and handle error
    if (op->writeTuple() == -1) 
    {
      ndbout << "writeTuple call failed: ";
      ndbout << trans->getNdbError() << endl;
1546
      exitHandler();
1547 1548 1549 1550 1551 1552 1553
    } // if
    
    for (int i = 0; i < tup.getNoOfAttributes(); i++) 
    {
      const AttributeS * attr = tup[i];
      int size = attr->Desc->size;
      int arraySize = attr->Desc->arraySize;
1554
      const char * dataPtr = attr->Data.string_value;
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
      
      const Uint32 length = (size * arraySize) / 8;
      if (attr->Desc->m_column->getPrimaryKey()) 
	op->equal(i, dataPtr, length);
    }
    
    for (int i = 0; i < tup.getNoOfAttributes(); i++) 
    {
      const AttributeS * attr = tup[i];
      int size = attr->Desc->size;
      int arraySize = attr->Desc->arraySize;
1566
      const char * dataPtr = attr->Data.string_value;
1567 1568 1569
      
      const Uint32 length = (size * arraySize) / 8;
      if (!attr->Desc->m_column->getPrimaryKey())
1570
	if (attr->Data.null)
1571 1572 1573 1574
	  op->setValue(i, NULL, 0);
	else
	  op->setValue(i, dataPtr, length);
    }
1575
    int ret = trans->execute(NdbTransaction::Commit);
1576 1577 1578 1579
    if (ret != 0)
    {
      ndbout << "execute failed: ";
      ndbout << trans->getNdbError() << endl;
1580
      exitHandler();
1581 1582 1583 1584 1585 1586 1587 1588
    }
    m_ndb->closeTransaction(trans);
    if (ret == 0)
      break;
  }
  m_dataCount++;
}
#endif
joreland@mysql.com's avatar
joreland@mysql.com committed
1589 1590 1591

template class Vector<NdbDictionary::Table*>;
template class Vector<const NdbDictionary::Table*>;
1592 1593
template class Vector<NdbDictionary::Tablespace*>;
template class Vector<NdbDictionary::LogfileGroup*>;