event_scheduler.cc 22.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (C) 2004-2006 MySQL AB

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

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

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

17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include "mysql_priv.h"
#include "events.h"
#include "event_data_objects.h"
#include "event_scheduler.h"
#include "event_queue.h"

#ifdef __GNUC__
#if __GNUC__ >= 2
#define SCHED_FUNC __FUNCTION__
#endif
#else
#define SCHED_FUNC "<unknown>"
#endif

31 32 33 34
#define LOCK_DATA()       lock_data(SCHED_FUNC, __LINE__)
#define UNLOCK_DATA()     unlock_data(SCHED_FUNC, __LINE__)
#define COND_STATE_WAIT(mythd, abstime, msg) \
        cond_wait(mythd, abstime, msg, SCHED_FUNC, __LINE__)
35 36 37 38

extern pthread_attr_t connection_attrib;

static
39
const LEX_STRING scheduler_states_names[] =
40
{
41 42 43
  { C_STRING_WITH_LEN("INITIALIZED") },
  { C_STRING_WITH_LEN("RUNNING") },
  { C_STRING_WITH_LEN("STOPPING") }
44 45
};

46 47 48 49 50
struct scheduler_param {
  THD *thd;
  Event_scheduler *scheduler;
};

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

/*
  Prints the stack of infos, warnings, errors from thd to
  the console so it can be fetched by the logs-into-tables and
  checked later.

  SYNOPSIS
    evex_print_warnings
      thd  Thread used during the execution of the event
      et   The event itself
*/

static void
evex_print_warnings(THD *thd, Event_job_data *et)
{
  MYSQL_ERROR *err;
  DBUG_ENTER("evex_print_warnings");
  if (!thd->warn_list.elements)
    DBUG_VOID_RETURN;

  char msg_buf[10 * STRING_BUFFER_USUAL_SIZE];
  char prefix_buf[5 * STRING_BUFFER_USUAL_SIZE];
  String prefix(prefix_buf, sizeof(prefix_buf), system_charset_info);
  prefix.length(0);
  prefix.append("SCHEDULER: [");

  append_identifier(thd, &prefix, et->definer.str, et->definer.length);
  prefix.append("][", 2);
  append_identifier(thd,&prefix, et->dbname.str, et->dbname.length);
  prefix.append('.');
  append_identifier(thd,&prefix, et->name.str, et->name.length);
  prefix.append("] ", 2);

  List_iterator_fast<MYSQL_ERROR> it(thd->warn_list);
  while ((err= it++))
  {
    String err_msg(msg_buf, sizeof(msg_buf), system_charset_info);
    /* set it to 0 or we start adding at the end. That's the trick ;) */
    err_msg.length(0);
    err_msg.append(prefix);
    err_msg.append(err->msg, strlen(err->msg), system_charset_info);
    err_msg.append("]");
    DBUG_ASSERT(err->level < 3);
    (sql_print_message_handlers[err->level])("%*s", err_msg.length(),
                                              err_msg.c_ptr());
  }
  DBUG_VOID_RETURN;
}


101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
/*
  Performs post initialization of structures in a new thread.

  SYNOPSIS
    post_init_event_thread()
      thd  Thread
*/

bool
post_init_event_thread(THD *thd)
{
  my_thread_init();
  pthread_detach_this_thread();
  thd->real_id= pthread_self();
  if (init_thr_lock() || thd->store_globals())
  {
    thd->cleanup();
    return TRUE;
  }

#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
  sigset_t set;
    VOID(sigemptyset(&set));                    // Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
#endif
126 127 128 129 130 131
  pthread_mutex_lock(&LOCK_thread_count);
  threads.append(thd);
  thread_count++;
  thread_running++;
  pthread_mutex_unlock(&LOCK_thread_count);

132
  return FALSE;
133 134 135 136 137 138 139 140 141 142 143
}


