~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2003 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
17
/**
18
  @file
19
20
  @brief
21
  logging of commands
22
23
  @todo
24
    Abort logging when we get an error in reading or writing log files
25
*/
26
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
27
#include <drizzled/server_includes.h>
1 by brian
clean slate
28
#include "sql_repl.h"
29
#include "rpl_filter.h"
30
#include "rpl_rli.h"
31
212.5.38 by Monty Taylor
Moved my_dir (and removed references to a lot of places)
32
#include <mysys/my_dir.h>
1 by brian
clean slate
33
#include <stdarg.h>
34
212.5.10 by Monty Taylor
Moved drizzle/plugin*h to drizzled
35
#include <drizzled/plugin.h>
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
36
#include <drizzled/drizzled_error_messages.h>
338 by Monty Taylor
Tagged more strings.
37
#include <libdrizzle/gettext.h>
1 by brian
clean slate
38
39
/* max size of the log message */
40
#define MAX_LOG_BUFFER_SIZE 1024
41
#define MAX_USER_HOST_SIZE 512
42
#define MAX_TIME_SIZE 32
43
#define MY_OFF_T_UNDEF (~(my_off_t)0UL)
44
45
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
46
47
LOGGER logger;
48
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
49
DRIZZLE_BIN_LOG mysql_bin_log;
1 by brian
clean slate
50
ulong sync_binlog_counter= 0;
51
52
static bool test_if_number(const char *str,
53
			   long *res, bool allow_wildcards);
54
static int binlog_init(void *p);
55
static int binlog_close_connection(handlerton *hton, THD *thd);
56
static int binlog_savepoint_set(handlerton *hton, THD *thd, void *sv);
57
static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv);
58
static int binlog_commit(handlerton *hton, THD *thd, bool all);
59
static int binlog_rollback(handlerton *hton, THD *thd, bool all);
60
static int binlog_prepare(handlerton *hton, THD *thd, bool all);
61
62
63
sql_print_message_func sql_print_message_handlers[3] =
64
{
65
  sql_print_information,
66
  sql_print_warning,
67
  sql_print_error
68
};
69
70
71
char *make_default_log_name(char *buff,const char* log_ext)
72
{
73
  strmake(buff, pidfile_name, FN_REFLEN-5);
74
  return fn_format(buff, buff, mysql_data_home, log_ext,
75
                   MYF(MY_UNPACK_FILENAME|MY_REPLACE_EXT));
76
}
77
78
/*
79
  Helper class to hold a mutex for the duration of the
80
  block.
81
82
  Eliminates the need for explicit unlocking of mutexes on, e.g.,
83
  error returns.  On passing a null pointer, the sentry will not do
84
  anything.
85
 */
86
class Mutex_sentry
87
{
88
public:
89
  Mutex_sentry(pthread_mutex_t *mutex)
90
    : m_mutex(mutex)
91
  {
92
    if (m_mutex)
93
      pthread_mutex_lock(mutex);
94
  }
95
96
  ~Mutex_sentry()
97
  {
98
    if (m_mutex)
99
      pthread_mutex_unlock(m_mutex);
100
    m_mutex= 0;
101
  }
102
103
private:
104
  pthread_mutex_t *m_mutex;
105
106
  // It's not allowed to copy this object in any way
107
  Mutex_sentry(Mutex_sentry const&);
108
  void operator=(Mutex_sentry const&);
109
};
110
111
/*
112
  Helper class to store binary log transaction data.
113
*/
114
class binlog_trx_data {
115
public:
116
  binlog_trx_data()
117
    : at_least_one_stmt(0), m_pending(0), before_stmt_pos(MY_OFF_T_UNDEF)
118
  {
119
    trans_log.end_of_file= max_binlog_cache_size;
120
  }
121
122
  ~binlog_trx_data()
123
  {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
124
    assert(pending() == NULL);
1 by brian
clean slate
125
    close_cached_file(&trans_log);
126
  }
127
128
  my_off_t position() const {
129
    return my_b_tell(&trans_log);
130
  }
131
132
  bool empty() const
133
  {
134
    return pending() == NULL && my_b_tell(&trans_log) == 0;
135
  }
136
137
  /*
138
    Truncate the transaction cache to a certain position. This
139
    includes deleting the pending event.
140
   */
141
  void truncate(my_off_t pos)
142
  {
143
    delete pending();
144
    set_pending(0);
145
    reinit_io_cache(&trans_log, WRITE_CACHE, pos, 0, 0);
146
    if (pos < before_stmt_pos)
147
      before_stmt_pos= MY_OFF_T_UNDEF;
148
149
    /*
150
      The only valid positions that can be truncated to are at the
151
      beginning of a statement. We are relying on this fact to be able
152
      to set the at_least_one_stmt flag correctly. In other word, if
153
      we are truncating to the beginning of the transaction cache,
154
      there will be no statements in the cache, otherwhise, we will
155
      have at least one statement in the transaction cache.
156
     */
157
    at_least_one_stmt= (pos > 0);
158
  }
159
160
  /*
161
    Reset the entire contents of the transaction cache, emptying it
162
    completely.
163
   */
164
  void reset() {
165
    if (!empty())
166
      truncate(0);
167
    before_stmt_pos= MY_OFF_T_UNDEF;
168
    trans_log.end_of_file= max_binlog_cache_size;
169
  }
170
171
  Rows_log_event *pending() const
172
  {
173
    return m_pending;
174
  }
175
176
  void set_pending(Rows_log_event *const pending)
177
  {
178
    m_pending= pending;
179
  }
180
181
  IO_CACHE trans_log;                         // The transaction cache
182
183
  /**
184
    Boolean that is true if there is at least one statement in the
185
    transaction cache.
186
  */
187
  bool at_least_one_stmt;
188
189
private:
190
  /*
191
    Pending binrows event. This event is the event where the rows are
192
    currently written.
193
   */
194
  Rows_log_event *m_pending;
195
196
public:
197
  /*
198
    Binlog position before the start of the current statement.
199
  */
200
  my_off_t before_stmt_pos;
201
};
202
203
handlerton *binlog_hton;
204
205
206
/* Check if a given table is opened log table */
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
207
int check_if_log_table(uint db_len __attribute__((unused)),
208
                       const char *db __attribute__((unused)),
209
                       uint table_name_len __attribute__((unused)),
210
                       const char *table_name __attribute__((unused)),
211
                       uint check_if_opened __attribute__((unused)))
1 by brian
clean slate
212
{
213
  return 0;
214
}
215
216
/* log event handlers */
217
218
bool Log_to_file_event_handler::
219
  log_error(enum loglevel level, const char *format,
220
            va_list args)
221
{
222
  return vprint_msg_to_log(level, format, args);
223
}
224
225
void Log_to_file_event_handler::init_pthread_objects()
226
{
227
  mysql_log.init_pthread_objects();
228
  mysql_slow_log.init_pthread_objects();
229
}
230
231
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
232
/** Wrapper around DRIZZLE_LOG::write() for slow log. */
1 by brian
clean slate
233
234
bool Log_to_file_event_handler::
235
  log_slow(THD *thd, time_t current_time, time_t query_start_arg,
236
           const char *user_host, uint user_host_len,
151 by Brian Aker
Ulonglong to uint64_t
237
           uint64_t query_utime, uint64_t lock_utime, bool is_command,
1 by brian
clean slate
238
           const char *sql_text, uint sql_text_len)
239
{
240
  return mysql_slow_log.write(thd, current_time, query_start_arg,
241
                              user_host, user_host_len,
242
                              query_utime, lock_utime, is_command,
243
                              sql_text, sql_text_len);
244
}
245
246
247
/**
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
248
   Wrapper around DRIZZLE_LOG::write() for general log. We need it since we
1 by brian
clean slate
249
   want all log event handlers to have the same signature.
250
*/
251
252
bool Log_to_file_event_handler::
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
253
  log_general(THD *thd __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
254
              time_t event_time, const char *user_host,
1 by brian
clean slate
255
              uint user_host_len, int thread_id,
256
              const char *command_type, uint command_type_len,
257
              const char *sql_text, uint sql_text_len,
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
258
              const CHARSET_INFO * const client_cs __attribute__((unused)))
1 by brian
clean slate
259
{
260
  return mysql_log.write(event_time, user_host, user_host_len,
261
                         thread_id, command_type, command_type_len,
262
                         sql_text, sql_text_len);
263
}
264
265
266
bool Log_to_file_event_handler::init()
267
{
268
  if (!is_initialized)
269
  {
270
    if (opt_slow_log)
271
      mysql_slow_log.open_slow_log(sys_var_slow_log_path.value);
272
273
    if (opt_log)
274
      mysql_log.open_query_log(sys_var_general_log_path.value);
275
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
276
    is_initialized= true;
1 by brian
clean slate
277
  }
278
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
279
  return false;
1 by brian
clean slate
280
}
281
282
283
void Log_to_file_event_handler::cleanup()
284
{
285
  mysql_log.cleanup();
286
  mysql_slow_log.cleanup();
287
}
288
289
void Log_to_file_event_handler::flush()
290
{
291
  /* reopen log files */
292
  if (opt_log)
293
    mysql_log.reopen_file();
294
  if (opt_slow_log)
295
    mysql_slow_log.reopen_file();
296
}
297
298
/*
299
  Log error with all enabled log event handlers
300
301
  SYNOPSIS
302
    error_log_print()
303
304
    level             The level of the error significance: NOTE,
305
                      WARNING or ERROR.
306
    format            format string for the error message
307
    args              list of arguments for the format string
308
309
  RETURN
310
    FALSE - OK
311
    TRUE - error occured
312
*/
313
314
bool LOGGER::error_log_print(enum loglevel level, const char *format,
315
                             va_list args)
316
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
317
  bool error= false;
1 by brian
clean slate
318
  Log_event_handler **current_handler;
319
320
  /* currently we don't need locking here as there is no error_log table */
321
  for (current_handler= error_log_handler_list ; *current_handler ;)
322
    error= (*current_handler++)->log_error(level, format, args) || error;
323
324
  return error;
325
}
326
327
328
void LOGGER::cleanup_base()
329
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
330
  assert(inited == 1);
1 by brian
clean slate
331
  rwlock_destroy(&LOCK_logger);
332
  if (file_log_handler)
333
    file_log_handler->cleanup();
334
}
335
336
337
void LOGGER::cleanup_end()
338
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
339
  assert(inited == 1);
1 by brian
clean slate
340
  if (file_log_handler)
341
    delete file_log_handler;
342
}
343
344
345
/**
346
  Perform basic log initialization: create file-based log handler and
347
  init error log.
348
*/
349
void LOGGER::init_base()
350
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
351
  assert(inited == 0);
1 by brian
clean slate
352
  inited= 1;
353
354
  /*
355
    Here we create file log handler. We don't do it for the table log handler
356
    here as it cannot be created so early. The reason is THD initialization,
357
    which depends on the system variables (parsed later).
358
  */
359
  if (!file_log_handler)
360
    file_log_handler= new Log_to_file_event_handler;
361
362
  /* by default we use traditional error log */
363
  init_error_log(LOG_FILE);
364
365
  file_log_handler->init_pthread_objects();
366
  my_rwlock_init(&LOCK_logger, NULL);
367
}
368
369
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
370
bool LOGGER::flush_logs(THD *thd __attribute__((unused)))
1 by brian
clean slate
371
{
372
  int rc= 0;
373
374
  /*
375
    Now we lock logger, as nobody should be able to use logging routines while
376
    log tables are closed
377
  */
378
  logger.lock_exclusive();
379
380
  /* reopen log files */
381
  file_log_handler->flush();
382
383
  /* end of log flush */
384
  logger.unlock();
385
  return rc;
386
}
387
388
389
/*
390
  Log slow query with all enabled log event handlers
391
392
  SYNOPSIS
393
    slow_log_print()
394
395
    thd                 THD of the query being logged
396
    query               The query being logged
397
    query_length        The length of the query string
398
    current_utime       Current time in microseconds (from undefined start)
399
400
  RETURN
401
    FALSE   OK
402
    TRUE    error occured
403
*/
404
405
bool LOGGER::slow_log_print(THD *thd, const char *query, uint query_length,
151 by Brian Aker
Ulonglong to uint64_t
406
                            uint64_t current_utime)
1 by brian
clean slate
407
408
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
409
  bool error= false;
1 by brian
clean slate
410
  Log_event_handler **current_handler;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
411
  bool is_command= false;
1 by brian
clean slate
412
  char user_host_buff[MAX_USER_HOST_SIZE];
413
  Security_context *sctx= thd->security_ctx;
414
  uint user_host_len= 0;
151 by Brian Aker
Ulonglong to uint64_t
415
  uint64_t query_utime, lock_utime;
1 by brian
clean slate
416
417
  /*
418
    Print the message to the buffer if we have slow log enabled
419
  */
420
421
  if (*slow_log_handler_list)
422
  {
423
    time_t current_time;
424
425
    /* do not log slow queries from replication threads */
426
    if (thd->slave_thread && !opt_log_slow_slave_statements)
427
      return 0;
428
429
    lock_shared();
430
    if (!opt_slow_log)
431
    {
432
      unlock();
433
      return 0;
434
    }
435
436
    /* fill in user_host value: the format is "%s[%s] @ %s [%s]" */
437
    user_host_len= (strxnmov(user_host_buff, MAX_USER_HOST_SIZE,
265 by brian
First pass through cleaning up security context.
438
                             sctx->user, "[", sctx->user, "] @ ",
439
                             sctx->ip, " [",
440
                             sctx->ip, "]", NullS) -
1 by brian
clean slate
441
                    user_host_buff);
442
443
    current_time= my_time_possible_from_micro(current_utime);
444
    if (thd->start_utime)
445
    {
446
      query_utime= (current_utime - thd->start_utime);
447
      lock_utime=  (thd->utime_after_lock - thd->start_utime);
448
    }
449
    else
450
    {
451
      query_utime= lock_utime= 0;
452
    }
453
454
    if (!query)
455
    {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
456
      is_command= true;
1 by brian
clean slate
457
      query= command_name[thd->command].str;
458
      query_length= command_name[thd->command].length;
459
    }
460
461
    for (current_handler= slow_log_handler_list; *current_handler ;)
462
      error= (*current_handler++)->log_slow(thd, current_time, thd->start_time,
463
                                            user_host_buff, user_host_len,
464
                                            query_utime, lock_utime, is_command,
465
                                            query, query_length) || error;
466
467
    unlock();
468
  }
469
  return error;
470
}
471
472
bool LOGGER::general_log_write(THD *thd, enum enum_server_command command,
473
                               const char *query, uint query_length)
474
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
475
  bool error= false;
1 by brian
clean slate
476
  Log_event_handler **current_handler= general_log_handler_list;
477
  char user_host_buff[MAX_USER_HOST_SIZE];
478
  Security_context *sctx= thd->security_ctx;
479
  ulong id;
480
  uint user_host_len= 0;
481
  time_t current_time;
482
483
  if (thd)
484
    id= thd->thread_id;                 /* Normal thread */
485
  else
486
    id= 0;                              /* Log from connect handler */
487
488
  lock_shared();
489
  if (!opt_log)
490
  {
491
    unlock();
492
    return 0;
493
  }
494
  user_host_len= strxnmov(user_host_buff, MAX_USER_HOST_SIZE,
265 by brian
First pass through cleaning up security context.
495
                          sctx->user, "[",
496
                          sctx->user, "] @ ",
497
                          sctx->ip, " [",
498
                          sctx->ip, "]", NullS) -
1 by brian
clean slate
499
                                                          user_host_buff;
500
501
  current_time= my_time(0);
502
503
  while (*current_handler)
504
    error|= (*current_handler++)->
505
      log_general(thd, current_time, user_host_buff,
506
                  user_host_len, id,
507
                  command_name[(uint) command].str,
508
                  command_name[(uint) command].length,
509
                  query, query_length,
510
                  thd->variables.character_set_client) || error;
511
  unlock();
512
513
  return error;
514
}
515
516
bool LOGGER::general_log_print(THD *thd, enum enum_server_command command,
517
                               const char *format, va_list args)
518
{
519
  uint message_buff_len= 0;
520
  char message_buff[MAX_LOG_BUFFER_SIZE];
521
522
  /* prepare message */
523
  if (format)
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
524
    message_buff_len= vsnprintf(message_buff, sizeof(message_buff),
1 by brian
clean slate
525
                                   format, args);
526
  else
527
    message_buff[0]= '\0';
528
529
  return general_log_write(thd, command, message_buff, message_buff_len);
530
}
531
532
void LOGGER::init_error_log(uint error_log_printer)
533
{
534
  if (error_log_printer & LOG_NONE)
535
  {
536
    error_log_handler_list[0]= 0;
537
    return;
538
  }
539
540
  switch (error_log_printer) {
541
  case LOG_FILE:
542
    error_log_handler_list[0]= file_log_handler;
543
    error_log_handler_list[1]= 0;
544
    break;
545
  }
546
}
547
548
void LOGGER::init_slow_log(uint slow_log_printer)
549
{
550
  if (slow_log_printer & LOG_NONE)
551
  {
552
    slow_log_handler_list[0]= 0;
553
    return;
554
  }
555
556
  slow_log_handler_list[0]= file_log_handler;
557
  slow_log_handler_list[1]= 0;
558
}
559
560
void LOGGER::init_general_log(uint general_log_printer)
561
{
562
  if (general_log_printer & LOG_NONE)
563
  {
564
    general_log_handler_list[0]= 0;
565
    return;
566
  }
567
568
  general_log_handler_list[0]= file_log_handler;
569
  general_log_handler_list[1]= 0;
570
}
571
572
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
573
bool LOGGER::activate_log_handler(THD* thd __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
574
                                  uint log_type)
1 by brian
clean slate
575
{
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
576
  DRIZZLE_QUERY_LOG *file_log;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
577
  bool res= false;
1 by brian
clean slate
578
  lock_exclusive();
579
  switch (log_type) {
580
  case QUERY_LOG_SLOW:
581
    if (!opt_slow_log)
582
    {
583
      file_log= file_log_handler->get_mysql_slow_log();
584
585
      file_log->open_slow_log(sys_var_slow_log_path.value);
586
      init_slow_log(log_output_options);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
587
      opt_slow_log= true;
1 by brian
clean slate
588
    }
589
    break;
590
  case QUERY_LOG_GENERAL:
591
    if (!opt_log)
592
    {
593
      file_log= file_log_handler->get_mysql_log();
594
595
      file_log->open_query_log(sys_var_general_log_path.value);
596
      init_general_log(log_output_options);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
597
      opt_log= true;
1 by brian
clean slate
598
    }
599
    break;
600
  default:
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
601
    assert(0);
1 by brian
clean slate
602
  }
603
  unlock();
604
  return res;
605
}
606
607
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
608
void LOGGER::deactivate_log_handler(THD *thd __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
609
                                    uint log_type)
1 by brian
clean slate
610
{
147 by Brian Aker
More my_bool conversion. This time the set_var class.
611
  bool *tmp_opt= 0;
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
612
  DRIZZLE_LOG *file_log;
1 by brian
clean slate
613
614
  switch (log_type) {
615
  case QUERY_LOG_SLOW:
616
    tmp_opt= &opt_slow_log;
617
    file_log= file_log_handler->get_mysql_slow_log();
618
    break;
619
  case QUERY_LOG_GENERAL:
620
    tmp_opt= &opt_log;
621
    file_log= file_log_handler->get_mysql_log();
622
    break;
623
  default:
624
    assert(0);                                  // Impossible
625
  }
626
627
  if (!(*tmp_opt))
628
    return;
629
630
  lock_exclusive();
631
  file_log->close(0);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
632
  *tmp_opt= false;
1 by brian
clean slate
633
  unlock();
634
}
635
636
int LOGGER::set_handlers(uint error_log_printer,
637
                         uint slow_log_printer,
638
                         uint general_log_printer)
639
{
640
  /* error log table is not supported yet */
641
  lock_exclusive();
642
643
  init_error_log(error_log_printer);
644
  init_slow_log(slow_log_printer);
645
  init_general_log(general_log_printer);
646
647
  unlock();
648
649
  return 0;
650
}
651
652
653
 /*
654
  Save position of binary log transaction cache.
655
656
  SYNPOSIS
657
    binlog_trans_log_savepos()
658
659
    thd      The thread to take the binlog data from
660
    pos      Pointer to variable where the position will be stored
661
662
  DESCRIPTION
663
664
    Save the current position in the binary log transaction cache into
665
    the variable pointed to by 'pos'
666
 */
667
668
static void
669
binlog_trans_log_savepos(THD *thd, my_off_t *pos)
670
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
671
  assert(pos != NULL);
1 by brian
clean slate
672
  if (thd_get_ha_data(thd, binlog_hton) == NULL)
673
    thd->binlog_setup_trx_data();
674
  binlog_trx_data *const trx_data=
675
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
676
  assert(mysql_bin_log.is_open());
1 by brian
clean slate
677
  *pos= trx_data->position();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
678
  return;
1 by brian
clean slate
679
}
680
681
682
/*
683
  Truncate the binary log transaction cache.
684
685
  SYNPOSIS
686
    binlog_trans_log_truncate()
687
688
    thd      The thread to take the binlog data from
689
    pos      Position to truncate to
690
691
  DESCRIPTION
692
693
    Truncate the binary log to the given position. Will not change
694
    anything else.
695
696
 */
697
static void
698
binlog_trans_log_truncate(THD *thd, my_off_t pos)
699
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
700
  assert(thd_get_ha_data(thd, binlog_hton) != NULL);
1 by brian
clean slate
701
  /* Only true if binlog_trans_log_savepos() wasn't called before */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
702
  assert(pos != ~(my_off_t) 0);
1 by brian
clean slate
703
704
  binlog_trx_data *const trx_data=
705
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
706
  trx_data->truncate(pos);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
707
  return;
