wsrep_mysqld.cc 79.5 KB
Newer Older
1
/* Copyright 2008-2015 Codership Oy <http://www.codership.com>
2 3 4

   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.x1
6 7 8 9 10 11 12 13

   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
iangilfillan's avatar
iangilfillan committed
14
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */
15

16
#include "sql_plugin.h"                         /* wsrep_plugins_pre_init() */
Brave Galera Crew's avatar
Brave Galera Crew committed
17 18 19 20
#include "my_global.h"
#include "wsrep_server_state.h"

#include "mariadb.h"
21
#include <mysqld.h>
Brave Galera Crew's avatar
Brave Galera Crew committed
22
#include <transaction.h>
23 24
#include <sql_class.h>
#include <sql_parse.h>
25
#include <sql_base.h> /* find_temporary_table() */
26 27 28 29 30 31
#include "slave.h"
#include "rpl_mi.h"
#include "sql_repl.h"
#include "rpl_filter.h"
#include "sql_callback.h"
#include "sp_head.h"
Sergei Golubchik's avatar
Sergei Golubchik committed
32
#include "sql_show.h"
33 34 35 36 37 38 39 40
#include "sp.h"
#include "wsrep_priv.h"
#include "wsrep_thd.h"
#include "wsrep_sst.h"
#include "wsrep_utils.h"
#include "wsrep_var.h"
#include "wsrep_binlog.h"
#include "wsrep_applier.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
41
#include "wsrep_schema.h"
42
#include "wsrep_xid.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
43 44
#include "wsrep_trans_observer.h"
#include "mysql/service_wsrep.h"
45 46
#include <cstdio>
#include <cstdlib>
Brave Galera Crew's avatar
Brave Galera Crew committed
47
#include <string>
48 49 50
#include "log_event.h"
#include <slave.h>

Brave Galera Crew's avatar
Brave Galera Crew committed
51 52 53 54 55 56
#include <sstream>

/* wsrep-lib */
Wsrep_server_state* Wsrep_server_state::m_instance;

my_bool wsrep_emulate_bin_log  = FALSE; // activating parts of binlog interface
57 58 59 60 61 62
#ifdef GTID_SUPPORT
/* Sidno in global_sid_map corresponding to group uuid */
rpl_sidno wsrep_sidno= -1;
#endif /* GTID_SUPPORT */
my_bool wsrep_preordered_opt= FALSE;

Brave Galera Crew's avatar
Brave Galera Crew committed
63 64 65 66
/* Streaming Replication */
const char *wsrep_fragment_units[]= { "bytes", "rows", "statements", NullS };
const char *wsrep_SR_store_types[]= { "none", "table", NullS };

67
/*
68
 * Begin configuration options
69 70 71 72 73 74
 */

extern my_bool plugins_are_initialized;
extern uint kill_cached_threads;
extern mysql_cond_t COND_thread_cache;

75 76 77 78 79 80 81 82 83 84 85 86
/* System variables. */
const char *wsrep_provider;
const char *wsrep_provider_options;
const char *wsrep_cluster_address;
const char *wsrep_cluster_name;
const char *wsrep_node_name;
const char *wsrep_node_address;
const char *wsrep_node_incoming_address;
const char *wsrep_start_position;
const char *wsrep_data_home_dir;
const char *wsrep_dbug_option;
const char *wsrep_notify_cmd;
87

88 89 90 91 92 93 94 95
my_bool wsrep_debug;                            // Enable debug level logging
my_bool wsrep_convert_LOCK_to_trx;              // Convert locking sessions to trx
my_bool wsrep_auto_increment_control;           // Control auto increment variables
my_bool wsrep_drupal_282555_workaround;         // Retry autoinc insert after dupkey
my_bool wsrep_certify_nonPK;                    // Certify, even when no primary key
my_bool wsrep_recovery;                         // Recovery
my_bool wsrep_replicate_myisam;                 // Enable MyISAM replication
my_bool wsrep_log_conflicts;
Brave Galera Crew's avatar
Brave Galera Crew committed
96
my_bool wsrep_load_data_splitting= 0;           // Commit load data every 10K intervals
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
my_bool wsrep_slave_UK_checks;                  // Slave thread does UK checks
my_bool wsrep_slave_FK_checks;                  // Slave thread does FK checks
my_bool wsrep_restart_slave;                    // Should mysql slave thread be
                                                // restarted, when node joins back?
my_bool wsrep_desync;                           // De(re)synchronize the node from the
                                                // cluster
long wsrep_slave_threads;                       // No. of slave appliers threads
ulong wsrep_retry_autocommit;                   // Retry aborted autocommit trx
ulong wsrep_max_ws_size;                        // Max allowed ws (RBR buffer) size
ulong wsrep_max_ws_rows;                        // Max number of rows in ws
ulong wsrep_forced_binlog_format;
ulong wsrep_mysql_replication_bundle;
bool wsrep_gtid_mode;                           // Use wsrep_gtid_domain_id
                                                // for galera transactions?
uint32 wsrep_gtid_domain_id;                    // gtid_domain_id for galera
                                                // transactions
113

114 115 116 117 118 119 120
/* Other configuration variables and their default values. */
my_bool wsrep_incremental_data_collection= 0;   // Incremental data collection
my_bool wsrep_restart_slave_activated= 0;       // Node has dropped, and slave
                                                // restart will be needed
bool wsrep_new_cluster= false;                  // Bootstrap the cluster?
int wsrep_slave_count_change= 0;                // No. of appliers to stop/start
int wsrep_to_isolation= 0;                      // No. of active TO isolation threads
Brave Galera Crew's avatar
Brave Galera Crew committed
121 122 123 124 125 126 127
long wsrep_max_protocol_version= 4;             // Maximum protocol version to use
long int  wsrep_protocol_version= wsrep_max_protocol_version;
ulong wsrep_trx_fragment_unit= WSREP_FRAG_BYTES;
                                                // unit for fragment size
ulong wsrep_SR_store_type= WSREP_SR_STORE_TABLE;
uint  wsrep_ignore_apply_errors= 0;

128

129 130 131 132 133 134 135
/*
 * End configuration options
 */

/*
 * Other wsrep global variables.
 */
136 137 138 139 140 141 142 143 144 145 146

mysql_mutex_t LOCK_wsrep_ready;
mysql_cond_t  COND_wsrep_ready;
mysql_mutex_t LOCK_wsrep_sst;
mysql_cond_t  COND_wsrep_sst;
mysql_mutex_t LOCK_wsrep_sst_init;
mysql_cond_t  COND_wsrep_sst_init;
mysql_mutex_t LOCK_wsrep_replaying;
mysql_cond_t  COND_wsrep_replaying;
mysql_mutex_t LOCK_wsrep_slave_threads;
mysql_mutex_t LOCK_wsrep_desync;
147
mysql_mutex_t LOCK_wsrep_config_state;
Brave Galera Crew's avatar
Brave Galera Crew committed
148 149
mysql_mutex_t LOCK_wsrep_SR_pool;
mysql_mutex_t LOCK_wsrep_SR_store;
150

151
int wsrep_replaying= 0;
Brave Galera Crew's avatar
Brave Galera Crew committed
152
ulong  wsrep_running_threads= 0; // # of currently running wsrep threads
153 154 155
ulong  my_bind_addr;

#ifdef HAVE_PSI_INTERFACE
Brave Galera Crew's avatar
Brave Galera Crew committed
156
PSI_mutex_key 
157 158
  key_LOCK_wsrep_replaying, key_LOCK_wsrep_ready, key_LOCK_wsrep_sst,
  key_LOCK_wsrep_sst_thread, key_LOCK_wsrep_sst_init,
159
  key_LOCK_wsrep_slave_threads, key_LOCK_wsrep_desync,
Brave Galera Crew's avatar
Brave Galera Crew committed
160 161 162 163
  key_LOCK_wsrep_config_state,
  key_LOCK_wsrep_SR_pool,
  key_LOCK_wsrep_SR_store,
  key_LOCK_wsrep_thd_queue;
164

Brave Galera Crew's avatar
Brave Galera Crew committed
165
PSI_cond_key key_COND_wsrep_thd,
166
  key_COND_wsrep_replaying, key_COND_wsrep_ready, key_COND_wsrep_sst,
Brave Galera Crew's avatar
Brave Galera Crew committed
167 168 169
  key_COND_wsrep_sst_init, key_COND_wsrep_sst_thread,
  key_COND_wsrep_thd_queue;
  
170

171 172
PSI_file_key key_file_wsrep_gra_log;

173 174 175 176 177 178 179 180 181
static PSI_mutex_info wsrep_mutexes[]=
{
  { &key_LOCK_wsrep_ready, "LOCK_wsrep_ready", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_sst, "LOCK_wsrep_sst", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_sst_thread, "wsrep_sst_thread", 0},
  { &key_LOCK_wsrep_sst_init, "LOCK_wsrep_sst_init", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_sst, "LOCK_wsrep_sst", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_replaying, "LOCK_wsrep_replaying", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_slave_threads, "LOCK_wsrep_slave_threads", PSI_FLAG_GLOBAL},
182
  { &key_LOCK_wsrep_desync, "LOCK_wsrep_desync", PSI_FLAG_GLOBAL},
Brave Galera Crew's avatar
Brave Galera Crew committed
183 184 185
  { &key_LOCK_wsrep_config_state, "LOCK_wsrep_config_state", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_SR_pool, "LOCK_wsrep_SR_pool", PSI_FLAG_GLOBAL},
  { &key_LOCK_wsrep_SR_store, "LOCK_wsrep_SR_store", PSI_FLAG_GLOBAL}
186 187 188 189 190 191 192 193
};

static PSI_cond_info wsrep_conds[]=
{
  { &key_COND_wsrep_ready, "COND_wsrep_ready", PSI_FLAG_GLOBAL},
  { &key_COND_wsrep_sst, "COND_wsrep_sst", PSI_FLAG_GLOBAL},
  { &key_COND_wsrep_sst_init, "COND_wsrep_sst_init", PSI_FLAG_GLOBAL},
  { &key_COND_wsrep_sst_thread, "wsrep_sst_thread", 0},
Brave Galera Crew's avatar
Brave Galera Crew committed
194
  { &key_COND_wsrep_thd, "THD::COND_wsrep_thd", 0},
195 196
  { &key_COND_wsrep_replaying, "COND_wsrep_replaying", PSI_FLAG_GLOBAL}
};
197 198 199 200 201

static PSI_file_info wsrep_files[]=
{
  { &key_file_wsrep_gra_log, "wsrep_gra_log", 0}
};
202 203
#endif

Brave Galera Crew's avatar
Brave Galera Crew committed
204
my_bool wsrep_inited= 0; // initialized ?
205

Brave Galera Crew's avatar
Brave Galera Crew committed
206
static wsrep_uuid_t node_uuid= WSREP_UUID_UNDEFINED;
207 208 209 210 211 212 213
static char         cluster_uuid_str[40]= { 0, };

static char provider_name[256]= { 0, };
static char provider_version[256]= { 0, };
static char provider_vendor[256]= { 0, };

/*
Brave Galera Crew's avatar
Brave Galera Crew committed
214 215
 * Wsrep status variables. LOCK_status must be locked When modifying
 * these variables,
216
 */
Brave Galera Crew's avatar
Brave Galera Crew committed
217 218 219 220 221 222 223 224 225 226 227 228 229
my_bool     wsrep_connected         = FALSE;
my_bool     wsrep_ready             = FALSE;
const char* wsrep_cluster_state_uuid= cluster_uuid_str;
long long   wsrep_cluster_conf_id   = WSREP_SEQNO_UNDEFINED;
const char* wsrep_cluster_status    = "Disconnected";
long        wsrep_cluster_size      = 0;
long        wsrep_local_index       = -1;
long long   wsrep_local_bf_aborts   = 0;
const char* wsrep_provider_name     = provider_name;
const char* wsrep_provider_version  = provider_version;
const char* wsrep_provider_vendor   = provider_vendor;
char* wsrep_provider_capabilities   = NULL;
char* wsrep_cluster_capabilities    = NULL;
230 231
/* End wsrep status variables */

Monty's avatar
Monty committed
232
wsp::Config_state *wsrep_config_state;
233

234

Brave Galera Crew's avatar
Brave Galera Crew committed
235 236 237
wsrep_uuid_t               local_uuid       = WSREP_UUID_UNDEFINED;
wsrep_seqno_t              local_seqno      = WSREP_SEQNO_UNDEFINED;
wsp::node_status           local_status;
238

Brave Galera Crew's avatar
Brave Galera Crew committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/*
 */
Wsrep_schema *wsrep_schema= 0;

static void wsrep_log_cb(wsrep::log::level level, const char *msg)
{
  /*
    Silence all wsrep related logging from lib and provider if
    wsrep is not enabled.
  */
  if (WSREP_ON)
  {
    switch (level) {
    case wsrep::log::info:
      sql_print_information("WSREP: %s", msg);
      break;
    case wsrep::log::warning:
      sql_print_warning("WSREP: %s", msg);
      break;
    case wsrep::log::error:
259 260
    sql_print_error("WSREP: %s", msg);
    break;
Brave Galera Crew's avatar
Brave Galera Crew committed
261 262 263 264 265
    case wsrep::log::debug:
      if (wsrep_debug) sql_print_information ("[Debug] WSREP: %s", msg);
    default:
      break;
    }
266 267 268
  }
}

Brave Galera Crew's avatar
Brave Galera Crew committed
269
void wsrep_init_sidno(const wsrep::id& uuid)
270
{
Brave Galera Crew's avatar
Brave Galera Crew committed
271 272 273 274 275 276 277
  /*
    Protocol versions starting from 4 use group gtid as it is.
    For lesser protocol versions generate new Sid map entry from inverted
    uuid.
  */
  rpl_gtid sid;
  if (wsrep_protocol_version >= 4)
278
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
279
    memcpy((void*)&sid, (const uchar*)uuid.data(),16);
280
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
281 282 283 284 285 286 287 288 289 290
  else
  {
    wsrep_uuid_t ltid_uuid;
    for (size_t i= 0; i < sizeof(ltid_uuid.data); ++i)
    {
      ltid_uuid.data[i]= ~((const uchar*)uuid.data())[i];
    }
    memcpy((void*)&sid, (const uchar*)ltid_uuid.data,16);
  }
#ifdef GTID_SUPPORT
291 292
  global_sid_lock->wrlock();
  wsrep_sidno= global_sid_map->add_sid(sid);
293
  WSREP_INFO("Initialized wsrep sidno %d", wsrep_sidno);
294
  global_sid_lock->unlock();
Brave Galera Crew's avatar
Brave Galera Crew committed
295
#endif
296 297
}