/*
  Cleans up the THD and the threaded environment of the thread.

  SYNOPSIS
    deinit_event_thread()
      thd  Thread
*/

144
void
145 146 147 148 149
deinit_event_thread(THD *thd)
{
  thd->proc_info= "Clearing";
  DBUG_ASSERT(thd->net.buff != 0);
  net_end(&thd->net);
150
  DBUG_PRINT("exit", ("Event thread finishing"));
151 152 153 154 155 156 157 158 159 160
  pthread_mutex_lock(&LOCK_thread_count);
  thread_count--;
  thread_running--;
  delete thd;
  pthread_mutex_unlock(&LOCK_thread_count);

  my_thread_end();
}


161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
/*
  Performs pre- pthread_create() initialisation of THD. Do this
  in the thread that will pass THD to the child thread. In the
  child thread call post_init_event_thread().

  SYNOPSIS
    pre_init_event_thread()
      thd  The THD of the thread. Has to be allocated by the caller.

  NOTES
    1. The host of the thead is my_localhost
    2. thd->net is initted with NULL - no communication.
*/

void
pre_init_event_thread(THD* thd)
{
  DBUG_ENTER("pre_init_event_thread");
  thd->client_capabilities= 0;
  thd->security_ctx->master_access= 0;
  thd->security_ctx->db_access= 0;
  thd->security_ctx->host_or_ip= (char*)my_localhost;
  my_net_init(&thd->net, NULL);
  thd->security_ctx->set_user((char*)"event_scheduler");
  thd->net.read_timeout= slave_net_timeout;
  thd->slave_thread= 0;
  thd->options|= OPTION_AUTO_IS_NULL;
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
  pthread_mutex_lock(&LOCK_thread_count);
  thd->thread_id= thread_id++;
  pthread_mutex_unlock(&LOCK_thread_count);

  /*
    Guarantees that we will see the thread in SHOW PROCESSLIST though its
    vio is NULL.
  */

  thd->proc_info= "Initialized";
  thd->version= refresh_version;
  thd->set_time();

  DBUG_VOID_RETURN;
}


206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
/*
  Function that executes the scheduler,

  SYNOPSIS
    event_scheduler_thread()
      arg  Pointer to `struct scheduler_param`

  RETURN VALUE
    0  OK
*/

pthread_handler_t
event_scheduler_thread(void *arg)
{
  /* needs to be first for thread_stack */
221 222
  THD *thd= (THD *)((struct scheduler_param *) arg)->thd;
  Event_scheduler *scheduler= ((struct scheduler_param *) arg)->scheduler;
223

224
  my_free((char*)arg, MYF(0));
225

226
  thd->thread_stack= (char *)&thd;              // remember where our stack is
227

228
  DBUG_ENTER("event_scheduler_thread");
229

230 231
  if (!post_init_event_thread(thd))
    scheduler->run(thd);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

  deinit_event_thread(thd);

  DBUG_RETURN(0);                               // Against gcc warnings
}


/*
  Function that executes an event in a child thread. Setups the 
  environment for the event execution and cleans after that.

  SYNOPSIS
    event_worker_thread()
      arg  The Event_job_data object to be processed

  RETURN VALUE
    0  OK
*/