1 by brian
clean slate
708
}
709
710
711
/*
712
  this function is mostly a placeholder.
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
713
  conceptually, binlog initialization (now mostly done in DRIZZLE_BIN_LOG::open)
1 by brian
clean slate
714
  should be moved here.
715
*/
716
717
int binlog_init(void *p)
718
{
719
  binlog_hton= (handlerton *)p;
720
  binlog_hton->state=opt_bin_log ? SHOW_OPTION_YES : SHOW_OPTION_NO;
721
  binlog_hton->savepoint_offset= sizeof(my_off_t);
722
  binlog_hton->close_connection= binlog_close_connection;
723
  binlog_hton->savepoint_set= binlog_savepoint_set;
724
  binlog_hton->savepoint_rollback= binlog_savepoint_rollback;
725
  binlog_hton->commit= binlog_commit;
726
  binlog_hton->rollback= binlog_rollback;
727
  binlog_hton->prepare= binlog_prepare;
728
  binlog_hton->flags= HTON_NOT_USER_SELECTABLE | HTON_HIDDEN;
224.2.3 by Brian Aker
Fix for memory leak in shutdown/restart of an engine (not fixed in 5.1)
729
1 by brian
clean slate
730
  return 0;
731
}
732
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
733
static int binlog_close_connection(handlerton *hton __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
734
                                   THD *thd)
1 by brian
clean slate
735
{
736
  binlog_trx_data *const trx_data=
737
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
738
  assert(trx_data->empty());
1 by brian
clean slate
739
  thd_set_ha_data(thd, binlog_hton, NULL);
740
  trx_data->~binlog_trx_data();
741
  my_free((uchar*)trx_data, MYF(0));
742
  return 0;
743
}
744
745
/*
746
  End a transaction.
747
748
  SYNOPSIS
749
    binlog_end_trans()
750
751
    thd      The thread whose transaction should be ended
752
    trx_data Pointer to the transaction data to use
753
    end_ev   The end event to use, or NULL
754
    all      True if the entire transaction should be ended, false if
755
             only the statement transaction should be ended.
756
757
  DESCRIPTION
758
759
    End the currently open transaction. The transaction can be either
760
    a real transaction (if 'all' is true) or a statement transaction
761
    (if 'all' is false).
762
763
    If 'end_ev' is NULL, the transaction is a rollback of only
764
    transactional tables, so the transaction cache will be truncated
765
    to either just before the last opened statement transaction (if
766
    'all' is false), or reset completely (if 'all' is true).
767
 */
768
static int
769
binlog_end_trans(THD *thd, binlog_trx_data *trx_data,
770
                 Log_event *end_ev, bool all)
771
{
772
  int error=0;
773
  IO_CACHE *trans_log= &trx_data->trans_log;
774
775
  /*
776
    NULL denotes ROLLBACK with nothing to replicate: i.e., rollback of
777
    only transactional tables.  If the transaction contain changes to
778
    any non-transactiona tables, we need write the transaction and log
779
    a ROLLBACK last.
780
  */
781
  if (end_ev != NULL)
782
  {
783
    /*
784
      Doing a commit or a rollback including non-transactional tables,
785
      i.e., ending a transaction where we might write the transaction
786
      cache to the binary log.
787
788
      We can always end the statement when ending a transaction since
789
      transactions are not allowed inside stored functions.  If they
790
      were, we would have to ensure that we're not ending a statement
791
      inside a stored function.
792
     */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
793
    thd->binlog_flush_pending_rows_event(true);
1 by brian
clean slate
794
795
    error= mysql_bin_log.write(thd, &trx_data->trans_log, end_ev);
796
    trx_data->reset();
797
798
    /*
799
      We need to step the table map version after writing the
800
      transaction cache to disk.
801
    */
802
    mysql_bin_log.update_table_map_version();
803
    statistic_increment(binlog_cache_use, &LOCK_status);
804
    if (trans_log->disk_writes != 0)
805
    {
806
      statistic_increment(binlog_cache_disk_use, &LOCK_status);
807
      trans_log->disk_writes= 0;
808
    }
809
  }
810
  else
811
  {
812
    /*
813
      If rolling back an entire transaction or a single statement not
814
      inside a transaction, we reset the transaction cache.
815
816
      If rolling back a statement in a transaction, we truncate the
817
      transaction cache to remove the statement.
818
     */
819
    if (all || !(thd->options & (OPTION_BEGIN | OPTION_NOT_AUTOCOMMIT)))
820
    {
821
      trx_data->reset();
822
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
823
      assert(!thd->binlog_get_pending_rows_event());
1 by brian
clean slate
824
      thd->clear_binlog_table_maps();
825
    }
826
    else                                        // ...statement
827
      trx_data->truncate(trx_data->before_stmt_pos);
828
829
    /*
830
      We need to step the table map version on a rollback to ensure
831
      that a new table map event is generated instead of the one that
832
      was written to the thrown-away transaction cache.
833
    */
834
    mysql_bin_log.update_table_map_version();
835
  }
836
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
837
  return(error);
1 by brian
clean slate
838
}
839
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
840
static int binlog_prepare(handlerton *hton __attribute__((unused)),
841
                          THD *thd __attribute__((unused)),
842
                          bool all __attribute__((unused)))
1 by brian
clean slate
843
{
844
  /*
845
    do nothing.
846
    just pretend we can do 2pc, so that MySQL won't
847
    switch to 1pc.
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
848
    real work will be done in DRIZZLE_BIN_LOG::log_xid()
1 by brian
clean slate
849
  */
850
  return 0;
851
}
852
853
#define YESNO(X) ((X) ? "yes" : "no")
854
855
/**
856
  This function is called once after each statement.
857
858
  It has the responsibility to flush the transaction cache to the
859
  binlog file on commits.
860
861
  @param hton  The binlog handlerton.
862
  @param thd   The client thread that executes the transaction.
863
  @param all   This is @c true if this is a real transaction commit, and
864
               @false otherwise.
865
866
  @see handlerton::commit
867
*/
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
868
static int binlog_commit(handlerton *hton __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
869
                         THD *thd, bool all)
1 by brian
clean slate
870
{
871
  binlog_trx_data *const trx_data=
872
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
873
874
  if (trx_data->empty())
875
  {
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
876
    // we're here because trans_log was flushed in DRIZZLE_BIN_LOG::log_xid()
1 by brian
clean slate
877
    trx_data->reset();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
878
    return(0);
1 by brian
clean slate
879
  }
880
881
  /*
882
    Decision table for committing a transaction. The top part, the
883
    *conditions* represent different cases that can occur, and hte
884
    bottom part, the *actions*, represent what should be done in that
885
    particular case.
886
887
    Real transaction        'all' was true
888
889
    Statement in cache      There were at least one statement in the
890
                            transaction cache
891
892
    In transaction          We are inside a transaction
893
894
    Stmt modified non-trans The statement being committed modified a
895
                            non-transactional table
896
897
    All modified non-trans  Some statement before this one in the
898
                            transaction modified a non-transactional
899
                            table
900
901
902
    =============================  = = = = = = = = = = = = = = = =
903
    Real transaction               N N N N N N N N N N N N N N N N
904
    Statement in cache             N N N N N N N N Y Y Y Y Y Y Y Y
905
    In transaction                 N N N N Y Y Y Y N N N N Y Y Y Y
906
    Stmt modified non-trans        N N Y Y N N Y Y N N Y Y N N Y Y
907
    All modified non-trans         N Y N Y N Y N Y N Y N Y N Y N Y
908
909
    Action: (C)ommit/(A)ccumulate  C C - C A C - C - - - - A A - A
910
    =============================  = = = = = = = = = = = = = = = =
911
912
913
    =============================  = = = = = = = = = = = = = = = =
914
    Real transaction               Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y
915
    Statement in cache             N N N N N N N N Y Y Y Y Y Y Y Y
916
    In transaction                 N N N N Y Y Y Y N N N N Y Y Y Y
917
    Stmt modified non-trans        N N Y Y N N Y Y N N Y Y N N Y Y
918
    All modified non-trans         N Y N Y N Y N Y N Y N Y N Y N Y
919
920
    (C)ommit/(A)ccumulate/(-)      - - - - C C - C - - - - C C - C
921
    =============================  = = = = = = = = = = = = = = = =
922
923
    In other words, we commit the transaction if and only if both of
924
    the following are true:
925
     - We are not in a transaction and committing a statement
926
927
     - We are in a transaction and one (or more) of the following are
928
       true:
929
930
       - A full transaction is committed
931
932
         OR
933
934
       - A non-transactional statement is committed and there is
935
         no statement cached
936
937
    Otherwise, we accumulate the statement
938
  */
151 by Brian Aker
Ulonglong to uint64_t
939
  uint64_t const in_transaction=
1 by brian
clean slate
940
    thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
941
  if ((in_transaction && (all || (!trx_data->at_least_one_stmt && thd->transaction.stmt.modified_non_trans_table))) || (!in_transaction && !all))
942
  {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
943
    Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), true, false);
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
944
    qev.error_code= 0; // see comment in DRIZZLE_LOG::write(THD, IO_CACHE)
1 by brian
clean slate
945
    int error= binlog_end_trans(thd, trx_data, &qev, all);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
946
    return(error);
1 by brian
clean slate
947
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
948
  return(0);
1 by brian
clean slate
949
}
950
951
/**
952
  This function is called when a transaction involving a transactional
953
  table is rolled back.
954
955
  It has the responsibility to flush the transaction cache to the
956
  binlog file. However, if the transaction does not involve
957
  non-transactional tables, nothing needs to be logged.
958
959
  @param hton  The binlog handlerton.
960
  @param thd   The client thread that executes the transaction.
961
  @param all   This is @c true if this is a real transaction rollback, and
962
               @false otherwise.
963
964
  @see handlerton::rollback
965
*/
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
966
static int binlog_rollback(handlerton *hton __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
967
                           THD *thd, bool all)