Brave Galera Crew's avatar
Brave Galera Crew committed
298
void wsrep_init_schema()
299
{
Brave Galera Crew's avatar
Brave Galera Crew committed
300
  DBUG_ASSERT(!wsrep_schema);
301

Brave Galera Crew's avatar
Brave Galera Crew committed
302 303
  WSREP_INFO("wsrep_init_schema_and_SR %p", wsrep_schema);
  if (!wsrep_schema)
304
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
305 306
    wsrep_schema= new Wsrep_schema();
    if (wsrep_schema->init())
307
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
308 309
      WSREP_ERROR("Failed to init wsrep schema");
      unireg_abort(1);
310
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
311 312
  }
}
313

Brave Galera Crew's avatar
Brave Galera Crew committed
314 315 316 317 318
void wsrep_deinit_schema()
{
  delete wsrep_schema;
  wsrep_schema= 0;
}
319

Brave Galera Crew's avatar
Brave Galera Crew committed
320 321 322 323 324 325
void wsrep_recover_sr_from_storage(THD *orig_thd)
{
  switch (wsrep_SR_store_type)
  {
  case WSREP_SR_STORE_TABLE:
    if (!wsrep_schema)
326
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
327 328 329
      WSREP_ERROR("Wsrep schema not initialized when trying to recover "
                  "streaming transactions");
      unireg_abort(1);
330
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
331
    if (wsrep_schema->recover_sr_transactions(orig_thd))
332
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
333 334
      WSREP_ERROR("Failed to recover SR transactions from schema");
      unireg_abort(1);
335
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
336 337 338 339 340 341
    break;
  default:
    /* */
    WSREP_ERROR("Unsupported wsrep SR store type: %lu", wsrep_SR_store_type);
    unireg_abort(1);
    break;
342
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
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
}

/** Export the WSREP provider's capabilities as a human readable string.
 * The result is saved in a dynamically allocated string of the form:
 * :cap1:cap2:cap3:
 */
static void wsrep_capabilities_export(wsrep_cap_t const cap, char** str)
{
  static const char* names[] =
  {
    /* Keep in sync with wsrep/wsrep_api.h WSREP_CAP_* macros. */
    "MULTI_MASTER",
    "CERTIFICATION",
    "PARALLEL_APPLYING",
    "TRX_REPLAY",
    "ISOLATION",
    "PAUSE",
    "CAUSAL_READS",
    "CAUSAL_TRX",
    "INCREMENTAL_WRITESET",
    "SESSION_LOCKS",
    "DISTRIBUTED_LOCKS",
    "CONSISTENCY_CHECK",
    "UNORDERED",
    "ANNOTATION",
    "PREORDERED",
    "STREAMING",
    "SNAPSHOT",
    "NBO",
  };

  std::string s;
  for (size_t i= 0; i < sizeof(names) / sizeof(names[0]); ++i)
  {
    if (cap & (1ULL << i))
378
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
379
      if (s.empty())
380
      {
Brave Galera Crew's avatar
Brave Galera Crew committed
381
        s= ":";
382
      }
Brave Galera Crew's avatar
Brave Galera Crew committed
383 384
      s += names[i];
      s += ":";
385 386 387
    }
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
388 389
  /* A read from the string pointed to by *str may be started at any time,
   * so it must never point to free(3)d memory or non '\0' terminated string. */
390

Brave Galera Crew's avatar
Brave Galera Crew committed
391
  char* const previous= *str;
392

Brave Galera Crew's avatar
Brave Galera Crew committed
393
  *str= strdup(s.c_str());
394

Brave Galera Crew's avatar
Brave Galera Crew committed
395 396 397 398
  if (previous != NULL)
  {
    free(previous);
  }
399 400
}

Brave Galera Crew's avatar
Brave Galera Crew committed
401 402 403 404
/* Verifies that SE position is consistent with the group position
 * and initializes other variables */
void wsrep_verify_SE_checkpoint(const wsrep_uuid_t& uuid,
                                wsrep_seqno_t const seqno)
405
{
406 407
}

Brave Galera Crew's avatar
Brave Galera Crew committed
408 409 410 411 412 413 414 415
/*
  Wsrep is considered ready if
  1) Provider is not loaded (native mode)
  2) Server has reached synced state
  3) Server is in joiner mode and mysqldump SST method has been
     specified
  See Wsrep_server_service::log_state_change() for further details.
 */
416 417 418 419 420 421 422 423 424 425 426 427 428 429
my_bool wsrep_ready_get (void)
{
  if (mysql_mutex_lock (&LOCK_wsrep_ready)) abort();
  my_bool ret= wsrep_ready;
  mysql_mutex_unlock (&LOCK_wsrep_ready);
  return ret;
}

int wsrep_show_ready(THD *thd, SHOW_VAR *var, char *buff)
{
  var->type= SHOW_MY_BOOL;
  var->value= buff;
  *((my_bool *)buff)= wsrep_ready_get();
  return 0;
430 431
}

Brave Galera Crew's avatar
Brave Galera Crew committed
432
void wsrep_update_cluster_state_uuid(const char* uuid)
433
{
Brave Galera Crew's avatar
Brave Galera Crew committed
434
  strncpy(cluster_uuid_str, uuid, sizeof(cluster_uuid_str) - 1);
435 436
}

Brave Galera Crew's avatar
Brave Galera Crew committed
437
static void wsrep_init_position()
438 439 440
{
}

Brave Galera Crew's avatar
Brave Galera Crew committed
441 442 443 444
/****************************************************************************
                         Helpers for wsrep_init()
 ****************************************************************************/
static std::string wsrep_server_name()
445
{
Brave Galera Crew's avatar
Brave Galera Crew committed
446 447
  std::string ret(wsrep_node_name ? wsrep_node_name : "");
  return ret;
448 449
}

Brave Galera Crew's avatar
Brave Galera Crew committed
450
static std::string wsrep_server_id()
451
{
Brave Galera Crew's avatar
Brave Galera Crew committed
452 453 454 455 456 457
  /* using empty server_id, which enables view change handler to
     set final server_id later on
  */
  std::string ret("");
  return ret;
}
458

Brave Galera Crew's avatar
Brave Galera Crew committed
459 460
static std::string wsrep_server_node_address()
{
461

Brave Galera Crew's avatar
Brave Galera Crew committed
462
  std::string ret;
Jan Lindström's avatar
Jan Lindström committed
463
  if (!wsrep_data_home_dir || strlen(wsrep_data_home_dir) == 0)
Brave Galera Crew's avatar
Brave Galera Crew committed
464
    wsrep_data_home_dir= mysql_real_data_home;
Jan Lindström's avatar
Jan Lindström committed
465

466
  /* Initialize node address */
467 468
  if (!wsrep_node_address || !strcmp(wsrep_node_address, ""))
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
469 470 471 472
    char node_addr[512]= {0, };
    const size_t node_addr_max= sizeof(node_addr) - 1;
    size_t guess_ip_ret= wsrep_guess_ip(node_addr, node_addr_max);
    if (!(guess_ip_ret > 0 && guess_ip_ret < node_addr_max))
473 474 475
    {
      WSREP_WARN("Failed to guess base node address. Set it explicitly via "
                 "wsrep_node_address.");
Brave Galera Crew's avatar
Brave Galera Crew committed
476 477 478 479
    }
    else
    {
      ret= node_addr;
480 481 482 483
    }
  }
  else
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
484
    ret= wsrep_node_address;
485
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
486 487
  return ret;
}
488

Brave Galera Crew's avatar
Brave Galera Crew committed
489 490 491 492
static std::string wsrep_server_incoming_address()
{
  std::string ret;
  const std::string node_addr(wsrep_server_node_address());
493 494
  char inc_addr[512]= { 0, };
  size_t const inc_addr_max= sizeof (inc_addr);
495 496 497 498 499 500

  /*
    In case wsrep_node_incoming_address is either not set or set to AUTO,
    we need to use mysqld's my_bind_addr_str:mysqld_port, lastly fallback
    to wsrep_node_address' value if mysqld's bind-address is not set either.
  */
501 502 503
  if ((!wsrep_node_incoming_address ||
       !strcmp (wsrep_node_incoming_address, WSREP_NODE_INCOMING_AUTO)))
  {
504
    bool is_ipv6= false;
505
    unsigned int my_bind_ip= INADDR_ANY; // default if not set
506

Brave Galera Crew's avatar
Brave Galera Crew committed
507 508
    if (my_bind_addr_str && strlen(my_bind_addr_str) && 
        strcmp(my_bind_addr_str, "*") != 0)
509
    {
510
      my_bind_ip= wsrep_check_ip(my_bind_addr_str, &is_ipv6);
511 512 513 514
    }

    if (INADDR_ANY != my_bind_ip)
    {
515 516 517 518
      /*
        If its a not a valid address, leave inc_addr as empty string. mysqld
        is not listening for client connections on network interfaces.
      */
519 520
      if (INADDR_NONE != my_bind_ip && INADDR_LOOPBACK != my_bind_ip)
      {
521 522 523
        const char *fmt= (is_ipv6) ? "[%s]:%u" : "%s:%u";
        snprintf(inc_addr, inc_addr_max, fmt, my_bind_addr_str, mysqld_port);
      }
524
    }
525
    else /* mysqld binds to 0.0.0.0, try taking IP from wsrep_node_address. */
526
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
527
      if (node_addr.size())
528
      {
Brave Galera Crew's avatar
Brave Galera Crew committed
529 530
        size_t const ip_len= wsrep_host_len(node_addr.c_str(), node_addr.size());
        if (ip_len + 7 /* :55555\0 */ < inc_addr_max)
531
        {
Brave Galera Crew's avatar
Brave Galera Crew committed
532 533 534
          memcpy (inc_addr, node_addr.c_str(), ip_len);
          snprintf(inc_addr + ip_len, inc_addr_max - ip_len, ":%u",
                   (int)mysqld_port);
535
        }
Brave Galera Crew's avatar
Brave Galera Crew committed
536 537 538 539 540 541 542
        else
        {
          WSREP_WARN("Guessing address for incoming client connections: "
                     "address too long.");
          inc_addr[0]= '\0';
        }
      }
543

Brave Galera Crew's avatar
Brave Galera Crew committed
544 545 546 547 548
      if (!strlen(inc_addr))
      {
        WSREP_WARN("Guessing address for incoming client connections failed. "
                   "Try setting wsrep_node_incoming_address explicitly.");
        WSREP_INFO("Node addr: %s", node_addr.c_str());
549 550 551 552 553
      }
    }
  }
  else
  {
554 555 556 557 558 559 560
    wsp::Address addr(wsrep_node_incoming_address);

    if (!addr.is_valid())
    {
      WSREP_WARN("Could not parse wsrep_node_incoming_address : %s",
                 wsrep_node_incoming_address);
      goto done;
561
    }
562 563 564 565 566 567 568 569 570

    /*
      In case port is not specified in wsrep_node_incoming_address, we use
      mysqld_port.
    */
    int port= (addr.get_port() > 0) ? addr.get_port() : (int) mysqld_port;
    const char *fmt= (addr.is_ipv6()) ? "[%s]:%u" : "%s:%u";

    snprintf(inc_addr, inc_addr_max, fmt, addr.get_address(), port);
571
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  
 done:
  ret= wsrep_node_incoming_address;
  return ret;
}

static std::string wsrep_server_working_dir()
{
  std::string ret;
  if (!wsrep_data_home_dir || strlen(wsrep_data_home_dir) == 0)
  {
    ret= mysql_real_data_home;
  }
  else
  {
    ret= wsrep_data_home_dir;
  }
  return ret;
}

static wsrep::gtid wsrep_server_initial_position()
{
  wsrep::gtid ret;
595
  WSREP_DEBUG("Server initial position: %s", wsrep_start_position);
Brave Galera Crew's avatar
Brave Galera Crew committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
  std::istringstream is(wsrep_start_position);
  is >> ret;
  return ret;
}

/*
  Intitialize provider specific status variables
 */
static void wsrep_init_provider_status_variables()
{
  const wsrep::provider& provider=
    Wsrep_server_state::instance().provider();
  strncpy(provider_name,
          provider.name().c_str(),    sizeof(provider_name) - 1);
  strncpy(provider_version,
          provider.version().c_str(), sizeof(provider_version) - 1);
  strncpy(provider_vendor,
          provider.vendor().c_str(),  sizeof(provider_vendor) - 1);
}

int wsrep_init_server()
{
  wsrep::log::logger_fn(wsrep_log_cb);
  try
  {
    std::string server_name;
    std::string server_id;
    std::string node_address;
    std::string incoming_address;
    std::string working_dir;
    wsrep::gtid initial_position;

    server_name= wsrep_server_name();
    server_id= wsrep_server_id();
    node_address= wsrep_server_node_address();
    incoming_address= wsrep_server_incoming_address();
    working_dir= wsrep_server_working_dir();
    initial_position= wsrep_server_initial_position();

    Wsrep_server_state::init_once(server_name,
                                  incoming_address,
                                  node_address,
                                  working_dir,
                                  initial_position,
                                  wsrep_max_protocol_version);
  }
  catch (const wsrep::runtime_error& e)
  {
    WSREP_ERROR("Failed to init wsrep server %s", e.what());
    return 1;
  }
  catch (const std::exception& e)
  {
    WSREP_ERROR("Failed to init wsrep server %s", e.what());
  }
  return 0;
}

void wsrep_init_globals()
{
  wsrep_init_sidno(Wsrep_server_state::instance().connected_gtid().id());
  wsrep_init_schema();
  if (WSREP_ON)
  {
    Wsrep_server_state::instance().initialized();
  }
}
663

Brave Galera Crew's avatar
Brave Galera Crew committed
664 665 666 667 668 669 670 671 672 673 674 675
void wsrep_deinit_server()
{
  wsrep_deinit_schema();
  Wsrep_server_state::destroy();
}