pthread_handler_t
event_worker_thread(void *arg)
{
  /* needs to be first for thread_stack */
  THD *thd; 
  Event_job_data *event= (Event_job_data *)arg;
  int ret;

  thd= event->thd;

261 262
  thd->thread_stack= (char *) &thd;             // remember where our stack is
  DBUG_ENTER("event_worker_thread");
263

264 265 266 267
  if (!post_init_event_thread(thd))
  {
    DBUG_PRINT("info", ("Baikonur, time is %d, BURAN reporting and operational."
               "THD=0x%lx", time(NULL), thd));
268

269 270
    sql_print_information("SCHEDULER: [%s.%s of %s] executing in thread %lu. "
                          "Execution %u",
271
                          event->dbname.str, event->name.str,
272 273
                          event->definer.str, thd->thread_id,
                          event->execution_count);
274

275
    thd->enable_slow_log= TRUE;
276

277
    ret= event->execute(thd);
278

279
    evex_print_warnings(thd, event);
280

281 282
    sql_print_information("SCHEDULER: [%s.%s of %s] executed in thread %lu. "
                          "RetCode=%d", event->dbname.str, event->name.str,
283 284 285 286 287 288 289 290
                          event->definer.str, thd->thread_id, ret);
    if (ret == EVEX_COMPILE_ERROR)
      sql_print_information("SCHEDULER: COMPILE ERROR for event %s.%s of %s",
                            event->dbname.str, event->name.str,
                            event->definer.str);
    else if (ret == EVEX_MICROSECOND_UNSUP)
      sql_print_information("SCHEDULER: MICROSECOND is not supported");
  }
291 292 293 294 295 296 297
end:
  DBUG_PRINT("info", ("BURAN %s.%s is landing!", event->dbname.str,
             event->name.str));
  delete event;

  deinit_event_thread(thd);

298
  DBUG_RETURN(0);                               // Can't return anything here
299 300 301 302 303 304 305 306 307 308 309
}


/*
  Performs initialization of the scheduler data, outside of the
  threading primitives.

  SYNOPSIS
    Event_scheduler::init_scheduler()
*/

310
void
311 312
Event_scheduler::init_scheduler(Event_queue *q)
{
313
  LOCK_DATA();
314 315
  queue= q;
  started_events= 0;
316
  scheduler_thd= NULL;
317 318
  state= INITIALIZED;
  UNLOCK_DATA();
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
}


void
Event_scheduler::deinit_scheduler() {}


/*
  Inits scheduler's threading primitives.

  SYNOPSIS
    Event_scheduler::init_mutexes()
*/

void
Event_scheduler::init_mutexes()
{
  pthread_mutex_init(&LOCK_scheduler_state, MY_MUTEX_INIT_FAST);
  pthread_cond_init(&COND_state, NULL);
}


/*
  Deinits scheduler's threading primitives.

  SYNOPSIS
    Event_scheduler::deinit_mutexes()
*/

void
Event_scheduler::deinit_mutexes()
{
  pthread_mutex_destroy(&LOCK_scheduler_state);
  pthread_cond_destroy(&COND_state);
}


/*
  Starts the scheduler (again). Creates a new THD and passes it to
  a forked thread. Does not wait for acknowledgement from the new
  thread that it has started. Asynchronous starting. Most of the
  needed initializations are done in the current thread to minimize
  the chance of failure in the spawned thread.

  SYNOPSIS
    Event_scheduler::start()

  RETURN VALUE
    FALSE  OK
    TRUE   Error (not reported)
*/

bool
Event_scheduler::start()
{
  THD *new_thd= NULL;
  bool ret= FALSE;
  pthread_t th;
377
  struct scheduler_param *scheduler_param_value;
378 379
  DBUG_ENTER("Event_scheduler::start");

380
  LOCK_DATA();
381 382 383 384
  DBUG_PRINT("info", ("state before action %s", scheduler_states_names[state]));
  if (state > INITIALIZED)
    goto end;

385
  if (!(new_thd= new THD))
386
  {
387
    sql_print_error("SCHEDULER: Cannot init manager event thread");
388 389 390
    ret= TRUE;
    goto end;
  }
391
  pre_init_event_thread(new_thd);
392 393 394
  new_thd->system_thread= SYSTEM_THREAD_EVENT_SCHEDULER;
  new_thd->command= COM_DAEMON;

395 396 397 398
  scheduler_param_value=
    (struct scheduler_param *)my_malloc(sizeof(struct scheduler_param), MYF(0));
  scheduler_param_value->thd= new_thd;
  scheduler_param_value->scheduler= this;
399

400 401 402
  scheduler_thd= new_thd;
  DBUG_PRINT("info", ("Setting state go RUNNING"));
  state= RUNNING;
403 404
  DBUG_PRINT("info", ("Forking new thread for scheduduler. THD=0x%lx", new_thd));
  if (pthread_create(&th, &connection_attrib, event_scheduler_thread,
405
                    (void*)scheduler_param_value))
406 407 408
  {
    DBUG_PRINT("error", ("cannot create a new thread"));
    state= INITIALIZED;
409
    scheduler_thd= NULL;
410 411 412 413 414 415 416 417 418 419 420
    ret= TRUE;

    new_thd->proc_info= "Clearing";
    DBUG_ASSERT(new_thd->net.buff != 0);
    net_end(&new_thd->net);
    pthread_mutex_lock(&LOCK_thread_count);
    thread_count--;
    thread_running--;
    delete new_thd;
    pthread_mutex_unlock(&LOCK_thread_count);
  }
421 422 423
end:
  UNLOCK_DATA();

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  DBUG_RETURN(ret);
}