1 by brian
clean slate
968
{
969
  int error=0;
970
  binlog_trx_data *const trx_data=
971
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
972
973
  if (trx_data->empty()) {
974
    trx_data->reset();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
975
    return(0);
1 by brian
clean slate
976
  }
977
978
  if ((all && thd->transaction.all.modified_non_trans_table) ||
979
      (!all && thd->transaction.stmt.modified_non_trans_table) ||
980
      (thd->options & OPTION_KEEP_LOG))
981
  {
982
    /*
983
      We write the transaction cache with a rollback last if we have
984
      modified any non-transactional table. We do this even if we are
985
      committing a single statement that has modified a
986
      non-transactional table since it can have modified a
987
      transactional table in that statement as well, which needs to be
988
      rolled back on the slave.
989
    */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
990
    Query_log_event qev(thd, STRING_WITH_LEN("ROLLBACK"), true, false);
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
991
    qev.error_code= 0; // see comment in DRIZZLE_LOG::write(THD, IO_CACHE)
1 by brian
clean slate
992
    error= binlog_end_trans(thd, trx_data, &qev, all);
993
  }
994
  else if ((all && !thd->transaction.all.modified_non_trans_table) ||
995
           (!all && !thd->transaction.stmt.modified_non_trans_table))
996
  {
997
    /*
998
      If we have modified only transactional tables, we can truncate
999
      the transaction cache without writing anything to the binary
1000
      log.
1001
     */
1002
    error= binlog_end_trans(thd, trx_data, 0, all);
1003
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1004
  return(error);
1 by brian
clean slate
1005
}
1006
1007
/**
1008
  @note
1009
  How do we handle this (unlikely but legal) case:
1010
  @verbatim
1011
    [transaction] + [update to non-trans table] + [rollback to savepoint] ?
1012
  @endverbatim
1013
  The problem occurs when a savepoint is before the update to the
1014
  non-transactional table. Then when there's a rollback to the savepoint, if we
1015
  simply truncate the binlog cache, we lose the part of the binlog cache where
1016
  the update is. If we want to not lose it, we need to write the SAVEPOINT
1017
  command and the ROLLBACK TO SAVEPOINT command to the binlog cache. The latter
1018
  is easy: it's just write at the end of the binlog cache, but the former
1019
  should be *inserted* to the place where the user called SAVEPOINT. The
1020
  solution is that when the user calls SAVEPOINT, we write it to the binlog
1021
  cache (so no need to later insert it). As transactions are never intermixed
1022
  in the binary log (i.e. they are serialized), we won't have conflicts with
1023
  savepoint names when using mysqlbinlog or in the slave SQL thread.
1024
  Then when ROLLBACK TO SAVEPOINT is called, if we updated some
1025
  non-transactional table, we don't truncate the binlog cache but instead write
1026
  ROLLBACK TO SAVEPOINT to it; otherwise we truncate the binlog cache (which
1027
  will chop the SAVEPOINT command from the binlog cache, which is good as in
1028
  that case there is no need to have it in the binlog).
1029
*/
1030
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
1031
static int binlog_savepoint_set(handlerton *hton __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
1032
                                THD *thd, void *sv)
1 by brian
clean slate
1033
{
1034
  binlog_trans_log_savepos(thd, (my_off_t*) sv);
1035
  /* Write it to the binary log */
1036
  
1037
  int const error=
1038
    thd->binlog_query(THD::STMT_QUERY_TYPE,
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1039
                      thd->query, thd->query_length, true, false);
1040
  return(error);
1 by brian
clean slate
1041
}
1042
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
1043
static int binlog_savepoint_rollback(handlerton *hton __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
1044
                                     THD *thd, void *sv)
1 by brian
clean slate
1045
{
1046
  /*
1047
    Write ROLLBACK TO SAVEPOINT to the binlog cache if we have updated some
1048
    non-transactional table. Otherwise, truncate the binlog cache starting
1049
    from the SAVEPOINT command.
1050
  */
1051
  if (unlikely(thd->transaction.all.modified_non_trans_table || 
1052
               (thd->options & OPTION_KEEP_LOG)))
1053
  {
1054
    int error=
1055
      thd->binlog_query(THD::STMT_QUERY_TYPE,
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1056
                        thd->query, thd->query_length, true, false);
1057
    return(error);
1 by brian
clean slate
1058
  }
1059
  binlog_trans_log_truncate(thd, *(my_off_t*)sv);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1060
  return(0);
1 by brian
clean slate
1061
}
1062
1063
1064
int check_binlog_magic(IO_CACHE* log, const char** errmsg)
1065
{
1066
  char magic[4];
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1067
  assert(my_b_tell(log) == 0);
1 by brian
clean slate
1068
1069
  if (my_b_read(log, (uchar*) magic, sizeof(magic)))
1070
  {
338 by Monty Taylor
Tagged more strings.
1071
    *errmsg = _("I/O error reading the header from the binary log");
1 by brian
clean slate
1072
    sql_print_error("%s, errno=%d, io cache code=%d", *errmsg, my_errno,
1073
		    log->error);
1074
    return 1;
1075
  }
1076
  if (memcmp(magic, BINLOG_MAGIC, sizeof(magic)))
1077
  {
338 by Monty Taylor
Tagged more strings.
1078
    *errmsg = _("Binlog has bad magic number;  It's not a binary log file "
1079
		"that can be used by this version of Drizzle");
1 by brian
clean slate
1080
    return 1;
1081
  }
1082
  return 0;
1083
}
1084
1085
1086
File open_binlog(IO_CACHE *log, const char *log_file_name, const char **errmsg)
1087
{
1088
  File file;
1089
1090
  if ((file = my_open(log_file_name, O_RDONLY | O_BINARY | O_SHARE, 
1091
                      MYF(MY_WME))) < 0)
1092
  {
338 by Monty Taylor
Tagged more strings.
1093
    sql_print_error(_("Failed to open log (file '%s', errno %d)"),
1 by brian
clean slate
1094
                    log_file_name, my_errno);
338 by Monty Taylor
Tagged more strings.
1095
    *errmsg = _("Could not open log file");
1 by brian
clean slate
1096
    goto err;
1097
  }
1098
  if (init_io_cache(log, file, IO_SIZE*2, READ_CACHE, 0, 0,
1099
                    MYF(MY_WME|MY_DONT_CHECK_FILESIZE)))
1100
  {
338 by Monty Taylor
Tagged more strings.
1101
    sql_print_error(_("Failed to create a cache on log (file '%s')"),
1 by brian
clean slate
1102
                    log_file_name);
338 by Monty Taylor
Tagged more strings.
1103
    *errmsg = _("Could not open log file");
1 by brian
clean slate
1104
    goto err;
1105
  }
1106
  if (check_binlog_magic(log,errmsg))
1107
    goto err;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1108
  return(file);
1 by brian
clean slate
1109
1110
err:
1111
  if (file >= 0)
1112
  {
1113
    my_close(file,MYF(0));
1114
    end_io_cache(log);
1115
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1116
  return(-1);
1 by brian
clean slate
1117
}
1118
1119
1120
/**
1121
  Find a unique filename for 'filename.#'.
1122
1123
  Set '#' to a number as low as possible.
1124
1125
  @return
1126
    nonzero if not possible to get unique filename
1127
*/
1128
1129
static int find_uniq_filename(char *name)
1130
{
1131
  long                  number;
1132
  uint                  i;
1133
  char                  buff[FN_REFLEN];
1134
  struct st_my_dir     *dir_info;
1135
  register struct fileinfo *file_info;
1136
  ulong                 max_found=0;
1137
  size_t		buf_length, length;
1138
  char			*start, *end;
1139
1140
  length= dirname_part(buff, name, &buf_length);
1141
  start=  name + length;
376 by Brian Aker
strend remove
1142
  end= strchr(start, '\0');
1 by brian
clean slate
1143
1144
  *end='.';
1145
  length= (size_t) (end-start+1);
1146
1147
  if (!(dir_info = my_dir(buff,MYF(MY_DONT_SORT))))
1148
  {						// This shouldn't happen
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1149
    stpcpy(end,".1");				// use name+1
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1150
    return(0);
1 by brian
clean slate
1151
  }
1152
  file_info= dir_info->dir_entry;
1153
  for (i=dir_info->number_off_files ; i-- ; file_info++)
1154
  {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1155
    if (memcmp(file_info->name, start, length) == 0 &&
1 by brian
clean slate
1156
	test_if_number(file_info->name+length, &number,0))
1157
    {
1158
      set_if_bigger(max_found,(ulong) number);
1159
    }
1160
  }
1161
  my_dirend(dir_info);
1162
1163
  *end++='.';
1164
  sprintf(end,"%06ld",max_found+1);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1165
  return(0);
1 by brian
clean slate
1166
}
1167
1168
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1169
void DRIZZLE_LOG::init(enum_log_type log_type_arg,
1 by brian
clean slate
1170
                     enum cache_type io_cache_type_arg)
1171
{
1172
  log_type= log_type_arg;
1173
  io_cache_type= io_cache_type_arg;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1174
  return;
1 by brian
clean slate
1175
}
1176
1177
1178
/*
1179
  Open a (new) log file.
1180
1181
  SYNOPSIS
1182
    open()
1183
1184
    log_name            The name of the log to open
1185
    log_type_arg        The type of the log. E.g. LOG_NORMAL
1186
    new_name            The new name for the logfile. This is only needed
1187
                        when the method is used to open the binlog file.
1188
    io_cache_type_arg   The type of the IO_CACHE to use for this log file
1189
1190
  DESCRIPTION
1191
    Open the logfile, init IO_CACHE and write startup messages
1192
    (in case of general and slow query logs).
1193
1194
  RETURN VALUES
1195
    0   ok
1196
    1   error
1197
*/
1198
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1199
bool DRIZZLE_LOG::open(const char *log_name, enum_log_type log_type_arg,
1 by brian
clean slate
1200
                     const char *new_name, enum cache_type io_cache_type_arg)
1201
{
1202
  char buff[FN_REFLEN];
1203
  File file= -1;
1204
  int open_flags= O_CREAT | O_BINARY;
1205
1206
  write_error= 0;
1207
1208
  init(log_type_arg, io_cache_type_arg);
1209
1210
  if (!(name= my_strdup(log_name, MYF(MY_WME))))
1211
  {
1212
    name= (char *)log_name; // for the error message
1213
    goto err;
1214
  }
1215
1216
  if (new_name)
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1217
    stpcpy(log_file_name, new_name);
1 by brian
clean slate
1218
  else if (generate_new_name(log_file_name, name))
1219
    goto err;
1220
1221
  if (io_cache_type == SEQ_READ_APPEND)
1222
    open_flags |= O_RDWR | O_APPEND;
1223
  else
1224
    open_flags |= O_WRONLY | (log_type == LOG_BIN ? 0 : O_APPEND);
1225
1226
  db[0]= 0;
1227
1228
  if ((file= my_open(log_file_name, open_flags,
1229
                     MYF(MY_WME | ME_WAITTANG))) < 0 ||
1230
      init_io_cache(&log_file, file, IO_SIZE, io_cache_type,
1231
                    my_tell(file, MYF(MY_WME)), 0,
1232
                    MYF(MY_WME | MY_NABP |
1233
                        ((log_type == LOG_BIN) ? MY_WAIT_IF_FULL : 0))))
1234
    goto err;
1235
1236
  if (log_type == LOG_NORMAL)
1237
  {
1238
    char *end;
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1239
    int len=snprintf(buff, sizeof(buff), "%s, Version: %s (%s). "
1240
		     "started with:\nTCP Port: %d, Named Pipe: %s\n",
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1241
                     my_progname, server_version, DRIZZLE_COMPILATION_COMMENT,
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1242
                     mysqld_port, ""
1243
                     );
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1244
    end= stpncpy(buff + len, "Time                 Id Command    Argument\n",
1 by brian
clean slate
1245
                 sizeof(buff) - len);
1246
    if (my_b_write(&log_file, (uchar*) buff, (uint) (end-buff)) ||
1247
	flush_io_cache(&log_file))
1248
      goto err;
1249
  }
1250
1251
  log_state= LOG_OPENED;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1252
  return(0);
1 by brian
clean slate
1253
1254
err:
338 by Monty Taylor
Tagged more strings.
1255
  sql_print_error(_("Could not use %s for logging (error %d). "
1256
                    "Turning logging off for the whole duration of the "
1257
                    "Drizzle server process. "
1258
                    "To turn it on again: fix the cause, "
1259
                    "shutdown the Drizzle server and restart it."),
1260
                    name, errno);
1 by brian
clean slate
1261
  if (file >= 0)
1262
    my_close(file, MYF(0));
1263
  end_io_cache(&log_file);
1264
  safeFree(name);
1265
  log_state= LOG_CLOSED;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1266
  return(1);
1 by brian
clean slate
1267
}
1268
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1269
DRIZZLE_LOG::DRIZZLE_LOG()
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1270
  : name(0), write_error(false), inited(false), log_type(LOG_UNKNOWN),
1 by brian
clean slate
1271
    log_state(LOG_CLOSED)
1272
{
1273
  /*
1274
    We don't want to initialize LOCK_Log here as such initialization depends on
1275
    safe_mutex (when using safe_mutex) which depends on MY_INIT(), which is
1276
    called only in main(). Doing initialization here would make it happen
1277
    before main().
1278
  */
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1279
  memset(&log_file, 0, sizeof(log_file));
1 by brian
clean slate
1280
}
1281
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1282
void DRIZZLE_LOG::init_pthread_objects()
1 by brian
clean slate
1283
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1284
  assert(inited == 0);
1 by brian
clean slate
1285
  inited= 1;
1286
  (void) pthread_mutex_init(&LOCK_log, MY_MUTEX_INIT_SLOW);
1287
}
1288
1289
/*
1290
  Close the log file
1291
1292
  SYNOPSIS
1293
    close()
1294
    exiting     Bitmask. For the slow and general logs the only used bit is
1295
                LOG_CLOSE_TO_BE_OPENED. This is used if we intend to call
1296
                open at once after close.
1297
1298
  NOTES
1299
    One can do an open on the object at once after doing a close.
1300
    The internal structures are not freed until cleanup() is called
1301
*/
1302
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1303
void DRIZZLE_LOG::close(uint exiting)
1 by brian
clean slate
1304
{					// One can't set log_type here!
1305
  if (log_state == LOG_OPENED)
1306
  {
1307
    end_io_cache(&log_file);
1308
1309
    if (my_sync(log_file.file, MYF(MY_WME)) && ! write_error)
1310
    {
1311
      write_error= 1;
1312
      sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
1313
    }
1314
1315
    if (my_close(log_file.file, MYF(MY_WME)) && ! write_error)
1316
    {
1317
      write_error= 1;
1318
      sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
1319
    }
1320
  }
1321
1322
  log_state= (exiting & LOG_CLOSE_TO_BE_OPENED) ? LOG_TO_BE_OPENED : LOG_CLOSED;
1323
  safeFree(name);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1324
  return;
1 by brian
clean slate
1325
}
1326
1327
/** This is called only once. */
1328
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1329
void DRIZZLE_LOG::cleanup()
1 by brian
clean slate
1330
{
1331
  if (inited)
1332
  {
1333
    inited= 0;
1334
    (void) pthread_mutex_destroy(&LOCK_log);
1335
    close(0);
1336
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1337
  return;
1 by brian
clean slate
1338
}
1339
1340
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1341
int DRIZZLE_LOG::generate_new_name(char *new_name, const char *log_name)
1 by brian
clean slate
1342
{
1343
  fn_format(new_name, log_name, mysql_data_home, "", 4);
1344
  if (log_type == LOG_BIN)
1345
  {
1346
    if (!fn_ext(log_name)[0])
1347
    {
1348
      if (find_uniq_filename(new_name))
1349
      {
1350
	sql_print_error(ER(ER_NO_UNIQUE_LOGFILE), log_name);
1351
	return 1;
1352
      }
1353
    }
1354
  }
1355
  return 0;
1356
}
1357
1358
1359
/*
1360
  Reopen the log file
1361
1362
  SYNOPSIS
1363
    reopen_file()
1364
1365
  DESCRIPTION
1366
    Reopen the log file. The method is used during FLUSH LOGS
1367
    and locks LOCK_log mutex
1368
*/
1369
1370
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1371
void DRIZZLE_QUERY_LOG::reopen_file()
1 by brian
clean slate
1372
{
1373
  char *save_name;
1374
1375
  if (!is_open())
1376
  {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1377
    return;
1 by brian
clean slate
1378
  }
1379
1380
  pthread_mutex_lock(&LOCK_log);
1381
1382
  save_name= name;
1383
  name= 0;				// Don't free name
1384
  close(LOG_CLOSE_TO_BE_OPENED);
1385
1386
  /*
1387
     Note that at this point, log_state != LOG_CLOSED (important for is_open()).
1388
  */
1389
1390
  open(save_name, log_type, 0, io_cache_type);
1391
  my_free(save_name, MYF(0));
1392
1393
  pthread_mutex_unlock(&LOCK_log);
1394
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1395
  return;
1 by brian
clean slate
1396
}
1397
1398
1399
/*
1400
  Write a command to traditional general log file
1401
1402
  SYNOPSIS
1403
    write()
1404
1405
    event_time        command start timestamp
1406
    user_host         the pointer to the string with user@host info
1407
    user_host_len     length of the user_host string. this is computed once
1408
                      and passed to all general log  event handlers
1409
    thread_id         Id of the thread, issued a query
1410
    command_type      the type of the command being logged
1411
    command_type_len  the length of the string above
1412
    sql_text          the very text of the query being executed
1413
    sql_text_len      the length of sql_text string
1414
1415
  DESCRIPTION
1416
1417
   Log given command to to normal (not rotable) log file
1418
1419
  RETURN
1420
    FASE - OK
1421
    TRUE - error occured
1422
*/
1423
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1424
bool DRIZZLE_QUERY_LOG::write(time_t event_time,
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
1425
                            const char *user_host __attribute__((unused)),
1426
                            uint user_host_len __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
1427
                            int thread_id,
1 by brian
clean slate
1428
                            const char *command_type, uint command_type_len,
1429
                            const char *sql_text, uint sql_text_len)
1430
{
1431
  char buff[32];
1432
  uint length= 0;
1433
  char local_time_buff[MAX_TIME_SIZE];
1434
  struct tm start;
1435
  uint time_buff_len= 0;
1436
1437
  (void) pthread_mutex_lock(&LOCK_log);
1438
1439
  /* Test if someone closed between the is_open test and lock */
1440
  if (is_open())
1441
  {
1442
    /* Note that my_b_write() assumes it knows the length for this */
1443
      if (event_time != last_time)
1444
      {
1445
        last_time= event_time;
1446
1447
        localtime_r(&event_time, &start);
1448
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1449
        time_buff_len= snprintf(local_time_buff, MAX_TIME_SIZE,
1450
                                "%02d%02d%02d %2d:%02d:%02d",
1451
                                start.tm_year % 100, start.tm_mon + 1,
1452
                                start.tm_mday, start.tm_hour,
1453
                                start.tm_min, start.tm_sec);
1 by brian
clean slate
1454
1455
        if (my_b_write(&log_file, (uchar*) local_time_buff, time_buff_len))
1456
          goto err;
1457
      }
1458
      else
1459
        if (my_b_write(&log_file, (uchar*) "\t\t" ,2) < 0)
1460
          goto err;
1461
1462
      /* command_type, thread_id */
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1463
      length= snprintf(buff, 32, "%5ld ", (long) thread_id);
1 by brian
clean slate
1464
1465
    if (my_b_write(&log_file, (uchar*) buff, length))
1466
      goto err;
1467
1468
    if (my_b_write(&log_file, (uchar*) command_type, command_type_len))
1469
      goto err;
1470
1471
    if (my_b_write(&log_file, (uchar*) "\t", 1))
1472
      goto err;
1473
1474
    /* sql_text */
1475
    if (my_b_write(&log_file, (uchar*) sql_text, sql_text_len))
1476
      goto err;
1477
1478
    if (my_b_write(&log_file, (uchar*) "\n", 1) ||
1479
        flush_io_cache(&log_file))
1480
      goto err;
1481
  }
1482
1483
  (void) pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1484
  return false;
1 by brian
clean slate
1485
err:
1486
1487
  if (!write_error)
1488
  {
1489
    write_error= 1;
1490
    sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
1491
  }
1492
  (void) pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1493
  return true;
1 by brian
clean slate
1494
}
1495
1496
1497
/*
1498
  Log a query to the traditional slow log file
1499
1500
  SYNOPSIS
1501
    write()
1502
1503
    thd               THD of the query
1504
    current_time      current timestamp
1505
    query_start_arg   command start timestamp
1506
    user_host         the pointer to the string with user@host info
1507
    user_host_len     length of the user_host string. this is computed once
1508
                      and passed to all general log event handlers
1509
    query_utime       Amount of time the query took to execute (in microseconds)
1510
    lock_utime        Amount of time the query was locked (in microseconds)
1511
    is_command        The flag, which determines, whether the sql_text is a
1512
                      query or an administrator command.
1513
    sql_text          the very text of the query or administrator command
1514
                      processed
1515
    sql_text_len      the length of sql_text string
1516
1517
  DESCRIPTION
1518
1519
   Log a query to the slow log file.
1520
1521
  RETURN
1522
    FALSE - OK
1523
    TRUE - error occured
1524
*/
1525
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1526
bool DRIZZLE_QUERY_LOG::write(THD *thd, time_t current_time,
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
1527
                            time_t query_start_arg __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
1528
                            const char *user_host,
151 by Brian Aker
Ulonglong to uint64_t
1529
                            uint user_host_len, uint64_t query_utime,
1530
                            uint64_t lock_utime, bool is_command,
1 by brian
clean slate
1531
                            const char *sql_text, uint sql_text_len)
1532
{
1533
  bool error= 0;
1534
1535
  (void) pthread_mutex_lock(&LOCK_log);
1536
1537
  if (!is_open())
1538
  {
1539
    (void) pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1540
    return(0);
1 by brian
clean slate
1541
  }
1542
1543
  if (is_open())
1544
  {						// Safety agains reopen
1545
    int tmp_errno= 0;
1546
    char buff[80], *end;
1547
    char query_time_buff[22+7], lock_time_buff[22+7];
1548
    uint buff_len;
1549
    end= buff;
1550
1551
    {
1552
      if (current_time != last_time)
1553
      {
1554
        last_time= current_time;
1555
        struct tm start;
1556
        localtime_r(&current_time, &start);
1557
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1558
        buff_len= snprintf(buff, sizeof buff,
1559
                           "# Time: %02d%02d%02d %2d:%02d:%02d\n",
1560
                           start.tm_year % 100, start.tm_mon + 1,
1561
                           start.tm_mday, start.tm_hour,
1562
                           start.tm_min, start.tm_sec);
1 by brian
clean slate
1563
1564
        /* Note that my_b_write() assumes it knows the length for this */
1565
        if (my_b_write(&log_file, (uchar*) buff, buff_len))
1566
          tmp_errno= errno;
1567
      }
1568
      const uchar uh[]= "# User@Host: ";
1569
      if (my_b_write(&log_file, uh, sizeof(uh) - 1))
1570
        tmp_errno= errno;
1571
      if (my_b_write(&log_file, (uchar*) user_host, user_host_len))
1572
        tmp_errno= errno;
1573
      if (my_b_write(&log_file, (uchar*) "\n", 1))
1574
        tmp_errno= errno;
1575
    }
1576
    /* For slow query log */
151 by Brian Aker
Ulonglong to uint64_t
1577
    sprintf(query_time_buff, "%.6f", uint64_t2double(query_utime)/1000000.0);
1578
    sprintf(lock_time_buff,  "%.6f", uint64_t2double(lock_utime)/1000000.0);
1 by brian
clean slate
1579
    if (my_b_printf(&log_file,
1580
                    "# Query_time: %s  Lock_time: %s"
1581
                    " Rows_sent: %lu  Rows_examined: %lu\n",
1582
                    query_time_buff, lock_time_buff,
1583
                    (ulong) thd->sent_row_count,
1584
                    (ulong) thd->examined_row_count) == (uint) -1)
1585
      tmp_errno= errno;
1586
    if (thd->db && strcmp(thd->db, db))
1587
    {						// Database changed
1588
      if (my_b_printf(&log_file,"use %s;\n",thd->db) == (uint) -1)
1589
        tmp_errno= errno;
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1590
      stpcpy(db,thd->db);
1 by brian
clean slate
1591
    }
1592
    if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt)
1593
    {
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1594
      end=stpcpy(end, ",last_insert_id=");
152 by Brian Aker
longlong replacement
1595
      end=int64_t10_to_str((int64_t)
1 by brian
clean slate
1596
                            thd->first_successful_insert_id_in_prev_stmt_for_binlog,
1597
                            end, -10);
1598
    }
1599
    // Save value if we do an insert.
1600
    if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0)
1601
    {
1602
      {
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1603
        end=stpcpy(end,",insert_id=");
152 by Brian Aker
longlong replacement
1604
        end=int64_t10_to_str((int64_t)
1 by brian
clean slate
1605
                              thd->auto_inc_intervals_in_cur_stmt_for_binlog.minimum(),
1606
                              end, -10);
1607
      }
1608
    }
1609
1610
    /*
1611
      This info used to show up randomly, depending on whether the query
1612
      checked the query start time or not. now we always write current
1613
      timestamp to the slow log
1614
    */
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
1615
    end= stpcpy(end, ",timestamp=");
1 by brian
clean slate
1616
    end= int10_to_str((long) current_time, end, 10);
1617
1618
    if (end != buff)
1619
    {
1620
      *end++=';';
1621
      *end='\n';
1622
      if (my_b_write(&log_file, (uchar*) "SET ", 4) ||
1623
          my_b_write(&log_file, (uchar*) buff + 1, (uint) (end-buff)))
1624
        tmp_errno= errno;
1625
    }
1626
    if (is_command)
1627
    {
1628
      end= strxmov(buff, "# administrator command: ", NullS);
1629
      buff_len= (ulong) (end - buff);
1630
      my_b_write(&log_file, (uchar*) buff, buff_len);
1631
    }
1632
    if (my_b_write(&log_file, (uchar*) sql_text, sql_text_len) ||
1633
        my_b_write(&log_file, (uchar*) ";\n",2) ||
1634
        flush_io_cache(&log_file))
1635
      tmp_errno= errno;
1636
    if (tmp_errno)
1637
    {
1638
      error= 1;
1639
      if (! write_error)
1640
      {
1641
        write_error= 1;
1642
        sql_print_error(ER(ER_ERROR_ON_WRITE), name, error);
1643
      }
1644
    }
1645
  }
1646
  (void) pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1647
  return(error);
1 by brian
clean slate
1648
}
1649
1650
1651
/**
1652
  @todo
1653
  The following should be using fn_format();  We just need to
1654
  first change fn_format() to cut the file name if it's too long.
1655
*/
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1656
const char *DRIZZLE_LOG::generate_name(const char *log_name,
1 by brian
clean slate
1657
                                      const char *suffix,
1658
                                      bool strip_ext, char *buff)
1659
{
1660
  if (!log_name || !log_name[0])
1661
  {
1662
    strmake(buff, pidfile_name, FN_REFLEN - strlen(suffix) - 1);
1663
    return (const char *)
1664
      fn_format(buff, buff, "", suffix, MYF(MY_REPLACE_EXT|MY_REPLACE_DIR));
1665
  }
1666
  // get rid of extension if the log is binary to avoid problems
1667
  if (strip_ext)
1668
  {
1669
    char *p= fn_ext(log_name);
1670
    uint length= (uint) (p - log_name);
287.3.8 by Monty Taylor
Oy. Replaced max and min macros with std::max and std::min so that we get
1671
    strmake(buff, log_name, min(length, (uint)FN_REFLEN));
1 by brian
clean slate
1672
    return (const char*)buff;
1673
  }
1674
  return log_name;
1675
}
1676
1677
1678
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1679
DRIZZLE_BIN_LOG::DRIZZLE_BIN_LOG()
1 by brian
clean slate
1680
  :bytes_written(0), prepared_xids(0), file_id(1), open_count(1),
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1681
   need_start_event(true), m_table_map_version(0),
1 by brian
clean slate
1682
   description_event_for_exec(0), description_event_for_queue(0)
1683
{
1684
  /*
1685
    We don't want to initialize locks here as such initialization depends on
1686
    safe_mutex (when using safe_mutex) which depends on MY_INIT(), which is
1687
    called only in main(). Doing initialization here would make it happen
1688
    before main().
1689
  */
1690
  index_file_name[0] = 0;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1691
  memset(&index_file, 0, sizeof(index_file));
1 by brian
clean slate
1692
}
1693
1694
/* this is called only once */
1695
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1696
void DRIZZLE_BIN_LOG::cleanup()
1 by brian
clean slate
1697
{
1698
  if (inited)
1699
  {
1700
    inited= 0;
1701
    close(LOG_CLOSE_INDEX|LOG_CLOSE_STOP_EVENT);
1702
    delete description_event_for_queue;
1703
    delete description_event_for_exec;
1704
    (void) pthread_mutex_destroy(&LOCK_log);
1705
    (void) pthread_mutex_destroy(&LOCK_index);
1706
    (void) pthread_cond_destroy(&update_cond);
1707
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1708
  return;
1 by brian
clean slate
1709
}
1710
1711
1712
/* Init binlog-specific vars */
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1713
void DRIZZLE_BIN_LOG::init(bool no_auto_events_arg, ulong max_size_arg)
1 by brian
clean slate
1714
{
1715
  no_auto_events= no_auto_events_arg;
1716
  max_size= max_size_arg;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1717
  return;
1 by brian
clean slate
1718
}
1719
1720
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1721
void DRIZZLE_BIN_LOG::init_pthread_objects()
1 by brian
clean slate
1722
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1723
  assert(inited == 0);
1 by brian
clean slate
1724
  inited= 1;
1725
  (void) pthread_mutex_init(&LOCK_log, MY_MUTEX_INIT_SLOW);
1726
  (void) pthread_mutex_init(&LOCK_index, MY_MUTEX_INIT_SLOW);
1727
  (void) pthread_cond_init(&update_cond, 0);
1728
}
1729
1730
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1731
bool DRIZZLE_BIN_LOG::open_index_file(const char *index_file_name_arg,
1 by brian
clean slate
1732
                                const char *log_name)