int wsrep_init()
{
  assert(wsrep_provider);

  wsrep_init_position();
  wsrep_sst_auth_init();
676

Brave Galera Crew's avatar
Brave Galera Crew committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  if (strlen(wsrep_provider)== 0 ||
      !strcmp(wsrep_provider, WSREP_NONE))
  {
    // enable normal operation in case no provider is specified
    global_system_variables.wsrep_on= 0;
    int err= Wsrep_server_state::instance().load_provider(wsrep_provider, wsrep_provider_options ? wsrep_provider_options : "");
    if (err)
    {
      DBUG_PRINT("wsrep",("wsrep::init() failed: %d", err));
      WSREP_ERROR("wsrep::init() failed: %d, must shutdown", err);
    }
    else
    {
      wsrep_init_provider_status_variables();
    }
    return err;
  }
694

Brave Galera Crew's avatar
Brave Galera Crew committed
695
  global_system_variables.wsrep_on= 1;
696

Brave Galera Crew's avatar
Brave Galera Crew committed
697 698 699 700 701 702 703
  if (wsrep_gtid_mode && opt_bin_log && !opt_log_slave_updates)
  {
    WSREP_ERROR("Option --log-slave-updates is required if "
                "binlog is enabled, GTID mode is on and wsrep provider "
                "is specified");
    return 1;
  }
704

Brave Galera Crew's avatar
Brave Galera Crew committed
705 706
  if (!wsrep_data_home_dir || strlen(wsrep_data_home_dir) == 0)
    wsrep_data_home_dir= mysql_real_data_home;
707

Brave Galera Crew's avatar
Brave Galera Crew committed
708 709 710 711 712 713
  if (Wsrep_server_state::instance().load_provider(wsrep_provider,
                                                   wsrep_provider_options))
  {
    WSREP_ERROR("Failed to load provider");
    return 1;
  }
714

Brave Galera Crew's avatar
Brave Galera Crew committed
715 716
  if (!wsrep_provider_is_SR_capable() &&
      global_system_variables.wsrep_trx_fragment_size > 0)
717
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
718 719 720 721 722 723 724 725
    WSREP_ERROR("The WSREP provider (%s) does not support streaming "
                "replication but wsrep_trx_fragment_size is set to a "
                "value other than 0 (%llu). Cannot continue. Either set "
                "wsrep_trx_fragment_size to 0 or use wsrep_provider that "
                "supports streaming replication.",
                wsrep_provider, global_system_variables.wsrep_trx_fragment_size);
    Wsrep_server_state::instance().unload_provider();
    return 1;
726
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
727
  wsrep_inited= 1;
728

Brave Galera Crew's avatar
Brave Galera Crew committed
729 730 731
  wsrep_init_provider_status_variables();
  wsrep_capabilities_export(Wsrep_server_state::instance().provider().capabilities(),
                            &wsrep_provider_capabilities);
732

Brave Galera Crew's avatar
Brave Galera Crew committed
733 734 735 736 737
  WSREP_DEBUG("SR storage init for: %s",
              (wsrep_SR_store_type == WSREP_SR_STORE_TABLE) ? "table" : "void");

  return 0;
}
738 739 740 741

/* Initialize wsrep thread LOCKs and CONDs */
void wsrep_thr_init()
{
Monty's avatar
Monty committed
742
  DBUG_ENTER("wsrep_thr_init");
Brave Galera Crew's avatar
Brave Galera Crew committed
743
  wsrep_config_state= new wsp::Config_state;
744
#ifdef HAVE_PSI_INTERFACE
745 746
  mysql_mutex_register("sql", wsrep_mutexes, array_elements(wsrep_mutexes));
  mysql_cond_register("sql", wsrep_conds, array_elements(wsrep_conds));
747 748
  mysql_file_register("sql", wsrep_files, array_elements(wsrep_files));
#endif
749 750 751 752 753 754 755 756 757 758 759 760

  mysql_mutex_init(key_LOCK_wsrep_ready, &LOCK_wsrep_ready, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_wsrep_ready, &COND_wsrep_ready, NULL);
  mysql_mutex_init(key_LOCK_wsrep_sst, &LOCK_wsrep_sst, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_wsrep_sst, &COND_wsrep_sst, NULL);
  mysql_mutex_init(key_LOCK_wsrep_sst_init, &LOCK_wsrep_sst_init, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_wsrep_sst_init, &COND_wsrep_sst_init, NULL);
  mysql_mutex_init(key_LOCK_wsrep_replaying, &LOCK_wsrep_replaying, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_wsrep_replaying, &COND_wsrep_replaying, NULL);
  mysql_mutex_init(key_LOCK_wsrep_slave_threads, &LOCK_wsrep_slave_threads, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_wsrep_desync, &LOCK_wsrep_desync, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_wsrep_config_state, &LOCK_wsrep_config_state, MY_MUTEX_INIT_FAST);
Brave Galera Crew's avatar
Brave Galera Crew committed
761 762 763 764
  mysql_mutex_init(key_LOCK_wsrep_SR_pool,
                   &LOCK_wsrep_SR_pool, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_wsrep_SR_store,
                   &LOCK_wsrep_SR_store, MY_MUTEX_INIT_FAST);
Monty's avatar
Monty committed
765
  DBUG_VOID_RETURN;
766 767
}

Brave Galera Crew's avatar
Brave Galera Crew committed
768
void wsrep_init_startup (bool sst_first)
769 770 771
{
  if (wsrep_init()) unireg_abort(1);

Brave Galera Crew's avatar
Brave Galera Crew committed
772 773
  wsrep_thr_lock_init(wsrep_thd_is_BF, wsrep_thd_bf_abort,
                      wsrep_debug, wsrep_convert_LOCK_to_trx, wsrep_on);
774

775 776 777 778
  /*
    Pre-initialize global_system_variables.table_plugin with a dummy engine
    (placeholder) required during the initialization of wsrep threads (THDs).
    (see: plugin_thdvar_init())
779
    Note: This only needs to be done for rsync & mariabackup based SST methods.
780 781
    In case of mysqldump SST method, the wsrep threads are created after the
    server plugins & global system variables are initialized.
782
  */
783 784
  if (wsrep_before_SE())
    wsrep_plugins_pre_init();
785

786 787 788
  /* Skip replication start if dummy wsrep provider is loaded */
  if (!strcmp(wsrep_provider, WSREP_NONE)) return;

789
  /* Skip replication start if no cluster address */
790
  if (!wsrep_cluster_address || wsrep_cluster_address[0] == 0) return;
791

Brave Galera Crew's avatar
Brave Galera Crew committed
792 793 794 795
  /*
    Read value of wsrep_new_cluster before wsrep_start_replication(),
    the value is reset to FALSE inside wsrep_start_replication.
  */
796 797 798 799 800
  if (!wsrep_start_replication()) unireg_abort(1);

  wsrep_create_rollbacker();
  wsrep_create_appliers(1);

Brave Galera Crew's avatar
Brave Galera Crew committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
  Wsrep_server_state& server_state= Wsrep_server_state::instance();
  /*
    If the SST happens before server initialization, wait until the server
    state reaches initializing. This indicates that
    either SST was not necessary or SST has been delivered.

    With mysqldump SST (!sst_first) wait until the server reaches
    joiner state and procedd to accepting connections.
  */
  if (sst_first)
  {
    server_state.wait_until_state(Wsrep_server_state::s_initializing);
  }
  else
  {
    server_state.wait_until_state(Wsrep_server_state::s_joiner);
  }
818 819 820 821 822 823
}


void wsrep_deinit(bool free_options)
{
  DBUG_ASSERT(wsrep_inited == 1);
Brave Galera Crew's avatar
Brave Galera Crew committed
824 825 826
  WSREP_DEBUG("wsrep_deinit");

  Wsrep_server_state::instance().unload_provider();
827 828 829
  provider_name[0]=    '\0';
  provider_version[0]= '\0';
  provider_vendor[0]=  '\0';
830

831 832
  wsrep_inited= 0;

Brave Galera Crew's avatar
Brave Galera Crew committed
833 834 835 836 837 838 839
  if (wsrep_provider_capabilities != NULL)
  {
    char* p= wsrep_provider_capabilities;
    wsrep_provider_capabilities= NULL;
    free(p);
  }

840 841 842 843
  if (free_options)
  {
    wsrep_sst_auth_free();
  }
844
}
845

846 847 848
/* Destroy wsrep thread LOCKs and CONDs */
void wsrep_thr_deinit()
{
Monty's avatar
Monty committed
849 850
  if (!wsrep_config_state)
    return;                                     // Never initialized
Brave Galera Crew's avatar
Brave Galera Crew committed
851
  WSREP_DEBUG("wsrep_thr_deinit");
852 853 854 855 856 857 858 859 860 861
  mysql_mutex_destroy(&LOCK_wsrep_ready);
  mysql_cond_destroy(&COND_wsrep_ready);
  mysql_mutex_destroy(&LOCK_wsrep_sst);
  mysql_cond_destroy(&COND_wsrep_sst);
  mysql_mutex_destroy(&LOCK_wsrep_sst_init);
  mysql_cond_destroy(&COND_wsrep_sst_init);
  mysql_mutex_destroy(&LOCK_wsrep_replaying);
  mysql_cond_destroy(&COND_wsrep_replaying);
  mysql_mutex_destroy(&LOCK_wsrep_slave_threads);
  mysql_mutex_destroy(&LOCK_wsrep_desync);
862
  mysql_mutex_destroy(&LOCK_wsrep_config_state);
Brave Galera Crew's avatar
Brave Galera Crew committed
863 864 865
  mysql_mutex_destroy(&LOCK_wsrep_SR_pool);
  mysql_mutex_destroy(&LOCK_wsrep_SR_store);

Monty's avatar
Monty committed
866 867
  delete wsrep_config_state;
  wsrep_config_state= 0;                        // Safety
Brave Galera Crew's avatar
Brave Galera Crew committed
868 869 870 871 872 873 874

  if (wsrep_cluster_capabilities != NULL)
  {
    char* p= wsrep_cluster_capabilities;
    wsrep_cluster_capabilities= NULL;
    free(p);
  }
875 876 877 878
}

void wsrep_recover()
{
879 880
  char uuid_str[40];

Brave Galera Crew's avatar
Brave Galera Crew committed
881
  if (wsrep_uuid_compare(&local_uuid, &WSREP_UUID_UNDEFINED) == 0 &&
882 883 884 885 886 887 888
      local_seqno == -2)
  {
    wsrep_uuid_print(&local_uuid, uuid_str, sizeof(uuid_str));
    WSREP_INFO("Position %s:%lld given at startup, skipping position recovery",
               uuid_str, (long long)local_seqno);
    return;
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
889 890 891 892
  wsrep::gtid gtid= wsrep_get_SE_checkpoint();
  std::ostringstream oss;
  oss << gtid;
  WSREP_INFO("Recovered position: %s", oss.str().c_str());
893 894 895 896 897 898
}


void wsrep_stop_replication(THD *thd)
{
  WSREP_INFO("Stop replication");
Brave Galera Crew's avatar
Brave Galera Crew committed
899 900
  if (Wsrep_server_state::instance().state() !=
      Wsrep_server_state::s_disconnected)
901
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
902 903 904
    WSREP_DEBUG("Disconnect provider");
    Wsrep_server_state::instance().disconnect();
    Wsrep_server_state::instance().wait_until_state(Wsrep_server_state::s_disconnected);
905 906
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
907 908 909 910 911 912 913 914 915 916 917
  /* my connection, should not terminate with wsrep_close_client_connection(),
     make transaction to rollback
  */
  if (thd && !thd->wsrep_applier) trans_rollback(thd);
  wsrep_close_client_connections(TRUE, thd);
 
  /* wait until appliers have stopped */
  wsrep_wait_appliers_close(thd);

  node_uuid= WSREP_UUID_UNDEFINED;
}
918

Brave Galera Crew's avatar
Brave Galera Crew committed
919 920 921 922 923 924 925 926 927
void wsrep_shutdown_replication()
{
  WSREP_INFO("Shutdown replication");
  if (Wsrep_server_state::instance().state() != wsrep::server_state::s_disconnected)
  {
    WSREP_DEBUG("Disconnect provider");
    Wsrep_server_state::instance().disconnect();
    Wsrep_server_state::instance().wait_until_state(Wsrep_server_state::s_disconnected);
  }
928 929 930 931

  wsrep_close_client_connections(TRUE);

  /* wait until appliers have stopped */
Brave Galera Crew's avatar
Brave Galera Crew committed
932 933
  wsrep_wait_appliers_close(NULL);
  node_uuid= WSREP_UUID_UNDEFINED;
934

Brave Galera Crew's avatar
Brave Galera Crew committed
935 936
  /* Undocking the thread specific data. */
  my_pthread_setspecific_ptr(THR_THD, NULL);
937 938 939 940
}

bool wsrep_start_replication()
{
Brave Galera Crew's avatar
Brave Galera Crew committed
941 942
  int rcode;
  WSREP_DEBUG("wsrep_start_replication");
943

944 945 946 947 948 949 950 951 952 953
  /*
    if provider is trivial, don't even try to connect,
    but resume local node operation
  */
  if (!WSREP_PROVIDER_EXISTS)
  {
    // enable normal operation in case no provider is specified
    return true;
  }

954
  if (!wsrep_cluster_address || wsrep_cluster_address[0]== 0)
955 956 957 958 959
  {
    // if provider is non-trivial, but no address is specified, wait for address
    return true;
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
960 961
  bool const bootstrap(TRUE == wsrep_new_cluster);
  wsrep_new_cluster= FALSE;
962 963 964

  WSREP_INFO("Start replication");

Brave Galera Crew's avatar
Brave Galera Crew committed
965 966 967 968 969
  if ((rcode= Wsrep_server_state::instance().connect(
        wsrep_cluster_name,
        wsrep_cluster_address,
        wsrep_sst_donor,
        bootstrap)))
Monty's avatar
Monty committed
970
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
971
    DBUG_PRINT("wsrep",("wsrep_ptr->connect(%s) failed: %d",
972 973 974
                        wsrep_cluster_address, rcode));
    WSREP_ERROR("wsrep::connect(%s) failed: %d",
                wsrep_cluster_address, rcode);
975 976 977 978
    return false;
  }
  else
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
979
    try
980
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
981 982
      std::string opts= Wsrep_server_state::instance().provider().options();
      wsrep_provider_options_init(opts.c_str());
983
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
984
    catch (const wsrep::runtime_error&)
985 986 987 988 989 990 991 992
    {
      WSREP_WARN("Failed to get wsrep options");
    }
  }

  return true;
}

993 994
bool wsrep_must_sync_wait (THD* thd, uint mask)
{
Brave Galera Crew's avatar
Brave Galera Crew committed
995 996 997 998
  bool ret;
  mysql_mutex_lock(&thd->LOCK_thd_data);
  ret= (thd->variables.wsrep_sync_wait & mask) &&
    thd->wsrep_client_thread &&
999
    thd->variables.wsrep_on &&
1000 1001
    !(thd->variables.wsrep_dirty_reads &&
      !is_update_query(thd->lex->sql_command)) &&
1002
    !thd->in_active_multi_stmt_transaction() &&
Brave Galera Crew's avatar
Brave Galera Crew committed
1003 1004 1005 1006 1007
    thd->wsrep_trx().state() !=
    wsrep::transaction::s_replaying &&
    thd->wsrep_cs().sync_wait_gtid().is_undefined();
  mysql_mutex_unlock(&thd->LOCK_thd_data);
  return ret;
1008 1009
}