/*
  The main loop of the scheduler.

  SYNOPSIS
    Event_scheduler::run()
      thd  Thread

  RETURN VALUE
    FALSE  OK
    TRUE   Error (Serious error)
*/

bool
Event_scheduler::run(THD *thd)
{
443
  int res= FALSE;
444 445 446 447 448
  struct timespec abstime;
  Event_job_data *job_data;
  DBUG_ENTER("Event_scheduler::run");

  sql_print_information("SCHEDULER: Manager thread started with id %lu",
449
                        thd->thread_id);
450 451 452 453 454
  /*
    Recalculate the values in the queue because there could have been stops
    in executions of the scheduler and some times could have passed by.
  */
  queue->recalculate_activation_times(thd);
455 456

  while (is_running())
457 458
  {
    /* Gets a minimized version */
459
    if (queue->get_top_for_execution_if_time(thd, &job_data))
460
    {
461 462
      sql_print_information("SCHEDULER: Serious error during getting next "
                            "event to execute. Stopping");
463 464 465
      break;
    }

466 467
    DBUG_PRINT("info", ("get_top returned job_data=0x%lx", job_data));
    if (job_data)
468
    {
469 470
      if ((res= execute_top(thd, job_data)))
        break;
471 472 473
    }
    else
    {
474 475
      DBUG_ASSERT(thd->killed);
      DBUG_PRINT("info", ("job_data is NULL, the thread was killed"));
476 477 478
    }
    DBUG_PRINT("info", ("state=%s", scheduler_states_names[state].str));
  }
479
  LOCK_DATA();
480 481
  DBUG_PRINT("info", ("Signalling back to the stopper COND_state"));
  state= INITIALIZED;
482
  pthread_cond_signal(&COND_state);
483
  UNLOCK_DATA();
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  sql_print_information("SCHEDULER: Stopped");

  DBUG_RETURN(res);
}


/*
  Creates a new THD instance and then forks a new thread, while passing
  the THD pointer and job_data to it.

  SYNOPSIS
    Event_scheduler::execute_top()

  RETURN VALUE
    FALSE  OK
    TRUE   Error (Serious error)
*/