1733
{
1734
  File index_file_nr= -1;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1735
  assert(!my_b_inited(&index_file));
1 by brian
clean slate
1736
1737
  /*
1738
    First open of this class instance
1739
    Create an index file that will hold all file names uses for logging.
1740
    Add new entries to the end of it.
1741
  */
1742
  myf opt= MY_UNPACK_FILENAME;
1743
  if (!index_file_name_arg)
1744
  {
1745
    index_file_name_arg= log_name;    // Use same basename for index file
1746
    opt= MY_UNPACK_FILENAME | MY_REPLACE_EXT;
1747
  }
1748
  fn_format(index_file_name, index_file_name_arg, mysql_data_home,
1749
            ".index", opt);
1750
  if ((index_file_nr= my_open(index_file_name,
1751
                              O_RDWR | O_CREAT | O_BINARY ,
1752
                              MYF(MY_WME))) < 0 ||
1753
       my_sync(index_file_nr, MYF(MY_WME)) ||
1754
       init_io_cache(&index_file, index_file_nr,
1755
                     IO_SIZE, WRITE_CACHE,
1756
                     my_seek(index_file_nr,0L,MY_SEEK_END,MYF(0)),
1757
			0, MYF(MY_WME | MY_WAIT_IF_FULL)))
1758
  {
1759
    /*
1760
      TODO: all operations creating/deleting the index file or a log, should
1761
      call my_sync_dir() or my_sync_dir_by_file() to be durable.
1762
      TODO: file creation should be done with my_create() not my_open().
1763
    */
1764
    if (index_file_nr >= 0)
1765
      my_close(index_file_nr,MYF(0));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1766
    return true;
1 by brian
clean slate
1767
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1768
  return false;
1 by brian
clean slate
1769
}
1770
1771
1772
/**
1773
  Open a (new) binlog file.
1774
1775
  - Open the log file and the index file. Register the new
1776
  file name in it
1777
  - When calling this when the file is in use, you must have a locks
1778
  on LOCK_log and LOCK_index.
1779
1780
  @retval
1781
    0	ok
1782
  @retval
1783
    1	error
1784
*/
1785
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1786
bool DRIZZLE_BIN_LOG::open(const char *log_name,
1 by brian
clean slate
1787
                         enum_log_type log_type_arg,
1788
                         const char *new_name,
1789
                         enum cache_type io_cache_type_arg,
1790
                         bool no_auto_events_arg,
1791
                         ulong max_size_arg,
1792
                         bool null_created_arg)
1793
{
1794
  File file= -1;
1795
1796
  write_error=0;
1797
1798
  /* open the main log file */
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1799
  if (DRIZZLE_LOG::open(log_name, log_type_arg, new_name, io_cache_type_arg))
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1800
    return(1);                            /* all warnings issued */
1 by brian
clean slate
1801
1802
  init(no_auto_events_arg, max_size_arg);
1803
1804
  open_count++;
1805
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1806
  assert(log_type == LOG_BIN);
1 by brian
clean slate
1807
1808
  {
1809
    bool write_file_name_to_index_file=0;
1810
1811
    if (!my_b_filelength(&log_file))
1812
    {
1813
      /*
1814
	The binary log file was empty (probably newly created)
1815
	This is the normal case and happens when the user doesn't specify
1816
	an extension for the binary log files.
1817
	In this case we write a standard header to it.
1818
      */
1819
      if (my_b_safe_write(&log_file, (uchar*) BINLOG_MAGIC,
1820
			  BIN_LOG_HEADER_SIZE))
1821
        goto err;
1822
      bytes_written+= BIN_LOG_HEADER_SIZE;
1823
      write_file_name_to_index_file= 1;
1824
    }
1825
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1826
    assert(my_b_inited(&index_file) != 0);
1 by brian
clean slate
1827
    reinit_io_cache(&index_file, WRITE_CACHE,
1828
                    my_b_filelength(&index_file), 0, 0);
1829
    if (need_start_event && !no_auto_events)
1830
    {
1831
      /*
1832
        In 4.x we set need_start_event=0 here, but in 5.0 we want a Start event
1833
        even if this is not the very first binlog.
1834
      */
1835
      Format_description_log_event s(BINLOG_VERSION);
1836
      /*
1837
        don't set LOG_EVENT_BINLOG_IN_USE_F for SEQ_READ_APPEND io_cache
1838
        as we won't be able to reset it later
1839
      */
1840
      if (io_cache_type == WRITE_CACHE)
1841
        s.flags|= LOG_EVENT_BINLOG_IN_USE_F;
1842
      if (!s.is_valid())
1843
        goto err;
1844
      s.dont_set_created= null_created_arg;
1845
      if (s.write(&log_file))
1846
        goto err;
1847
      bytes_written+= s.data_written;
1848
    }
1849
    if (description_event_for_queue &&
1850
        description_event_for_queue->binlog_version>=4)
1851
    {
1852
      /*
1853
        This is a relay log written to by the I/O slave thread.
1854
        Write the event so that others can later know the format of this relay
1855
        log.
1856
        Note that this event is very close to the original event from the
1857
        master (it has binlog version of the master, event types of the
1858
        master), so this is suitable to parse the next relay log's event. It
1859
        has been produced by
1860
        Format_description_log_event::Format_description_log_event(char* buf,).
1861
        Why don't we want to write the description_event_for_queue if this
1862
        event is for format<4 (3.23 or 4.x): this is because in that case, the
1863
        description_event_for_queue describes the data received from the
1864
        master, but not the data written to the relay log (*conversion*),
1865
        which is in format 4 (slave's).
1866
      */
1867
      /*
1868
        Set 'created' to 0, so that in next relay logs this event does not
1869
        trigger cleaning actions on the slave in
1870
        Format_description_log_event::apply_event_impl().
1871
      */
1872
      description_event_for_queue->created= 0;
1873
      /* Don't set log_pos in event header */
1874
      description_event_for_queue->artificial_event=1;
1875
1876
      if (description_event_for_queue->write(&log_file))
1877
        goto err;
1878
      bytes_written+= description_event_for_queue->data_written;
1879
    }
1880
    if (flush_io_cache(&log_file) ||
1881
        my_sync(log_file.file, MYF(MY_WME)))
1882
      goto err;
1883
1884
    if (write_file_name_to_index_file)
1885
    {
1886
      /*
1887
        As this is a new log file, we write the file name to the index
1888
        file. As every time we write to the index file, we sync it.
1889
      */
1890
      if (my_b_write(&index_file, (uchar*) log_file_name,
1891
		     strlen(log_file_name)) ||
1892
	  my_b_write(&index_file, (uchar*) "\n", 1) ||
1893
	  flush_io_cache(&index_file) ||
1894
          my_sync(index_file.file, MYF(MY_WME)))
1895
	goto err;
1896
    }
1897
  }
1898
  log_state= LOG_OPENED;
1899
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1900
  return(0);
1 by brian
clean slate
1901
1902
err:
338 by Monty Taylor
Tagged more strings.
1903
  sql_print_error(_("Could not use %s for logging (error %d). "
1904
                    "Turning logging off for the whole duration of the "
1905
                    "Drizzle server process. "
1906
                    "To turn it on again: fix the cause, "
342 by Monty Taylor
Fixed syntax error.
1907
                    "shutdown the Drizzle server and restart it."),
338 by Monty Taylor
Tagged more strings.
1908
                    name, errno);
1 by brian
clean slate
1909
  if (file >= 0)
1910
    my_close(file,MYF(0));
1911
  end_io_cache(&log_file);
1912
  end_io_cache(&index_file);
1913
  safeFree(name);
1914
  log_state= LOG_CLOSED;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1915
  return(1);
1 by brian
clean slate
1916
}
1917
1918
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1919
int DRIZZLE_BIN_LOG::get_current_log(LOG_INFO* linfo)
1 by brian
clean slate
1920
{
1921
  pthread_mutex_lock(&LOCK_log);
1922
  int ret = raw_get_current_log(linfo);
1923
  pthread_mutex_unlock(&LOCK_log);
1924
  return ret;
1925
}
1926
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1927
int DRIZZLE_BIN_LOG::raw_get_current_log(LOG_INFO* linfo)
1 by brian
clean slate
1928
{
1929
  strmake(linfo->log_file_name, log_file_name, sizeof(linfo->log_file_name)-1);
1930
  linfo->pos = my_b_tell(&log_file);
1931
  return 0;
1932
}
1933
1934
/**
1935
  Move all data up in a file in an filename index file.
1936
1937
    We do the copy outside of the IO_CACHE as the cache buffers would just
1938
    make things slower and more complicated.
1939
    In most cases the copy loop should only do one read.
1940
1941
  @param index_file			File to move
1942
  @param offset			Move everything from here to beginning
1943
1944
  @note
1945
    File will be truncated to be 'offset' shorter or filled up with newlines
1946
1947
  @retval
1948
    0	ok
1949
*/
1950
1951
#ifdef HAVE_REPLICATION
1952
1953
static bool copy_up_file_and_fill(IO_CACHE *index_file, my_off_t offset)
1954
{
1955
  int bytes_read;
1956
  my_off_t init_offset= offset;
1957
  File file= index_file->file;
1958
  uchar io_buf[IO_SIZE*2];
1959
1960
  for (;; offset+= bytes_read)
1961
  {
1962
    (void) my_seek(file, offset, MY_SEEK_SET, MYF(0));
1963
    if ((bytes_read= (int) my_read(file, io_buf, sizeof(io_buf), MYF(MY_WME)))
1964
	< 0)
1965
      goto err;
1966
    if (!bytes_read)
1967
      break;					// end of file
1968
    (void) my_seek(file, offset-init_offset, MY_SEEK_SET, MYF(0));
1969
    if (my_write(file, io_buf, bytes_read, MYF(MY_WME | MY_NABP)))
1970
      goto err;
1971
  }
1972
  /* The following will either truncate the file or fill the end with \n' */
30 by Brian Aker
Large file and ftruncate() support
1973
  if (ftruncate(file, offset - init_offset) || my_sync(file, MYF(MY_WME)))
1 by brian
clean slate
1974
    goto err;
1975
1976
  /* Reset data in old index cache */
1977
  reinit_io_cache(index_file, READ_CACHE, (my_off_t) 0, 0, 1);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1978
  return(0);
1 by brian
clean slate
1979
1980
err:
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1981
  return(1);
1 by brian
clean slate
1982
}
1983
1984
#endif /* HAVE_REPLICATION */
1985
1986
/**
1987
  Find the position in the log-index-file for the given log name.
1988
1989
  @param linfo		Store here the found log file name and position to
1990
                       the NEXT log file name in the index file.
1991
  @param log_name	Filename to find in the index file.
1992
                       Is a null pointer if we want to read the first entry
1993
  @param need_lock	Set this to 1 if the parent doesn't already have a
1994
                       lock on LOCK_index
1995
1996
  @note
1997
    On systems without the truncate function the file will end with one or
1998
    more empty lines.  These will be ignored when reading the file.
1999
2000
  @retval
2001
    0			ok
2002
  @retval
2003
    LOG_INFO_EOF	        End of log-index-file found
2004
  @retval
2005
    LOG_INFO_IO		Got IO error while reading file
2006
*/
2007
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2008
int DRIZZLE_BIN_LOG::find_log_pos(LOG_INFO *linfo, const char *log_name,
1 by brian
clean slate
2009
			    bool need_lock)
2010
{
2011
  int error= 0;
2012
  char *fname= linfo->log_file_name;
2013
  uint log_name_len= log_name ? (uint) strlen(log_name) : 0;
2014
2015
  /*
2016
    Mutex needed because we need to make sure the file pointer does not
2017
    move from under our feet
2018
  */
2019
  if (need_lock)
2020
    pthread_mutex_lock(&LOCK_index);
2021
  safe_mutex_assert_owner(&LOCK_index);
2022
2023
  /* As the file is flushed, we can't get an error here */
2024
  (void) reinit_io_cache(&index_file, READ_CACHE, (my_off_t) 0, 0, 0);
2025
2026
  for (;;)
2027
  {
2028
    uint length;
2029
    my_off_t offset= my_b_tell(&index_file);
2030
    /* If we get 0 or 1 characters, this is the end of the file */
2031
2032
    if ((length= my_b_gets(&index_file, fname, FN_REFLEN)) <= 1)
2033
    {
2034
      /* Did not find the given entry; Return not found or error */
2035
      error= !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO;
2036
      break;
2037
    }
2038
2039
    // if the log entry matches, null string matching anything
2040
    if (!log_name ||
2041
	(log_name_len == length-1 && fname[log_name_len] == '\n' &&
2042
	 !memcmp(fname, log_name, log_name_len)))
2043
    {
2044
      fname[length-1]=0;			// remove last \n
2045
      linfo->index_file_start_offset= offset;
2046
      linfo->index_file_offset = my_b_tell(&index_file);
2047
      break;
2048
    }
2049
  }
2050
2051
  if (need_lock)
2052
    pthread_mutex_unlock(&LOCK_index);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2053
  return(error);
1 by brian
clean slate
2054
}
2055
2056
2057
/**
2058
  Find the position in the log-index-file for the given log name.
2059
2060
  @param
2061
    linfo		Store here the next log file name and position to
2062
			the file name after that.
2063
  @param
2064
    need_lock		Set this to 1 if the parent doesn't already have a
2065
			lock on LOCK_index
2066
2067
  @note
2068
    - Before calling this function, one has to call find_log_pos()
2069
    to set up 'linfo'
2070
    - Mutex needed because we need to make sure the file pointer does not move
2071
    from under our feet
2072
2073
  @retval
2074
    0			ok
2075
  @retval
2076
    LOG_INFO_EOF	        End of log-index-file found
2077
  @retval
2078
    LOG_INFO_IO		Got IO error while reading file
2079
*/
2080
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2081
int DRIZZLE_BIN_LOG::find_next_log(LOG_INFO* linfo, bool need_lock)
1 by brian
clean slate
2082
{
2083
  int error= 0;
2084
  uint length;
2085
  char *fname= linfo->log_file_name;
2086
2087
  if (need_lock)
2088
    pthread_mutex_lock(&LOCK_index);
2089
  safe_mutex_assert_owner(&LOCK_index);
2090
2091
  /* As the file is flushed, we can't get an error here */
2092
  (void) reinit_io_cache(&index_file, READ_CACHE, linfo->index_file_offset, 0,
2093
			 0);
2094
2095
  linfo->index_file_start_offset= linfo->index_file_offset;
2096
  if ((length=my_b_gets(&index_file, fname, FN_REFLEN)) <= 1)
2097
  {
2098
    error = !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO;
2099
    goto err;
2100
  }
2101
  fname[length-1]=0;				// kill \n
2102
  linfo->index_file_offset = my_b_tell(&index_file);
2103
2104
err:
2105
  if (need_lock)
2106
    pthread_mutex_unlock(&LOCK_index);
2107
  return error;
2108
}
2109
2110
2111
/**
2112
  Delete all logs refered to in the index file.
2113
  Start writing to a new log file.
2114
2115
  The new index file will only contain this file.
2116
2117
  @param thd		Thread
2118
2119
  @note
2120
    If not called from slave thread, write start event to new log
2121
2122
  @retval
2123
    0	ok
2124
  @retval
2125
    1   error
2126
*/
2127
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2128
bool DRIZZLE_BIN_LOG::reset_logs(THD* thd)
1 by brian
clean slate
2129
{
2130
  LOG_INFO linfo;
2131
  bool error=0;
2132
  const char* save_name;
2133
2134
  ha_reset_logs(thd);
2135
  /*
2136
    We need to get both locks to be sure that no one is trying to
2137
    write to the index log file.
2138
  */
2139
  pthread_mutex_lock(&LOCK_log);
2140
  pthread_mutex_lock(&LOCK_index);
2141
2142
  /*
2143
    The following mutex is needed to ensure that no threads call
2144
    'delete thd' as we would then risk missing a 'rollback' from this
2145
    thread. If the transaction involved MyISAM tables, it should go
2146
    into binlog even on rollback.
2147
  */
2148
  VOID(pthread_mutex_lock(&LOCK_thread_count));
2149
2150
  /* Save variables so that we can reopen the log */
2151
  save_name=name;
2152
  name=0;					// Protect against free
2153
  close(LOG_CLOSE_TO_BE_OPENED);
2154
2155
  /* First delete all old log files */
2156
2157
  if (find_log_pos(&linfo, NullS, 0))
2158
  {
2159
    error=1;
2160
    goto err;
2161
  }
2162
2163
  for (;;)
2164
  {
2165
    if ((error= my_delete_allow_opened(linfo.log_file_name, MYF(0))) != 0)
2166
    {
2167
      if (my_errno == ENOENT) 
2168
      {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2169
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2170
                            ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2171
                            linfo.log_file_name);
338 by Monty Taylor
Tagged more strings.
2172
        sql_print_information(_("Failed to delete file '%s'"),
1 by brian
clean slate
2173
                              linfo.log_file_name);
2174
        my_errno= 0;
2175
        error= 0;
2176
      }
2177
      else
2178
      {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2179
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2180
                            ER_BINLOG_PURGE_FATAL_ERR,
338 by Monty Taylor
Tagged more strings.
2181
                            _("a problem with deleting %s; "
1 by brian
clean slate
2182
                            "consider examining correspondence "
2183
                            "of your binlog index file "
338 by Monty Taylor
Tagged more strings.
2184
                            "to the actual binlog files"),
1 by brian
clean slate
2185
                            linfo.log_file_name);
2186
        error= 1;
2187
        goto err;
2188
      }
2189
    }
2190
    if (find_next_log(&linfo, 0))
2191
      break;
2192
  }
2193
2194
  /* Start logging with a new file */
2195
  close(LOG_CLOSE_INDEX);
2196
  if ((error= my_delete_allow_opened(index_file_name, MYF(0))))	// Reset (open will update)
2197
  {
2198
    if (my_errno == ENOENT) 
2199
    {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2200
      push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2201
                          ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2202
                          index_file_name);
338 by Monty Taylor
Tagged more strings.
2203
      sql_print_information(_("Failed to delete file '%s'"),
1 by brian
clean slate
2204
                            index_file_name);
2205
      my_errno= 0;
2206
      error= 0;
2207
    }
2208
    else
2209
    {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2210
      push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2211
                          ER_BINLOG_PURGE_FATAL_ERR,
2212
                          "a problem with deleting %s; "
2213
                          "consider examining correspondence "
2214
                          "of your binlog index file "
2215
                          "to the actual binlog files",
2216
                          index_file_name);
2217
      error= 1;
2218
      goto err;
2219
    }
2220
  }
2221
  if (!thd->slave_thread)
2222
    need_start_event=1;
2223
  if (!open_index_file(index_file_name, 0))
2224
    open(save_name, log_type, 0, io_cache_type, no_auto_events, max_size, 0);
2225
  my_free((uchar*) save_name, MYF(0));
2226
2227
err:
2228
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
2229
  pthread_mutex_unlock(&LOCK_index);
2230
  pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2231
  return(error);
1 by brian
clean slate
2232
}
2233
2234
2235
/**
2236
  Delete relay log files prior to rli->group_relay_log_name
2237
  (i.e. all logs which are not involved in a non-finished group
2238
  (transaction)), remove them from the index file and start on next
2239
  relay log.
2240
2241
  IMPLEMENTATION
2242
  - Protects index file with LOCK_index
2243
  - Delete relevant relay log files
2244
  - Copy all file names after these ones to the front of the index file
2245
  - If the OS has truncate, truncate the file, else fill it with \n'
2246
  - Read the next file name from the index file and store in rli->linfo
2247
2248
  @param rli	       Relay log information
2249
  @param included     If false, all relay logs that are strictly before
2250
                      rli->group_relay_log_name are deleted ; if true, the
2251
                      latter is deleted too (i.e. all relay logs
2252
                      read by the SQL slave thread are deleted).
2253
2254
  @note
2255
    - This is only called from the slave-execute thread when it has read
2256
    all commands from a relay log and want to switch to a new relay log.
2257
    - When this happens, we can be in an active transaction as
2258
    a transaction can span over two relay logs
2259
    (although it is always written as a single block to the master's binary
2260
    log, hence cannot span over two master's binary logs).
2261
2262
  @retval
2263
    0			ok
2264
  @retval
2265
    LOG_INFO_EOF	        End of log-index-file found
2266
  @retval
2267
    LOG_INFO_SEEK	Could not allocate IO cache
2268
  @retval
2269
    LOG_INFO_IO		Got IO error while reading file
2270
*/
2271
2272
#ifdef HAVE_REPLICATION
2273
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2274
int DRIZZLE_BIN_LOG::purge_first_log(Relay_log_info* rli, bool included)
1 by brian
clean slate
2275
{
2276
  int error;
2277
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2278
  assert(is_open());
2279
  assert(rli->slave_running == 1);
2280
  assert(!strcmp(rli->linfo.log_file_name,rli->event_relay_log_name));
1 by brian
clean slate
2281
2282
  pthread_mutex_lock(&LOCK_index);
2283
  pthread_mutex_lock(&rli->log_space_lock);
2284
  rli->relay_log.purge_logs(rli->group_relay_log_name, included,
2285
                            0, 0, &rli->log_space_total);
2286
  // Tell the I/O thread to take the relay_log_space_limit into account
2287
  rli->ignore_log_space_limit= 0;
2288
  pthread_mutex_unlock(&rli->log_space_lock);
2289
2290
  /*
2291
    Ok to broadcast after the critical region as there is no risk of
2292
    the mutex being destroyed by this thread later - this helps save
2293
    context switches
2294
  */
2295
  pthread_cond_broadcast(&rli->log_space_cond);
2296
  
2297
  /*
2298
    Read the next log file name from the index file and pass it back to
2299
    the caller
2300
    If included is true, we want the first relay log;
2301
    otherwise we want the one after event_relay_log_name.
2302
  */
2303
  if ((included && (error=find_log_pos(&rli->linfo, NullS, 0))) ||
2304
      (!included &&
2305
       ((error=find_log_pos(&rli->linfo, rli->event_relay_log_name, 0)) ||
2306
        (error=find_next_log(&rli->linfo, 0)))))
2307
  {
2308
    char buff[22];
338 by Monty Taylor
Tagged more strings.
2309
    sql_print_error(_("next log error: %d  offset: %s  log: %s included: %d"),
1 by brian
clean slate
2310
                    error,
2311
                    llstr(rli->linfo.index_file_offset,buff),
2312
                    rli->group_relay_log_name,
2313
                    included);
2314
    goto err;
2315
  }
2316
2317
  /*
2318
    Reset rli's coordinates to the current log.
2319
  */
2320
  rli->event_relay_log_pos= BIN_LOG_HEADER_SIZE;
2321
  strmake(rli->event_relay_log_name,rli->linfo.log_file_name,
2322
	  sizeof(rli->event_relay_log_name)-1);
2323
2324
  /*
2325
    If we removed the rli->group_relay_log_name file,
2326
    we must update the rli->group* coordinates, otherwise do not touch it as the
2327
    group's execution is not finished (e.g. COMMIT not executed)
2328
  */
2329
  if (included)
2330
  {
2331
    rli->group_relay_log_pos = BIN_LOG_HEADER_SIZE;
2332
    strmake(rli->group_relay_log_name,rli->linfo.log_file_name,
2333
            sizeof(rli->group_relay_log_name)-1);
2334
    rli->notify_group_relay_log_name_update();
2335
  }
2336
2337
  /* Store where we are in the new file for the execution thread */
2338
  flush_relay_log_info(rli);
2339
2340
err:
2341
  pthread_mutex_unlock(&LOCK_index);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2342
  return(error);
1 by brian
clean slate
2343
}
2344
2345
/**
2346
  Update log index_file.
2347
*/
2348
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2349
int DRIZZLE_BIN_LOG::update_log_index(LOG_INFO* log_info, bool need_update_threads)
1 by brian
clean slate
2350
{
2351
  if (copy_up_file_and_fill(&index_file, log_info->index_file_start_offset))
2352
    return LOG_INFO_IO;
2353
2354
  // now update offsets in index file for running threads
2355
  if (need_update_threads)
2356
    adjust_linfo_offsets(log_info->index_file_start_offset);
2357
  return 0;
2358
}
2359
2360
/**
2361
  Remove all logs before the given log from disk and from the index file.
2362
2363
  @param to_log	      Delete all log file name before this file.
2364
  @param included            If true, to_log is deleted too.
2365
  @param need_mutex
2366
  @param need_update_threads If we want to update the log coordinates of
2367
                             all threads. False for relay logs, true otherwise.
2368
  @param freed_log_space     If not null, decrement this variable of
2369
                             the amount of log space freed
2370
2371
  @note
2372
    If any of the logs before the deleted one is in use,
2373
    only purge logs up to this one.
2374
2375
  @retval
2376
    0			ok
2377
  @retval
2378
    LOG_INFO_EOF		to_log not found
2379
    LOG_INFO_EMFILE             too many files opened
2380
    LOG_INFO_FATAL              if any other than ENOENT error from
15 by brian
Fix for stat, NETWARE removal
2381
                                stat() or my_delete()
1 by brian
clean slate
2382
*/
2383
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2384
int DRIZZLE_BIN_LOG::purge_logs(const char *to_log, 
1 by brian
clean slate
2385
                          bool included,
2386
                          bool need_mutex, 
2387
                          bool need_update_threads, 
151 by Brian Aker
Ulonglong to uint64_t
2388
                          uint64_t *decrease_log_space)
1 by brian
clean slate
2389
{
2390
  int error;
2391
  int ret = 0;
2392
  bool exit_loop= 0;
2393
  LOG_INFO log_info;
2394
2395
  if (need_mutex)
2396
    pthread_mutex_lock(&LOCK_index);
2397
  if ((error=find_log_pos(&log_info, to_log, 0 /*no mutex*/)))
2398
    goto err;
2399
2400
  /*
2401
    File name exists in index file; delete until we find this file
2402
    or a file that is used.
2403
  */
2404
  if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/)))