1010 1011
bool wsrep_sync_wait (THD* thd, uint mask)
{
1012
  if (wsrep_must_sync_wait(thd, mask))
1013
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1014 1015 1016 1017 1018 1019 1020 1021 1022
    WSREP_DEBUG("wsrep_sync_wait: thd->variables.wsrep_sync_wait= %u, "
                "mask= %u, thd->variables.wsrep_on= %d",
                thd->variables.wsrep_sync_wait, mask,
                thd->variables.wsrep_on);
    /*
      This allows autocommit SELECTs and a first SELECT after SET AUTOCOMMIT=0
      TODO: modify to check if thd has locked any rows.
    */
    if (thd->wsrep_cs().sync_wait(-1))
1023 1024 1025 1026
    {
      const char* msg;
      int err;

Brave Galera Crew's avatar
Brave Galera Crew committed
1027 1028 1029 1030 1031 1032
      /*
        Possibly relevant error codes:
        ER_CHECKREAD, ER_ERROR_ON_READ, ER_INVALID_DEFAULT, ER_EMPTY_QUERY,
        ER_FUNCTION_NOT_DEFINED, ER_NOT_ALLOWED_COMMAND, ER_NOT_SUPPORTED_YET,
        ER_FEATURE_DISABLED, ER_QUERY_INTERRUPTED
      */
1033

Brave Galera Crew's avatar
Brave Galera Crew committed
1034
      switch (thd->wsrep_cs().current_error())
1035
      {
Brave Galera Crew's avatar
Brave Galera Crew committed
1036
      case wsrep::e_not_supported_error:
1037
        msg= "synchronous reads by wsrep backend. "
Brave Galera Crew's avatar
Brave Galera Crew committed
1038
          "Please unset wsrep_causal_reads variable.";
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        err= ER_NOT_SUPPORTED_YET;
        break;
      default:
        msg= "Synchronous wait failed.";
        err= ER_LOCK_WAIT_TIMEOUT; // NOTE: the above msg won't be displayed
                                   //       with ER_LOCK_WAIT_TIMEOUT
      }

      my_error(err, MYF(0), msg);

      return true;
    }
  }

  return false;
}

Brave Galera Crew's avatar
Brave Galera Crew committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
enum wsrep::provider::status
wsrep_sync_wait_upto (THD*          thd,
                      wsrep_gtid_t* upto,
                      int           timeout)
{
  DBUG_ASSERT(upto);
  enum wsrep::provider::status ret;
  if (upto)
  {
    wsrep::gtid upto_gtid(wsrep::id(upto->uuid.data, sizeof(upto->uuid.data)),
                          wsrep::seqno(upto->seqno));
    ret= Wsrep_server_state::instance().wait_for_gtid(upto_gtid, timeout);
  }
  else
  {
    ret= Wsrep_server_state::instance().causal_read(timeout).second;
  }
  WSREP_DEBUG("wsrep_sync_wait_upto: %d", ret);
  return ret;
}

1077
void wsrep_keys_free(wsrep_key_arr_t* key_arr)
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
{
    for (size_t i= 0; i < key_arr->keys_len; ++i)
    {
        my_free((void*)key_arr->keys[i].key_parts);
    }
    my_free(key_arr->keys);
    key_arr->keys= 0;
    key_arr->keys_len= 0;
}

/*!
 * @param db      Database string
 * @param table   Table string
 * @param key     Array of wsrep_key_t
 * @param key_len In: number of elements in key array, Out: number of
 *                elements populated
 *
 * @return true if preparation was successful, otherwise false.
 */

static bool wsrep_prepare_key_for_isolation(const char* db,
Brave Galera Crew's avatar
Brave Galera Crew committed
1099 1100 1101
                                           const char* table,
                                           wsrep_buf_t* key,
                                           size_t* key_len)
1102
{
1103
  if (*key_len < 2) return false;
1104

1105 1106 1107 1108 1109 1110 1111 1112
  switch (wsrep_protocol_version)
  {
  case 0:
    *key_len= 0;
    break;
  case 1:
  case 2:
  case 3:
Brave Galera Crew's avatar
Brave Galera Crew committed
1113
  case 4:
1114 1115 1116
  {
    *key_len= 0;
    if (db)
1117
    {
1118 1119 1120 1121 1122 1123 1124 1125 1126
      key[*key_len].ptr= db;
      key[*key_len].len= strlen(db);
      ++(*key_len);
      if (table)
      {
        key[*key_len].ptr= table;
        key[*key_len].len= strlen(table);
        ++(*key_len);
      }
1127
    }
1128 1129 1130
    break;
  }
  default:
Brave Galera Crew's avatar
Brave Galera Crew committed
1131 1132 1133
    assert(0);
    WSREP_ERROR("Unsupported protocol version: %ld", wsrep_protocol_version);
    unireg_abort(1);
1134 1135 1136
    return false;
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
1137 1138
    return true;
}
1139 1140 1141 1142 1143 1144

static bool wsrep_prepare_key_for_isolation(const char* db,
                                            const char* table,
                                            wsrep_key_arr_t* ka)
{
  wsrep_key_t* tmp;
Brave Galera Crew's avatar
Brave Galera Crew committed
1145 1146 1147
  tmp= (wsrep_key_t*)my_realloc(ka->keys,
                                (ka->keys_len + 1) * sizeof(wsrep_key_t),
                                MYF(MY_ALLOW_ZERO_PTR));
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  if (!tmp)
  {
    WSREP_ERROR("Can't allocate memory for key_array");
    return false;
  }
  ka->keys= tmp;
  if (!(ka->keys[ka->keys_len].key_parts= (wsrep_buf_t*)
        my_malloc(sizeof(wsrep_buf_t)*2, MYF(0))))
  {
    WSREP_ERROR("Can't allocate memory for key_parts");
    return false;
  }
  ka->keys[ka->keys_len].key_parts_num= 2;
  ++ka->keys_len;
  if (!wsrep_prepare_key_for_isolation(db, table,
                                       (wsrep_buf_t*)ka->keys[ka->keys_len - 1].key_parts,
                                       &ka->keys[ka->keys_len - 1].key_parts_num))
  {
    WSREP_ERROR("Preparing keys for isolation failed");
    return false;
  }

  return true;
}

1173
static bool wsrep_prepare_keys_for_alter_add_fk(const char* child_table_db,
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
                                                Alter_info* alter_info,
                                                wsrep_key_arr_t* ka)
{
  Key *key;
  List_iterator<Key> key_iterator(alter_info->key_list);
  while ((key= key_iterator++))
  {
    if (key->type == Key::FOREIGN_KEY)
    {
      Foreign_key *fk_key= (Foreign_key *)key;
1184 1185
      const char *db_name= fk_key->ref_db.str;
      const char *table_name= fk_key->ref_table.str;
1186 1187 1188 1189 1190 1191
      if (!db_name)
      {
        db_name= child_table_db;
      }
      if (!wsrep_prepare_key_for_isolation(db_name, table_name, ka))
      {
1192
        return false;
1193
      }
1194
    }
1195 1196
  }
  return true;
1197 1198
}

1199 1200 1201 1202 1203 1204
static bool wsrep_prepare_keys_for_isolation(THD*              thd,
                                             const char*       db,
                                             const char*       table,
                                             const TABLE_LIST* table_list,
                                             Alter_info*       alter_info,
                                             wsrep_key_arr_t*  ka)
1205
{
1206 1207
  ka->keys= 0;
  ka->keys_len= 0;
1208

1209 1210
  if (db || table)
  {
1211
    if (!wsrep_prepare_key_for_isolation(db, table, ka))
1212 1213
      goto err;
  }
1214

1215 1216
  for (const TABLE_LIST* table= table_list; table; table= table->next_global)
  {
1217
    if (!wsrep_prepare_key_for_isolation(table->db.str, table->table_name.str, ka))
1218
      goto err;
1219 1220
  }

1221
  if (alter_info && (alter_info->flags & (ALTER_ADD_FOREIGN_KEY)))
1222
  {
1223
    if (!wsrep_prepare_keys_for_alter_add_fk(table_list->db.str, alter_info, ka))
1224 1225
      goto err;
  }
1226 1227
  return false;

1228
err:
Brave Galera Crew's avatar
Brave Galera Crew committed
1229 1230
    wsrep_keys_free(ka);
    return true;
1231 1232
}

Brave Galera Crew's avatar
Brave Galera Crew committed
1233 1234 1235 1236 1237
/*
 * Prepare key list from db/table and table_list
 *
 * Return zero in case of success, 1 in case of failure.
 */
1238

1239 1240 1241 1242 1243
bool wsrep_prepare_keys_for_isolation(THD*              thd,
                                      const char*       db,
                                      const char*       table,
                                      const TABLE_LIST* table_list,
                                      wsrep_key_arr_t*  ka)
1244
{
1245
  return wsrep_prepare_keys_for_isolation(thd, db, table, table_list, NULL, ka);
1246 1247
}

1248 1249 1250
bool wsrep_prepare_key(const uchar* cache_key, size_t cache_key_len,
                       const uchar* row_id, size_t row_id_len,
                       wsrep_buf_t* key, size_t* key_len)
1251 1252 1253 1254 1255 1256 1257 1258
{
    if (*key_len < 3) return false;

    *key_len= 0;
    switch (wsrep_protocol_version)
    {
    case 0:
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
1259 1260
        key[0].ptr= cache_key;
        key[0].len= cache_key_len;
1261

Brave Galera Crew's avatar
Brave Galera Crew committed
1262
        *key_len= 1;
1263 1264 1265 1266 1267
        break;
    }
    case 1:
    case 2:
    case 3:
Brave Galera Crew's avatar
Brave Galera Crew committed
1268
    case 4:
1269
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
1270 1271
        key[0].ptr= cache_key;
        key[0].len= strlen( (char*)cache_key );
1272

Brave Galera Crew's avatar
Brave Galera Crew committed
1273 1274
        key[1].ptr= cache_key + strlen( (char*)cache_key ) + 1;
        key[1].len= strlen( (char*)(key[1].ptr) );
1275

Brave Galera Crew's avatar
Brave Galera Crew committed
1276
        *key_len= 2;
1277 1278 1279 1280 1281 1282
        break;
    }
    default:
        return false;
    }

Brave Galera Crew's avatar
Brave Galera Crew committed
1283 1284
    key[*key_len].ptr= row_id;
    key[*key_len].len= row_id_len;
1285 1286 1287 1288 1289
    ++(*key_len);

    return true;
}

Brave Galera Crew's avatar
Brave Galera Crew committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
bool wsrep_prepare_key_for_innodb(THD* thd,
                                  const uchar* cache_key,
                                  size_t cache_key_len,
                                  const uchar* row_id,
                                  size_t row_id_len,
                                  wsrep_buf_t* key,
                                  size_t* key_len)
{

  return wsrep_prepare_key(cache_key, cache_key_len, row_id, row_id_len, key, key_len);
}

wsrep::key wsrep_prepare_key_for_toi(const char* db, const char* table,
                                     enum wsrep::key::type type)
{
  wsrep::key ret(type);
  DBUG_ASSERT(db);
  ret.append_key_part(db, strlen(db));
  if (table) ret.append_key_part(table, strlen(table));
  return ret;
}

wsrep::key_array
wsrep_prepare_keys_for_alter_add_fk(const char* child_table_db,
                                    Alter_info* alter_info)

{
  wsrep::key_array ret;
  Key *key;
  List_iterator<Key> key_iterator(alter_info->key_list);
  while ((key= key_iterator++))
  {
    if (key->type == Key::FOREIGN_KEY)
    {
      Foreign_key *fk_key= (Foreign_key *)key;
      const char *db_name= fk_key->ref_db.str;
      const char *table_name= fk_key->ref_table.str;
      if (!db_name)
      {
        db_name= child_table_db;
      }
      ret.push_back(wsrep_prepare_key_for_toi(db_name, table_name,
                                              wsrep::key::exclusive));
    }
  }
  return ret;
}
1337

Brave Galera Crew's avatar
Brave Galera Crew committed
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
wsrep::key_array wsrep_prepare_keys_for_toi(const char* db,
                                            const char* table,
                                            const TABLE_LIST* table_list,
                                            Alter_info* alter_info)
{
  wsrep::key_array ret;
  if (db || table)
  {
    ret.push_back(wsrep_prepare_key_for_toi(db, table, wsrep::key::exclusive));
  }
  for (const TABLE_LIST* table= table_list; table; table= table->next_global)
  {
    ret.push_back(wsrep_prepare_key_for_toi(table->db.str, table->table_name.str,
                                            wsrep::key::exclusive));
  }
  if (alter_info && (alter_info->flags & ALTER_ADD_FOREIGN_KEY))
  {
    wsrep::key_array fk(wsrep_prepare_keys_for_alter_add_fk(table_list->db.str, alter_info));
    if (!fk.empty())
    {
      ret.insert(ret.end(), fk.begin(), fk.end());
    }
  }
  return ret;
}
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
/*
 * Construct Query_log_Event from thd query and serialize it
 * into buffer.
 *
 * Return 0 in case of success, 1 in case of error.
 */