bool
Event_scheduler::execute_top(THD *thd, Event_job_data *job_data)
{
  THD *new_thd;
  pthread_t th;
  int res= 0;
  DBUG_ENTER("Event_scheduler::execute_top");
509
  if (!(new_thd= new THD()))
510 511
    goto error;

512
  pre_init_event_thread(new_thd);
513 514 515 516 517 518 519 520 521 522
  new_thd->system_thread= SYSTEM_THREAD_EVENT_WORKER;
  job_data->thd= new_thd;
  DBUG_PRINT("info", ("BURAN %s@%s ready for start t-3..2..1..0..ignition",
             job_data->dbname.str, job_data->name.str));

  /* Major failure */
  if ((res= pthread_create(&th, &connection_attrib, event_worker_thread,
                           job_data)))
    goto error;

523 524
  ++started_events;

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  DBUG_PRINT("info", ("Launch succeeded. BURAN is in THD=0x%lx", new_thd));
  DBUG_RETURN(FALSE);

error:
  DBUG_PRINT("error", ("Baikonur, we have a problem! res=%d", res));
  if (new_thd)
  {
    new_thd->proc_info= "Clearing";
    DBUG_ASSERT(new_thd->net.buff != 0);
    net_end(&new_thd->net);
    pthread_mutex_lock(&LOCK_thread_count);
    thread_count--;
    thread_running--;
    delete new_thd;
    pthread_mutex_unlock(&LOCK_thread_count);
  }
  delete job_data;
  DBUG_RETURN(TRUE);
}


546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
/*
  Checkes whether the state of the scheduler is RUNNING

  SYNOPSIS
    Event_scheduler::is_running()

  RETURN VALUE
    TRUE   RUNNING
    FALSE  Not RUNNING
*/

inline bool
Event_scheduler::is_running()
{
  LOCK_DATA();
  bool ret= (state == RUNNING);
  UNLOCK_DATA();
  return ret;
}


567
/*
568 569
  Stops the scheduler (again). Waits for acknowledgement from the
  scheduler that it has stopped - synchronous stopping.
570 571

  SYNOPSIS
572
    Event_scheduler::stop()
573 574

  RETURN VALUE
575 576
    FALSE  OK
    TRUE   Error (not reported)
577 578
*/

579 580
bool
Event_scheduler::stop()
581
{
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
  THD *thd= current_thd;
  DBUG_ENTER("Event_scheduler::stop");
  DBUG_PRINT("enter", ("thd=0x%lx", current_thd));

  LOCK_DATA();
  DBUG_PRINT("info", ("state before action %s", scheduler_states_names[state]));
  if (state != RUNNING)
    goto end;

  /* Guarantee we don't catch spurious signals */
  do {
    DBUG_PRINT("info", ("Waiting for COND_started_or_stopped from the manager "
                        "thread.  Current value of state is %s . "
                        "workers count=%d", scheduler_states_names[state].str,
                        workers_count()));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    /*
      NOTE: We don't use kill_one_thread() because it can't kill COM_DEAMON
      threads. In addition, kill_one_thread() requires THD but during shutdown
      current_thd is NULL. Hence, if kill_one_thread should be used it has to
      be modified to kill also daemons, by adding a flag, and also we have to
      create artificial THD here. To save all this work, we just do what
      kill_one_thread() does to kill a thread. See also sql_repl.cc for similar
      usage.
    */

    state= STOPPING;
    DBUG_PRINT("info", ("Manager thread has id %d", scheduler_thd->thread_id));
    /* Lock from delete */
    pthread_mutex_lock(&scheduler_thd->LOCK_delete);
    /* This will wake up the thread if it waits on Queue's conditional */
    sql_print_information("SCHEDULER: Killing manager thread %lu",
                          scheduler_thd->thread_id);
    scheduler_thd->awake(THD::KILL_CONNECTION);
    pthread_mutex_unlock(&scheduler_thd->LOCK_delete);

617
    /* thd could be 0x0, when shutting down */
618
    sql_print_information("SCHEDULER: Waiting the manager thread to reply");
619
    COND_STATE_WAIT(thd, NULL, "Waiting scheduler to stop");
620 621
  } while (state == STOPPING);
  DBUG_PRINT("info", ("Manager thread has cleaned up. Set state to INIT"));
622 623 624 625 626 627 628 629 630 631 632
  /*
    The rationale behind setting it to NULL here but not destructing it
    beforehand is because the THD will be deinited in event_scheduler_thread().
    It's more clear when the post_init and the deinit is done in one function.
    Here we just mark that the scheduler doesn't have a THD anymore. Though for
    milliseconds the old thread could exist we can't use it anymore. When we
    unlock the mutex in this function a little later the state will be
    INITIALIZED. Therefore, a connection thread could enter the critical section
    and will create a new THD object.
  */
  scheduler_thd= NULL;
633 634 635
end:
  UNLOCK_DATA();
  DBUG_RETURN(FALSE);
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 663 664 665
}