2405
    goto err;
2406
  while ((strcmp(to_log,log_info.log_file_name) || (exit_loop=included)) &&
2407
         !log_in_use(log_info.log_file_name))
2408
  {
15 by brian
Fix for stat, NETWARE removal
2409
    struct stat s;
2410
    if (stat(log_info.log_file_name, &s))
1 by brian
clean slate
2411
    {
15 by brian
Fix for stat, NETWARE removal
2412
      if (errno == ENOENT) 
1 by brian
clean slate
2413
      {
2414
        /*
2415
          It's not fatal if we can't stat a log file that does not exist;
2416
          If we could not stat, we won't delete.
2417
        */     
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2418
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2419
                            ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2420
                            log_info.log_file_name);
338 by Monty Taylor
Tagged more strings.
2421
        sql_print_information(_("Failed to execute stat() on file '%s'"),
1 by brian
clean slate
2422
			      log_info.log_file_name);
2423
        my_errno= 0;
2424
      }
2425
      else
2426
      {
2427
        /*
2428
          Other than ENOENT are fatal
2429
        */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2430
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2431
                            ER_BINLOG_PURGE_FATAL_ERR,
338 by Monty Taylor
Tagged more strings.
2432
                            _("a problem with getting info on being purged %s; "
1 by brian
clean slate
2433
                            "consider examining correspondence "
2434
                            "of your binlog index file "
338 by Monty Taylor
Tagged more strings.
2435
                            "to the actual binlog files"),
1 by brian
clean slate
2436
                            log_info.log_file_name);
2437
        error= LOG_INFO_FATAL;
2438
        goto err;
2439
      }
2440
    }
2441
    else
2442
    {
2443
      if (!my_delete(log_info.log_file_name, MYF(0)))
2444
      {
2445
        if (decrease_log_space)
2446
          *decrease_log_space-= s.st_size;
2447
      }
2448
      else
2449
      {
2450
        if (my_errno == ENOENT) 
2451
        {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2452
          push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2453
                              ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2454
                              log_info.log_file_name);
338 by Monty Taylor
Tagged more strings.
2455
          sql_print_information(_("Failed to delete file '%s'"),
1 by brian
clean slate
2456
                                log_info.log_file_name);
2457
          my_errno= 0;
2458
        }
2459
        else
2460
        {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2461
          push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2462
                              ER_BINLOG_PURGE_FATAL_ERR,
338 by Monty Taylor
Tagged more strings.
2463
                              _("a problem with deleting %s; "
1 by brian
clean slate
2464
                              "consider examining correspondence "
2465
                              "of your binlog index file "
338 by Monty Taylor
Tagged more strings.
2466
                              "to the actual binlog files"),
1 by brian
clean slate
2467
                              log_info.log_file_name);
2468
          if (my_errno == EMFILE)
2469
          {
2470
            error= LOG_INFO_EMFILE;
2471
          }
2472
          error= LOG_INFO_FATAL;
2473
          goto err;
2474
        }
2475
      }
2476
    }
2477
2478
    ha_binlog_index_purge_file(current_thd, log_info.log_file_name);
2479
2480
    if (find_next_log(&log_info, 0) || exit_loop)
2481
      break;
2482
  }
2483
  
2484
  /*
2485
    If we get killed -9 here, the sysadmin would have to edit
2486
    the log index file after restart - otherwise, this should be safe
2487
  */
2488
  error= update_log_index(&log_info, need_update_threads);
2489
  if (error == 0) {
2490
    error = ret;
2491
  }
2492
2493
err:
2494
  if (need_mutex)
2495
    pthread_mutex_unlock(&LOCK_index);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2496
  return(error);
1 by brian
clean slate
2497
}
2498
2499
/**
2500
  Remove all logs before the given file date from disk and from the
2501
  index file.
2502
2503
  @param thd		Thread pointer
2504
  @param before_date	Delete all log files before given date.
2505
2506
  @note
2507
    If any of the logs before the deleted one is in use,
2508
    only purge logs up to this one.
2509
2510
  @retval
2511
    0				ok
2512
  @retval
2513
    LOG_INFO_PURGE_NO_ROTATE	Binary file that can't be rotated
2514
    LOG_INFO_FATAL              if any other than ENOENT error from
15 by brian
Fix for stat, NETWARE removal
2515
                                stat() or my_delete()
1 by brian
clean slate
2516
*/
2517
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2518
int DRIZZLE_BIN_LOG::purge_logs_before_date(time_t purge_time)
1 by brian
clean slate
2519
{
2520
  int error;
2521
  LOG_INFO log_info;
15 by brian
Fix for stat, NETWARE removal
2522
  struct stat stat_area;
1 by brian
clean slate
2523
2524
  pthread_mutex_lock(&LOCK_index);
2525
2526
  /*
2527
    Delete until we find curren file
2528
    or a file that is used or a file
2529
    that is older than purge_time.
2530
  */
2531
  if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/)))
2532
    goto err;
2533
2534
  while (strcmp(log_file_name, log_info.log_file_name) &&
2535
	 !log_in_use(log_info.log_file_name))
2536
  {
15 by brian
Fix for stat, NETWARE removal
2537
    if (stat(log_info.log_file_name, &stat_area))
1 by brian
clean slate
2538
    {
15 by brian
Fix for stat, NETWARE removal
2539
      if (errno == ENOENT) 
1 by brian
clean slate
2540
      {
2541
        /*
2542
          It's not fatal if we can't stat a log file that does not exist.
2543
        */     
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2544
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2545
                            ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2546
                            log_info.log_file_name);
338 by Monty Taylor
Tagged more strings.
2547
	sql_print_information(_("Failed to execute stat() on file '%s'"),
1 by brian
clean slate
2548
			      log_info.log_file_name);
2549
        my_errno= 0;
2550
      }
2551
      else
2552
      {
2553
        /*
2554
          Other than ENOENT are fatal
2555
        */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2556
        push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2557
                            ER_BINLOG_PURGE_FATAL_ERR,
338 by Monty Taylor
Tagged more strings.
2558
                            _("a problem with getting info on being purged %s; "
1 by brian
clean slate
2559
                            "consider examining correspondence "
2560
                            "of your binlog index file "
338 by Monty Taylor
Tagged more strings.
2561
                            "to the actual binlog files"),
1 by brian
clean slate
2562
                            log_info.log_file_name);
2563
        error= LOG_INFO_FATAL;
2564
        goto err;
2565
      }
2566
    }
2567
    else
2568
    {
2569
      if (stat_area.st_mtime >= purge_time)
2570
        break;
2571
      if (my_delete(log_info.log_file_name, MYF(0)))
2572
      {
2573
        if (my_errno == ENOENT) 
2574
        {
2575
          /* It's not fatal even if we can't delete a log file */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2576
          push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
2577
                              ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE),
2578
                              log_info.log_file_name);
338 by Monty Taylor
Tagged more strings.
2579
          sql_print_information(_("Failed to delete file '%s'"),
1 by brian
clean slate
2580
                                log_info.log_file_name);
2581
          my_errno= 0;
2582
        }
2583
        else
2584
        {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2585
          push_warning_printf(current_thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
2586
                              ER_BINLOG_PURGE_FATAL_ERR,
338 by Monty Taylor
Tagged more strings.
2587
                              _("a problem with deleting %s; "
1 by brian
clean slate
2588
                              "consider examining correspondence "
2589
                              "of your binlog index file "
338 by Monty Taylor
Tagged more strings.
2590
                              "to the actual binlog files"),
1 by brian
clean slate
2591
                              log_info.log_file_name);
2592
          error= LOG_INFO_FATAL;
2593
          goto err;
2594
        }
2595
      }
2596
      ha_binlog_index_purge_file(current_thd, log_info.log_file_name);
2597
    }
2598
    if (find_next_log(&log_info, 0))
2599
      break;
2600
  }
2601
2602
  /*
2603
    If we get killed -9 here, the sysadmin would have to edit
2604
    the log index file after restart - otherwise, this should be safe
2605
  */
2606
  error= update_log_index(&log_info, 1);
2607
2608
err:
2609
  pthread_mutex_unlock(&LOCK_index);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2610
  return(error);
1 by brian
clean slate
2611
}
2612
#endif /* HAVE_REPLICATION */
2613
2614
2615
/**
2616
  Create a new log file name.
2617
2618
  @param buf		buf of at least FN_REFLEN where new name is stored
2619
2620
  @note
2621
    If file name will be longer then FN_REFLEN it will be truncated
2622
*/
2623
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2624
void DRIZZLE_BIN_LOG::make_log_name(char* buf, const char* log_ident)
1 by brian
clean slate
2625
{
2626
  uint dir_len = dirname_length(log_file_name); 
2627
  if (dir_len >= FN_REFLEN)
2628
    dir_len=FN_REFLEN-1;
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
2629
  stpncpy(buf, log_file_name, dir_len);
1 by brian
clean slate
2630
  strmake(buf+dir_len, log_ident, FN_REFLEN - dir_len -1);
2631
}
2632
2633
2634
/**
2635
  Check if we are writing/reading to the given log file.
2636
*/
2637
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2638
bool DRIZZLE_BIN_LOG::is_active(const char *log_file_name_arg)
1 by brian
clean slate
2639
{
2640
  return !strcmp(log_file_name, log_file_name_arg);
2641
}
2642
2643
2644
/*
2645
  Wrappers around new_file_impl to avoid using argument
2646
  to control locking. The argument 1) less readable 2) breaks
2647
  incapsulation 3) allows external access to the class without
2648
  a lock (which is not possible with private new_file_without_locking
2649
  method).
2650
*/
2651
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2652
void DRIZZLE_BIN_LOG::new_file()
1 by brian
clean slate
2653
{
2654
  new_file_impl(1);
2655
}
2656
2657
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2658
void DRIZZLE_BIN_LOG::new_file_without_locking()
1 by brian
clean slate
2659
{
2660
  new_file_impl(0);
2661
}
2662
2663
2664
/**
2665
  Start writing to a new log file or reopen the old file.
2666
2667
  @param need_lock		Set to 1 if caller has not locked LOCK_log
2668
2669
  @note
2670
    The new file name is stored last in the index file
2671
*/
2672
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2673
void DRIZZLE_BIN_LOG::new_file_impl(bool need_lock)
1 by brian
clean slate
2674
{
2675
  char new_name[FN_REFLEN], *new_name_ptr, *old_name;
2676
2677
  if (!is_open())
2678
  {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2679
    return;
1 by brian
clean slate
2680
  }
2681
2682
  if (need_lock)
2683
    pthread_mutex_lock(&LOCK_log);
2684
  pthread_mutex_lock(&LOCK_index);
2685
2686
  safe_mutex_assert_owner(&LOCK_log);
2687
  safe_mutex_assert_owner(&LOCK_index);
2688
2689
  /*
2690
    if binlog is used as tc log, be sure all xids are "unlogged",
2691
    so that on recover we only need to scan one - latest - binlog file
2692
    for prepared xids. As this is expected to be a rare event,
2693
    simple wait strategy is enough. We're locking LOCK_log to be sure no
2694
    new Xid_log_event's are added to the log (and prepared_xids is not
2695
    increased), and waiting on COND_prep_xids for late threads to
2696
    catch up.
2697
  */
2698
  if (prepared_xids)
2699
  {
2700
    tc_log_page_waits++;
2701
    pthread_mutex_lock(&LOCK_prep_xids);
2702
    while (prepared_xids) {
2703
      pthread_cond_wait(&COND_prep_xids, &LOCK_prep_xids);
2704
    }
2705
    pthread_mutex_unlock(&LOCK_prep_xids);
2706
  }
2707
2708
  /* Reuse old name if not binlog and not update log */
2709
  new_name_ptr= name;
2710
2711
  /*
2712
    If user hasn't specified an extension, generate a new log name
2713
    We have to do this here and not in open as we want to store the
2714
    new file name in the current binary log file.
2715
  */
2716
  if (generate_new_name(new_name, name))
2717
    goto end;
2718
  new_name_ptr=new_name;
2719
2720
  if (log_type == LOG_BIN)
2721
  {
2722
    if (!no_auto_events)
2723
    {
2724
      /*
2725
        We log the whole file name for log file as the user may decide
2726
        to change base names at some point.
2727
      */
2728
      Rotate_log_event r(new_name+dirname_length(new_name),
2729
                         0, LOG_EVENT_OFFSET, 0);
2730
      r.write(&log_file);
2731
      bytes_written += r.data_written;
2732
    }
2733
    /*
2734
      Update needs to be signalled even if there is no rotate event
2735
      log rotation should give the waiting thread a signal to
2736
      discover EOF and move on to the next log.
2737
    */
2738
    signal_update();
2739
  }
2740
  old_name=name;
2741
  name=0;				// Don't free name
2742
  close(LOG_CLOSE_TO_BE_OPENED);
2743
2744
  /*
2745
     Note that at this point, log_state != LOG_CLOSED (important for is_open()).
2746
  */
2747
2748
  /*
2749
     new_file() is only used for rotation (in FLUSH LOGS or because size >
2750
     max_binlog_size or max_relay_log_size).
2751
     If this is a binary log, the Format_description_log_event at the beginning of
2752
     the new file should have created=0 (to distinguish with the
2753
     Format_description_log_event written at server startup, which should
2754
     trigger temp tables deletion on slaves.
2755
  */
2756
2757
  open(old_name, log_type, new_name_ptr,
2758
       io_cache_type, no_auto_events, max_size, 1);
2759
  my_free(old_name,MYF(0));
2760
2761
end:
2762
  if (need_lock)
2763
    pthread_mutex_unlock(&LOCK_log);
2764
  pthread_mutex_unlock(&LOCK_index);
2765
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2766
  return;
1 by brian
clean slate
2767
}
2768
2769
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2770
bool DRIZZLE_BIN_LOG::append(Log_event* ev)
1 by brian
clean slate
2771
{
2772
  bool error = 0;
2773
  pthread_mutex_lock(&LOCK_log);
2774
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2775
  assert(log_file.type == SEQ_READ_APPEND);
1 by brian
clean slate
2776
  /*
2777
    Log_event::write() is smart enough to use my_b_write() or
2778
    my_b_append() depending on the kind of cache we have.
2779
  */
2780
  if (ev->write(&log_file))
2781
  {
2782
    error=1;
2783
    goto err;
2784
  }
2785
  bytes_written+= ev->data_written;
2786
  if ((uint) my_b_append_tell(&log_file) > max_size)
2787
    new_file_without_locking();
2788
2789
err:
2790
  pthread_mutex_unlock(&LOCK_log);
2791
  signal_update();				// Safe as we don't call close
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2792
  return(error);
1 by brian
clean slate
2793
}
2794
2795
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2796
bool DRIZZLE_BIN_LOG::appendv(const char* buf, uint len,...)
1 by brian
clean slate
2797
{
2798
  bool error= 0;
2799
  va_list(args);
2800
  va_start(args,len);
2801
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2802
  assert(log_file.type == SEQ_READ_APPEND);
1 by brian
clean slate
2803
2804
  safe_mutex_assert_owner(&LOCK_log);
2805
  do
2806
  {
2807
    if (my_b_append(&log_file,(uchar*) buf,len))
2808
    {
2809
      error= 1;
2810
      goto err;
2811
    }
2812
    bytes_written += len;
2813
  } while ((buf=va_arg(args,const char*)) && (len=va_arg(args,uint)));
2814
  if ((uint) my_b_append_tell(&log_file) > max_size)
2815
    new_file_without_locking();
2816
2817
err:
2818
  if (!error)
2819
    signal_update();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2820
  return(error);
1 by brian
clean slate
2821
}
2822
2823
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2824
bool DRIZZLE_BIN_LOG::flush_and_sync()
1 by brian
clean slate
2825
{
2826
  int err=0, fd=log_file.file;
2827
  safe_mutex_assert_owner(&LOCK_log);
2828
  if (flush_io_cache(&log_file))
2829
    return 1;
2830
  if (++sync_binlog_counter >= sync_binlog_period && sync_binlog_period)
2831
  {
2832
    sync_binlog_counter= 0;
2833
    err=my_sync(fd, MYF(MY_WME));
2834
  }
2835
  return err;
2836
}
2837
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2838
void DRIZZLE_BIN_LOG::start_union_events(THD *thd, query_id_t query_id_param)
1 by brian
clean slate
2839
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2840
  assert(!thd->binlog_evt_union.do_union);
2841
  thd->binlog_evt_union.do_union= true;
2842
  thd->binlog_evt_union.unioned_events= false;
2843
  thd->binlog_evt_union.unioned_events_trans= false;
1 by brian
clean slate
2844
  thd->binlog_evt_union.first_query_id= query_id_param;
2845
}
2846
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2847
void DRIZZLE_BIN_LOG::stop_union_events(THD *thd)
1 by brian
clean slate
2848
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2849
  assert(thd->binlog_evt_union.do_union);
2850
  thd->binlog_evt_union.do_union= false;