int wsrep_to_buf_helper(
    THD* thd, const char *query, uint query_len, uchar** buf, size_t* buf_len)
{
  IO_CACHE tmp_io_cache;
Brave Galera Crew's avatar
Brave Galera Crew committed
1373
  Log_event_writer writer(&tmp_io_cache, 0);
1374 1375 1376 1377
  if (open_cached_file(&tmp_io_cache, mysql_tmpdir, TEMP_PREFIX,
                       65536, MYF(MY_WME)))
    return 1;
  int ret(0);
1378 1379
  enum enum_binlog_checksum_alg current_binlog_check_alg=
    (enum_binlog_checksum_alg) binlog_checksum_options;
1380

1381
  Format_description_log_event *tmp_fd= new Format_description_log_event(4);
1382
  tmp_fd->checksum_alg= current_binlog_check_alg;
1383
  writer.write(tmp_fd);
1384 1385
  delete tmp_fd;

1386 1387 1388 1389 1390
#ifdef GTID_SUPPORT
  if (thd->variables.gtid_next.type == GTID_GROUP)
  {
      Gtid_log_event gtid_ev(thd, FALSE, &thd->variables.gtid_next);
      if (!gtid_ev.is_valid()) ret= 0;
1391
      if (!ret && writer.write(&gtid_ev)) ret= 1;
1392 1393
  }
#endif /* GTID_SUPPORT */
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
  if (wsrep_gtid_mode && thd->variables.gtid_seq_no)
  {
    Gtid_log_event gtid_event(thd, thd->variables.gtid_seq_no,
                          thd->variables.gtid_domain_id,
                          true, LOG_EVENT_SUPPRESS_USE_F,
                          true, 0);
    gtid_event.server_id= thd->variables.server_id;
    if (!gtid_event.is_valid()) ret= 0;
    ret= writer.write(&gtid_event);
  }
1404 1405 1406 1407 1408 1409 1410

  /* if there is prepare query, add event for it */
  if (!ret && thd->wsrep_TOI_pre_query)
  {
    Query_log_event ev(thd, thd->wsrep_TOI_pre_query,
		       thd->wsrep_TOI_pre_query_len,
		       FALSE, FALSE, FALSE, 0);
1411
    ev.checksum_alg= current_binlog_check_alg;
1412
    if (writer.write(&ev)) ret= 1;
1413 1414 1415 1416
  }

  /* continue to append the actual query */
  Query_log_event ev(thd, query, query_len, FALSE, FALSE, FALSE, 0);
1417
  ev.checksum_alg= current_binlog_check_alg;
1418
  if (!ret && writer.write(&ev)) ret= 1;
1419 1420 1421 1422 1423
  if (!ret && wsrep_write_cache_buf(&tmp_io_cache, buf, buf_len)) ret= 1;
  close_cached_file(&tmp_io_cache);
  return ret;
}

Sergei Golubchik's avatar
Sergei Golubchik committed
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
static int
wsrep_alter_query_string(THD *thd, String *buf)
{
  /* Append the "ALTER" part of the query */
  if (buf->append(STRING_WITH_LEN("ALTER ")))
    return 1;
  /* Append definer */
  append_definer(thd, buf, &(thd->lex->definer->user), &(thd->lex->definer->host));
  /* Append the left part of thd->query after event name part */
  if (buf->append(thd->lex->stmt_definition_begin,
                  thd->lex->stmt_definition_end -
                  thd->lex->stmt_definition_begin))
    return 1;

  return 0;
}

1441
static int wsrep_alter_event_query(THD *thd, uchar** buf, size_t* buf_len)
Sergei Golubchik's avatar
Sergei Golubchik committed
1442 1443 1444 1445 1446
{
  String log_query;

  if (wsrep_alter_query_string(thd, &log_query))
  {
1447
    WSREP_WARN("events alter string failed: schema: %s, query: %s",
1448
               thd->get_db(), thd->query());
Sergei Golubchik's avatar
Sergei Golubchik committed
1449 1450 1451 1452 1453
    return 1;
  }
  return wsrep_to_buf_helper(thd, log_query.ptr(), log_query.length(), buf, buf_len);
}

1454 1455 1456 1457 1458
#include "sql_show.h"
static int
create_view_query(THD *thd, uchar** buf, size_t* buf_len)
{
    LEX *lex= thd->lex;
1459
    SELECT_LEX *select_lex= lex->first_select_lex();
1460
    TABLE_LIST *first_table= select_lex->table_list.first;
Brave Galera Crew's avatar
Brave Galera Crew committed
1461
    TABLE_LIST *views= first_table;
Michael Widenius's avatar
Michael Widenius committed
1462
    LEX_USER *definer;
1463
    String buff;
1464 1465 1466 1467
    const LEX_CSTRING command[3]=
      {{ STRING_WITH_LEN("CREATE ") },
       { STRING_WITH_LEN("ALTER ") },
       { STRING_WITH_LEN("CREATE OR REPLACE ") }};
1468

Michael Widenius's avatar
Michael Widenius committed
1469
    buff.append(&command[thd->lex->create_view->mode]);
1470 1471 1472 1473

    if (lex->definer)
      definer= get_current_user(thd, lex->definer);
    else
1474 1475 1476 1477 1478 1479 1480
    {
      /*
        DEFINER-clause is missing; we have to create default definer in
        persistent arena to be PS/SP friendly.
        If this is an ALTER VIEW then the current user should be set as
        the definer.
      */
1481 1482
      definer= create_default_definer(thd, false);
    }
1483

1484 1485
    if (definer)
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
1486 1487
      views->definer.user= definer->user;
      views->definer.host= definer->host;
1488 1489 1490
    } else {
      WSREP_ERROR("Failed to get DEFINER for VIEW.");
      return 1;
1491 1492
    }

Brave Galera Crew's avatar
Brave Galera Crew committed
1493 1494 1495
    views->algorithm   = lex->create_view->algorithm;
    views->view_suid   = lex->create_view->suid;
    views->with_check  = lex->create_view->check;
1496 1497 1498 1499

    view_store_options(thd, views, &buff);
    buff.append(STRING_WITH_LEN("VIEW "));
    /* Test if user supplied a db (ie: we did not use thd->db) */
1500 1501
    if (views->db.str && views->db.str[0] &&
        (thd->db.str == NULL || cmp(&views->db, &thd->db)))
1502
    {
1503
      append_identifier(thd, &buff, &views->db);
1504 1505
      buff.append('.');
    }
1506
    append_identifier(thd, &buff, &views->table_name);
1507 1508
    if (lex->view_list.elements)
    {
1509 1510
      List_iterator_fast<LEX_CSTRING> names(lex->view_list);
      LEX_CSTRING *name;
1511 1512 1513 1514 1515
      int i;

      for (i= 0; (name= names++); i++)
      {
        buff.append(i ? ", " : "(");
1516
        append_identifier(thd, &buff, name);
1517 1518 1519 1520
      }
      buff.append(')');
    }
    buff.append(STRING_WITH_LEN(" AS "));
1521 1522
    buff.append(thd->lex->create_view->select.str,
                thd->lex->create_view->select.length);
1523 1524 1525
    return wsrep_to_buf_helper(thd, buff.ptr(), buff.length(), buf, buf_len);
}

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
/*
  Rewrite DROP TABLE for TOI. Temporary tables are eliminated from
  the query as they are visible only to client connection.

  TODO: See comments for sql_base.cc:drop_temporary_table() and refine
  the function to deal with transactional locked tables.
 */
static int wsrep_drop_table_query(THD* thd, uchar** buf, size_t* buf_len)
{

  LEX* lex= thd->lex;
Marko Mäkelä's avatar
Marko Mäkelä committed
1537
  SELECT_LEX* select_lex= lex->first_select_lex();
1538 1539 1540
  TABLE_LIST* first_table= select_lex->table_list.first;
  String buff;

1541
  DBUG_ASSERT(!lex->create_info.tmp_table());
1542 1543 1544 1545

  bool found_temp_table= false;
  for (TABLE_LIST* table= first_table; table; table= table->next_global)
  {
1546
    if (thd->find_temporary_table(table->db.str, table->table_name.str))
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
    {
      found_temp_table= true;
      break;
    }
  }

  if (found_temp_table)
  {
    buff.append("DROP TABLE ");
    if (lex->check_exists)
      buff.append("IF EXISTS ");

    for (TABLE_LIST* table= first_table; table; table= table->next_global)
    {
1561
      if (!thd->find_temporary_table(table->db.str, table->table_name.str))
1562
      {
1563
        append_identifier(thd, &buff, table->db.str, table->db.length);
1564
        buff.append(".");
1565 1566
        append_identifier(thd, &buff,
                          table->table_name.str, table->table_name.length);
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
        buff.append(",");
      }
    }

    /* Chop the last comma */
    buff.chop();
    buff.append(" /* generated by wsrep */");

    WSREP_DEBUG("Rewrote '%s' as '%s'", thd->query(), buff.ptr());

    return wsrep_to_buf_helper(thd, buff.ptr(), buff.length(), buf, buf_len);
  }
  else
  {
    return wsrep_to_buf_helper(thd, thd->query(), thd->query_length(),
                               buf, buf_len);
  }
}

1586

1587
/* Forward declarations. */
Brave Galera Crew's avatar
Brave Galera Crew committed
1588
int wsrep_create_trigger_query(THD *thd, uchar** buf, size_t* buf_len);
1589

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
/*
  Decide if statement should run in TOI.

  Look if table or table_list contain temporary tables. If the
  statement affects only temporary tables,   statement should not run
  in TOI. If the table list contains mix of regular and temporary tables
  (DROP TABLE, OPTIMIZE, ANALYZE), statement should be run in TOI but
  should be rewritten at later time for replication to contain only
  non-temporary tables.
 */
static bool wsrep_can_run_in_toi(THD *thd, const char *db, const char *table,
                                 const TABLE_LIST *table_list)
{
  DBUG_ASSERT(!table || db);
  DBUG_ASSERT(table_list || db);

  LEX* lex= thd->lex;
1607
  SELECT_LEX* select_lex= lex->first_select_lex();
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  TABLE_LIST* first_table= select_lex->table_list.first;

  switch (lex->sql_command)
  {
  case SQLCOM_CREATE_TABLE:
    DBUG_ASSERT(!table_list);
    if (thd->lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)
    {
      return false;
    }
    return true;

  case SQLCOM_CREATE_VIEW:

    DBUG_ASSERT(!table_list);
    DBUG_ASSERT(first_table); /* First table is view name */
    /*
      If any of the remaining tables refer to temporary table error
      is returned to client, so TOI can be skipped
    */
    for (TABLE_LIST* it= first_table->next_global; it; it= it->next_global)
    {
Marko Mäkelä's avatar
Marko Mäkelä committed
1630
      if (thd->find_temporary_table(it))
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
      {
        return false;
      }
    }
    return true;

  case SQLCOM_CREATE_TRIGGER:

    DBUG_ASSERT(!table_list);
    DBUG_ASSERT(first_table);

Marko Mäkelä's avatar
Marko Mäkelä committed
1642
    if (thd->find_temporary_table(first_table))
1643 1644 1645 1646 1647 1648
    {
      return false;
    }
    return true;

  default:
Marko Mäkelä's avatar
Marko Mäkelä committed
1649
    if (table && !thd->find_temporary_table(db, table))
1650 1651 1652 1653 1654 1655 1656 1657
    {
      return true;
    }

    if (table_list)
    {
      for (TABLE_LIST* table= first_table; table; table= table->next_global)
      {
1658
        if (!thd->find_temporary_table(table->db.str, table->table_name.str))
1659 1660 1661 1662 1663 1664 1665 1666 1667
        {
          return true;
        }
      }
    }
    return !(table || table_list);
  }
}

Brave Galera Crew's avatar
Brave Galera Crew committed
1668
#if UNUSED /* 323f269d4099 (Jan Lindström     2018-07-19) */
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
static const char* wsrep_get_query_or_msg(const THD* thd)
{
  switch(thd->lex->sql_command)
  {
    case SQLCOM_CREATE_USER:
      return "CREATE USER";
    case SQLCOM_GRANT:
      return "GRANT";
    case SQLCOM_REVOKE:
      return "REVOKE";
    case SQLCOM_SET_OPTION:
      if (thd->lex->definer)
Brave Galera Crew's avatar
Brave Galera Crew committed
1681
        return "SET PASSWORD";
1682 1683 1684 1685 1686
      /* fallthrough */
    default:
      return thd->query();
   }
}
Brave Galera Crew's avatar
Brave Galera Crew committed
1687
#endif //UNUSED
1688

Brave Galera Crew's avatar
Brave Galera Crew committed
1689
static int wsrep_create_sp(THD *thd, uchar** buf, size_t* buf_len)
1690
{
Brave Galera Crew's avatar
Brave Galera Crew committed
1691 1692 1693 1694 1695 1696 1697 1698
  String log_query;
  sp_head *sp= thd->lex->sphead;
  sql_mode_t saved_mode= thd->variables.sql_mode;
  String retstr(64);
  LEX_CSTRING returns= empty_clex_str;
  retstr.set_charset(system_charset_info);

  log_query.set_charset(system_charset_info);
1699

Brave Galera Crew's avatar
Brave Galera Crew committed
1700
  if (sp->m_handler->type() == TYPE_ENUM_FUNCTION)
1701
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
    sp_returns_type(thd, retstr, sp);
    returns= retstr.lex_cstring();
  }
  if (sp->m_handler->
      show_create_sp(thd, &log_query,
                     sp->m_explicit_name ? sp->m_db : null_clex_str,
                     sp->m_name, sp->m_params, returns,
                     sp->m_body, sp->chistics(),
                     thd->lex->definer[0],
                     thd->lex->create_info,
                     saved_mode))
  {
    WSREP_WARN("SP create string failed: schema: %s, query: %s",
               thd->get_db(), thd->query());
1716 1717 1718
    return 1;
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
1719 1720
  return wsrep_to_buf_helper(thd, log_query.ptr(), log_query.length(), buf, buf_len);
}
1721