/*
  Returns the number of living event worker threads.

  SYNOPSIS
    Event_scheduler::workers_count()
*/

uint
Event_scheduler::workers_count()
{
  THD *tmp;
  uint count= 0;
  
  DBUG_ENTER("Event_scheduler::workers_count");
  pthread_mutex_lock(&LOCK_thread_count);       // For unlink from list
  I_List_iterator<THD> it(threads);
  while ((tmp=it++))
    if (tmp->system_thread == SYSTEM_THREAD_EVENT_WORKER)
      ++count;
  pthread_mutex_unlock(&LOCK_thread_count);
  DBUG_PRINT("exit", ("%d", count));
  DBUG_RETURN(count);
}


/*
  Auxiliary function for locking LOCK_scheduler_state. Used
666
  by the LOCK_DATA macro.
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

  SYNOPSIS
    Event_scheduler::lock_data()
      func  Which function is requesting mutex lock
      line  On which line mutex lock is requested
*/

void
Event_scheduler::lock_data(const char *func, uint line)
{
  DBUG_ENTER("Event_scheduler::lock_data");
  DBUG_PRINT("enter", ("func=%s line=%u", func, line));
  pthread_mutex_lock(&LOCK_scheduler_state);
  mutex_last_locked_in_func= func;
  mutex_last_locked_at_line= line;
  mutex_scheduler_data_locked= TRUE;
  DBUG_VOID_RETURN;
}


/*
  Auxiliary function for unlocking LOCK_scheduler_state. Used
689
  by the UNLOCK_DATA macro.
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714

  SYNOPSIS
    Event_scheduler::unlock_data()
      func  Which function is requesting mutex unlock
      line  On which line mutex unlock is requested
*/

void
Event_scheduler::unlock_data(const char *func, uint line)
{
  DBUG_ENTER("Event_scheduler::unlock_data");
  DBUG_PRINT("enter", ("func=%s line=%u", func, line));
  mutex_last_unlocked_at_line= line;
  mutex_scheduler_data_locked= FALSE;
  mutex_last_unlocked_in_func= func;
  pthread_mutex_unlock(&LOCK_scheduler_state);
  DBUG_VOID_RETURN;
}


/*
  Wrapper for pthread_cond_wait/timedwait

  SYNOPSIS
    Event_scheduler::cond_wait()
715 716
      thd     Thread (Could be NULL during shutdown procedure)
      abstime If not null then call pthread_cond_timedwait()
717
      msg     Message for thd->proc_info
718 719
      func    Which function is requesting cond_wait
      line    On which line cond_wait is requested
720 721 722
*/

void
723 724
Event_scheduler::cond_wait(THD *thd, struct timespec *abstime, const char* msg,
                           const char *func, uint line)
725
{
726
  DBUG_ENTER("Event_scheduler::cond_wait");
727 728 729 730
  waiting_on_cond= TRUE;
  mutex_last_unlocked_at_line= line;
  mutex_scheduler_data_locked= FALSE;
  mutex_last_unlocked_in_func= func;
731 732 733 734
  if (thd)
    thd->enter_cond(&COND_state, &LOCK_scheduler_state, msg);

  DBUG_PRINT("info", ("pthread_cond_%swait", abstime? "timed":""));
735
  if (!abstime)
736
    pthread_cond_wait(&COND_state, &LOCK_scheduler_state);
737 738
  else
    pthread_cond_timedwait(&COND_state, &LOCK_scheduler_state, abstime);
739 740 741 742 743 744 745 746 747
  if (thd)
  {
    /*
      This will free the lock so we need to relock. Not the best thing to
      do but we need to obey cond_wait()
    */
    thd->exit_cond("");
    LOCK_DATA();
  }
748 749 750 751
  mutex_last_locked_in_func= func;
  mutex_last_locked_at_line= line;
  mutex_scheduler_data_locked= TRUE;
  waiting_on_cond= FALSE;
752
  DBUG_VOID_RETURN;
753
}
754