1 by brian
clean slate
2851
}
2852
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
2853
bool DRIZZLE_BIN_LOG::is_query_in_union(THD *thd, query_id_t query_id_param)
1 by brian
clean slate
2854
{
2855
  return (thd->binlog_evt_union.do_union && 
2856
          query_id_param >= thd->binlog_evt_union.first_query_id);
2857
}
2858
2859
2860
/*
2861
  These functions are placed in this file since they need access to
2862
  binlog_hton, which has internal linkage.
2863
*/
2864
2865
int THD::binlog_setup_trx_data()
2866
{
2867
  binlog_trx_data *trx_data=
2868
    (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
2869
2870
  if (trx_data)
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2871
    return(0);                             // Already set up
1 by brian
clean slate
2872
2873
  trx_data= (binlog_trx_data*) my_malloc(sizeof(binlog_trx_data), MYF(MY_ZEROFILL));
2874
  if (!trx_data ||
2875
      open_cached_file(&trx_data->trans_log, mysql_tmpdir,
2876
                       LOG_PREFIX, binlog_cache_size, MYF(MY_WME)))
2877
  {
2878
    my_free((uchar*)trx_data, MYF(MY_ALLOW_ZERO_PTR));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2879
    return(1);                      // Didn't manage to set it up
1 by brian
clean slate
2880
  }
2881
  thd_set_ha_data(this, binlog_hton, trx_data);
2882
2883
  trx_data= new (thd_get_ha_data(this, binlog_hton)) binlog_trx_data;
2884
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2885
  return(0);
1 by brian
clean slate
2886
}
2887
2888
/*
2889
  Function to start a statement and optionally a transaction for the
2890
  binary log.
2891
2892
  SYNOPSIS
2893
    binlog_start_trans_and_stmt()
2894
2895
  DESCRIPTION
2896
2897
    This function does three things:
2898
    - Start a transaction if not in autocommit mode or if a BEGIN
2899
      statement has been seen.
2900
2901
    - Start a statement transaction to allow us to truncate the binary
2902
      log.
2903
2904
    - Save the currrent binlog position so that we can roll back the
2905
      statement by truncating the transaction log.
2906
2907
      We only update the saved position if the old one was undefined,
2908
      the reason is that there are some cases (e.g., for CREATE-SELECT)
2909
      where the position is saved twice (e.g., both in
2910
      select_create::prepare() and THD::binlog_write_table_map()) , but
2911
      we should use the first. This means that calls to this function
2912
      can be used to start the statement before the first table map
2913
      event, to include some extra events.
2914
 */
2915
2916
void
2917
THD::binlog_start_trans_and_stmt()
2918
{
2919
  binlog_trx_data *trx_data= (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
2920
2921
  if (trx_data == NULL ||
2922
      trx_data->before_stmt_pos == MY_OFF_T_UNDEF)
2923
  {
2924
    this->binlog_set_stmt_begin();
2925
    if (options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2926
      trans_register_ha(this, true, binlog_hton);
2927
    trans_register_ha(this, false, binlog_hton);
1 by brian
clean slate
2928
    /*
2929
      Mark statement transaction as read/write. We never start
2930
      a binary log transaction and keep it read-only,
2931
      therefore it's best to mark the transaction read/write just
2932
      at the same time we start it.
2933
      Not necessary to mark the normal transaction read/write
2934
      since the statement-level flag will be propagated automatically
2935
      inside ha_commit_trans.
2936
    */
2937
    ha_data[binlog_hton->slot].ha_info[0].set_trx_read_write();
2938
  }
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2939
  return;
1 by brian
clean slate
2940
}
2941
2942
void THD::binlog_set_stmt_begin() {
2943
  binlog_trx_data *trx_data=
2944
    (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
2945
2946
  /*
2947
    The call to binlog_trans_log_savepos() might create the trx_data
2948
    structure, if it didn't exist before, so we save the position
2949
    into an auto variable and then write it into the transaction
2950
    data for the binary log (i.e., trx_data).
2951
  */
2952
  my_off_t pos= 0;
2953
  binlog_trans_log_savepos(this, &pos);
2954
  trx_data= (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
2955
  trx_data->before_stmt_pos= pos;
2956
}
2957
2958
2959
/*
2960
  Write a table map to the binary log.
2961
 */
2962
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2963
int THD::binlog_write_table_map(Table *table, bool is_trans)
1 by brian
clean slate
2964
{
2965
  int error;
2966
2967
  /* Pre-conditions */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2968
  assert(current_stmt_binlog_row_based && mysql_bin_log.is_open());
365.2.4 by Monty Taylor
Updated some Long refs to use stdint constants.
2969
  assert(table->s->table_map_id != UINT32_MAX);
1 by brian
clean slate
2970
2971
  Table_map_log_event::flag_set const
2972
    flags= Table_map_log_event::TM_NO_FLAGS;
2973
2974
  Table_map_log_event
2975
    the_event(this, table, table->s->table_map_id, is_trans, flags);
2976
2977
  if (is_trans && binlog_table_maps == 0)
2978
    binlog_start_trans_and_stmt();
2979
2980
  if ((error= mysql_bin_log.write(&the_event)))
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2981
    return(error);
1 by brian
clean slate
2982
2983
  binlog_table_maps++;
2984
  table->s->table_map_version= mysql_bin_log.table_map_version();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2985
  return(0);
1 by brian
clean slate
2986
}
2987
2988
Rows_log_event*
2989
THD::binlog_get_pending_rows_event() const
2990
{
2991
  binlog_trx_data *const trx_data=
2992
    (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
2993
  /*
2994
    This is less than ideal, but here's the story: If there is no
2995
    trx_data, prepare_pending_rows_event() has never been called
2996
    (since the trx_data is set up there). In that case, we just return
2997
    NULL.
2998
   */
2999
  return trx_data ? trx_data->pending() : NULL;
3000
}
3001
3002
void
3003
THD::binlog_set_pending_rows_event(Rows_log_event* ev)
3004
{
3005
  if (thd_get_ha_data(this, binlog_hton) == NULL)
3006
    binlog_setup_trx_data();
3007
3008
  binlog_trx_data *const trx_data=
3009
    (binlog_trx_data*) thd_get_ha_data(this, binlog_hton);
3010
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3011
  assert(trx_data);
1 by brian
clean slate
3012
  trx_data->set_pending(ev);
3013
}
3014
3015
3016
/*
3017
  Moves the last bunch of rows from the pending Rows event to the binlog
3018
  (either cached binlog if transaction, or disk binlog). Sets a new pending
3019
  event.
3020
*/
3021
int
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3022
DRIZZLE_BIN_LOG::flush_and_set_pending_rows_event(THD *thd,
1 by brian
clean slate
3023
                                                Rows_log_event* event)
3024
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3025
  assert(mysql_bin_log.is_open());
1 by brian
clean slate
3026
3027
  int error= 0;
3028
3029
  binlog_trx_data *const trx_data=
3030
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
3031
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3032
  assert(trx_data);
1 by brian
clean slate
3033
3034
  if (Rows_log_event* pending= trx_data->pending())
3035
  {
3036
    IO_CACHE *file= &log_file;
3037
3038
    /*
3039
      Decide if we should write to the log file directly or to the
3040
      transaction log.
3041
    */
3042
    if (pending->get_cache_stmt() || my_b_tell(&trx_data->trans_log))
3043
      file= &trx_data->trans_log;
3044
3045
    /*
3046
      If we are writing to the log file directly, we could avoid
3047
      locking the log. This does not work since we need to step the
3048
      m_table_map_version below, and that change has to be protected
3049
      by the LOCK_log mutex.
3050
    */
3051
    pthread_mutex_lock(&LOCK_log);
3052
3053
    /*
3054
      Write pending event to log file or transaction cache
3055
    */
3056
    if (pending->write(file))
3057
    {
3058
      pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3059
      return(1);
1 by brian
clean slate
3060
    }
3061
3062
    /*
3063
      We step the table map version if we are writing an event
3064
      representing the end of a statement.  We do this regardless of
3065
      wheather we write to the transaction cache or to directly to the
3066
      file.
3067
3068
      In an ideal world, we could avoid stepping the table map version
3069
      if we were writing to a transaction cache, since we could then
3070
      reuse the table map that was written earlier in the transaction
3071
      cache.  This does not work since STMT_END_F implies closing all
3072
      table mappings on the slave side.
3073
3074
      TODO: Find a solution so that table maps does not have to be
3075
      written several times within a transaction.
3076
     */
3077
    if (pending->get_flags(Rows_log_event::STMT_END_F))
3078
      ++m_table_map_version;
3079
3080
    delete pending;
3081
3082
    if (file == &log_file)
3083
    {
3084
      error= flush_and_sync();
3085
      if (!error)
3086
      {
3087
        signal_update();
3088
        rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
3089
      }
3090
    }
3091
3092
    pthread_mutex_unlock(&LOCK_log);
3093
  }
3094
3095
  thd->binlog_set_pending_rows_event(event);
3096
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3097
  return(error);
1 by brian
clean slate
3098
}
3099
3100
/**
3101
  Write an event to the binary log.
3102
*/
3103
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3104
bool DRIZZLE_BIN_LOG::write(Log_event *event_info)
1 by brian
clean slate
3105
{
3106
  THD *thd= event_info->thd;
3107
  bool error= 1;
3108
3109
  if (thd->binlog_evt_union.do_union)
3110
  {
3111
    /*
3112
      In Stored function; Remember that function call caused an update.
3113
      We will log the function call to the binary log on function exit
3114
    */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3115
    thd->binlog_evt_union.unioned_events= true;
1 by brian
clean slate
3116
    thd->binlog_evt_union.unioned_events_trans |= event_info->cache_stmt;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3117
    return(0);
1 by brian
clean slate
3118
  }
3119
3120
  /*
3121
    Flush the pending rows event to the transaction cache or to the
3122
    log file.  Since this function potentially aquire the LOCK_log
3123
    mutex, we do this before aquiring the LOCK_log mutex in this
3124
    function.
3125
3126
    We only end the statement if we are in a top-level statement.  If
3127
    we are inside a stored function, we do not end the statement since
3128
    this will close all tables on the slave.
3129
  */
3130
  bool const end_stmt= false;
3131
  thd->binlog_flush_pending_rows_event(end_stmt);
3132
3133
  pthread_mutex_lock(&LOCK_log);
3134
3135
  /*
3136
     In most cases this is only called if 'is_open()' is true; in fact this is
3137
     mostly called if is_open() *was* true a few instructions before, but it
3138
     could have changed since.
3139
  */
3140
  if (likely(is_open()))
3141
  {
3142
    IO_CACHE *file= &log_file;
3143
    /*
3144
      In the future we need to add to the following if tests like
3145
      "do the involved tables match (to be implemented)
3146
      binlog_[wild_]{do|ignore}_table?" (WL#1049)"
3147
    */
3148
    const char *local_db= event_info->get_db();
3149
    if ((thd && !(thd->options & OPTION_BIN_LOG)) ||
3150
	(!binlog_filter->db_ok(local_db)))
3151
    {
3152
      VOID(pthread_mutex_unlock(&LOCK_log));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3153
      return(0);
1 by brian
clean slate
3154
    }
3155
3156
    /*
3157
      Should we write to the binlog cache or to the binlog on disk?
3158
      Write to the binlog cache if:
3159
      - it is already not empty (meaning we're in a transaction; note that the
3160
     present event could be about a non-transactional table, but still we need
3161
     to write to the binlog cache in that case to handle updates to mixed
3162
     trans/non-trans table types the best possible in binlogging)
3163
      - or if the event asks for it (cache_stmt == TRUE).
3164
    */
3165
    if (opt_using_transactions && thd)
3166
    {
3167
      if (thd->binlog_setup_trx_data())
3168
        goto err;
3169
3170
      binlog_trx_data *const trx_data=
3171
        (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
3172
      IO_CACHE *trans_log= &trx_data->trans_log;
3173
      my_off_t trans_log_pos= my_b_tell(trans_log);
3174
      if (event_info->get_cache_stmt() || trans_log_pos != 0)
3175
      {
3176
        if (trans_log_pos == 0)
3177
          thd->binlog_start_trans_and_stmt();
3178
        file= trans_log;
3179
      }
3180
      /*
3181
        TODO as Mats suggested, for all the cases above where we write to
3182
        trans_log, it sounds unnecessary to lock LOCK_log. We should rather
3183
        test first if we want to write to trans_log, and if not, lock
3184
        LOCK_log.
3185
      */
3186
    }
3187
3188
    /*
3189
      No check for auto events flag here - this write method should
3190
      never be called if auto-events are enabled
3191
    */
3192
3193
    /*
3194
      1. Write first log events which describe the 'run environment'
3195
      of the SQL command
3196
    */
3197
3198
    /*
3199
      If row-based binlogging, Insert_id, Rand and other kind of "setting
3200
      context" events are not needed.
3201
    */
3202
    if (thd)
3203
    {
3204
      if (!thd->current_stmt_binlog_row_based)
3205
      {
3206
        if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt)
3207
        {
3208
          Intvar_log_event e(thd,(uchar) LAST_INSERT_ID_EVENT,
3209
                             thd->first_successful_insert_id_in_prev_stmt_for_binlog);
3210
          if (e.write(file))
3211
            goto err;
3212
        }
3213
        if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0)
3214
        {
3215
          /*
3216
            If the auto_increment was second in a table's index (possible with
3217
            MyISAM or BDB) (table->next_number_keypart != 0), such event is
3218
            in fact not necessary. We could avoid logging it.
3219
          */
3220
          Intvar_log_event e(thd, (uchar) INSERT_ID_EVENT,
3221
                             thd->auto_inc_intervals_in_cur_stmt_for_binlog.
3222
                             minimum());
3223
          if (e.write(file))
3224
            goto err;
3225
        }
3226
        if (thd->rand_used)
3227
        {
3228
          Rand_log_event e(thd,thd->rand_saved_seed1,thd->rand_saved_seed2);
3229
          if (e.write(file))
3230
            goto err;
3231
        }
3232
        if (thd->user_var_events.elements)
3233
        {
3234
          for (uint i= 0; i < thd->user_var_events.elements; i++)
3235
          {
3236
            BINLOG_USER_VAR_EVENT *user_var_event;
3237
            get_dynamic(&thd->user_var_events,(uchar*) &user_var_event, i);
3238
            User_var_log_event e(thd, user_var_event->user_var_event->name.str,
3239
                                 user_var_event->user_var_event->name.length,
3240
                                 user_var_event->value,
3241
                                 user_var_event->length,
3242
                                 user_var_event->type,
3243
                                 user_var_event->charset_number);
3244
            if (e.write(file))
3245
              goto err;
3246
          }
3247
        }
3248
      }
3249
    }
3250
3251
    /*
3252
       Write the SQL command
3253
     */
3254
3255
    if (event_info->write(file))
3256
      goto err;
3257
3258
    if (file == &log_file) // we are writing to the real log (disk)
3259
    {
3260
      if (flush_and_sync())
3261
	goto err;
3262
      signal_update();
3263
      rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
3264
    }
3265
    error=0;
3266
3267
err:
3268
    if (error)
3269
    {
3270
      if (my_errno == EFBIG)
3271
	my_message(ER_TRANS_CACHE_FULL, ER(ER_TRANS_CACHE_FULL), MYF(0));
3272
      else
3273
	my_error(ER_ERROR_ON_WRITE, MYF(0), name, errno);
3274
      write_error=1;
3275
    }
3276
  }
3277
3278
  if (event_info->flags & LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F)
3279
    ++m_table_map_version;
3280
3281
  pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3282
  return(error);
1 by brian
clean slate
3283
}
3284
3285
3286
int error_log_print(enum loglevel level, const char *format,
3287
                    va_list args)
3288
{
3289
  return logger.error_log_print(level, format, args);
3290
}
3291
3292
3293
bool slow_log_print(THD *thd, const char *query, uint query_length,
151 by Brian Aker
Ulonglong to uint64_t
3294
                    uint64_t current_utime)
1 by brian
clean slate
3295
{
3296
  return logger.slow_log_print(thd, query, query_length, current_utime);
3297
}
3298
3299
3300
bool LOGGER::log_command(THD *thd, enum enum_server_command command)
3301
{
3302
  /*
3303
    Log command if we have at least one log event handler enabled and want
3304
    to log this king of commands
3305
  */
3306
  if (*general_log_handler_list && (what_to_log & (1L << (uint) command)))
3307
  {
3308
    if (thd->options & OPTION_LOG_OFF)
3309
    {
3310
      /* No logging */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3311
      return false;
1 by brian
clean slate
3312
    }
3313
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3314
    return true;
1 by brian
clean slate
3315
  }
3316
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3317
  return false;
1 by brian
clean slate
3318
}
3319
3320
3321
bool general_log_print(THD *thd, enum enum_server_command command,
3322
                       const char *format, ...)
3323
{
3324
  va_list args;
3325
  uint error= 0;
3326
3327
  /* Print the message to the buffer if we want to log this king of commands */
3328
  if (! logger.log_command(thd, command))
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3329
    return false;
1 by brian
clean slate
3330
3331
  va_start(args, format);
3332
  error= logger.general_log_print(thd, command, format, args);
3333
  va_end(args);
3334
3335
  return error;
3336
}
3337
3338
bool general_log_write(THD *thd, enum enum_server_command command,
3339
                       const char *query, uint query_length)
3340
{
3341
  /* Write the message to the log if we want to log this king of commands */
3342
  if (logger.log_command(thd, command))
3343
    return logger.general_log_write(thd, command, query, query_length);
3344
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3345
  return false;
1 by brian
clean slate
3346
}
3347
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3348
void DRIZZLE_BIN_LOG::rotate_and_purge(uint flags)
1 by brian
clean slate
3349
{
3350
  if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED))
3351
    pthread_mutex_lock(&LOCK_log);
3352
  if ((flags & RP_FORCE_ROTATE) ||
3353
      (my_b_tell(&log_file) >= (my_off_t) max_size))
3354
  {
3355
    new_file_without_locking();
3356
#ifdef HAVE_REPLICATION
3357
    if (expire_logs_days)
3358
    {
3359
      time_t purge_time= my_time(0) - expire_logs_days*24*60*60;
3360
      if (purge_time >= 0)
3361
        purge_logs_before_date(purge_time);
3362
    }
3363
#endif
3364
  }
3365
  if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED))
3366
    pthread_mutex_unlock(&LOCK_log);
3367
}
3368
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3369
uint DRIZZLE_BIN_LOG::next_file_id()
1 by brian
clean slate
3370
{
3371
  uint res;
3372
  pthread_mutex_lock(&LOCK_log);
3373
  res = file_id++;
3374
  pthread_mutex_unlock(&LOCK_log);
3375
  return res;
3376
}
3377
3378
3379
/*
3380
  Write the contents of a cache to the binary log.
3381
3382
  SYNOPSIS
3383
    write_cache()
3384
    cache    Cache to write to the binary log
3385
    lock_log True if the LOCK_log mutex should be aquired, false otherwise
3386
    sync_log True if the log should be flushed and sync:ed
3387
3388
  DESCRIPTION
3389
    Write the contents of the cache to the binary log. The cache will
3390
    be reset as a READ_CACHE to be able to read the contents from it.
3391
 */
3392
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3393
int DRIZZLE_BIN_LOG::write_cache(IO_CACHE *cache, bool lock_log, bool sync_log)
1 by brian
clean slate
3394
{
3395
  Mutex_sentry sentry(lock_log ? &LOCK_log : NULL);
3396
3397
  if (reinit_io_cache(cache, READ_CACHE, 0, 0, 0))
3398
    return ER_ERROR_ON_WRITE;
3399
  uint length= my_b_bytes_in_cache(cache), group, carry, hdr_offs;
3400
  long val;
3401
  uchar header[LOG_EVENT_HEADER_LEN];
3402
3403
  /*
3404
    The events in the buffer have incorrect end_log_pos data
3405
    (relative to beginning of group rather than absolute),
3406
    so we'll recalculate them in situ so the binlog is always
3407
    correct, even in the middle of a group. This is possible
3408
    because we now know the start position of the group (the
3409
    offset of this cache in the log, if you will); all we need
3410
    to do is to find all event-headers, and add the position of
3411
    the group to the end_log_pos of each event.  This is pretty
3412
    straight forward, except that we read the cache in segments,
3413
    so an event-header might end up on the cache-border and get
3414
    split.
3415
  */
3416
3417
  group= (uint)my_b_tell(&log_file);
3418
  hdr_offs= carry= 0;
3419
3420
  do
3421
  {
3422
3423
    /*
3424
      if we only got a partial header in the last iteration,
3425
      get the other half now and process a full header.
3426
    */
3427
    if (unlikely(carry > 0))
3428
    {
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3429
      assert(carry < LOG_EVENT_HEADER_LEN);
1 by brian
clean slate
3430
3431
      /* assemble both halves */
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
3432
      memcpy(&header[carry], cache->read_pos, LOG_EVENT_HEADER_LEN - carry);
1 by brian
clean slate
3433
3434
      /* fix end_log_pos */
3435
      val= uint4korr(&header[LOG_POS_OFFSET]) + group;
3436
      int4store(&header[LOG_POS_OFFSET], val);
3437
3438
      /* write the first half of the split header */
3439
      if (my_b_write(&log_file, header, carry))
3440
        return ER_ERROR_ON_WRITE;
3441
3442
      /*
3443
        copy fixed second half of header to cache so the correct
3444
        version will be written later.
3445
      */
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
3446
      memcpy(cache->read_pos, &header[carry], LOG_EVENT_HEADER_LEN - carry);
1 by brian
clean slate
3447
3448
      /* next event header at ... */
3449
      hdr_offs = uint4korr(&header[EVENT_LEN_OFFSET]) - carry;
3450
3451
      carry= 0;
3452
    }
3453
3454
    /* if there is anything to write, process it. */
3455
3456
    if (likely(length > 0))
3457
    {
3458
      /*
3459
        process all event-headers in this (partial) cache.
3460
        if next header is beyond current read-buffer,
3461
        we'll get it later (though not necessarily in the
3462
        very next iteration, just "eventually").
3463
      */
3464
3465
      while (hdr_offs < length)
3466
      {
3467
        /*
3468
          partial header only? save what we can get, process once
3469
          we get the rest.
3470
        */
3471
3472
        if (hdr_offs + LOG_EVENT_HEADER_LEN > length)
3473
        {
3474
          carry= length - hdr_offs;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
3475
          memcpy(header, cache->read_pos + hdr_offs, carry);
1 by brian
clean slate
3476
          length= hdr_offs;
3477
        }
3478
        else
3479
        {
3480
          /* we've got a full event-header, and it came in one piece */
3481
3482
          uchar *log_pos= (uchar *)cache->read_pos + hdr_offs + LOG_POS_OFFSET;
3483
3484
          /* fix end_log_pos */
3485
          val= uint4korr(log_pos) + group;
3486
          int4store(log_pos, val);
3487
3488
          /* next event header at ... */
3489
          log_pos= (uchar *)cache->read_pos + hdr_offs + EVENT_LEN_OFFSET;
3490
          hdr_offs += uint4korr(log_pos);
3491
3492
        }
3493
      }
3494
3495
      /*
3496
        Adjust hdr_offs. Note that it may still point beyond the segment
3497
        read in the next iteration; if the current event is very long,
3498
        it may take a couple of read-iterations (and subsequent adjustments
3499
        of hdr_offs) for it to point into the then-current segment.
3500
        If we have a split header (!carry), hdr_offs will be set at the
3501
        beginning of the next iteration, overwriting the value we set here:
3502
      */
3503
      hdr_offs -= length;
3504
    }
3505
3506
    /* Write data to the binary log file */
3507
    if (my_b_write(&log_file, cache->read_pos, length))
3508
      return ER_ERROR_ON_WRITE;
3509
    cache->read_pos=cache->read_end;		// Mark buffer used up
3510
  } while ((length= my_b_fill(cache)));
3511
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3512
  assert(carry == 0);
1 by brian
clean slate
3513
3514
  if (sync_log)
3515
    flush_and_sync();
3516
3517
  return 0;                                     // All OK
3518
}
3519
3520
/**
3521
  Write a cached log entry to the binary log.
3522
  - To support transaction over replication, we wrap the transaction
3523
  with BEGIN/COMMIT or BEGIN/ROLLBACK in the binary log.
3524
  We want to write a BEGIN/ROLLBACK block when a non-transactional table
3525
  was updated in a transaction which was rolled back. This is to ensure
3526
  that the same updates are run on the slave.
3527
3528
  @param thd
3529
  @param cache		The cache to copy to the binlog
3530
  @param commit_event   The commit event to print after writing the
3531
                        contents of the cache.
3532
3533
  @note
3534
    We only come here if there is something in the cache.
3535
  @note
3536
    The thing in the cache is always a complete transaction.
3537
  @note
3538
    'cache' needs to be reinitialized after this functions returns.
3539
*/
3540
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3541
bool DRIZZLE_BIN_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event)
1 by brian
clean slate
3542
{
3543
  VOID(pthread_mutex_lock(&LOCK_log));
3544
3545
  /* NULL would represent nothing to replicate after ROLLBACK */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3546
  assert(commit_event != NULL);
1 by brian
clean slate
3547
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3548
  assert(is_open());
1 by brian
clean slate
3549
  if (likely(is_open()))                       // Should always be true
3550
  {
3551
    /*
3552
      We only bother to write to the binary log if there is anything
3553
      to write.
3554
     */
3555
    if (my_b_tell(cache) > 0)
3556
    {
3557
      /*
3558
        Log "BEGIN" at the beginning of every transaction.  Here, a
3559
        transaction is either a BEGIN..COMMIT block or a single
3560
        statement in autocommit mode.
3561
      */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3562
      Query_log_event qinfo(thd, STRING_WITH_LEN("BEGIN"), true, false);
1 by brian
clean slate
3563
      /*
3564
        Imagine this is rollback due to net timeout, after all
3565
        statements of the transaction succeeded. Then we want a
3566
        zero-error code in BEGIN.  In other words, if there was a
3567
        really serious error code it's already in the statement's
3568
        events, there is no need to put it also in this internally
3569
        generated event, and as this event is generated late it would
3570
        lead to false alarms.
3571
3572
        This is safer than thd->clear_error() against kills at shutdown.
3573
      */
3574
      qinfo.error_code= 0;
3575
      /*
3576
        Now this Query_log_event has artificial log_pos 0. It must be
3577
        adjusted to reflect the real position in the log. Not doing it
3578
        would confuse the slave: it would prevent this one from
3579
        knowing where he is in the master's binlog, which would result
3580
        in wrong positions being shown to the user, MASTER_POS_WAIT
3581
        undue waiting etc.
3582
      */
3583
      if (qinfo.write(&log_file))
3584
        goto err;
3585
3586
      if ((write_error= write_cache(cache, false, false)))
3587
        goto err;
3588
3589
      if (commit_event && commit_event->write(&log_file))
3590
        goto err;
3591
      if (flush_and_sync())
3592
        goto err;
3593
      if (cache->error)				// Error on read
3594
      {
3595
        sql_print_error(ER(ER_ERROR_ON_READ), cache->file_name, errno);
3596
        write_error=1;				// Don't give more errors
3597
        goto err;
3598
      }
3599
      signal_update();
3600
    }
3601
3602
    /*
3603
      if commit_event is Xid_log_event, increase the number of
3604
      prepared_xids (it's decreasd in ::unlog()). Binlog cannot be rotated
3605
      if there're prepared xids in it - see the comment in new_file() for
3606
      an explanation.
3607
      If the commit_event is not Xid_log_event (then it's a Query_log_event)
3608
      rotate binlog, if necessary.
3609
    */
3610
    if (commit_event && commit_event->get_type_code() == XID_EVENT)
3611
    {
3612
      pthread_mutex_lock(&LOCK_prep_xids);
3613
      prepared_xids++;
3614
      pthread_mutex_unlock(&LOCK_prep_xids);
3615
    }
3616
    else
3617
      rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
3618
  }
3619
  VOID(pthread_mutex_unlock(&LOCK_log));
3620
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3621
  return(0);
1 by brian
clean slate
3622
3623
err:
3624
  if (!write_error)
3625
  {
3626
    write_error= 1;
3627
    sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
3628
  }
3629
  VOID(pthread_mutex_unlock(&LOCK_log));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3630
  return(1);
1 by brian
clean slate
3631
}
3632
3633
3634
/**
3635
  Wait until we get a signal that the relay log has been updated
3636
3637
  @param[in] thd   a THD struct
3638
  @note
3639
    LOCK_log must be taken before calling this function.
3640
    It will be released at the end of the function.
3641
*/
3642
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3643
void DRIZZLE_BIN_LOG::wait_for_update_relay_log(THD* thd)
1 by brian
clean slate
3644
{
3645
  const char *old_msg;
3646
  old_msg= thd->enter_cond(&update_cond, &LOCK_log,
3647
                           "Slave has read all relay log; " 
3648
                           "waiting for the slave I/O "
3649
                           "thread to update it" );
3650
  pthread_cond_wait(&update_cond, &LOCK_log);
3651
  thd->exit_cond(old_msg);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3652
  return;
1 by brian
clean slate
3653
}
3654
3655
3656
/**
3657
  Wait until we get a signal that the binary log has been updated.
3658
  Applies to master only.
3659
     
3660
  NOTES
3661
  @param[in] thd        a THD struct
3662
  @param[in] timeout    a pointer to a timespec;
3663
                        NULL means to wait w/o timeout.
3664
  @retval    0          if got signalled on update
3665
  @retval    non-0      if wait timeout elapsed
3666
  @note
3667
    LOCK_log must be taken before calling this function.
3668
    LOCK_log is being released while the thread is waiting.
3669
    LOCK_log is released by the caller.
3670
*/
3671
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3672
int DRIZZLE_BIN_LOG::wait_for_update_bin_log(THD* thd,
1 by brian
clean slate
3673
                                           const struct timespec *timeout)