Brave Galera Crew's avatar
Brave Galera Crew committed
1722 1723 1724
static int wsrep_TOI_event_buf(THD* thd, uchar** buf, size_t* buf_len)
{
  int err;
1725 1726 1727
  switch (thd->lex->sql_command)
  {
  case SQLCOM_CREATE_VIEW:
Brave Galera Crew's avatar
Brave Galera Crew committed
1728
    err= create_view_query(thd, buf, buf_len);
1729 1730 1731
    break;
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
Brave Galera Crew's avatar
Brave Galera Crew committed
1732
    err= wsrep_create_sp(thd, buf, buf_len);
1733 1734
    break;
  case SQLCOM_CREATE_TRIGGER:
Brave Galera Crew's avatar
Brave Galera Crew committed
1735
    err= wsrep_create_trigger_query(thd, buf, buf_len);
1736 1737
    break;
  case SQLCOM_CREATE_EVENT:
Brave Galera Crew's avatar
Brave Galera Crew committed
1738
    err= wsrep_create_event_query(thd, buf, buf_len);
1739 1740
    break;
  case SQLCOM_ALTER_EVENT:
Brave Galera Crew's avatar
Brave Galera Crew committed
1741
    err= wsrep_alter_event_query(thd, buf, buf_len);
1742
    break;
Jan Lindström's avatar
Jan Lindström committed
1743
  case SQLCOM_DROP_TABLE:
Brave Galera Crew's avatar
Brave Galera Crew committed
1744
    err= wsrep_drop_table_query(thd, buf, buf_len);
Jan Lindström's avatar
Jan Lindström committed
1745
    break;
1746 1747 1748 1749 1750 1751
  case SQLCOM_CREATE_ROLE:
    if (sp_process_definer(thd))
    {
      WSREP_WARN("Failed to set CREATE ROLE definer for TOI.");
    }
    /* fallthrough */
1752
  default:
Brave Galera Crew's avatar
Brave Galera Crew committed
1753 1754
    err= wsrep_to_buf_helper(thd, thd->query(), thd->query_length(), buf,
                             buf_len);
1755 1756 1757
    break;
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  return err;
}

static void wsrep_TOI_begin_failed(THD* thd, const wsrep_buf_t* /* const err */)
{
  if (wsrep_thd_trx_seqno(thd) > 0)
  {
    /* GTID was granted and TO acquired - need to log event and release TO */
    if (wsrep_emulate_bin_log) wsrep_thd_binlog_trx_reset(thd);
    if (wsrep_write_dummy_event(thd, "TOI begin failed")) { goto fail; }
    wsrep::client_state& cs(thd->wsrep_cs());
    int const ret= cs.leave_toi();
    if (ret)
    {
      WSREP_ERROR("Leaving critical section for failed TOI failed: thd: %lld, "
                  "schema: %s, SQL: %s, rcode: %d wsrep_error: %s",
                  (long long)thd->real_id, thd->db.str,
                  thd->query(), ret, wsrep::to_c_string(cs.current_error()));
      goto fail;
    }
1778
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1779 1780 1781 1782
  return;
fail:
  WSREP_ERROR("Failed to release TOI resources. Need to abort.");
  unireg_abort(1);
1783 1784 1785
}


Brave Galera Crew's avatar
Brave Galera Crew committed
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
/*
  returns:
   0: statement was replicated as TOI
   1: TOI replication was skipped
  -1: TOI replication failed
 */
static int wsrep_TOI_begin(THD *thd, const char *db, const char *table,
                           const TABLE_LIST* table_list,
                           Alter_info* alter_info)
{
  DBUG_ASSERT(thd->variables.wsrep_OSU_method == WSREP_OSU_TOI);
1797

Brave Galera Crew's avatar
Brave Galera Crew committed
1798 1799 1800 1801 1802
  WSREP_DEBUG("TOI Begin");
  if (wsrep_can_run_in_toi(thd, db, table, table_list) == false)
  {
    WSREP_DEBUG("No TOI for %s", WSREP_QUERY(thd));
    return 1;
1803
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817

  uchar* buf= 0;
  size_t buf_len(0);
  int buf_err;
  int rc;

  buf_err= wsrep_TOI_event_buf(thd, &buf, &buf_len);
  if (buf_err) {
    WSREP_ERROR("Failed to create TOI event buf: %d", buf_err);
    my_message(ER_UNKNOWN_ERROR,
               "WSREP replication failed to prepare TOI event buffer. "
               "Check your query.",
               MYF(0));
    return -1;
1818
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1819
  struct wsrep_buf buff= { buf, buf_len };
1820

Brave Galera Crew's avatar
Brave Galera Crew committed
1821 1822
  wsrep::key_array key_array=
    wsrep_prepare_keys_for_toi(db, table, table_list, alter_info);
1823

Brave Galera Crew's avatar
Brave Galera Crew committed
1824
  if (thd->has_read_only_protection())
1825
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1826 1827 1828 1829 1830 1831
    /* non replicated DDL, affecting temporary tables only */
    WSREP_DEBUG("TO isolation skipped, sql: %s."
                "Only temporary tables affected.",
                WSREP_QUERY(thd));
    if (buf) my_free(buf);
    return -1;
1832
  }
1833

Brave Galera Crew's avatar
Brave Galera Crew committed
1834
  thd_proc_info(thd, "acquiring total order isolation");
1835

Brave Galera Crew's avatar
Brave Galera Crew committed
1836 1837 1838 1839 1840 1841 1842
  wsrep::client_state& cs(thd->wsrep_cs());
  int ret= cs.enter_toi(key_array,
                        wsrep::const_buffer(buff.ptr, buff.len),
                        wsrep::provider::flag::start_transaction |
                        wsrep::provider::flag::commit);

  if (ret)
1843
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
    DBUG_ASSERT(cs.current_error());
    WSREP_DEBUG("to_execute_start() failed for %llu: %s, seqno: %lld",
                thd->thread_id, WSREP_QUERY(thd),
                (long long)wsrep_thd_trx_seqno(thd));

    /* jump to error handler in mysql_execute_command() */
    switch (cs.current_error())
    {
    case wsrep::e_size_exceeded_error:
      WSREP_WARN("TO isolation failed for: %d, schema: %s, sql: %s. "
                 "Maximum size exceeded.",
                 ret,
                 (thd->db.str ? thd->db.str : "(null)"),
                 WSREP_QUERY(thd));
      my_error(ER_ERROR_DURING_COMMIT, MYF(0), WSREP_SIZE_EXCEEDED);
      break;
    default:
      WSREP_WARN("TO isolation failed for: %d, schema: %s, sql: %s. "
                 "Check wsrep connection state and retry the query.",
                 ret,
                 (thd->db.str ? thd->db.str : "(null)"),
                 WSREP_QUERY(thd));
      if (!thd->is_error())
      {
        my_error(ER_LOCK_DEADLOCK, MYF(0), "WSREP replication failed. Check "
                 "your wsrep connection state and retry the query.");
      }
    }
    rc= -1;
  }
  else {
    ++wsrep_to_isolation;
    rc= 0;
  }

  if (buf) my_free(buf);

  if (rc) wsrep_TOI_begin_failed(thd, NULL);

  return rc;
}

static void wsrep_TOI_end(THD *thd) {
  wsrep_to_isolation--;
  wsrep::client_state& client_state(thd->wsrep_cs());
  DBUG_ASSERT(wsrep_thd_is_local_toi(thd));
  WSREP_DEBUG("TO END: %lld: %s", client_state.toi_meta().seqno().get(),
              WSREP_QUERY(thd));
1892

Brave Galera Crew's avatar
Brave Galera Crew committed
1893 1894 1895
  if (wsrep_thd_is_local_toi(thd))
  {
    wsrep_set_SE_checkpoint(client_state.toi_meta().gtid());
1896 1897
    int ret= client_state.leave_toi();
    if (!ret)
Brave Galera Crew's avatar
Brave Galera Crew committed
1898 1899 1900 1901 1902 1903 1904 1905
    {
      WSREP_DEBUG("TO END: %lld", client_state.toi_meta().seqno().get());
    }
    else
    {
      WSREP_WARN("TO isolation end failed for: %d, schema: %s, sql: %s",
                 ret, (thd->db.str ? thd->db.str : "(null)"), WSREP_QUERY(thd));
    }
1906
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1907
}
1908

Brave Galera Crew's avatar
Brave Galera Crew committed
1909 1910 1911 1912 1913
static int wsrep_RSU_begin(THD *thd, const char *db_, const char *table_)
{
  WSREP_DEBUG("RSU BEGIN: %lld, : %s", wsrep_thd_trx_seqno(thd),
              WSREP_QUERY(thd));
  if (thd->wsrep_cs().begin_rsu(5000))
1914
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1915 1916 1917 1918 1919
    WSREP_WARN("RSU begin failed");
  }
  else
  {
    thd->variables.wsrep_on= 0;
1920 1921 1922 1923 1924 1925
  }
  return 0;
}

static void wsrep_RSU_end(THD *thd)
{
Brave Galera Crew's avatar
Brave Galera Crew committed
1926 1927 1928
  WSREP_DEBUG("RSU END: %lld : %s", wsrep_thd_trx_seqno(thd),
              WSREP_QUERY(thd));
  if (thd->wsrep_cs().end_rsu())
1929
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1930
    WSREP_WARN("Failed to end RSU, server may need to be restarted");
1931
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1932
  thd->variables.wsrep_on= 1;
1933 1934
}

1935
int wsrep_to_isolation_begin(THD *thd, const char *db_, const char *table_,
1936 1937
                             const TABLE_LIST* table_list,
                             Alter_info* alter_info)
1938 1939 1940 1941
{
  /*
    No isolation for applier or replaying threads.
   */
Brave Galera Crew's avatar
Brave Galera Crew committed
1942
  if (!wsrep_thd_is_local(thd)) return 0;
1943

Brave Galera Crew's avatar
Brave Galera Crew committed
1944
  int ret= 0;
1945
  mysql_mutex_lock(&thd->LOCK_thd_data);
1946

Brave Galera Crew's avatar
Brave Galera Crew committed
1947
  if (thd->wsrep_trx().state() == wsrep::transaction::s_must_abort)
1948
  {
1949
    WSREP_INFO("thread: %lld  schema: %s  query: %s has been aborted due to multi-master conflict",
1950
               (longlong) thd->thread_id, thd->get_db(), thd->query());
1951
    mysql_mutex_unlock(&thd->LOCK_thd_data);
1952 1953
    return WSREP_TRX_FAIL;
  }
1954
  mysql_mutex_unlock(&thd->LOCK_thd_data);
1955

Brave Galera Crew's avatar
Brave Galera Crew committed
1956 1957
  DBUG_ASSERT(wsrep_thd_is_local(thd));
  DBUG_ASSERT(thd->wsrep_trx().ws_meta().seqno().is_undefined());
1958

Brave Galera Crew's avatar
Brave Galera Crew committed
1959
  if (thd->global_read_lock.is_acquired())
1960
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1961 1962
    WSREP_DEBUG("Aborting TOI: Global Read-Lock (FTWRL) in place: %s %llu",
                WSREP_QUERY(thd), thd->thread_id);
1963 1964 1965 1966 1967
    return -1;
  }

  if (wsrep_debug && thd->mdl_context.has_locks())
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1968 1969
    WSREP_DEBUG("thread holds MDL locks at TI begin: %s %llu",
                WSREP_QUERY(thd), thd->thread_id);
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
  }

  /*
    It makes sense to set auto_increment_* to defaults in TOI operations.
    Must be done before wsrep_TOI_begin() since Query_log_event encapsulating
    TOI statement and auto inc variables for wsrep replication is constructed
    there. Variables are reset back in THD::reset_for_next_command() before
    processing of next command.
   */
  if (wsrep_auto_increment_control)
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
1981 1982
    thd->variables.auto_increment_offset= 1;
    thd->variables.auto_increment_increment= 1;
1983 1984
  }

Brave Galera Crew's avatar
Brave Galera Crew committed
1985
  if (thd->variables.wsrep_on && wsrep_thd_is_local(thd))
1986
  {
1987
    switch (thd->variables.wsrep_OSU_method) {
1988
    case WSREP_OSU_TOI:
1989
      ret= wsrep_TOI_begin(thd, db_, table_, table_list, alter_info);
1990 1991
      break;
    case WSREP_OSU_RSU:
1992
      ret= wsrep_RSU_begin(thd, db_, table_);
1993
      break;
1994 1995 1996 1997 1998
    default:
      WSREP_ERROR("Unsupported OSU method: %lu",
                  thd->variables.wsrep_OSU_method);
      ret= -1;
      break;
1999
    }
2000
    switch (ret) {
Brave Galera Crew's avatar
Brave Galera Crew committed
2001
    case 0: /* wsrep_TOI_begin sould set toi mode */ break;
2002 2003
    case 1:
      /* TOI replication skipped, treat as success */
Brave Galera Crew's avatar
Brave Galera Crew committed
2004
      ret= 0;
2005 2006 2007 2008
      break;
    case -1:
      /* TOI replication failed, treat as error */
      break;
2009 2010
    }
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
2011

2012 2013 2014 2015 2016
  return ret;
}

void wsrep_to_isolation_end(THD *thd)
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2017 2018 2019
  DBUG_ASSERT(wsrep_thd_is_local_toi(thd) ||
              wsrep_thd_is_in_rsu(thd));
  if (wsrep_thd_is_local_toi(thd))
2020
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
    DBUG_ASSERT(thd->variables.wsrep_OSU_method == WSREP_OSU_TOI);
    wsrep_TOI_end(thd);
  }
  else if (wsrep_thd_is_in_rsu(thd))
  {
    DBUG_ASSERT(thd->variables.wsrep_OSU_method == WSREP_OSU_RSU);
    wsrep_RSU_end(thd);
  }
  else
  {
    DBUG_ASSERT(0);
2032
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
2033
  if (wsrep_emulate_bin_log) wsrep_thd_binlog_trx_reset(thd);
2034 2035
}

2036
#define WSREP_MDL_LOG(severity, msg, schema, schema_len, req, gra)             \
2037 2038
    WSREP_##severity(                                                          \
      "%s\n"                                                                   \
2039
      "schema:  %.*s\n"                                                        \
Brave Galera Crew's avatar
Brave Galera Crew committed
2040 2041
      "request: (%llu \tseqno %lld \twsrep (%s, %s, %s) cmd %d %d \t%s)\n"     \
      "granted: (%llu \tseqno %lld \twsrep (%s, %s, %s) cmd %d %d \t%s)",      \
2042
      msg, schema_len, schema,                                                 \
Brave Galera Crew's avatar
Brave Galera Crew committed
2043 2044
      req->thread_id, (long long)wsrep_thd_trx_seqno(req),                     \
      wsrep_thd_client_mode_str(req), wsrep_thd_client_state_str(req), wsrep_thd_transaction_state_str(req), \
2045
      req->get_command(), req->lex->sql_command, req->query(),                 \
Brave Galera Crew's avatar
Brave Galera Crew committed
2046 2047
      gra->thread_id, (long long)wsrep_thd_trx_seqno(gra),                     \
      wsrep_thd_client_mode_str(gra), wsrep_thd_client_state_str(gra), wsrep_thd_transaction_state_str(gra), \
2048 2049
      gra->get_command(), gra->lex->sql_command, gra->query());

2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
/**
  Check if request for the metadata lock should be granted to the requester.

  @param  requestor_ctx        The MDL context of the requestor
  @param  ticket               MDL ticket for the requested lock

  @retval TRUE   Lock request can be granted
  @retval FALSE  Lock request cannot be granted
*/