755

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
/*
  Dumps the internal status of the scheduler

  SYNOPSIS
    Event_scheduler::dump_internal_status()
      thd  Thread

  RETURN VALUE
    FALSE  OK
    TRUE   Error
*/

bool
Event_scheduler::dump_internal_status(THD *thd)
{
  int ret= 0;
  DBUG_ENTER("Event_scheduler::dump_internal_status");

#ifndef DBUG_OFF
  CHARSET_INFO *scs= system_charset_info;
  Protocol *protocol= thd->protocol;
  char tmp_buff[5*STRING_BUFFER_USUAL_SIZE];
  char int_buff[STRING_BUFFER_USUAL_SIZE];
  String tmp_string(tmp_buff, sizeof(tmp_buff), scs);
  String int_string(int_buff, sizeof(int_buff), scs);
  tmp_string.length(0);
  int_string.length(0);

784 785 786 787 788 789
  do
  {
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler state"), scs);
    protocol->store(scheduler_states_names[state].str,
                    scheduler_states_names[state].length, scs);
790

791 792
    if ((ret= protocol->write()))
      break;
793

794 795 796 797 798
    /* thread_id */
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("thread_id"), scs);
    if (thread_id)
    {
799
      int_string.set((longlong) scheduler_thd->thread_id, scs);
800 801 802 803 804 805
      protocol->store(&int_string);
    }
    else
      protocol->store_null();
    if ((ret= protocol->write()))
      break;
806

807 808 809 810 811 812 813 814 815 816
    /* last locked at*/
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler last locked at"), scs);
    tmp_string.length(scs->cset->snprintf(scs, (char*) tmp_string.ptr(),
                                          tmp_string.alloced_length(), "%s::%d",
                                          mutex_last_locked_in_func,
                                          mutex_last_locked_at_line));
    protocol->store(&tmp_string);
    if ((ret= protocol->write()))
      break;
817

818 819 820 821 822 823 824 825 826 827
    /* last unlocked at*/
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler last unlocked at"), scs);
    tmp_string.length(scs->cset->snprintf(scs, (char*) tmp_string.ptr(),
                                          tmp_string.alloced_length(), "%s::%d",
                                          mutex_last_unlocked_in_func,
                                          mutex_last_unlocked_at_line));
    protocol->store(&tmp_string);
    if ((ret= protocol->write()))
      break;
828

829 830 831 832 833 834 835
    /* waiting on */
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler waiting on condition"), scs);
    int_string.set((longlong) waiting_on_cond, scs);
    protocol->store(&int_string);
    if ((ret= protocol->write()))
      break;
836

837 838 839 840 841 842 843
    /* workers_count */
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler workers count"), scs);
    int_string.set((longlong) workers_count(), scs);
    protocol->store(&int_string);
    if ((ret= protocol->write()))
      break;
844

845 846 847 848 849 850 851
    /* workers_count */
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler executed events"), scs);
    int_string.set((longlong) started_events, scs);
    protocol->store(&int_string);
    if ((ret= protocol->write()))
      break;
852

853 854 855 856 857 858 859
    /* scheduler_data_locked */
    protocol->prepare_for_resend();
    protocol->store(STRING_WITH_LEN("scheduler data locked"), scs);
    int_string.set((longlong) mutex_scheduler_data_locked, scs);
    protocol->store(&int_string);
    ret= protocol->write();
  } while (0);
860 861 862 863
#endif

  DBUG_RETURN(ret);
}