3674
{
3675
  int ret= 0;
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
3676
  const char* old_msg = thd->get_proc_info();
1 by brian
clean slate
3677
  old_msg= thd->enter_cond(&update_cond, &LOCK_log,
3678
                           "Master has sent all binlog to slave; "
3679
                           "waiting for binlog to be updated");
3680
  if (!timeout)
3681
    pthread_cond_wait(&update_cond, &LOCK_log);
3682
  else
3683
    ret= pthread_cond_timedwait(&update_cond, &LOCK_log,
3684
                                const_cast<struct timespec *>(timeout));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3685
  return(ret);
1 by brian
clean slate
3686
}
3687
3688
3689
/**
3690
  Close the log file.
3691
3692
  @param exiting     Bitmask for one or more of the following bits:
3693
          - LOG_CLOSE_INDEX : if we should close the index file
3694
          - LOG_CLOSE_TO_BE_OPENED : if we intend to call open
3695
                                     at once after close.
3696
          - LOG_CLOSE_STOP_EVENT : write a 'stop' event to the log
3697
3698
  @note
3699
    One can do an open on the object at once after doing a close.
3700
    The internal structures are not freed until cleanup() is called
3701
*/
3702
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3703
void DRIZZLE_BIN_LOG::close(uint exiting)
1 by brian
clean slate
3704
{					// One can't set log_type here!
3705
  if (log_state == LOG_OPENED)
3706
  {
3707
#ifdef HAVE_REPLICATION
3708
    if (log_type == LOG_BIN && !no_auto_events &&
3709
	(exiting & LOG_CLOSE_STOP_EVENT))
3710
    {
3711
      Stop_log_event s;
3712
      s.write(&log_file);
3713
      bytes_written+= s.data_written;
3714
      signal_update();
3715
    }
3716
#endif /* HAVE_REPLICATION */
3717
3718
    /* don't pwrite in a file opened with O_APPEND - it doesn't work */
3719
    if (log_file.type == WRITE_CACHE && log_type == LOG_BIN)
3720
    {
3721
      my_off_t offset= BIN_LOG_HEADER_SIZE + FLAGS_OFFSET;
3722
      uchar flags= 0;            // clearing LOG_EVENT_BINLOG_IN_USE_F
31 by Brian Aker
Removed my versions of pread/pwrite from the Kernel
3723
      pwrite(log_file.file, &flags, 1, offset);
1 by brian
clean slate
3724
    }
3725
3726
    /* this will cleanup IO_CACHE, sync and close the file */
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3727
    DRIZZLE_LOG::close(exiting);
1 by brian
clean slate
3728
  }
3729
3730
  /*
3731
    The following test is needed even if is_open() is not set, as we may have
3732
    called a not complete close earlier and the index file is still open.
3733
  */
3734
3735
  if ((exiting & LOG_CLOSE_INDEX) && my_b_inited(&index_file))
3736
  {
3737
    end_io_cache(&index_file);
3738
    if (my_close(index_file.file, MYF(0)) < 0 && ! write_error)
3739
    {
3740
      write_error= 1;
3741
      sql_print_error(ER(ER_ERROR_ON_WRITE), index_file_name, errno);
3742
    }
3743
  }
3744
  log_state= (exiting & LOG_CLOSE_TO_BE_OPENED) ? LOG_TO_BE_OPENED : LOG_CLOSED;
3745
  safeFree(name);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3746
  return;
1 by brian
clean slate
3747
}
3748
3749
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3750
void DRIZZLE_BIN_LOG::set_max_size(ulong max_size_arg)
1 by brian
clean slate
3751
{
3752
  /*
3753
    We need to take locks, otherwise this may happen:
3754
    new_file() is called, calls open(old_max_size), then before open() starts,
3755
    set_max_size() sets max_size to max_size_arg, then open() starts and
3756
    uses the old_max_size argument, so max_size_arg has been overwritten and
3757
    it's like if the SET command was never run.
3758
  */
3759
  pthread_mutex_lock(&LOCK_log);
3760
  if (is_open())
3761
    max_size= max_size_arg;
3762
  pthread_mutex_unlock(&LOCK_log);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3763
  return;
1 by brian
clean slate
3764
}
3765
3766
3767
/**
3768
  Check if a string is a valid number.
3769
3770
  @param str			String to test
3771
  @param res			Store value here
3772
  @param allow_wildcards	Set to 1 if we should ignore '%' and '_'
3773
3774
  @note
3775
    For the moment the allow_wildcards argument is not used
3776
    Should be move to some other file.
3777
3778
  @retval
3779
    1	String is a number
3780
  @retval
3781
    0	Error
3782
*/
3783
3784
static bool test_if_number(register const char *str,
3785
			   long *res, bool allow_wildcards)
3786
{
3787
  register int flag;
3788
  const char *start;
3789
3790
  flag= 0; 
3791
  start= str;
3792
  while (*str++ == ' ') ;
3793
  if (*--str == '-' || *str == '+')
3794
    str++;
3795
  while (my_isdigit(files_charset_info,*str) ||
3796
	 (allow_wildcards && (*str == wild_many || *str == wild_one)))
3797
  {
3798
    flag=1;
3799
    str++;
3800
  }
3801
  if (*str == '.')
3802
  {
3803
    for (str++ ;
3804
	 my_isdigit(files_charset_info,*str) ||
3805
	   (allow_wildcards && (*str == wild_many || *str == wild_one)) ;
3806
	 str++, flag=1) ;
3807
  }
3808
  if (*str != 0 || flag == 0)
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3809
    return(0);
1 by brian
clean slate
3810
  if (res)
3811
    *res=atol(start);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3812
  return(1);			/* Number ok */
1 by brian
clean slate
3813
} /* test_if_number */
3814
3815
3816
void sql_perror(const char *message)
3817
{
3818
#ifdef HAVE_STRERROR
3819
  sql_print_error("%s: %s",message, strerror(errno));
3820
#else
3821
  perror(message);
3822
#endif
3823
}
3824
3825
3826
bool flush_error_log()
3827
{
3828
  bool result=0;
3829
  if (opt_error_log)
3830
  {
3831
    char err_renamed[FN_REFLEN], *end;
3832
    end= strmake(err_renamed,log_error_file,FN_REFLEN-4);
266.1.21 by Monty Taylor
Removed references to strmov and strnmov
3833
    stpcpy(end, "-old");
1 by brian
clean slate
3834
    VOID(pthread_mutex_lock(&LOCK_error_log));
3835
    char err_temp[FN_REFLEN+4];
3836
    /*
3837
     On Windows is necessary a temporary file for to rename
3838
     the current error file.
3839
    */
3840
    strxmov(err_temp, err_renamed,"-tmp",NullS);
3841
    (void) my_delete(err_temp, MYF(0)); 
3842
    if (freopen(err_temp,"a+",stdout))
3843
    {
3844
      int fd;
3845
      size_t bytes;
3846
      uchar buf[IO_SIZE];
3847
3848
      freopen(err_temp,"a+",stderr);
3849
      (void) my_delete(err_renamed, MYF(0));
3850
      my_rename(log_error_file,err_renamed,MYF(0));
3851
      if (freopen(log_error_file,"a+",stdout))
3852
        freopen(log_error_file,"a+",stderr);
3853
3854
      if ((fd = my_open(err_temp, O_RDONLY, MYF(0))) >= 0)
3855
      {
3856
        while ((bytes= my_read(fd, buf, IO_SIZE, MYF(0))) &&
3857
               bytes != MY_FILE_ERROR)
3858
          my_fwrite(stderr, buf, bytes, MYF(0));
3859
        my_close(fd, MYF(0));
3860
      }
3861
      (void) my_delete(err_temp, MYF(0)); 
3862
    }
3863
    else
3864
     result= 1;
3865
    VOID(pthread_mutex_unlock(&LOCK_error_log));
3866
  }
3867
   return result;
3868
}
3869
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
3870
void DRIZZLE_BIN_LOG::signal_update()
1 by brian
clean slate
3871
{
3872
  pthread_cond_broadcast(&update_cond);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3873
  return;
1 by brian
clean slate
3874
}
3875
3876
/**
3877
  Prints a printf style message to the error log and, under NT, to the
3878
  Windows event log.
3879
3880
  This function prints the message into a buffer and then sends that buffer
3881
  to other functions to write that message to other logging sources.
3882
3883
  @param event_type          Type of event to write (Error, Warning, or Info)
3884
  @param format              Printf style format of message
3885
  @param args                va_list list of arguments for the message
3886
3887
  @returns
3888
    The function always returns 0. The return value is present in the
3889
    signature to be compatible with other logging routines, which could
3890
    return an error (e.g. logging to the log tables)
3891
*/
77.1.45 by Monty Taylor
Warning fixes.
3892
static void print_buffer_to_file(enum loglevel level,
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
3893
                                 int error_code __attribute__((unused)),
77.1.45 by Monty Taylor
Warning fixes.
3894
                                 const char *buffer,
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
3895
                                 size_t buffer_length __attribute__((unused)))