Brave Galera Crew's avatar
Brave Galera Crew committed
2060
void wsrep_handle_mdl_conflict(MDL_context *requestor_ctx,
2061 2062 2063
                               MDL_ticket *ticket,
                               const MDL_key *key)
{
2064
  /* Fallback to the non-wsrep behaviour */
Brave Galera Crew's avatar
Brave Galera Crew committed
2065
  if (!WSREP_ON) return;
2066

2067 2068
  THD *request_thd= requestor_ctx->get_thd();
  THD *granted_thd= ticket->get_ctx()->get_thd();
2069

2070 2071 2072
  const char* schema= key->db_name();
  int schema_len= key->db_name_length();

2073
  mysql_mutex_lock(&request_thd->LOCK_thd_data);
Brave Galera Crew's avatar
Brave Galera Crew committed
2074 2075
  if (wsrep_thd_is_toi(request_thd) ||
      wsrep_thd_is_applying(request_thd)) {
2076

2077
    mysql_mutex_unlock(&request_thd->LOCK_thd_data);
2078 2079
    WSREP_MDL_LOG(DEBUG, "MDL conflict ", schema, schema_len,
                  request_thd, granted_thd);
2080 2081
    ticket->wsrep_report(wsrep_debug);

2082
    mysql_mutex_lock(&granted_thd->LOCK_thd_data);
Brave Galera Crew's avatar
Brave Galera Crew committed
2083 2084
    if (wsrep_thd_is_toi(granted_thd) ||
        wsrep_thd_is_applying(granted_thd))
2085
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
      if (wsrep_thd_is_SR(granted_thd) && !wsrep_thd_is_SR(request_thd))
      {
        WSREP_MDL_LOG(INFO, "MDL conflict, DDL vs SR", 
                      schema, schema_len, request_thd, granted_thd);
        mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
        wsrep_abort_thd((void*)request_thd, (void*)granted_thd, 1);
      }
      else
      {
        WSREP_MDL_LOG(INFO, "MDL BF-BF conflict", schema, schema_len,
                      request_thd, granted_thd);
        ticket->wsrep_report(true);
        mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
        unireg_abort(1);
      }
    }
    else if (granted_thd->lex->sql_command == SQLCOM_FLUSH ||
             granted_thd->mdl_context.has_explicit_locks())
2104
    {
sjaakola's avatar
sjaakola committed
2105
      WSREP_DEBUG("BF thread waiting for FLUSH");
2106
      ticket->wsrep_report(wsrep_debug);
2107
      mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
Brave Galera Crew's avatar
Brave Galera Crew committed
2108 2109 2110 2111 2112 2113 2114 2115
    }
    else if (request_thd->lex->sql_command == SQLCOM_DROP_TABLE)
    {
      WSREP_DEBUG("DROP caused BF abort, conf %s",
                  wsrep_thd_transaction_state_str(granted_thd));
      ticket->wsrep_report(wsrep_debug);
      mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
      wsrep_abort_thd((void*)request_thd, (void*)granted_thd, 1);
2116 2117 2118
    }
    else
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
2119 2120 2121 2122
      WSREP_MDL_LOG(DEBUG, "MDL conflict-> BF abort", schema, schema_len,
                    request_thd, granted_thd);
      ticket->wsrep_report(wsrep_debug);
      if (granted_thd->wsrep_trx().active())
2123
      {
Brave Galera Crew's avatar
Brave Galera Crew committed
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
        mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
        wsrep_abort_thd(request_thd, granted_thd, 1);
      }
      else
      {
        /*
          Granted_thd is likely executing with wsrep_on=0. If the requesting
          thd is BF, BF abort and wait.
        */
        mysql_mutex_unlock(&granted_thd->LOCK_thd_data);
        if (wsrep_thd_is_BF(request_thd, FALSE))
2135
        {
Brave Galera Crew's avatar
Brave Galera Crew committed
2136
          ha_abort_transaction(request_thd, granted_thd, TRUE);
2137 2138 2139
        }
        else
        {
Brave Galera Crew's avatar
Brave Galera Crew committed
2140 2141 2142 2143
	  WSREP_MDL_LOG(INFO, "MDL unknown BF-BF conflict", schema, schema_len,
                      request_thd, granted_thd);
	  ticket->wsrep_report(true);
	  unireg_abort(1);
2144 2145
        }
      }
2146 2147 2148 2149
    }
  }
  else
  {
2150
    mysql_mutex_unlock(&request_thd->LOCK_thd_data);
2151 2152 2153 2154 2155 2156 2157
  }
}

/**/
static bool abort_replicated(THD *thd)
{
  bool ret_code= false;
Brave Galera Crew's avatar
Brave Galera Crew committed
2158
  if (thd->wsrep_trx().state() == wsrep::transaction::s_committing)
2159
  {
2160
    WSREP_DEBUG("aborting replicated trx: %llu", (ulonglong)(thd->real_id));
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177

    (void)wsrep_abort_thd(thd, thd, TRUE);
    ret_code= true;
  }
  return ret_code;
}

/**/
static inline bool is_client_connection(THD *thd)
{
  return (thd->wsrep_client_thread && thd->variables.wsrep_on);
}

static inline bool is_replaying_connection(THD *thd)
{
  bool ret;

2178
  mysql_mutex_lock(&thd->LOCK_thd_data);
Brave Galera Crew's avatar
Brave Galera Crew committed
2179
  ret=  (thd->wsrep_trx().state() == wsrep::transaction::s_replaying) ? true : false;
2180
  mysql_mutex_unlock(&thd->LOCK_thd_data);
2181 2182 2183 2184 2185 2186 2187 2188

  return ret;
}

static inline bool is_committing_connection(THD *thd)
{
  bool ret;

2189
  mysql_mutex_lock(&thd->LOCK_thd_data);
Brave Galera Crew's avatar
Brave Galera Crew committed
2190
  ret=  (thd->wsrep_trx().state() == wsrep::transaction::s_committing) ? true : false;
2191
  mysql_mutex_unlock(&thd->LOCK_thd_data);
2192 2193 2194 2195

  return ret;
}

2196
static my_bool have_client_connections(THD *thd, void*)
2197
{
2198 2199 2200
  DBUG_PRINT("quit",("Informing thread %lld that it's time to die",
                     (longlong) thd->thread_id));
  if (is_client_connection(thd) && thd->killed == KILL_CONNECTION)
2201
  {
2202 2203
    (void)abort_replicated(thd);
    return 1;
2204
  }
2205
  return 0;
2206 2207 2208 2209
}

static void wsrep_close_thread(THD *thd)
{
2210
  thd->set_killed(KILL_CONNECTION);
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
  MYSQL_CALLBACK(thread_scheduler, post_kill_notification, (thd));
  if (thd->mysys_var)
  {
    thd->mysys_var->abort=1;
    mysql_mutex_lock(&thd->mysys_var->mutex);
    if (thd->mysys_var->current_cond)
    {
      mysql_mutex_lock(thd->mysys_var->current_mutex);
      mysql_cond_broadcast(thd->mysys_var->current_cond);
      mysql_mutex_unlock(thd->mysys_var->current_mutex);
    }
    mysql_mutex_unlock(&thd->mysys_var->mutex);
  }
}

2226
static my_bool have_committing_connections(THD *thd, void *)
2227
{
2228
  return is_client_connection(thd) && is_committing_connection(thd) ? 1 : 0;
2229 2230 2231 2232 2233 2234
}

int wsrep_wait_committing_connections_close(int wait_time)
{
  int sleep_time= 100;

2235
  while (server_threads.iterate(have_committing_connections) && wait_time > 0)
2236 2237 2238 2239 2240
  {
    WSREP_DEBUG("wait for committing transaction to close: %d", wait_time);
    my_sleep(sleep_time);
    wait_time -= sleep_time;
  }
2241 2242 2243 2244 2245 2246 2247 2248 2249
  return server_threads.iterate(have_committing_connections);
}

static my_bool kill_all_threads(THD *thd, THD *caller_thd)
{
  DBUG_PRINT("quit", ("Informing thread %lld that it's time to die",
                      (longlong) thd->thread_id));
  /* We skip slave threads & scheduler on this first loop through. */
  if (is_client_connection(thd) && thd != caller_thd)
2250
  {
2251 2252 2253 2254 2255 2256 2257 2258 2259
    if (is_replaying_connection(thd))
      thd->set_killed(KILL_CONNECTION);
    else if (!abort_replicated(thd))
    {
      /* replicated transactions must be skipped */
      WSREP_DEBUG("closing connection %lld", (longlong) thd->thread_id);
      /* instead of wsrep_close_thread() we do now  soft kill by THD::awake */
      thd->awake(KILL_CONNECTION);
    }
2260 2261 2262 2263
  }
  return 0;
}

2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
static my_bool kill_remaining_threads(THD *thd, THD *caller_thd)
{
#ifndef __bsdi__				// Bug in BSDI kernel
  if (is_client_connection(thd) &&
      !abort_replicated(thd)    &&
      !is_replaying_connection(thd) &&
      thd != caller_thd)
  {
    WSREP_INFO("killing local connection: %lld", (longlong) thd->thread_id);
    close_connection(thd, 0);
  }
#endif
  return 0;
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2279
void wsrep_close_client_connections(my_bool wait_to_end, THD* except_caller_thd)
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
{
  /*
    First signal all threads that it's time to die
  */

  mysql_mutex_lock(&LOCK_thread_count); // For unlink from list

  bool kill_cached_threads_saved= kill_cached_threads;
  kill_cached_threads= true; // prevent future threads caching
  mysql_cond_broadcast(&COND_thread_cache); // tell cached threads to die

2291
  server_threads.iterate(kill_all_threads, except_caller_thd);
2292 2293 2294 2295 2296 2297 2298 2299 2300
  mysql_mutex_unlock(&LOCK_thread_count);

  if (thread_count)
    sleep(2);                               // Give threads time to die

  mysql_mutex_lock(&LOCK_thread_count);
  /*
    Force remaining threads to die by closing the connection to the client
  */
2301
  server_threads.iterate(kill_remaining_threads, except_caller_thd);
2302

2303 2304 2305 2306
  DBUG_PRINT("quit", ("Waiting for threads to die (count=%u)",
             uint32_t(thread_count)));
  WSREP_DEBUG("waiting for client connections to close: %u",
              uint32_t(thread_count));
2307

2308
  while (wait_to_end && server_threads.iterate(have_client_connections))
2309 2310
  {
    mysql_cond_wait(&COND_thread_count, &LOCK_thread_count);
2311
    DBUG_PRINT("quit",("One thread died (count=%u)", uint32_t(thread_count)));
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
  }

  kill_cached_threads= kill_cached_threads_saved;

  mysql_mutex_unlock(&LOCK_thread_count);

  /* All client connection threads have now been aborted */
}


void wsrep_close_applier(THD *thd)
{
2324
  WSREP_DEBUG("closing applier %lld", (longlong) thd->thread_id);
2325 2326 2327
  wsrep_close_thread(thd);
}

2328
static my_bool wsrep_close_threads_callback(THD *thd, THD *caller_thd)
2329
{
2330 2331 2332 2333
  DBUG_PRINT("quit",("Informing thread %lld that it's time to die",
                     (longlong) thd->thread_id));
  /* We skip slave threads & scheduler on this first loop through. */
  if (thd->wsrep_applier && thd != caller_thd)
2334
  {
2335 2336
    WSREP_DEBUG("closing wsrep thread %lld", (longlong) thd->thread_id);
    wsrep_close_thread(thd);
2337
  }
2338 2339
  return 0;
}
2340

2341 2342 2343
void wsrep_close_threads(THD *thd)
{
  server_threads.iterate(wsrep_close_threads_callback, thd);
2344 2345 2346 2347 2348 2349
}

void wsrep_wait_appliers_close(THD *thd)
{
  /* Wait for wsrep appliers to gracefully exit */
  mysql_mutex_lock(&LOCK_thread_count);
Brave Galera Crew's avatar
Brave Galera Crew committed
2350 2351 2352 2353 2354 2355
  while (wsrep_running_threads > 2)
    /*
      2 is for rollbacker thread which needs to be killed explicitly.
      This gotta be fixed in a more elegant manner if we gonna have arbitrary
      number of non-applier wsrep threads.
    */
2356 2357 2358 2359 2360 2361 2362 2363 2364
  {
    if (thread_handling > SCHEDULER_ONE_THREAD_PER_CONNECTION)
    {
      mysql_mutex_unlock(&LOCK_thread_count);
      my_sleep(100);
      mysql_mutex_lock(&LOCK_thread_count);
    }
    else
      mysql_cond_wait(&COND_thread_count,&LOCK_thread_count);
2365
    DBUG_PRINT("quit",("One applier died (count=%u)", uint32_t(thread_count)));
2366 2367 2368 2369 2370 2371
  }
  mysql_mutex_unlock(&LOCK_thread_count);
  /* Now kill remaining wsrep threads: rollbacker */
  wsrep_close_threads (thd);
  /* and wait for them to die */
  mysql_mutex_lock(&LOCK_thread_count);
2372
  while (wsrep_running_threads > 0)
2373 2374 2375 2376 2377 2378 2379 2380 2381
  {
   if (thread_handling > SCHEDULER_ONE_THREAD_PER_CONNECTION)
    {
      mysql_mutex_unlock(&LOCK_thread_count);
      my_sleep(100);
      mysql_mutex_lock(&LOCK_thread_count);
    }
    else
      mysql_cond_wait(&COND_thread_count,&LOCK_thread_count);
2382
    DBUG_PRINT("quit",("One thread died (count=%u)", uint32_t(thread_count)));
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
  }
  mysql_mutex_unlock(&LOCK_thread_count);

  /* All wsrep applier threads have now been aborted. However, if this thread
     is also applier, we are still running...
  */
}

void wsrep_kill_mysql(THD *thd)
{
  if (mysqld_server_started)
  {
2395
    if (!abort_loop)
2396 2397
    {
      WSREP_INFO("starting shutdown");
2398
      kill_mysql(thd);
2399 2400 2401 2402 2403 2404 2405 2406
    }
  }
  else
  {
    unireg_abort(1);
  }
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2407 2408
void
wsrep_last_committed_id(wsrep_gtid_t* gtid)
2409
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2410 2411 2412
  wsrep::gtid ret= Wsrep_server_state::instance().last_committed_gtid();
  memcpy(gtid->uuid.data, ret.id().data(), sizeof(gtid->uuid.data));
  gtid->seqno= ret.seqno().get();
2413 2414
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2415 2416
void
wsrep_node_uuid(wsrep_uuid_t& uuid)
2417
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2418
  uuid= node_uuid;
2419 2420
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2421
int wsrep_must_ignore_error(THD* thd)
2422
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2423 2424
  const int error= thd->get_stmt_da()->sql_errno();
  const uint flags= sql_command_flags[thd->lex->sql_command];
2425

Brave Galera Crew's avatar
Brave Galera Crew committed
2426 2427 2428
  DBUG_ASSERT(error);
  DBUG_ASSERT((wsrep_thd_is_toi(thd)) ||
              (wsrep_thd_is_applying(thd) && thd->wsrep_apply_toi));
2429

Brave Galera Crew's avatar
Brave Galera Crew committed
2430 2431
  if ((wsrep_ignore_apply_errors & WSREP_IGNORE_ERRORS_ON_DDL))
    goto ignore_error;
2432

Brave Galera Crew's avatar
Brave Galera Crew committed
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
  if ((flags & CF_WSREP_MAY_IGNORE_ERRORS) &&
      (wsrep_ignore_apply_errors & WSREP_IGNORE_ERRORS_ON_RECONCILING_DDL))
  {
    switch (error)
    {
    case ER_DB_DROP_EXISTS:
    case ER_BAD_TABLE_ERROR:
    case ER_CANT_DROP_FIELD_OR_KEY:
      goto ignore_error;
    }
  }
2444

Brave Galera Crew's avatar
Brave Galera Crew committed
2445
  return 0;
2446

Brave Galera Crew's avatar
Brave Galera Crew committed
2447 2448 2449 2450 2451 2452 2453 2454
ignore_error:
  WSREP_WARN("Ignoring error '%s' on query. "
             "Default database: '%s'. Query: '%s', Error_code: %d",
             thd->get_stmt_da()->message(),
             print_slave_db_safe(thd->db.str),
             thd->query(),
             error);
  return 1;
2455 2456
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2457
int wsrep_ignored_error_code(Log_event* ev, int error)
2458
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2459
  const THD* thd= ev->thd;
2460

Brave Galera Crew's avatar
Brave Galera Crew committed
2461 2462 2463
  DBUG_ASSERT(error);
  DBUG_ASSERT(wsrep_thd_is_applying(thd) &&
              !wsrep_thd_is_local_toi(thd));
2464

Brave Galera Crew's avatar
Brave Galera Crew committed
2465 2466 2467 2468 2469 2470 2471
  if ((wsrep_ignore_apply_errors & WSREP_IGNORE_ERRORS_ON_RECONCILING_DML))
  {
    const int ev_type= ev->get_type_code();
    if ((ev_type == DELETE_ROWS_EVENT || ev_type == DELETE_ROWS_EVENT_V1)
        && error == ER_KEY_NOT_FOUND)
      goto ignore_error;
  }
2472

Brave Galera Crew's avatar
Brave Galera Crew committed
2473
  return 0;
2474

Brave Galera Crew's avatar
Brave Galera Crew committed
2475 2476 2477 2478 2479 2480
ignore_error:
  WSREP_WARN("Ignoring error '%s' on %s event. Error_code: %d",
             thd->get_stmt_da()->message(),
             ev->get_type_str(),
             error);
  return 1;
2481 2482
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2483
bool wsrep_provider_is_SR_capable()
2484
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2485
  return Wsrep_server_state::has_capability(wsrep::provider::capability::streaming);
2486 2487 2488
}


Brave Galera Crew's avatar
Brave Galera Crew committed
2489
int wsrep_ordered_commit_if_no_binlog(THD* thd, bool all)
2490
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2491 2492 2493 2494 2495 2496 2497 2498 2499
  if (((wsrep_thd_is_local(thd) &&
        (WSREP_EMULATE_BINLOG(thd) || !thd->variables.sql_log_bin)) ||
       (wsrep_thd_is_applying(thd) && !opt_log_slave_updates))
      && wsrep_thd_trx_seqno(thd) > 0)
  {
    wsrep_apply_error unused;
    return wsrep_ordered_commit(thd, all, unused);
  }
  return 0;
2500 2501
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2502
int wsrep_thd_retry_counter(const THD *thd)
2503
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2504
  return thd->wsrep_retry_counter;
2505 2506
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2507
extern  bool wsrep_thd_ignore_table(THD *thd)
2508
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2509
  return thd->wsrep_ignore_table;
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
}