1 by brian
clean slate
3896
{
3897
  time_t skr;
3898
  struct tm tm_tmp;
3899
  struct tm *start;
3900
3901
  VOID(pthread_mutex_lock(&LOCK_error_log));
3902
3903
  skr= my_time(0);
3904
  localtime_r(&skr, &tm_tmp);
3905
  start=&tm_tmp;
3906
3907
  fprintf(stderr, "%02d%02d%02d %2d:%02d:%02d [%s] %s\n",
3908
          start->tm_year % 100,
3909
          start->tm_mon+1,
3910
          start->tm_mday,
3911
          start->tm_hour,
3912
          start->tm_min,
3913
          start->tm_sec,
3914
          (level == ERROR_LEVEL ? "ERROR" : level == WARNING_LEVEL ?
3915
           "Warning" : "Note"),
3916
          buffer);
3917
3918
  fflush(stderr);
3919
3920
  VOID(pthread_mutex_unlock(&LOCK_error_log));
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3921
  return;
1 by brian
clean slate
3922
}
3923
3924
3925
int vprint_msg_to_log(enum loglevel level, const char *format, va_list args)
3926
{
3927
  char   buff[1024];
3928
  size_t length;
3929
  int error_code= errno;
3930
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
3931
  length= vsnprintf(buff, sizeof(buff), format, args);
1 by brian
clean slate
3932
3933
  print_buffer_to_file(level, error_code, buff, length);
3934
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3935
  return(0);
1 by brian
clean slate
3936
}
3937
3938
3939
void sql_print_error(const char *format, ...) 
3940
{
3941
  va_list args;
3942
3943
  va_start(args, format);
3944
  error_log_print(ERROR_LEVEL, format, args);
3945
  va_end(args);
3946
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3947
  return;
1 by brian
clean slate
3948
}
3949
3950
3951
void sql_print_warning(const char *format, ...) 
3952
{
3953
  va_list args;
3954
3955
  va_start(args, format);
3956
  error_log_print(WARNING_LEVEL, format, args);
3957
  va_end(args);
3958
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3959
  return;
1 by brian
clean slate
3960
}
3961
3962
3963
void sql_print_information(const char *format, ...) 
3964
{
3965
  va_list args;
3966
3967
  va_start(args, format);
3968
  error_log_print(INFORMATION_LEVEL, format, args);
3969
  va_end(args);
3970
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3971
  return;
1 by brian
clean slate
3972
}
3973
3974
3975
/********* transaction coordinator log for 2pc - mmap() based solution *******/
3976
3977
/*
3978
  the log consists of a file, mmapped to a memory.
3979
  file is divided on pages of tc_log_page_size size.
3980
  (usable size of the first page is smaller because of log header)
3981
  there's PAGE control structure for each page
3982
  each page (or rather PAGE control structure) can be in one of three
3983
  states - active, syncing, pool.
3984
  there could be only one page in active or syncing states,
3985
  but many in pool - pool is fifo queue.
3986
  usual lifecycle of a page is pool->active->syncing->pool
3987
  "active" page - is a page where new xid's are logged.
3988
  the page stays active as long as syncing slot is taken.
3989
  "syncing" page is being synced to disk. no new xid can be added to it.
3990
  when the sync is done the page is moved to a pool and an active page
3991
  becomes "syncing".
3992
3993
  the result of such an architecture is a natural "commit grouping" -
3994
  If commits are coming faster than the system can sync, they do not
3995
  stall. Instead, all commit that came since the last sync are
3996
  logged to the same page, and they all are synced with the next -
3997
  one - sync. Thus, thought individual commits are delayed, throughput
3998
  is not decreasing.
3999
4000
  when a xid is added to an active page, the thread of this xid waits
4001
  for a page's condition until the page is synced. when syncing slot
4002
  becomes vacant one of these waiters is awaken to take care of syncing.
4003
  it syncs the page and signals all waiters that the page is synced.
4004
  PAGE::waiters is used to count these waiters, and a page may never
4005
  become active again until waiters==0 (that is all waiters from the
4006
  previous sync have noticed the sync was completed)
4007
4008
  note, that the page becomes "dirty" and has to be synced only when a
4009
  new xid is added into it. Removing a xid from a page does not make it
4010
  dirty - we don't sync removals to disk.
4011
*/
4012
4013
ulong tc_log_page_waits= 0;
4014
4015
#ifdef HAVE_MMAP
4016
4017
#define TC_LOG_HEADER_SIZE (sizeof(tc_log_magic)+1)
4018
4019
static const char tc_log_magic[]={(char) 254, 0x23, 0x05, 0x74};
4020
4021
ulong opt_tc_log_size= TC_LOG_MIN_SIZE;
4022
ulong tc_log_max_pages_used=0, tc_log_page_size=0, tc_log_cur_pages_used=0;
4023
4024
int TC_LOG_MMAP::open(const char *opt_name)
4025
{
4026
  uint i;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4027
  bool crashed= false;
1 by brian
clean slate
4028
  PAGE *pg;
4029
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4030
  assert(total_ha_2pc > 1);
4031
  assert(opt_name && opt_name[0]);
1 by brian
clean slate
4032
236.1.53 by Monty Taylor
Made getpagesize an automake compat LIBOBJ.
4033
  tc_log_page_size= getpagesize();
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4034
  assert(TC_LOG_PAGE_SIZE % tc_log_page_size == 0);
1 by brian
clean slate
4035
4036
  fn_format(logname,opt_name,mysql_data_home,"",MY_UNPACK_FILENAME);
4037
  if ((fd= my_open(logname, O_RDWR, MYF(0))) < 0)
4038
  {
4039
    if (my_errno != ENOENT)
4040
      goto err;
4041
    if (using_heuristic_recover())
4042
      return 1;
4043
    if ((fd= my_create(logname, CREATE_MODE, O_RDWR, MYF(MY_WME))) < 0)
4044
      goto err;
4045
    inited=1;
4046
    file_length= opt_tc_log_size;
30 by Brian Aker
Large file and ftruncate() support
4047
    if (ftruncate(fd, file_length))
1 by brian
clean slate
4048
      goto err;
4049
  }
4050
  else
4051
  {
4052
    inited= 1;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4053
    crashed= true;
338 by Monty Taylor
Tagged more strings.
4054
    sql_print_information(_("Recovering after a crash using %s"), opt_name);
1 by brian
clean slate
4055
    if (tc_heuristic_recover)
4056
    {
338 by Monty Taylor
Tagged more strings.
4057
      sql_print_error(_("Cannot perform automatic crash recovery when "
4058
                      "--tc-heuristic-recover is used"));
1 by brian
clean slate
4059
      goto err;
4060
    }
4061
    file_length= my_seek(fd, 0L, MY_SEEK_END, MYF(MY_WME+MY_FAE));
4062
    if (file_length == MY_FILEPOS_ERROR || file_length % tc_log_page_size)
4063
      goto err;
4064
  }
4065
4066
  data= (uchar *)my_mmap(0, (size_t)file_length, PROT_READ|PROT_WRITE,
4067
                        MAP_NOSYNC|MAP_SHARED, fd, 0);
4068
  if (data == MAP_FAILED)
4069
  {
4070
    my_errno=errno;
4071
    goto err;
4072
  }
4073
  inited=2;
4074
4075
  npages=(uint)file_length/tc_log_page_size;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4076
  assert(npages >= 3);             // to guarantee non-empty pool
1 by brian
clean slate
4077
  if (!(pages=(PAGE *)my_malloc(npages*sizeof(PAGE), MYF(MY_WME|MY_ZEROFILL))))
4078
    goto err;
4079
  inited=3;
4080
  for (pg=pages, i=0; i < npages; i++, pg++)
4081
  {
4082
    pg->next=pg+1;
4083
    pg->waiters=0;
4084
    pg->state=POOL;
4085
    pthread_mutex_init(&pg->lock, MY_MUTEX_INIT_FAST);
4086
    pthread_cond_init (&pg->cond, 0);
4087
    pg->start=(my_xid *)(data + i*tc_log_page_size);
4088
    pg->ptr=pg->start;
4089
    pg->end=(my_xid *)(pg->start + tc_log_page_size);
4090
    pg->size=pg->free=tc_log_page_size/sizeof(my_xid);
4091
  }
4092
  pages[0].size=pages[0].free=
4093
                (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid);
4094
  pages[0].start=pages[0].end-pages[0].size;
4095
  pages[npages-1].next=0;
4096
  inited=4;
4097
4098
  if (crashed && recover())
4099
      goto err;
4100
4101
  memcpy(data, tc_log_magic, sizeof(tc_log_magic));
4102
  data[sizeof(tc_log_magic)]= (uchar)total_ha_2pc;
15 by brian
Fix for stat, NETWARE removal
4103
  msync(data, tc_log_page_size, MS_SYNC);
4104
  my_sync(fd, MYF(0));
1 by brian
clean slate
4105
  inited=5;
4106
4107
  pthread_mutex_init(&LOCK_sync,    MY_MUTEX_INIT_FAST);
4108
  pthread_mutex_init(&LOCK_active,  MY_MUTEX_INIT_FAST);
4109
  pthread_mutex_init(&LOCK_pool,    MY_MUTEX_INIT_FAST);
4110
  pthread_cond_init(&COND_active, 0);
4111
  pthread_cond_init(&COND_pool, 0);
4112
4113
  inited=6;
4114
4115
  syncing= 0;
4116
  active=pages;
4117
  pool=pages+1;
4118
  pool_last=pages+npages-1;
4119
4120
  return 0;
4121
4122
err:
4123
  close();
4124
  return 1;
4125
}
4126
4127
/**
4128
  there is no active page, let's got one from the pool.
4129
4130
  Two strategies here:
4131
    -# take the first from the pool
4132
    -# if there're waiters - take the one with the most free space.
4133
4134
  @todo
4135
    TODO page merging. try to allocate adjacent page first,
4136
    so that they can be flushed both in one sync
4137
*/
4138
4139
void TC_LOG_MMAP::get_active_from_pool()
4140
{
4141
  PAGE **p, **best_p=0;
4142
  int best_free;
4143
4144
  if (syncing)
4145
    pthread_mutex_lock(&LOCK_pool);
4146
4147
  do
4148
  {
4149
    best_p= p= &pool;
4150
    if ((*p)->waiters == 0) // can the first page be used ?
4151
      break;                // yes - take it.
4152
4153
    best_free=0;            // no - trying second strategy
4154
    for (p=&(*p)->next; *p; p=&(*p)->next)
4155
    {
4156
      if ((*p)->waiters == 0 && (*p)->free > best_free)
4157
      {
4158
        best_free=(*p)->free;
4159
        best_p=p;
4160
      }
4161
    }
4162
  }
4163
  while ((*best_p == 0 || best_free == 0) && overflow());
4164
4165
  active=*best_p;
4166
  if (active->free == active->size) // we've chosen an empty page
4167
  {
4168
    tc_log_cur_pages_used++;
4169
    set_if_bigger(tc_log_max_pages_used, tc_log_cur_pages_used);
4170
  }
4171
4172
  if ((*best_p)->next)              // unlink the page from the pool
4173
    *best_p=(*best_p)->next;
4174
  else
4175
    pool_last=*best_p;
4176
4177
  if (syncing)
4178
    pthread_mutex_unlock(&LOCK_pool);
4179
}
4180
4181
/**
4182
  @todo
4183
  perhaps, increase log size ?
4184
*/
4185
int TC_LOG_MMAP::overflow()
4186
{
4187
  /*
4188
    simple overflow handling - just wait
4189
    TODO perhaps, increase log size ?
4190
    let's check the behaviour of tc_log_page_waits first
4191
  */
4192
  tc_log_page_waits++;
4193
  pthread_cond_wait(&COND_pool, &LOCK_pool);
4194
  return 1; // always return 1
4195
}
4196
4197
/**
4198
  Record that transaction XID is committed on the persistent storage.
4199
4200
    This function is called in the middle of two-phase commit:
4201
    First all resources prepare the transaction, then tc_log->log() is called,
4202
    then all resources commit the transaction, then tc_log->unlog() is called.
4203
4204
    All access to active page is serialized but it's not a problem, as
4205
    we're assuming that fsync() will be a main bottleneck.
4206
    That is, parallelizing writes to log pages we'll decrease number of
4207
    threads waiting for a page, but then all these threads will be waiting
4208
    for a fsync() anyway
4209
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
4210
   If tc_log == DRIZZLE_LOG then tc_log writes transaction to binlog and
1 by brian
clean slate
4211
   records XID in a special Xid_log_event.
4212
   If tc_log = TC_LOG_MMAP then xid is written in a special memory-mapped
4213
   log.
4214
4215
  @retval
4216
    0  - error
4217
  @retval
4218
    \# - otherwise, "cookie", a number that will be passed as an argument
4219
    to unlog() call. tc_log can define it any way it wants,
4220
    and use for whatever purposes. TC_LOG_MMAP sets it
4221
    to the position in memory where xid was logged to.
4222
*/
4223
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
4224
int TC_LOG_MMAP::log_xid(THD *thd __attribute__((unused)), my_xid xid)
1 by brian
clean slate
4225
{
4226
  int err;
4227
  PAGE *p;
4228
  ulong cookie;
4229
4230
  pthread_mutex_lock(&LOCK_active);
4231
4232
  /*
4233
    if active page is full - just wait...
4234
    frankly speaking, active->free here accessed outside of mutex
4235
    protection, but it's safe, because it only means we may miss an
4236
    unlog() for the active page, and we're not waiting for it here -
4237
    unlog() does not signal COND_active.
4238
  */
4239
  while (unlikely(active && active->free == 0))
4240
    pthread_cond_wait(&COND_active, &LOCK_active);
4241
4242
  /* no active page ? take one from the pool */
4243
  if (active == 0)
4244
    get_active_from_pool();
4245
4246
  p=active;
4247
  pthread_mutex_lock(&p->lock);
4248
4249
  /* searching for an empty slot */
4250
  while (*p->ptr)
4251
  {
4252
    p->ptr++;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4253
    assert(p->ptr < p->end);               // because p->free > 0
1 by brian
clean slate
4254
  }
4255
4256
  /* found! store xid there and mark the page dirty */
4257
  cookie= (ulong)((uchar *)p->ptr - data);      // can never be zero
4258
  *p->ptr++= xid;
4259
  p->free--;
4260
  p->state= DIRTY;
4261
4262
  /* to sync or not to sync - this is the question */
4263
  pthread_mutex_unlock(&LOCK_active);
4264
  pthread_mutex_lock(&LOCK_sync);
4265
  pthread_mutex_unlock(&p->lock);
4266
4267
  if (syncing)
4268
  {                                          // somebody's syncing. let's wait
4269
    p->waiters++;
4270
    /*
4271
      note - it must be while (), not do ... while () here
4272
      as p->state may be not DIRTY when we come here
4273
    */
4274
    while (p->state == DIRTY && syncing)
4275
      pthread_cond_wait(&p->cond, &LOCK_sync);
4276
    p->waiters--;
4277
    err= p->state == ERROR;
4278
    if (p->state != DIRTY)                   // page was synced
4279
    {
4280
      if (p->waiters == 0)
4281
        pthread_cond_signal(&COND_pool);     // in case somebody's waiting
4282
      pthread_mutex_unlock(&LOCK_sync);
4283
      goto done;                             // we're done
4284
    }
4285
  }                                          // page was not synced! do it now
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4286
  assert(active == p && syncing == 0);
1 by brian
clean slate
4287
  pthread_mutex_lock(&LOCK_active);
4288
  syncing=p;                                 // place is vacant - take it
4289
  active=0;                                  // page is not active anymore
4290
  pthread_cond_broadcast(&COND_active);      // in case somebody's waiting
4291
  pthread_mutex_unlock(&LOCK_active);
4292
  pthread_mutex_unlock(&LOCK_sync);
4293
  err= sync();
4294
4295
done:
4296
  return err ? 0 : cookie;
4297
}
4298
4299
int TC_LOG_MMAP::sync()
4300
{
4301
  int err;
4302
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4303
  assert(syncing != active);
1 by brian
clean slate
4304
4305
  /*
4306
    sit down and relax - this can take a while...
4307
    note - no locks are held at this point
4308
  */
15 by brian
Fix for stat, NETWARE removal
4309
  err= msync(syncing->start, 1, MS_SYNC);
4310
  if(err==0)
4311
    err= my_sync(fd, MYF(0));
1 by brian
clean slate
4312
4313
  /* page is synced. let's move it to the pool */
4314
  pthread_mutex_lock(&LOCK_pool);
4315
  pool_last->next=syncing;
4316
  pool_last=syncing;
4317
  syncing->next=0;
4318
  syncing->state= err ? ERROR : POOL;
4319
  pthread_cond_broadcast(&syncing->cond);    // signal "sync done"
4320
  pthread_cond_signal(&COND_pool);           // in case somebody's waiting
4321
  pthread_mutex_unlock(&LOCK_pool);
4322
4323
  /* marking 'syncing' slot free */
4324
  pthread_mutex_lock(&LOCK_sync);
4325
  syncing=0;
4326
  pthread_cond_signal(&active->cond);        // wake up a new syncer
4327
  pthread_mutex_unlock(&LOCK_sync);
4328
  return err;
4329
}
4330
4331
/**
4332
  erase xid from the page, update page free space counters/pointers.
4333
  cookie points directly to the memory where xid was logged.
4334
*/
4335
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
4336
void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid __attribute__((unused)))
1 by brian
clean slate
4337
{
4338
  PAGE *p=pages+(cookie/tc_log_page_size);
4339
  my_xid *x=(my_xid *)(data+cookie);
4340
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4341
  assert(*x == xid);
4342
  assert(x >= p->start && x < p->end);
1 by brian
clean slate
4343
  *x=0;
4344
4345
  pthread_mutex_lock(&p->lock);
4346
  p->free++;
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4347
  assert(p->free <= p->size);
1 by brian
clean slate
4348
  set_if_smaller(p->ptr, x);
4349
  if (p->free == p->size)               // the page is completely empty
4350
    statistic_decrement(tc_log_cur_pages_used, &LOCK_status);
4351
  if (p->waiters == 0)                 // the page is in pool and ready to rock
4352
    pthread_cond_signal(&COND_pool);   // ping ... for overflow()
4353
  pthread_mutex_unlock(&p->lock);
4354
}
4355
4356
void TC_LOG_MMAP::close()
4357
{
4358
  uint i;
4359
  switch (inited) {
4360
  case 6:
4361
    pthread_mutex_destroy(&LOCK_sync);
4362
    pthread_mutex_destroy(&LOCK_active);
4363
    pthread_mutex_destroy(&LOCK_pool);
4364
    pthread_cond_destroy(&COND_pool);
4365
  case 5:
4366
    data[0]='A'; // garble the first (signature) byte, in case my_delete fails
4367
  case 4:
4368
    for (i=0; i < npages; i++)
4369
    {
4370
      if (pages[i].ptr == 0)
4371
        break;
4372
      pthread_mutex_destroy(&pages[i].lock);
4373
      pthread_cond_destroy(&pages[i].cond);
4374
    }
4375
  case 3:
4376
    my_free((uchar*)pages, MYF(0));
4377
  case 2:
4378
    my_munmap((char*)data, (size_t)file_length);
4379
  case 1:
4380
    my_close(fd, MYF(0));
4381
  }
4382
  if (inited>=5) // cannot do in the switch because of Windows
4383
    my_delete(logname, MYF(MY_WME));
4384
  inited=0;
4385
}
4386
4387
int TC_LOG_MMAP::recover()
4388
{
4389
  HASH xids;
4390
  PAGE *p=pages, *end_p=pages+npages;
4391
4392
  if (memcmp(data, tc_log_magic, sizeof(tc_log_magic)))
4393
  {
338 by Monty Taylor
Tagged more strings.
4394
    sql_print_error(_("Bad magic header in tc log"));
1 by brian
clean slate
4395
    goto err1;
4396
  }
4397
4398
  /*
4399
    the first byte after magic signature is set to current
4400
    number of storage engines on startup
4401
  */
4402
  if (data[sizeof(tc_log_magic)] != total_ha_2pc)
4403
  {
338 by Monty Taylor
Tagged more strings.
4404
    sql_print_error(_("Recovery failed! You must enable "
1 by brian
clean slate
4405
                    "exactly %d storage engines that support "
338 by Monty Taylor
Tagged more strings.
4406
                    "two-phase commit protocol"),
1 by brian
clean slate
4407
                    data[sizeof(tc_log_magic)]);
4408
    goto err1;
4409
  }
4410
4411
  if (hash_init(&xids, &my_charset_bin, tc_log_page_size/3, 0,
4412
                sizeof(my_xid), 0, 0, MYF(0)))
4413
    goto err1;
4414
4415
  for ( ; p < end_p ; p++)
4416
  {
4417
    for (my_xid *x=p->start; x < p->end; x++)
4418
      if (*x && my_hash_insert(&xids, (uchar *)x))
4419
        goto err2; // OOM
4420
  }
4421
4422
  if (ha_recover(&xids))
4423
    goto err2;
4424
4425
  hash_free(&xids);
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
4426
  memset(data, 0, (size_t)file_length);
1 by brian
clean slate
4427
  return 0;
4428
4429
err2:
4430
  hash_free(&xids);
4431
err1:
338 by Monty Taylor
Tagged more strings.
4432
  sql_print_error(_("Crash recovery failed. Either correct the problem "
1 by brian
clean slate
4433
                  "(if it's, for example, out of memory error) and restart, "
338 by Monty Taylor
Tagged more strings.
4434
                  "or delete tc log and start drizzled with "
4435
                  "--tc-heuristic-recover={commit|rollback}"));
1 by brian
clean slate
4436
  return 1;
4437
}
4438
#endif
4439
4440
TC_LOG *tc_log;
4441
TC_LOG_DUMMY tc_log_dummy;
4442
TC_LOG_MMAP  tc_log_mmap;
4443
4444
/**
4445
  Perform heuristic recovery, if --tc-heuristic-recover was used.
4446
4447
  @note
4448
    no matter whether heuristic recovery was successful or not
4449
    mysqld must exit. So, return value is the same in both cases.
4450
4451
  @retval
4452
    0	no heuristic recovery was requested
4453
  @retval
4454
    1   heuristic recovery was performed
4455
*/
4456
4457
int TC_LOG::using_heuristic_recover()
4458
{
4459
  if (!tc_heuristic_recover)
4460
    return 0;
4461
338 by Monty Taylor
Tagged more strings.
4462
  sql_print_information(_("Heuristic crash recovery mode"));
1 by brian
clean slate
4463
  if (ha_recover(0))
338 by Monty Taylor
Tagged more strings.
4464
    sql_print_error(_("Heuristic crash recovery failed"));
4465
  sql_print_information(_("Please restart mysqld without --tc-heuristic-recover"));
1 by brian
clean slate
4466
  return 1;
4467
}
4468
4469
/****** transaction coordinator log for 2pc - binlog() based solution ******/
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
4470
#define TC_LOG_BINLOG DRIZZLE_BIN_LOG
1 by brian
clean slate
4471
4472
/**
4473
  @todo
4474
  keep in-memory list of prepared transactions
4475
  (add to list in log(), remove on unlog())
4476
  and copy it to the new binlog if rotated
4477
  but let's check the behaviour of tc_log_page_waits first!
4478
*/
4479
4480
int TC_LOG_BINLOG::open(const char *opt_name)
4481
{
4482
  LOG_INFO log_info;
4483
  int      error= 1;
4484
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4485
  assert(total_ha_2pc > 1);
4486
  assert(opt_name && opt_name[0]);
1 by brian
clean slate
4487
4488
  pthread_mutex_init(&LOCK_prep_xids, MY_MUTEX_INIT_FAST);
4489
  pthread_cond_init (&COND_prep_xids, 0);
4490
4491
  if (!my_b_inited(&index_file))
4492
  {
4493
    /* There was a failure to open the index file, can't open the binlog */
4494
    cleanup();
4495
    return 1;
4496
  }
4497
4498
  if (using_heuristic_recover())
4499
  {
4500
    /* generate a new binlog to mask a corrupted one */
4501
    open(opt_name, LOG_BIN, 0, WRITE_CACHE, 0, max_binlog_size, 0);
4502
    cleanup();
4503
    return 1;
4504
  }
4505
4506
  if ((error= find_log_pos(&log_info, NullS, 1)))
4507
  {
4508
    if (error != LOG_INFO_EOF)
338 by Monty Taylor
Tagged more strings.
4509
      sql_print_error(_("find_log_pos() failed (error: %d)"), error);
1 by brian
clean slate
4510
    else
4511
      error= 0;
4512
    goto err;
4513
  }
4514
4515
  {
4516
    const char *errmsg;
4517
    IO_CACHE    log;
4518
    File        file;
4519
    Log_event  *ev=0;
4520
    Format_description_log_event fdle(BINLOG_VERSION);
4521
    char        log_name[FN_REFLEN];
4522
4523
    if (! fdle.is_valid())
4524
      goto err;
4525
4526
    do
4527
    {
4528
      strmake(log_name, log_info.log_file_name, sizeof(log_name)-1);
4529
    } while (!(error= find_next_log(&log_info, 1)));
4530
4531
    if (error !=  LOG_INFO_EOF)
4532
    {
338 by Monty Taylor
Tagged more strings.
4533
      sql_print_error(_("find_log_pos() failed (error: %d)"), error);
1 by brian
clean slate
4534
      goto err;
4535
    }
4536
4537
    if ((file= open_binlog(&log, log_name, &errmsg)) < 0)
4538
    {
4539
      sql_print_error("%s", errmsg);
4540
      goto err;
4541
    }
4542
4543
    if ((ev= Log_event::read_log_event(&log, 0, &fdle)) &&
4544
        ev->get_type_code() == FORMAT_DESCRIPTION_EVENT &&
4545
        ev->flags & LOG_EVENT_BINLOG_IN_USE_F)
4546
    {
338 by Monty Taylor
Tagged more strings.
4547
      sql_print_information(_("Recovering after a crash using %s"), opt_name);
1 by brian
clean slate
4548
      error= recover(&log, (Format_description_log_event *)ev);
4549
    }
4550
    else
4551
      error=0;
4552
4553
    delete ev;
4554
    end_io_cache(&log);
4555
    my_close(file, MYF(MY_WME));
4556
4557
    if (error)
4558
      goto err;
4559
  }
4560
4561
err:
4562
  return error;
4563
}
4564
4565
/** This is called on shutdown, after ha_panic. */
4566
void TC_LOG_BINLOG::close()
4567
{
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4568
  assert(prepared_xids==0);
1 by brian
clean slate
4569
  pthread_mutex_destroy(&LOCK_prep_xids);
4570
  pthread_cond_destroy (&COND_prep_xids);
4571
}
4572
4573
/**
4574
  @todo
4575
  group commit
4576
4577
  @retval
4578
    0    error
4579
  @retval
4580
    1    success
4581
*/
4582
int TC_LOG_BINLOG::log_xid(THD *thd, my_xid xid)
4583
{
4584
  Xid_log_event xle(thd, xid);
4585
  binlog_trx_data *trx_data=
4586
    (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton);
4587
  /*
4588
    We always commit the entire transaction when writing an XID. Also
4589
    note that the return value is inverted.
4590
   */
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4591
  return(!binlog_end_trans(thd, trx_data, &xle, true));
1 by brian
clean slate
4592
}
4593
212.3.1 by Jay Pipes
Fix for Bug#252309 "log output to tables is enabled but ineffective".
4594
void TC_LOG_BINLOG::unlog(ulong cookie __attribute__((unused)),
4595
                          my_xid xid __attribute__((unused)))
1 by brian
clean slate
4596
{
4597
  pthread_mutex_lock(&LOCK_prep_xids);
51.1.29 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4598
  assert(prepared_xids > 0);
1 by brian
clean slate
4599
  if (--prepared_xids == 0) {
4600
    pthread_cond_signal(&COND_prep_xids);
4601
  }
4602
  pthread_mutex_unlock(&LOCK_prep_xids);
4603
  rotate_and_purge(0);     // as ::write() did not rotate
4604
}
4605
4606
int TC_LOG_BINLOG::recover(IO_CACHE *log, Format_description_log_event *fdle)
4607
{
4608
  Log_event  *ev;
4609
  HASH xids;
4610
  MEM_ROOT mem_root;
4611
4612
  if (! fdle->is_valid() ||
4613
      hash_init(&xids, &my_charset_bin, TC_LOG_PAGE_SIZE/3, 0,
4614
                sizeof(my_xid), 0, 0, MYF(0)))
4615
    goto err1;
4616
4617
  init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE);
4618
4619
  fdle->flags&= ~LOG_EVENT_BINLOG_IN_USE_F; // abort on the first error
4620
4621
  while ((ev= Log_event::read_log_event(log,0,fdle)) && ev->is_valid())
4622
  {
4623
    if (ev->get_type_code() == XID_EVENT)
4624
    {
4625
      Xid_log_event *xev=(Xid_log_event *)ev;
4626
      uchar *x= (uchar *) memdup_root(&mem_root, (uchar*) &xev->xid,
4627
                                      sizeof(xev->xid));
4628
      if (! x)
4629
        goto err2;
4630
      my_hash_insert(&xids, x);
4631
    }
4632
    delete ev;
4633
  }
4634
4635
  if (ha_recover(&xids))
4636
    goto err2;
4637
4638
  free_root(&mem_root, MYF(0));
4639
  hash_free(&xids);
4640
  return 0;
4641
4642
err2:
4643
  free_root(&mem_root, MYF(0));
4644
  hash_free(&xids);
4645
err1:
338 by Monty Taylor
Tagged more strings.
4646
  sql_print_error(_("Crash recovery failed. Either correct the problem "
1 by brian
clean slate
4647
                  "(if it's, for example, out of memory error) and restart, "
4648
                  "or delete (or rename) binary log and start mysqld with "
338 by Monty Taylor
Tagged more strings.
4649
                  "--tc-heuristic-recover={commit|rollback}"));
1 by brian
clean slate
4650
  return 1;
4651
}
4652
4653
4654
#ifdef INNODB_COMPATIBILITY_HOOKS
4655
/**
4656
  Get the file name of the MySQL binlog.
4657
  @return the name of the binlog file
4658
*/
4659
extern "C"
4660
const char* mysql_bin_log_file_name(void)
4661
{
4662
  return mysql_bin_log.get_log_fname();
4663
}
4664
/**
4665
  Get the current position of the MySQL binlog.
4666
  @return byte offset from the beginning of the binlog
4667
*/
4668
extern "C"
151 by Brian Aker
Ulonglong to uint64_t
4669
uint64_t mysql_bin_log_file_pos(void)
1 by brian
clean slate
4670
{
151 by Brian Aker
Ulonglong to uint64_t
4671
  return (uint64_t) mysql_bin_log.get_log_file()->pos_in_file;
1 by brian
clean slate
4672
}
4673
#endif /* INNODB_COMPATIBILITY_HOOKS */
4674
4675
4676
mysql_declare_plugin(binlog)
4677
{
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
4678
  DRIZZLE_STORAGE_ENGINE_PLUGIN,
1 by brian
clean slate
4679
  "binlog",
177.4.3 by mark
ripped out more plugin ABI and API version checking, and plugin versions are now strings
4680
  "1.0",
1 by brian
clean slate
4681
  "MySQL AB",
4682
  "This is a pseudo storage engine to represent the binlog in a transaction",
4683
  PLUGIN_LICENSE_GPL,
4684
  binlog_init, /* Plugin Init */
4685
  NULL, /* Plugin Deinit */
4686
  NULL,                       /* status variables                */
4687
  NULL,                       /* system variables                */
4688
  NULL                        /* config options                  */
4689
}
4690
mysql_declare_plugin_end;