bool wsrep_is_show_query(enum enum_sql_command command)
{
  DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
  return (sql_command_flags[command] & CF_STATUS_COMMAND) != 0;
}
bool wsrep_create_like_table(THD* thd, TABLE_LIST* table,
                             TABLE_LIST* src_table,
                             HA_CREATE_INFO *create_info)
{
2521
  if (create_info->tmp_table())
2522 2523 2524 2525 2526
  {
    /* CREATE TEMPORARY TABLE LIKE must be skipped from replication */
    WSREP_DEBUG("CREATE TEMPORARY TABLE LIKE... skipped replication\n %s", 
                thd->query());
  }
2527
  else if (!(thd->find_temporary_table(src_table)))
2528
  {
2529 2530
    /* this is straight CREATE TABLE LIKE... with no tmp tables */
    WSREP_TO_ISOLATION_BEGIN(table->db.str, table->table_name.str, NULL);
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
  }
  else
  {
    /* here we have CREATE TABLE LIKE <temporary table> 
       the temporary table definition will be needed in slaves to
       enable the create to succeed
     */
    TABLE_LIST tbl;
    bzero((void*) &tbl, sizeof(tbl));
    tbl.db= src_table->db;
    tbl.table_name= tbl.alias= src_table->table_name;
2542
    tbl.table= src_table->table;
2543 2544 2545 2546
    char buf[2048];
    String query(buf, sizeof(buf), system_charset_info);
    query.length(0);  // Have to zero it since constructor doesn't

Sergei Golubchik's avatar
Sergei Golubchik committed
2547
    (void)  show_create_table(thd, &tbl, &query, NULL, WITH_DB_NAME);
2548 2549 2550 2551 2552
    WSREP_DEBUG("TMP TABLE: %s", query.ptr());

    thd->wsrep_TOI_pre_query=     query.ptr();
    thd->wsrep_TOI_pre_query_len= query.length();

2553
    WSREP_TO_ISOLATION_BEGIN(table->db.str, table->table_name.str, NULL);
2554 2555 2556 2557 2558 2559

    thd->wsrep_TOI_pre_query=      NULL;
    thd->wsrep_TOI_pre_query_len= 0;
  }

  return(false);
Marko Mäkelä's avatar
Marko Mäkelä committed
2560 2561
#ifdef WITH_WSREP
wsrep_error_label:
2562 2563
  thd->wsrep_TOI_pre_query= NULL;
  return (true);
Marko Mäkelä's avatar
Marko Mäkelä committed
2564
#endif
2565 2566
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2567
int wsrep_create_trigger_query(THD *thd, uchar** buf, size_t* buf_len)
2568 2569 2570 2571
{
  LEX *lex= thd->lex;
  String stmt_query;

2572 2573
  LEX_CSTRING definer_user;
  LEX_CSTRING definer_host;
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586

  if (!lex->definer)
  {
    if (!thd->slave_thread)
    {
      if (!(lex->definer= create_default_definer(thd, false)))
        return 1;
    }
  }

  if (lex->definer)
  {
    /* SUID trigger. */
2587 2588 2589 2590
    LEX_USER *d= get_current_user(thd, lex->definer);

    if (!d)
      return 1;
2591

2592 2593
    definer_user= d->user;
    definer_host= d->host;
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
  }
  else
  {
    /* non-SUID trigger. */

    definer_user.str= 0;
    definer_user.length= 0;

    definer_host.str= 0;
    definer_host.length= 0;
  }

  stmt_query.append(STRING_WITH_LEN("CREATE "));

  append_definer(thd, &stmt_query, &definer_user, &definer_host);

2610
  LEX_CSTRING stmt_definition;
2611 2612 2613
  stmt_definition.str= (char*) thd->lex->stmt_definition_begin;
  stmt_definition.length= thd->lex->stmt_definition_end
    - thd->lex->stmt_definition_begin;
2614
  trim_whitespace(thd->charset(), &stmt_definition);
2615 2616 2617 2618 2619 2620

  stmt_query.append(stmt_definition.str, stmt_definition.length);

  return wsrep_to_buf_helper(thd, stmt_query.c_ptr(), stmt_query.length(),
                             buf, buf_len);
}
2621

Brave Galera Crew's avatar
Brave Galera Crew committed
2622
void* start_wsrep_THD(void *arg)
2623
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2624
  THD *thd;
2625

Brave Galera Crew's avatar
Brave Galera Crew committed
2626
  Wsrep_thd_args* thd_args= (Wsrep_thd_args*) arg;
2627

Brave Galera Crew's avatar
Brave Galera Crew committed
2628 2629 2630 2631
  if (my_thread_init() || (!(thd= new THD(next_thread_id(), true))))
  {
    goto error;
  }
2632

2633
  statistic_increment(thread_created, &LOCK_status);
2634

Brave Galera Crew's avatar
Brave Galera Crew committed
2635 2636 2637 2638 2639
  if (wsrep_gtid_mode)
  {
    /* Adjust domain_id. */
    thd->variables.gtid_domain_id= wsrep_gtid_domain_id;
  }
2640

Brave Galera Crew's avatar
Brave Galera Crew committed
2641
  thd->real_id=pthread_self(); // Keep purify happy
2642

Brave Galera Crew's avatar
Brave Galera Crew committed
2643
  my_net_init(&thd->net,(st_vio*) 0, thd, MYF(0));
2644

Brave Galera Crew's avatar
Brave Galera Crew committed
2645 2646
  DBUG_PRINT("wsrep",(("creating thread %lld"), (long long)thd->thread_id));
  thd->prior_thr_create_utime= thd->start_utime= microsecond_interval_timer();
2647 2648

  server_threads.insert(thd);
2649

Brave Galera Crew's avatar
Brave Galera Crew committed
2650 2651 2652 2653
  /* from bootstrap()... */
  thd->bootstrap=1;
  thd->max_client_packet_length= thd->net.max_packet;
  thd->security_ctx->master_access= ~(ulong)0;
2654

Brave Galera Crew's avatar
Brave Galera Crew committed
2655 2656
  /* from handle_one_connection... */
  pthread_detach_this_thread();
2657

Brave Galera Crew's avatar
Brave Galera Crew committed
2658 2659 2660
  mysql_thread_set_psi_id(thd->thread_id);
  thd->thr_create_utime=  microsecond_interval_timer();
  if (MYSQL_CALLBACK_ELSE(thread_scheduler, init_new_connection_thread, (), 0))
2661
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
2662 2663 2664 2665
    close_connection(thd, ER_OUT_OF_RESOURCES);
    statistic_increment(aborted_connects,&LOCK_status);
    MYSQL_CALLBACK(thread_scheduler, end_thread, (thd, 0));
    goto error;
2666
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743

// </5.1.17>
  /*
    handle_one_connection() is normally the only way a thread would
    start and would always be on the very high end of the stack ,
    therefore, the thread stack always starts at the address of the
    first local variable of handle_one_connection, which is thd. We
    need to know the start of the stack so that we could check for
    stack overruns.
  */
  DBUG_PRINT("wsrep", ("handle_one_connection called by thread %lld\n",
                       (long long)thd->thread_id));
  /* now that we've called my_thread_init(), it is safe to call DBUG_* */

  thd->thread_stack= (char*) &thd;
  if (thd->store_globals())
  {
    close_connection(thd, ER_OUT_OF_RESOURCES);
    statistic_increment(aborted_connects,&LOCK_status);
    MYSQL_CALLBACK(thread_scheduler, end_thread, (thd, 0));
    delete thd;
    delete thd_args;
    goto error;
  }

  thd->system_thread= SYSTEM_THREAD_SLAVE_SQL;
  thd->security_ctx->skip_grants();

  /* handle_one_connection() again... */
  thd->proc_info= 0;
  thd->set_command(COM_SLEEP);
  thd->init_for_queries();
  mysql_mutex_lock(&LOCK_thread_count);
  wsrep_running_threads++;
  mysql_cond_broadcast(&COND_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);

  WSREP_DEBUG("wsrep system thread %llu, %p starting",
              thd->thread_id, thd);
  thd_args->fun()(thd, thd_args->args());

  WSREP_DEBUG("wsrep system thread: %llu, %p closing",
              thd->thread_id, thd);

  /* Wsrep may reset globals during thread context switches, store globals
     before cleanup. */
  thd->store_globals();

  close_connection(thd, 0);

  delete thd_args;

  mysql_mutex_lock(&LOCK_thread_count);
  wsrep_running_threads--;
  WSREP_DEBUG("wsrep running threads now: %lu", wsrep_running_threads);
  mysql_cond_broadcast(&COND_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
  /*
    Note: We can't call THD destructor without crashing
    if plugins have not been initialized. However, in most of the
    cases this means that pre SE initialization SST failed and
    we are going to exit anyway.
  */
  if (plugins_are_initialized)
  {
    net_end(&thd->net);
    MYSQL_CALLBACK(thread_scheduler, end_thread, (thd, 1));
  }
  else
  {
    /*
      TODO: lightweight cleanup to get rid of:
      'Error in my_thread_global_end(): 2 threads didn't exit'
      at server shutdown
    */
  }

2744
  server_threads.erase(thd);
Brave Galera Crew's avatar
Brave Galera Crew committed
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
  delete thd;
  my_thread_end();
  return(NULL);

error:
  WSREP_ERROR("Failed to create/initialize system thread");

  /* Abort if its the first applier/rollbacker thread. */
  if (!mysqld_server_initialized)
    unireg_abort(1);
  else
    return NULL;
2757 2758
}

Brave Galera Crew's avatar
Brave Galera Crew committed
2759
enum wsrep::streaming_context::fragment_unit wsrep_fragment_unit(ulong unit)
2760
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2761 2762 2763 2764 2765 2766 2767 2768 2769
  switch (unit)
  {
  case WSREP_FRAG_BYTES: return wsrep::streaming_context::bytes;
  case WSREP_FRAG_ROWS: return wsrep::streaming_context::row;
  case WSREP_FRAG_STATEMENTS: return wsrep::streaming_context::statement;
  default:
    DBUG_ASSERT(0);
    return wsrep::streaming_context::bytes;
  }
2770
}
2771

Brave Galera Crew's avatar
Brave Galera Crew committed
2772 2773 2774
/***** callbacks for wsrep service ************/

my_bool get_wsrep_recovery()
sjaakola's avatar
sjaakola committed
2775
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2776
  return wsrep_recovery;
sjaakola's avatar
sjaakola committed
2777
}
2778

Brave Galera Crew's avatar
Brave Galera Crew committed
2779
bool wsrep_consistency_check(THD *thd)
sjaakola's avatar
sjaakola committed
2780
{
Brave Galera Crew's avatar
Brave Galera Crew committed
2781
  return thd->wsrep_consistency_check == CONSISTENCY_CHECK_RUNNING;
sjaakola's avatar
sjaakola committed
2782
}