You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3103 lines
86 KiB

22 years ago
26 years ago
22 years ago
26 years ago
22 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
21 years ago
21 years ago
26 years ago
22 years ago
22 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
23 years ago
21 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
22 years ago
25 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
21 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
22 years ago
26 years ago
26 years ago
23 years ago
23 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
25 years ago
26 years ago
25 years ago
26 years ago
26 years ago
25 years ago
26 years ago
25 years ago
26 years ago
26 years ago
26 years ago
26 years ago
19 years ago
19 years ago
26 years ago
26 years ago
26 years ago
23 years ago
23 years ago
23 years ago
21 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
23 years ago
22 years ago
21 years ago
22 years ago
22 years ago
22 years ago
22 years ago
22 years ago
22 years ago
22 years ago
21 years ago
  1. /* Copyright (C) 2000-2003 MySQL AB
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; version 2 of the License.
  5. This program is distributed in the hope that it will be useful,
  6. but WITHOUT ANY WARRANTY; without even the implied warranty of
  7. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8. GNU General Public License for more details.
  9. You should have received a copy of the GNU General Public License
  10. along with this program; if not, write to the Free Software
  11. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
  12. /* logging of commands */
  13. /* TODO: Abort logging when we get an error in reading or writing log files */
  14. #ifdef __EMX__
  15. #include <io.h>
  16. #endif
  17. #include "mysql_priv.h"
  18. #include "sql_repl.h"
  19. #include <my_dir.h>
  20. #include <stdarg.h>
  21. #include <m_ctype.h> // For test_if_number
  22. #ifdef __NT__
  23. #include "message.h"
  24. #endif
  25. MYSQL_LOG mysql_log, mysql_slow_log, mysql_bin_log;
  26. ulong sync_binlog_counter= 0;
  27. static Muted_query_log_event invisible_commit;
  28. static bool test_if_number(const char *str,
  29. long *res, bool allow_wildcards);
  30. static bool binlog_init();
  31. static int binlog_close_connection(THD *thd);
  32. static int binlog_savepoint_set(THD *thd, void *sv);
  33. static int binlog_savepoint_rollback(THD *thd, void *sv);
  34. static int binlog_commit(THD *thd, bool all);
  35. static int binlog_rollback(THD *thd, bool all);
  36. static int binlog_prepare(THD *thd, bool all);
  37. handlerton binlog_hton = {
  38. "binlog",
  39. SHOW_OPTION_YES,
  40. "This is a meta storage engine to represent the binlog in a transaction",
  41. DB_TYPE_UNKNOWN, /* IGNORE for now */
  42. binlog_init,
  43. 0,
  44. sizeof(my_off_t), /* savepoint size = binlog offset */
  45. binlog_close_connection,
  46. binlog_savepoint_set,
  47. binlog_savepoint_rollback,
  48. NULL, /* savepoint_release */
  49. binlog_commit,
  50. binlog_rollback,
  51. binlog_prepare,
  52. NULL, /* recover */
  53. NULL, /* commit_by_xid */
  54. NULL, /* rollback_by_xid */
  55. NULL, /* create_cursor_read_view */
  56. NULL, /* set_cursor_read_view */
  57. NULL, /* close_cursor_read_view */
  58. HTON_HIDDEN
  59. };
  60. /*
  61. this function is mostly a placeholder.
  62. conceptually, binlog initialization (now mostly done in MYSQL_LOG::open)
  63. should be moved here.
  64. */
  65. bool binlog_init()
  66. {
  67. return !opt_bin_log;
  68. }
  69. static int binlog_close_connection(THD *thd)
  70. {
  71. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  72. DBUG_ASSERT(mysql_bin_log.is_open() && !my_b_tell(trans_log));
  73. close_cached_file(trans_log);
  74. my_free((gptr)trans_log, MYF(0));
  75. return 0;
  76. }
  77. static int binlog_end_trans(THD *thd, IO_CACHE *trans_log, Log_event *end_ev)
  78. {
  79. int error=0;
  80. DBUG_ENTER("binlog_end_trans");
  81. /* NULL denotes ROLLBACK with nothing to replicate */
  82. if (end_ev != NULL)
  83. error= mysql_bin_log.write(thd, trans_log, end_ev);
  84. statistic_increment(binlog_cache_use, &LOCK_status);
  85. if (trans_log->disk_writes != 0)
  86. {
  87. statistic_increment(binlog_cache_disk_use, &LOCK_status);
  88. trans_log->disk_writes= 0;
  89. }
  90. reinit_io_cache(trans_log, WRITE_CACHE, (my_off_t) 0, 0, 1); // cannot fail
  91. trans_log->end_of_file= max_binlog_cache_size;
  92. DBUG_RETURN(error);
  93. }
  94. static int binlog_prepare(THD *thd, bool all)
  95. {
  96. /*
  97. do nothing.
  98. just pretend we can do 2pc, so that MySQL won't
  99. switch to 1pc.
  100. real work will be done in MYSQL_LOG::log_xid()
  101. */
  102. return 0;
  103. }
  104. static int binlog_commit(THD *thd, bool all)
  105. {
  106. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  107. DBUG_ENTER("binlog_commit");
  108. DBUG_ASSERT(mysql_bin_log.is_open() &&
  109. (all || !(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))));
  110. if (my_b_tell(trans_log) == 0)
  111. {
  112. // we're here because trans_log was flushed in MYSQL_LOG::log_xid()
  113. DBUG_RETURN(0);
  114. }
  115. if (all)
  116. {
  117. Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, FALSE);
  118. qev.error_code= 0; // see comment in MYSQL_LOG::write(THD, IO_CACHE)
  119. DBUG_RETURN(binlog_end_trans(thd, trans_log, &qev));
  120. }
  121. else
  122. DBUG_RETURN(binlog_end_trans(thd, trans_log, &invisible_commit));
  123. }
  124. static int binlog_rollback(THD *thd, bool all)
  125. {
  126. int error=0;
  127. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  128. DBUG_ENTER("binlog_rollback");
  129. /*
  130. First assert is guaranteed - see trans_register_ha() call below.
  131. The second must be true. If it is not, we're registering
  132. unnecessary, doing extra work. The cause should be found and eliminated
  133. */
  134. DBUG_ASSERT(all || !(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)));
  135. DBUG_ASSERT(mysql_bin_log.is_open() && my_b_tell(trans_log));
  136. /*
  137. Update the binary log with a BEGIN/ROLLBACK block if we have
  138. cached some queries and we updated some non-transactional
  139. table. Such cases should be rare (updating a
  140. non-transactional table inside a transaction...)
  141. */
  142. if (unlikely(thd->no_trans_update.all))
  143. {
  144. Query_log_event qev(thd, STRING_WITH_LEN("ROLLBACK"), TRUE, FALSE);
  145. qev.error_code= 0; // see comment in MYSQL_LOG::write(THD, IO_CACHE)
  146. error= binlog_end_trans(thd, trans_log, &qev);
  147. }
  148. else
  149. error= binlog_end_trans(thd, trans_log, 0);
  150. DBUG_RETURN(error);
  151. }
  152. /*
  153. NOTE: how do we handle this (unlikely but legal) case:
  154. [transaction] + [update to non-trans table] + [rollback to savepoint] ?
  155. The problem occurs when a savepoint is before the update to the
  156. non-transactional table. Then when there's a rollback to the savepoint, if we
  157. simply truncate the binlog cache, we lose the part of the binlog cache where
  158. the update is. If we want to not lose it, we need to write the SAVEPOINT
  159. command and the ROLLBACK TO SAVEPOINT command to the binlog cache. The latter
  160. is easy: it's just write at the end of the binlog cache, but the former
  161. should be *inserted* to the place where the user called SAVEPOINT. The
  162. solution is that when the user calls SAVEPOINT, we write it to the binlog
  163. cache (so no need to later insert it). As transactions are never intermixed
  164. in the binary log (i.e. they are serialized), we won't have conflicts with
  165. savepoint names when using mysqlbinlog or in the slave SQL thread.
  166. Then when ROLLBACK TO SAVEPOINT is called, if we updated some
  167. non-transactional table, we don't truncate the binlog cache but instead write
  168. ROLLBACK TO SAVEPOINT to it; otherwise we truncate the binlog cache (which
  169. will chop the SAVEPOINT command from the binlog cache, which is good as in
  170. that case there is no need to have it in the binlog).
  171. */
  172. static int binlog_savepoint_set(THD *thd, void *sv)
  173. {
  174. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  175. DBUG_ENTER("binlog_savepoint_set");
  176. DBUG_ASSERT(mysql_bin_log.is_open() && my_b_tell(trans_log));
  177. *(my_off_t *)sv= my_b_tell(trans_log);
  178. /* Write it to the binary log */
  179. Query_log_event qinfo(thd, thd->query, thd->query_length, TRUE, FALSE);
  180. DBUG_RETURN(mysql_bin_log.write(&qinfo));
  181. }
  182. static int binlog_savepoint_rollback(THD *thd, void *sv)
  183. {
  184. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  185. DBUG_ENTER("binlog_savepoint_rollback");
  186. DBUG_ASSERT(mysql_bin_log.is_open() && my_b_tell(trans_log));
  187. /*
  188. Write ROLLBACK TO SAVEPOINT to the binlog cache if we have updated some
  189. non-transactional table. Otherwise, truncate the binlog cache starting
  190. from the SAVEPOINT command.
  191. */
  192. if (unlikely(thd->no_trans_update.all))
  193. {
  194. Query_log_event qinfo(thd, thd->query, thd->query_length, TRUE, FALSE);
  195. DBUG_RETURN(mysql_bin_log.write(&qinfo));
  196. }
  197. reinit_io_cache(trans_log, WRITE_CACHE, *(my_off_t *)sv, 0, 0);
  198. DBUG_RETURN(0);
  199. }
  200. int check_binlog_magic(IO_CACHE* log, const char** errmsg)
  201. {
  202. char magic[4];
  203. DBUG_ASSERT(my_b_tell(log) == 0);
  204. if (my_b_read(log, (byte*) magic, sizeof(magic)))
  205. {
  206. *errmsg = "I/O error reading the header from the binary log";
  207. sql_print_error("%s, errno=%d, io cache code=%d", *errmsg, my_errno,
  208. log->error);
  209. return 1;
  210. }
  211. if (memcmp(magic, BINLOG_MAGIC, sizeof(magic)))
  212. {
  213. *errmsg = "Binlog has bad magic number; It's not a binary log file that can be used by this version of MySQL";
  214. return 1;
  215. }
  216. return 0;
  217. }
  218. File open_binlog(IO_CACHE *log, const char *log_file_name, const char **errmsg)
  219. {
  220. File file;
  221. DBUG_ENTER("open_binlog");
  222. if ((file = my_open(log_file_name, O_RDONLY | O_BINARY | O_SHARE,
  223. MYF(MY_WME))) < 0)
  224. {
  225. sql_print_error("Failed to open log (file '%s', errno %d)",
  226. log_file_name, my_errno);
  227. *errmsg = "Could not open log file";
  228. goto err;
  229. }
  230. if (init_io_cache(log, file, IO_SIZE*2, READ_CACHE, 0, 0,
  231. MYF(MY_WME|MY_DONT_CHECK_FILESIZE)))
  232. {
  233. sql_print_error("Failed to create a cache on log (file '%s')",
  234. log_file_name);
  235. *errmsg = "Could not open log file";
  236. goto err;
  237. }
  238. if (check_binlog_magic(log,errmsg))
  239. goto err;
  240. DBUG_RETURN(file);
  241. err:
  242. if (file >= 0)
  243. {
  244. my_close(file,MYF(0));
  245. end_io_cache(log);
  246. }
  247. DBUG_RETURN(-1);
  248. }
  249. #ifdef __NT__
  250. static int eventSource = 0;
  251. static void setup_windows_event_source()
  252. {
  253. HKEY hRegKey= NULL;
  254. DWORD dwError= 0;
  255. TCHAR szPath[MAX_PATH];
  256. DWORD dwTypes;
  257. if (eventSource) // Ensure that we are only called once
  258. return;
  259. eventSource= 1;
  260. // Create the event source registry key
  261. dwError= RegCreateKey(HKEY_LOCAL_MACHINE,
  262. "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\MySQL",
  263. &hRegKey);
  264. /* Name of the PE module that contains the message resource */
  265. GetModuleFileName(NULL, szPath, MAX_PATH);
  266. /* Register EventMessageFile */
  267. dwError = RegSetValueEx(hRegKey, "EventMessageFile", 0, REG_EXPAND_SZ,
  268. (PBYTE) szPath, (DWORD) (strlen(szPath) + 1));
  269. /* Register supported event types */
  270. dwTypes= (EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
  271. EVENTLOG_INFORMATION_TYPE);
  272. dwError= RegSetValueEx(hRegKey, "TypesSupported", 0, REG_DWORD,
  273. (LPBYTE) &dwTypes, sizeof dwTypes);
  274. RegCloseKey(hRegKey);
  275. }
  276. #endif /* __NT__ */
  277. /****************************************************************************
  278. ** Find a uniq filename for 'filename.#'.
  279. ** Set # to a number as low as possible
  280. ** returns != 0 if not possible to get uniq filename
  281. ****************************************************************************/
  282. static int find_uniq_filename(char *name)
  283. {
  284. long number;
  285. uint i;
  286. char buff[FN_REFLEN];
  287. struct st_my_dir *dir_info;
  288. reg1 struct fileinfo *file_info;
  289. ulong max_found=0;
  290. DBUG_ENTER("find_uniq_filename");
  291. uint length = dirname_part(buff,name);
  292. char *start = name + length;
  293. char *end = strend(start);
  294. *end='.';
  295. length= (uint) (end-start+1);
  296. if (!(dir_info = my_dir(buff,MYF(MY_DONT_SORT))))
  297. { // This shouldn't happen
  298. strmov(end,".1"); // use name+1
  299. DBUG_RETURN(0);
  300. }
  301. file_info= dir_info->dir_entry;
  302. for (i=dir_info->number_off_files ; i-- ; file_info++)
  303. {
  304. if (bcmp(file_info->name,start,length) == 0 &&
  305. test_if_number(file_info->name+length, &number,0))
  306. {
  307. set_if_bigger(max_found,(ulong) number);
  308. }
  309. }
  310. my_dirend(dir_info);
  311. *end++='.';
  312. sprintf(end,"%06ld",max_found+1);
  313. DBUG_RETURN(0);
  314. }
  315. MYSQL_LOG::MYSQL_LOG()
  316. :bytes_written(0), last_time(0), query_start(0), name(0),
  317. prepared_xids(0), log_type(LOG_CLOSED), file_id(1), open_count(1),
  318. write_error(FALSE), inited(FALSE), need_start_event(TRUE),
  319. description_event_for_exec(0), description_event_for_queue(0)
  320. {
  321. /*
  322. We don't want to initialize LOCK_Log here as such initialization depends on
  323. safe_mutex (when using safe_mutex) which depends on MY_INIT(), which is
  324. called only in main(). Doing initialization here would make it happen
  325. before main().
  326. */
  327. index_file_name[0] = 0;
  328. bzero((char*) &log_file,sizeof(log_file));
  329. bzero((char*) &index_file, sizeof(index_file));
  330. }
  331. /* this is called only once */
  332. void MYSQL_LOG::cleanup()
  333. {
  334. DBUG_ENTER("cleanup");
  335. if (inited)
  336. {
  337. inited= 0;
  338. close(LOG_CLOSE_INDEX|LOG_CLOSE_STOP_EVENT);
  339. delete description_event_for_queue;
  340. delete description_event_for_exec;
  341. (void) pthread_mutex_destroy(&LOCK_log);
  342. (void) pthread_mutex_destroy(&LOCK_index);
  343. (void) pthread_cond_destroy(&update_cond);
  344. }
  345. DBUG_VOID_RETURN;
  346. }
  347. int MYSQL_LOG::generate_new_name(char *new_name, const char *log_name)
  348. {
  349. fn_format(new_name,log_name,mysql_data_home,"",4);
  350. if (log_type != LOG_NORMAL)
  351. {
  352. if (!fn_ext(log_name)[0])
  353. {
  354. if (find_uniq_filename(new_name))
  355. {
  356. sql_print_error(ER(ER_NO_UNIQUE_LOGFILE), log_name);
  357. return 1;
  358. }
  359. }
  360. }
  361. return 0;
  362. }
  363. void MYSQL_LOG::init(enum_log_type log_type_arg,
  364. enum cache_type io_cache_type_arg,
  365. bool no_auto_events_arg,
  366. ulong max_size_arg)
  367. {
  368. DBUG_ENTER("MYSQL_LOG::init");
  369. log_type = log_type_arg;
  370. io_cache_type = io_cache_type_arg;
  371. no_auto_events = no_auto_events_arg;
  372. max_size=max_size_arg;
  373. DBUG_PRINT("info",("log_type: %d max_size: %lu", log_type, max_size));
  374. DBUG_VOID_RETURN;
  375. }
  376. void MYSQL_LOG::init_pthread_objects()
  377. {
  378. DBUG_ASSERT(inited == 0);
  379. inited= 1;
  380. (void) pthread_mutex_init(&LOCK_log,MY_MUTEX_INIT_SLOW);
  381. (void) pthread_mutex_init(&LOCK_index, MY_MUTEX_INIT_SLOW);
  382. (void) pthread_cond_init(&update_cond, 0);
  383. }
  384. const char *MYSQL_LOG::generate_name(const char *log_name,
  385. const char *suffix,
  386. bool strip_ext, char *buff)
  387. {
  388. if (!log_name || !log_name[0])
  389. {
  390. /*
  391. TODO: The following should be using fn_format(); We just need to
  392. first change fn_format() to cut the file name if it's too long.
  393. */
  394. strmake(buff, pidfile_name,FN_REFLEN-5);
  395. strmov(fn_ext(buff),suffix);
  396. return (const char *)buff;
  397. }
  398. // get rid of extension if the log is binary to avoid problems
  399. if (strip_ext)
  400. {
  401. char *p = fn_ext(log_name);
  402. uint length=(uint) (p-log_name);
  403. strmake(buff,log_name,min(length,FN_REFLEN));
  404. return (const char*)buff;
  405. }
  406. return log_name;
  407. }
  408. bool MYSQL_LOG::open_index_file(const char *index_file_name_arg,
  409. const char *log_name)
  410. {
  411. File index_file_nr= -1;
  412. DBUG_ASSERT(!my_b_inited(&index_file));
  413. /*
  414. First open of this class instance
  415. Create an index file that will hold all file names uses for logging.
  416. Add new entries to the end of it.
  417. */
  418. myf opt= MY_UNPACK_FILENAME;
  419. if (!index_file_name_arg)
  420. {
  421. index_file_name_arg= log_name; // Use same basename for index file
  422. opt= MY_UNPACK_FILENAME | MY_REPLACE_EXT;
  423. }
  424. fn_format(index_file_name, index_file_name_arg, mysql_data_home,
  425. ".index", opt);
  426. if ((index_file_nr= my_open(index_file_name,
  427. O_RDWR | O_CREAT | O_BINARY ,
  428. MYF(MY_WME))) < 0 ||
  429. my_sync(index_file_nr, MYF(MY_WME)) ||
  430. init_io_cache(&index_file, index_file_nr,
  431. IO_SIZE, WRITE_CACHE,
  432. my_seek(index_file_nr,0L,MY_SEEK_END,MYF(0)),
  433. 0, MYF(MY_WME | MY_WAIT_IF_FULL)))
  434. {
  435. if (index_file_nr >= 0)
  436. my_close(index_file_nr,MYF(0));
  437. return TRUE;
  438. }
  439. return FALSE;
  440. }
  441. /*
  442. Open a (new) log file.
  443. DESCRIPTION
  444. - If binary logs, also open the index file and register the new
  445. file name in it
  446. - When calling this when the file is in use, you must have a locks
  447. on LOCK_log and LOCK_index.
  448. RETURN VALUES
  449. 0 ok
  450. 1 error
  451. */
  452. bool MYSQL_LOG::open(const char *log_name,
  453. enum_log_type log_type_arg,
  454. const char *new_name,
  455. enum cache_type io_cache_type_arg,
  456. bool no_auto_events_arg,
  457. ulong max_size_arg,
  458. bool null_created_arg)
  459. {
  460. char buff[FN_REFLEN];
  461. File file= -1;
  462. int open_flags = O_CREAT | O_BINARY;
  463. DBUG_ENTER("MYSQL_LOG::open");
  464. DBUG_PRINT("enter",("log_type: %d",(int) log_type_arg));
  465. last_time=query_start=0;
  466. write_error=0;
  467. init(log_type_arg,io_cache_type_arg,no_auto_events_arg,max_size_arg);
  468. if (!(name=my_strdup(log_name,MYF(MY_WME))))
  469. {
  470. name= (char *)log_name; // for the error message
  471. goto err;
  472. }
  473. if (new_name)
  474. strmov(log_file_name,new_name);
  475. else if (generate_new_name(log_file_name, name))
  476. goto err;
  477. if (io_cache_type == SEQ_READ_APPEND)
  478. open_flags |= O_RDWR | O_APPEND;
  479. else
  480. open_flags |= O_WRONLY | (log_type == LOG_BIN ? 0 : O_APPEND);
  481. db[0]=0;
  482. open_count++;
  483. if ((file=my_open(log_file_name,open_flags,
  484. MYF(MY_WME | ME_WAITTANG))) < 0 ||
  485. init_io_cache(&log_file, file, IO_SIZE, io_cache_type,
  486. my_tell(file,MYF(MY_WME)), 0,
  487. MYF(MY_WME | MY_NABP |
  488. ((log_type == LOG_BIN) ? MY_WAIT_IF_FULL : 0))))
  489. goto err;
  490. switch (log_type) {
  491. case LOG_NORMAL:
  492. {
  493. char *end;
  494. int len=my_snprintf(buff, sizeof(buff), "%s, Version: %s (%s). "
  495. #ifdef EMBEDDED_LIBRARY
  496. "embedded library\n",
  497. my_progname, server_version, MYSQL_COMPILATION_COMMENT
  498. #elif __NT__
  499. "started with:\nTCP Port: %d, Named Pipe: %s\n",
  500. my_progname, server_version, MYSQL_COMPILATION_COMMENT,
  501. mysqld_port, mysqld_unix_port
  502. #else
  503. "started with:\nTcp port: %d Unix socket: %s\n",
  504. my_progname, server_version, MYSQL_COMPILATION_COMMENT,
  505. mysqld_port, mysqld_unix_port
  506. #endif
  507. );
  508. end=strnmov(buff+len,"Time Id Command Argument\n",
  509. sizeof(buff)-len);
  510. if (my_b_write(&log_file, (byte*) buff,(uint) (end-buff)) ||
  511. flush_io_cache(&log_file))
  512. goto err;
  513. break;
  514. }
  515. case LOG_NEW:
  516. {
  517. uint len;
  518. time_t skr=time(NULL);
  519. struct tm tm_tmp;
  520. localtime_r(&skr,&tm_tmp);
  521. len= my_snprintf(buff,sizeof(buff),
  522. "# %s, Version: %s at %02d%02d%02d %2d:%02d:%02d\n",
  523. my_progname,server_version,
  524. tm_tmp.tm_year % 100,
  525. tm_tmp.tm_mon+1,
  526. tm_tmp.tm_mday,
  527. tm_tmp.tm_hour,
  528. tm_tmp.tm_min,
  529. tm_tmp.tm_sec);
  530. if (my_b_write(&log_file, (byte*) buff, len) ||
  531. flush_io_cache(&log_file))
  532. goto err;
  533. break;
  534. }
  535. case LOG_BIN:
  536. {
  537. bool write_file_name_to_index_file=0;
  538. if (!my_b_filelength(&log_file))
  539. {
  540. /*
  541. The binary log file was empty (probably newly created)
  542. This is the normal case and happens when the user doesn't specify
  543. an extension for the binary log files.
  544. In this case we write a standard header to it.
  545. */
  546. if (my_b_safe_write(&log_file, (byte*) BINLOG_MAGIC,
  547. BIN_LOG_HEADER_SIZE))
  548. goto err;
  549. bytes_written+= BIN_LOG_HEADER_SIZE;
  550. write_file_name_to_index_file= 1;
  551. }
  552. DBUG_ASSERT(my_b_inited(&index_file) != 0);
  553. reinit_io_cache(&index_file, WRITE_CACHE,
  554. my_b_filelength(&index_file), 0, 0);
  555. if (need_start_event && !no_auto_events)
  556. {
  557. /*
  558. In 4.x we set need_start_event=0 here, but in 5.0 we want a Start event
  559. even if this is not the very first binlog.
  560. */
  561. Format_description_log_event s(BINLOG_VERSION);
  562. /*
  563. don't set LOG_EVENT_BINLOG_IN_USE_F for SEQ_READ_APPEND io_cache
  564. as we won't be able to reset it later
  565. */
  566. if (io_cache_type == WRITE_CACHE)
  567. s.flags|= LOG_EVENT_BINLOG_IN_USE_F;
  568. if (!s.is_valid())
  569. goto err;
  570. if (null_created_arg)
  571. s.created= 0;
  572. if (s.write(&log_file))
  573. goto err;
  574. bytes_written+= s.data_written;
  575. }
  576. if (description_event_for_queue &&
  577. description_event_for_queue->binlog_version>=4)
  578. {
  579. /*
  580. This is a relay log written to by the I/O slave thread.
  581. Write the event so that others can later know the format of this relay
  582. log.
  583. Note that this event is very close to the original event from the
  584. master (it has binlog version of the master, event types of the
  585. master), so this is suitable to parse the next relay log's event. It
  586. has been produced by
  587. Format_description_log_event::Format_description_log_event(char* buf,).
  588. Why don't we want to write the description_event_for_queue if this
  589. event is for format<4 (3.23 or 4.x): this is because in that case, the
  590. description_event_for_queue describes the data received from the
  591. master, but not the data written to the relay log (*conversion*),
  592. which is in format 4 (slave's).
  593. */
  594. /*
  595. Set 'created' to 0, so that in next relay logs this event does not
  596. trigger cleaning actions on the slave in
  597. Format_description_log_event::exec_event().
  598. */
  599. description_event_for_queue->created= 0;
  600. /* Don't set log_pos in event header */
  601. description_event_for_queue->artificial_event=1;
  602. if (description_event_for_queue->write(&log_file))
  603. goto err;
  604. bytes_written+= description_event_for_queue->data_written;
  605. }
  606. if (flush_io_cache(&log_file) ||
  607. my_sync(log_file.file, MYF(MY_WME)))
  608. goto err;
  609. if (write_file_name_to_index_file)
  610. {
  611. /*
  612. As this is a new log file, we write the file name to the index
  613. file. As every time we write to the index file, we sync it.
  614. */
  615. if (my_b_write(&index_file, (byte*) log_file_name,
  616. strlen(log_file_name)) ||
  617. my_b_write(&index_file, (byte*) "\n", 1) ||
  618. flush_io_cache(&index_file) ||
  619. my_sync(index_file.file, MYF(MY_WME)))
  620. goto err;
  621. }
  622. break;
  623. }
  624. case LOG_CLOSED: // Impossible
  625. case LOG_TO_BE_OPENED:
  626. DBUG_ASSERT(1);
  627. break;
  628. }
  629. DBUG_RETURN(0);
  630. err:
  631. sql_print_error("Could not use %s for logging (error %d). \
  632. Turning logging off for the whole duration of the MySQL server process. \
  633. To turn it on again: fix the cause, \
  634. shutdown the MySQL server and restart it.", name, errno);
  635. if (file >= 0)
  636. my_close(file,MYF(0));
  637. end_io_cache(&log_file);
  638. end_io_cache(&index_file);
  639. safeFree(name);
  640. log_type= LOG_CLOSED;
  641. DBUG_RETURN(1);
  642. }
  643. int MYSQL_LOG::get_current_log(LOG_INFO* linfo)
  644. {
  645. pthread_mutex_lock(&LOCK_log);
  646. int ret = raw_get_current_log(linfo);
  647. pthread_mutex_unlock(&LOCK_log);
  648. return ret;
  649. }
  650. int MYSQL_LOG::raw_get_current_log(LOG_INFO* linfo)
  651. {
  652. strmake(linfo->log_file_name, log_file_name, sizeof(linfo->log_file_name)-1);
  653. linfo->pos = my_b_tell(&log_file);
  654. return 0;
  655. }
  656. /*
  657. Move all data up in a file in an filename index file
  658. SYNOPSIS
  659. copy_up_file_and_fill()
  660. index_file File to move
  661. offset Move everything from here to beginning
  662. NOTE
  663. File will be truncated to be 'offset' shorter or filled up with
  664. newlines
  665. IMPLEMENTATION
  666. We do the copy outside of the IO_CACHE as the cache buffers would just
  667. make things slower and more complicated.
  668. In most cases the copy loop should only do one read.
  669. RETURN VALUES
  670. 0 ok
  671. */
  672. #ifdef HAVE_REPLICATION
  673. static bool copy_up_file_and_fill(IO_CACHE *index_file, my_off_t offset)
  674. {
  675. int bytes_read;
  676. my_off_t init_offset= offset;
  677. File file= index_file->file;
  678. byte io_buf[IO_SIZE*2];
  679. DBUG_ENTER("copy_up_file_and_fill");
  680. for (;; offset+= bytes_read)
  681. {
  682. (void) my_seek(file, offset, MY_SEEK_SET, MYF(0));
  683. if ((bytes_read= (int) my_read(file, io_buf, sizeof(io_buf), MYF(MY_WME)))
  684. < 0)
  685. goto err;
  686. if (!bytes_read)
  687. break; // end of file
  688. (void) my_seek(file, offset-init_offset, MY_SEEK_SET, MYF(0));
  689. if (my_write(file, (byte*) io_buf, bytes_read, MYF(MY_WME | MY_NABP)))
  690. goto err;
  691. }
  692. /* The following will either truncate the file or fill the end with \n' */
  693. if (my_chsize(file, offset - init_offset, '\n', MYF(MY_WME)) ||
  694. my_sync(file, MYF(MY_WME)))
  695. goto err;
  696. /* Reset data in old index cache */
  697. reinit_io_cache(index_file, READ_CACHE, (my_off_t) 0, 0, 1);
  698. DBUG_RETURN(0);
  699. err:
  700. DBUG_RETURN(1);
  701. }
  702. #endif /* HAVE_REPLICATION */
  703. /*
  704. Find the position in the log-index-file for the given log name
  705. SYNOPSIS
  706. find_log_pos()
  707. linfo Store here the found log file name and position to
  708. the NEXT log file name in the index file.
  709. log_name Filename to find in the index file.
  710. Is a null pointer if we want to read the first entry
  711. need_lock Set this to 1 if the parent doesn't already have a
  712. lock on LOCK_index
  713. NOTE
  714. On systems without the truncate function the file will end with one or
  715. more empty lines. These will be ignored when reading the file.
  716. RETURN VALUES
  717. 0 ok
  718. LOG_INFO_EOF End of log-index-file found
  719. LOG_INFO_IO Got IO error while reading file
  720. */
  721. int MYSQL_LOG::find_log_pos(LOG_INFO *linfo, const char *log_name,
  722. bool need_lock)
  723. {
  724. int error= 0;
  725. char *fname= linfo->log_file_name;
  726. uint log_name_len= log_name ? (uint) strlen(log_name) : 0;
  727. DBUG_ENTER("find_log_pos");
  728. DBUG_PRINT("enter",("log_name: %s", log_name ? log_name : "NULL"));
  729. /*
  730. Mutex needed because we need to make sure the file pointer does not
  731. move from under our feet
  732. */
  733. if (need_lock)
  734. pthread_mutex_lock(&LOCK_index);
  735. safe_mutex_assert_owner(&LOCK_index);
  736. /* As the file is flushed, we can't get an error here */
  737. (void) reinit_io_cache(&index_file, READ_CACHE, (my_off_t) 0, 0, 0);
  738. for (;;)
  739. {
  740. uint length;
  741. my_off_t offset= my_b_tell(&index_file);
  742. /* If we get 0 or 1 characters, this is the end of the file */
  743. if ((length= my_b_gets(&index_file, fname, FN_REFLEN)) <= 1)
  744. {
  745. /* Did not find the given entry; Return not found or error */
  746. error= !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO;
  747. break;
  748. }
  749. // if the log entry matches, null string matching anything
  750. if (!log_name ||
  751. (log_name_len == length-1 && fname[log_name_len] == '\n' &&
  752. !memcmp(fname, log_name, log_name_len)))
  753. {
  754. DBUG_PRINT("info",("Found log file entry"));
  755. fname[length-1]=0; // remove last \n
  756. linfo->index_file_start_offset= offset;
  757. linfo->index_file_offset = my_b_tell(&index_file);
  758. break;
  759. }
  760. }
  761. if (need_lock)
  762. pthread_mutex_unlock(&LOCK_index);
  763. DBUG_RETURN(error);
  764. }
  765. /*
  766. Find the position in the log-index-file for the given log name
  767. SYNOPSIS
  768. find_next_log()
  769. linfo Store here the next log file name and position to
  770. the file name after that.
  771. need_lock Set this to 1 if the parent doesn't already have a
  772. lock on LOCK_index
  773. NOTE
  774. - Before calling this function, one has to call find_log_pos()
  775. to set up 'linfo'
  776. - Mutex needed because we need to make sure the file pointer does not move
  777. from under our feet
  778. RETURN VALUES
  779. 0 ok
  780. LOG_INFO_EOF End of log-index-file found
  781. LOG_INFO_IO Got IO error while reading file
  782. */
  783. int MYSQL_LOG::find_next_log(LOG_INFO* linfo, bool need_lock)
  784. {
  785. int error= 0;
  786. uint length;
  787. char *fname= linfo->log_file_name;
  788. if (need_lock)
  789. pthread_mutex_lock(&LOCK_index);
  790. safe_mutex_assert_owner(&LOCK_index);
  791. /* As the file is flushed, we can't get an error here */
  792. (void) reinit_io_cache(&index_file, READ_CACHE, linfo->index_file_offset, 0,
  793. 0);
  794. linfo->index_file_start_offset= linfo->index_file_offset;
  795. if ((length=my_b_gets(&index_file, fname, FN_REFLEN)) <= 1)
  796. {
  797. error = !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO;
  798. goto err;
  799. }
  800. fname[length-1]=0; // kill \n
  801. linfo->index_file_offset = my_b_tell(&index_file);
  802. err:
  803. if (need_lock)
  804. pthread_mutex_unlock(&LOCK_index);
  805. return error;
  806. }
  807. /*
  808. Delete all logs refered to in the index file
  809. Start writing to a new log file. The new index file will only contain
  810. this file.
  811. SYNOPSIS
  812. reset_logs()
  813. thd Thread
  814. NOTE
  815. If not called from slave thread, write start event to new log
  816. RETURN VALUES
  817. 0 ok
  818. 1 error
  819. */
  820. bool MYSQL_LOG::reset_logs(THD* thd)
  821. {
  822. LOG_INFO linfo;
  823. bool error=0;
  824. const char* save_name;
  825. enum_log_type save_log_type;
  826. DBUG_ENTER("reset_logs");
  827. /*
  828. We need to get both locks to be sure that no one is trying to
  829. write to the index log file.
  830. */
  831. pthread_mutex_lock(&LOCK_log);
  832. pthread_mutex_lock(&LOCK_index);
  833. /*
  834. The following mutex is needed to ensure that no threads call
  835. 'delete thd' as we would then risk missing a 'rollback' from this
  836. thread. If the transaction involved MyISAM tables, it should go
  837. into binlog even on rollback.
  838. */
  839. (void) pthread_mutex_lock(&LOCK_thread_count);
  840. /* Save variables so that we can reopen the log */
  841. save_name=name;
  842. name=0; // Protect against free
  843. save_log_type=log_type;
  844. close(LOG_CLOSE_TO_BE_OPENED);
  845. /* First delete all old log files */
  846. if (find_log_pos(&linfo, NullS, 0))
  847. {
  848. error=1;
  849. goto err;
  850. }
  851. for (;;)
  852. {
  853. my_delete_allow_opened(linfo.log_file_name, MYF(MY_WME));
  854. if (find_next_log(&linfo, 0))
  855. break;
  856. }
  857. /* Start logging with a new file */
  858. close(LOG_CLOSE_INDEX);
  859. my_delete_allow_opened(index_file_name, MYF(MY_WME)); // Reset (open will update)
  860. if (!thd->slave_thread)
  861. need_start_event=1;
  862. if (!open_index_file(index_file_name, 0))
  863. open(save_name, save_log_type, 0,
  864. io_cache_type, no_auto_events, max_size, 0);
  865. my_free((gptr) save_name, MYF(0));
  866. err:
  867. (void) pthread_mutex_unlock(&LOCK_thread_count);
  868. pthread_mutex_unlock(&LOCK_index);
  869. pthread_mutex_unlock(&LOCK_log);
  870. DBUG_RETURN(error);
  871. }
  872. /*
  873. Delete relay log files prior to rli->group_relay_log_name
  874. (i.e. all logs which are not involved in a non-finished group
  875. (transaction)), remove them from the index file and start on next relay log.
  876. SYNOPSIS
  877. purge_first_log()
  878. rli Relay log information
  879. included If false, all relay logs that are strictly before
  880. rli->group_relay_log_name are deleted ; if true, the latter is
  881. deleted too (i.e. all relay logs
  882. read by the SQL slave thread are deleted).
  883. NOTE
  884. - This is only called from the slave-execute thread when it has read
  885. all commands from a relay log and want to switch to a new relay log.
  886. - When this happens, we can be in an active transaction as
  887. a transaction can span over two relay logs
  888. (although it is always written as a single block to the master's binary
  889. log, hence cannot span over two master's binary logs).
  890. IMPLEMENTATION
  891. - Protects index file with LOCK_index
  892. - Delete relevant relay log files
  893. - Copy all file names after these ones to the front of the index file
  894. - If the OS has truncate, truncate the file, else fill it with \n'
  895. - Read the next file name from the index file and store in rli->linfo
  896. RETURN VALUES
  897. 0 ok
  898. LOG_INFO_EOF End of log-index-file found
  899. LOG_INFO_SEEK Could not allocate IO cache
  900. LOG_INFO_IO Got IO error while reading file
  901. */
  902. #ifdef HAVE_REPLICATION
  903. int MYSQL_LOG::purge_first_log(struct st_relay_log_info* rli, bool included)
  904. {
  905. int error;
  906. DBUG_ENTER("purge_first_log");
  907. DBUG_ASSERT(is_open());
  908. DBUG_ASSERT(rli->slave_running == 1);
  909. DBUG_ASSERT(!strcmp(rli->linfo.log_file_name,rli->event_relay_log_name));
  910. pthread_mutex_lock(&LOCK_index);
  911. pthread_mutex_lock(&rli->log_space_lock);
  912. rli->relay_log.purge_logs(rli->group_relay_log_name, included,
  913. 0, 0, &rli->log_space_total);
  914. // Tell the I/O thread to take the relay_log_space_limit into account
  915. rli->ignore_log_space_limit= 0;
  916. pthread_mutex_unlock(&rli->log_space_lock);
  917. /*
  918. Ok to broadcast after the critical region as there is no risk of
  919. the mutex being destroyed by this thread later - this helps save
  920. context switches
  921. */
  922. pthread_cond_broadcast(&rli->log_space_cond);
  923. /*
  924. Read the next log file name from the index file and pass it back to
  925. the caller
  926. If included is true, we want the first relay log;
  927. otherwise we want the one after event_relay_log_name.
  928. */
  929. if ((included && (error=find_log_pos(&rli->linfo, NullS, 0))) ||
  930. (!included &&
  931. ((error=find_log_pos(&rli->linfo, rli->event_relay_log_name, 0)) ||
  932. (error=find_next_log(&rli->linfo, 0)))))
  933. {
  934. char buff[22];
  935. sql_print_error("next log error: %d offset: %s log: %s included: %d",
  936. error,
  937. llstr(rli->linfo.index_file_offset,buff),
  938. rli->group_relay_log_name,
  939. included);
  940. goto err;
  941. }
  942. /*
  943. Reset rli's coordinates to the current log.
  944. */
  945. rli->event_relay_log_pos= BIN_LOG_HEADER_SIZE;
  946. strmake(rli->event_relay_log_name,rli->linfo.log_file_name,
  947. sizeof(rli->event_relay_log_name)-1);
  948. /*
  949. If we removed the rli->group_relay_log_name file,
  950. we must update the rli->group* coordinates, otherwise do not touch it as the
  951. group's execution is not finished (e.g. COMMIT not executed)
  952. */
  953. if (included)
  954. {
  955. rli->group_relay_log_pos = BIN_LOG_HEADER_SIZE;
  956. strmake(rli->group_relay_log_name,rli->linfo.log_file_name,
  957. sizeof(rli->group_relay_log_name)-1);
  958. rli->notify_group_relay_log_name_update();
  959. }
  960. /* Store where we are in the new file for the execution thread */
  961. flush_relay_log_info(rli);
  962. err:
  963. pthread_mutex_unlock(&LOCK_index);
  964. DBUG_RETURN(error);
  965. }
  966. /*
  967. Update log index_file
  968. */
  969. int MYSQL_LOG::update_log_index(LOG_INFO* log_info, bool need_update_threads)
  970. {
  971. if (copy_up_file_and_fill(&index_file, log_info->index_file_start_offset))
  972. return LOG_INFO_IO;
  973. // now update offsets in index file for running threads
  974. if (need_update_threads)
  975. adjust_linfo_offsets(log_info->index_file_start_offset);
  976. return 0;
  977. }
  978. /*
  979. Remove all logs before the given log from disk and from the index file.
  980. SYNOPSIS
  981. purge_logs()
  982. to_log Delete all log file name before this file.
  983. included If true, to_log is deleted too.
  984. need_mutex
  985. need_update_threads If we want to update the log coordinates of
  986. all threads. False for relay logs, true otherwise.
  987. freed_log_space If not null, decrement this variable of
  988. the amount of log space freed
  989. NOTES
  990. If any of the logs before the deleted one is in use,
  991. only purge logs up to this one.
  992. RETURN VALUES
  993. 0 ok
  994. LOG_INFO_EOF to_log not found
  995. */
  996. int MYSQL_LOG::purge_logs(const char *to_log,
  997. bool included,
  998. bool need_mutex,
  999. bool need_update_threads,
  1000. ulonglong *decrease_log_space)
  1001. {
  1002. int error;
  1003. bool exit_loop= 0;
  1004. LOG_INFO log_info;
  1005. DBUG_ENTER("purge_logs");
  1006. DBUG_PRINT("info",("to_log= %s",to_log));
  1007. if (need_mutex)
  1008. pthread_mutex_lock(&LOCK_index);
  1009. if ((error=find_log_pos(&log_info, to_log, 0 /*no mutex*/)))
  1010. goto err;
  1011. /*
  1012. File name exists in index file; delete until we find this file
  1013. or a file that is used.
  1014. */
  1015. if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/)))
  1016. goto err;
  1017. while ((strcmp(to_log,log_info.log_file_name) || (exit_loop=included)) &&
  1018. !log_in_use(log_info.log_file_name))
  1019. {
  1020. ulong file_size= 0;
  1021. if (decrease_log_space) //stat the file we want to delete
  1022. {
  1023. MY_STAT s;
  1024. /*
  1025. If we could not stat, we can't know the amount
  1026. of space that deletion will free. In most cases,
  1027. deletion won't work either, so it's not a problem.
  1028. */
  1029. if (my_stat(log_info.log_file_name,&s,MYF(0)))
  1030. file_size= s.st_size;
  1031. else
  1032. sql_print_information("Failed to execute my_stat on file '%s'",
  1033. log_info.log_file_name);
  1034. }
  1035. /*
  1036. It's not fatal if we can't delete a log file ;
  1037. if we could delete it, take its size into account
  1038. */
  1039. DBUG_PRINT("info",("purging %s",log_info.log_file_name));
  1040. if (!my_delete(log_info.log_file_name, MYF(0)) && decrease_log_space)
  1041. *decrease_log_space-= file_size;
  1042. if (find_next_log(&log_info, 0) || exit_loop)
  1043. break;
  1044. }
  1045. /*
  1046. If we get killed -9 here, the sysadmin would have to edit
  1047. the log index file after restart - otherwise, this should be safe
  1048. */
  1049. error= update_log_index(&log_info, need_update_threads);
  1050. err:
  1051. if (need_mutex)
  1052. pthread_mutex_unlock(&LOCK_index);
  1053. DBUG_RETURN(error);
  1054. }
  1055. /*
  1056. Remove all logs before the given file date from disk and from the
  1057. index file.
  1058. SYNOPSIS
  1059. purge_logs_before_date()
  1060. thd Thread pointer
  1061. before_date Delete all log files before given date.
  1062. NOTES
  1063. If any of the logs before the deleted one is in use,
  1064. only purge logs up to this one.
  1065. RETURN VALUES
  1066. 0 ok
  1067. LOG_INFO_PURGE_NO_ROTATE Binary file that can't be rotated
  1068. */
  1069. int MYSQL_LOG::purge_logs_before_date(time_t purge_time)
  1070. {
  1071. int error;
  1072. LOG_INFO log_info;
  1073. MY_STAT stat_area;
  1074. DBUG_ENTER("purge_logs_before_date");
  1075. pthread_mutex_lock(&LOCK_index);
  1076. /*
  1077. Delete until we find curren file
  1078. or a file that is used or a file
  1079. that is older than purge_time.
  1080. */
  1081. if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/)))
  1082. goto err;
  1083. while (strcmp(log_file_name, log_info.log_file_name) &&
  1084. !log_in_use(log_info.log_file_name))
  1085. {
  1086. /* It's not fatal even if we can't delete a log file */
  1087. if (!my_stat(log_info.log_file_name, &stat_area, MYF(0)) ||
  1088. stat_area.st_mtime >= purge_time)
  1089. break;
  1090. my_delete(log_info.log_file_name, MYF(0));
  1091. if (find_next_log(&log_info, 0))
  1092. break;
  1093. }
  1094. /*
  1095. If we get killed -9 here, the sysadmin would have to edit
  1096. the log index file after restart - otherwise, this should be safe
  1097. */
  1098. error= update_log_index(&log_info, 1);
  1099. err:
  1100. pthread_mutex_unlock(&LOCK_index);
  1101. DBUG_RETURN(error);
  1102. }
  1103. #endif /* HAVE_REPLICATION */
  1104. /*
  1105. Create a new log file name
  1106. SYNOPSIS
  1107. make_log_name()
  1108. buf buf of at least FN_REFLEN where new name is stored
  1109. NOTE
  1110. If file name will be longer then FN_REFLEN it will be truncated
  1111. */
  1112. void MYSQL_LOG::make_log_name(char* buf, const char* log_ident)
  1113. {
  1114. uint dir_len = dirname_length(log_file_name);
  1115. if (dir_len > FN_REFLEN)
  1116. dir_len=FN_REFLEN-1;
  1117. strnmov(buf, log_file_name, dir_len);
  1118. strmake(buf+dir_len, log_ident, FN_REFLEN - dir_len);
  1119. }
  1120. /*
  1121. Check if we are writing/reading to the given log file
  1122. */
  1123. bool MYSQL_LOG::is_active(const char *log_file_name_arg)
  1124. {
  1125. return !strcmp(log_file_name, log_file_name_arg);
  1126. }
  1127. /*
  1128. Start writing to a new log file or reopen the old file
  1129. SYNOPSIS
  1130. new_file()
  1131. need_lock Set to 1 if caller has not locked LOCK_log
  1132. NOTE
  1133. The new file name is stored last in the index file
  1134. */
  1135. void MYSQL_LOG::new_file(bool need_lock)
  1136. {
  1137. char new_name[FN_REFLEN], *new_name_ptr, *old_name;
  1138. enum_log_type save_log_type;
  1139. DBUG_ENTER("MYSQL_LOG::new_file");
  1140. if (!is_open())
  1141. {
  1142. DBUG_PRINT("info",("log is closed"));
  1143. DBUG_VOID_RETURN;
  1144. }
  1145. if (need_lock)
  1146. pthread_mutex_lock(&LOCK_log);
  1147. pthread_mutex_lock(&LOCK_index);
  1148. safe_mutex_assert_owner(&LOCK_log);
  1149. safe_mutex_assert_owner(&LOCK_index);
  1150. /*
  1151. if binlog is used as tc log, be sure all xids are "unlogged",
  1152. so that on recover we only need to scan one - latest - binlog file
  1153. for prepared xids. As this is expected to be a rare event,
  1154. simple wait strategy is enough. We're locking LOCK_log to be sure no
  1155. new Xid_log_event's are added to the log (and prepared_xids is not
  1156. increased), and waiting on COND_prep_xids for late threads to
  1157. catch up.
  1158. */
  1159. if (prepared_xids)
  1160. {
  1161. tc_log_page_waits++;
  1162. pthread_mutex_lock(&LOCK_prep_xids);
  1163. while (prepared_xids)
  1164. pthread_cond_wait(&COND_prep_xids, &LOCK_prep_xids);
  1165. pthread_mutex_unlock(&LOCK_prep_xids);
  1166. }
  1167. /* Reuse old name if not binlog and not update log */
  1168. new_name_ptr= name;
  1169. /*
  1170. If user hasn't specified an extension, generate a new log name
  1171. We have to do this here and not in open as we want to store the
  1172. new file name in the current binary log file.
  1173. */
  1174. if (generate_new_name(new_name, name))
  1175. goto end;
  1176. new_name_ptr=new_name;
  1177. if (log_type == LOG_BIN)
  1178. {
  1179. if (!no_auto_events)
  1180. {
  1181. /*
  1182. We log the whole file name for log file as the user may decide
  1183. to change base names at some point.
  1184. */
  1185. THD *thd = current_thd; /* may be 0 if we are reacting to SIGHUP */
  1186. Rotate_log_event r(thd,new_name+dirname_length(new_name),
  1187. 0, LOG_EVENT_OFFSET, 0);
  1188. r.write(&log_file);
  1189. bytes_written += r.data_written;
  1190. }
  1191. /*
  1192. Update needs to be signalled even if there is no rotate event
  1193. log rotation should give the waiting thread a signal to
  1194. discover EOF and move on to the next log.
  1195. */
  1196. signal_update();
  1197. }
  1198. old_name=name;
  1199. save_log_type=log_type;
  1200. name=0; // Don't free name
  1201. close(LOG_CLOSE_TO_BE_OPENED);
  1202. /*
  1203. Note that at this point, log_type != LOG_CLOSED (important for is_open()).
  1204. */
  1205. /*
  1206. new_file() is only used for rotation (in FLUSH LOGS or because size >
  1207. max_binlog_size or max_relay_log_size).
  1208. If this is a binary log, the Format_description_log_event at the beginning of
  1209. the new file should have created=0 (to distinguish with the
  1210. Format_description_log_event written at server startup, which should
  1211. trigger temp tables deletion on slaves.
  1212. */
  1213. open(old_name, save_log_type, new_name_ptr,
  1214. io_cache_type, no_auto_events, max_size, 1);
  1215. my_free(old_name,MYF(0));
  1216. end:
  1217. if (need_lock)
  1218. pthread_mutex_unlock(&LOCK_log);
  1219. pthread_mutex_unlock(&LOCK_index);
  1220. DBUG_VOID_RETURN;
  1221. }
  1222. bool MYSQL_LOG::append(Log_event* ev)
  1223. {
  1224. bool error = 0;
  1225. pthread_mutex_lock(&LOCK_log);
  1226. DBUG_ENTER("MYSQL_LOG::append");
  1227. DBUG_ASSERT(log_file.type == SEQ_READ_APPEND);
  1228. /*
  1229. Log_event::write() is smart enough to use my_b_write() or
  1230. my_b_append() depending on the kind of cache we have.
  1231. */
  1232. if (ev->write(&log_file))
  1233. {
  1234. error=1;
  1235. goto err;
  1236. }
  1237. bytes_written+= ev->data_written;
  1238. DBUG_PRINT("info",("max_size: %lu",max_size));
  1239. if ((uint) my_b_append_tell(&log_file) > max_size)
  1240. new_file(0);
  1241. err:
  1242. pthread_mutex_unlock(&LOCK_log);
  1243. signal_update(); // Safe as we don't call close
  1244. DBUG_RETURN(error);
  1245. }
  1246. bool MYSQL_LOG::appendv(const char* buf, uint len,...)
  1247. {
  1248. bool error= 0;
  1249. DBUG_ENTER("MYSQL_LOG::appendv");
  1250. va_list(args);
  1251. va_start(args,len);
  1252. DBUG_ASSERT(log_file.type == SEQ_READ_APPEND);
  1253. safe_mutex_assert_owner(&LOCK_log);
  1254. do
  1255. {
  1256. if (my_b_append(&log_file,(byte*) buf,len))
  1257. {
  1258. error= 1;
  1259. goto err;
  1260. }
  1261. bytes_written += len;
  1262. } while ((buf=va_arg(args,const char*)) && (len=va_arg(args,uint)));
  1263. DBUG_PRINT("info",("max_size: %lu",max_size));
  1264. if ((uint) my_b_append_tell(&log_file) > max_size)
  1265. new_file(0);
  1266. err:
  1267. if (!error)
  1268. signal_update();
  1269. DBUG_RETURN(error);
  1270. }
  1271. /*
  1272. Write to normal (not rotable) log
  1273. This is the format for the 'normal' log.
  1274. */
  1275. bool MYSQL_LOG::write(THD *thd,enum enum_server_command command,
  1276. const char *format,...)
  1277. {
  1278. if (is_open() && (what_to_log & (1L << (uint) command)))
  1279. {
  1280. uint length;
  1281. int error= 0;
  1282. VOID(pthread_mutex_lock(&LOCK_log));
  1283. /* Test if someone closed between the is_open test and lock */
  1284. if (is_open())
  1285. {
  1286. time_t skr;
  1287. ulong id;
  1288. va_list args;
  1289. va_start(args,format);
  1290. char buff[32];
  1291. if (thd)
  1292. { // Normal thread
  1293. if ((thd->options & OPTION_LOG_OFF)
  1294. #ifndef NO_EMBEDDED_ACCESS_CHECKS
  1295. && (thd->security_ctx->master_access & SUPER_ACL)
  1296. #endif
  1297. )
  1298. {
  1299. VOID(pthread_mutex_unlock(&LOCK_log));
  1300. return 0; // No logging
  1301. }
  1302. id=thd->thread_id;
  1303. if (thd->user_time || !(skr=thd->query_start()))
  1304. skr=time(NULL); // Connected
  1305. }
  1306. else
  1307. { // Log from connect handler
  1308. skr=time(NULL);
  1309. id=0;
  1310. }
  1311. if (skr != last_time)
  1312. {
  1313. last_time=skr;
  1314. struct tm tm_tmp;
  1315. struct tm *start;
  1316. localtime_r(&skr,&tm_tmp);
  1317. start=&tm_tmp;
  1318. /* Note that my_b_write() assumes it knows the length for this */
  1319. sprintf(buff,"%02d%02d%02d %2d:%02d:%02d\t",
  1320. start->tm_year % 100,
  1321. start->tm_mon+1,
  1322. start->tm_mday,
  1323. start->tm_hour,
  1324. start->tm_min,
  1325. start->tm_sec);
  1326. if (my_b_write(&log_file, (byte*) buff,16))
  1327. error=errno;
  1328. }
  1329. else if (my_b_write(&log_file, (byte*) "\t\t",2) < 0)
  1330. error=errno;
  1331. length=my_sprintf(buff,
  1332. (buff, "%7ld %-11.11s", id,
  1333. command_name[(uint) command]));
  1334. if (my_b_write(&log_file, (byte*) buff,length))
  1335. error=errno;
  1336. if (format)
  1337. {
  1338. if (my_b_write(&log_file, (byte*) " ",1) ||
  1339. my_b_vprintf(&log_file,format,args) == (uint) -1)
  1340. error=errno;
  1341. }
  1342. if (my_b_write(&log_file, (byte*) "\n",1) ||
  1343. flush_io_cache(&log_file))
  1344. error=errno;
  1345. if (error && ! write_error)
  1346. {
  1347. write_error=1;
  1348. sql_print_error(ER(ER_ERROR_ON_WRITE),name,error);
  1349. }
  1350. va_end(args);
  1351. }
  1352. VOID(pthread_mutex_unlock(&LOCK_log));
  1353. return error != 0;
  1354. }
  1355. return 0;
  1356. }
  1357. bool MYSQL_LOG::flush_and_sync()
  1358. {
  1359. int err=0, fd=log_file.file;
  1360. safe_mutex_assert_owner(&LOCK_log);
  1361. if (flush_io_cache(&log_file))
  1362. return 1;
  1363. if (++sync_binlog_counter >= sync_binlog_period && sync_binlog_period)
  1364. {
  1365. sync_binlog_counter= 0;
  1366. err=my_sync(fd, MYF(MY_WME));
  1367. }
  1368. return err;
  1369. }
  1370. void MYSQL_LOG::start_union_events(THD *thd, query_id_t query_id_param)
  1371. {
  1372. DBUG_ASSERT(!thd->binlog_evt_union.do_union);
  1373. thd->binlog_evt_union.do_union= TRUE;
  1374. thd->binlog_evt_union.unioned_events= FALSE;
  1375. thd->binlog_evt_union.unioned_events_trans= FALSE;
  1376. thd->binlog_evt_union.first_query_id= query_id_param;
  1377. }
  1378. void MYSQL_LOG::stop_union_events(THD *thd)
  1379. {
  1380. DBUG_ASSERT(thd->binlog_evt_union.do_union);
  1381. thd->binlog_evt_union.do_union= FALSE;
  1382. }
  1383. bool MYSQL_LOG::is_query_in_union(THD *thd, query_id_t query_id_param)
  1384. {
  1385. return (thd->binlog_evt_union.do_union &&
  1386. query_id_param >= thd->binlog_evt_union.first_query_id);
  1387. }
  1388. /*
  1389. Write an event to the binary log
  1390. */
  1391. bool MYSQL_LOG::write(Log_event *event_info)
  1392. {
  1393. THD *thd= event_info->thd;
  1394. bool error= 1;
  1395. DBUG_ENTER("MYSQL_LOG::write(Log_event *)");
  1396. if (thd->binlog_evt_union.do_union)
  1397. {
  1398. /*
  1399. In Stored function; Remember that function call caused an update.
  1400. We will log the function call to the binary log on function exit
  1401. */
  1402. thd->binlog_evt_union.unioned_events= TRUE;
  1403. thd->binlog_evt_union.unioned_events_trans |= event_info->cache_stmt;
  1404. DBUG_RETURN(0);
  1405. }
  1406. pthread_mutex_lock(&LOCK_log);
  1407. /*
  1408. In most cases this is only called if 'is_open()' is true; in fact this is
  1409. mostly called if is_open() *was* true a few instructions before, but it
  1410. could have changed since.
  1411. */
  1412. if (likely(is_open()))
  1413. {
  1414. IO_CACHE *file= &log_file;
  1415. #ifdef HAVE_REPLICATION
  1416. /*
  1417. In the future we need to add to the following if tests like
  1418. "do the involved tables match (to be implemented)
  1419. binlog_[wild_]{do|ignore}_table?" (WL#1049)"
  1420. */
  1421. const char *local_db= event_info->get_db();
  1422. if ((thd && !(thd->options & OPTION_BIN_LOG)) ||
  1423. (!db_ok(local_db, binlog_do_db, binlog_ignore_db)))
  1424. {
  1425. VOID(pthread_mutex_unlock(&LOCK_log));
  1426. DBUG_PRINT("error",("!db_ok('%s')", local_db));
  1427. DBUG_RETURN(0);
  1428. }
  1429. #endif /* HAVE_REPLICATION */
  1430. #ifdef USING_TRANSACTIONS
  1431. /*
  1432. Should we write to the binlog cache or to the binlog on disk?
  1433. Write to the binlog cache if:
  1434. - it is already not empty (meaning we're in a transaction; note that the
  1435. present event could be about a non-transactional table, but still we need
  1436. to write to the binlog cache in that case to handle updates to mixed
  1437. trans/non-trans table types the best possible in binlogging)
  1438. - or if the event asks for it (cache_stmt == TRUE).
  1439. */
  1440. if (opt_using_transactions && thd)
  1441. {
  1442. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  1443. if (event_info->get_cache_stmt())
  1444. {
  1445. if (!trans_log)
  1446. {
  1447. thd->ha_data[binlog_hton.slot]= trans_log= (IO_CACHE *)
  1448. my_malloc(sizeof(IO_CACHE), MYF(MY_ZEROFILL));
  1449. if (!trans_log || open_cached_file(trans_log, mysql_tmpdir,
  1450. LOG_PREFIX,
  1451. binlog_cache_size, MYF(MY_WME)))
  1452. {
  1453. my_free((gptr)trans_log, MYF(MY_ALLOW_ZERO_PTR));
  1454. thd->ha_data[binlog_hton.slot]= trans_log= 0;
  1455. goto err;
  1456. }
  1457. trans_log->end_of_file= max_binlog_cache_size;
  1458. trans_register_ha(thd,
  1459. test(thd->options & (OPTION_NOT_AUTOCOMMIT |
  1460. OPTION_BEGIN)),
  1461. &binlog_hton);
  1462. }
  1463. else if (!my_b_tell(trans_log))
  1464. trans_register_ha(thd,
  1465. test(thd->options & (OPTION_NOT_AUTOCOMMIT |
  1466. OPTION_BEGIN)),
  1467. &binlog_hton);
  1468. file= trans_log;
  1469. }
  1470. else if (trans_log && my_b_tell(trans_log))
  1471. file= trans_log;
  1472. }
  1473. #endif
  1474. DBUG_PRINT("info",("event type=%d",event_info->get_type_code()));
  1475. /*
  1476. No check for auto events flag here - this write method should
  1477. never be called if auto-events are enabled
  1478. */
  1479. /*
  1480. 1. Write first log events which describe the 'run environment'
  1481. of the SQL command
  1482. */
  1483. if (thd)
  1484. {
  1485. if (thd->last_insert_id_used_bin_log)
  1486. {
  1487. Intvar_log_event e(thd,(uchar) LAST_INSERT_ID_EVENT,
  1488. thd->current_insert_id);
  1489. if (e.write(file))
  1490. goto err;
  1491. }
  1492. if (thd->insert_id_used)
  1493. {
  1494. Intvar_log_event e(thd,(uchar) INSERT_ID_EVENT,thd->last_insert_id);
  1495. if (e.write(file))
  1496. goto err;
  1497. }
  1498. if (thd->rand_used)
  1499. {
  1500. Rand_log_event e(thd,thd->rand_saved_seed1,thd->rand_saved_seed2);
  1501. if (e.write(file))
  1502. goto err;
  1503. }
  1504. if (thd->user_var_events.elements)
  1505. {
  1506. for (uint i= 0; i < thd->user_var_events.elements; i++)
  1507. {
  1508. BINLOG_USER_VAR_EVENT *user_var_event;
  1509. get_dynamic(&thd->user_var_events,(gptr) &user_var_event, i);
  1510. User_var_log_event e(thd, user_var_event->user_var_event->name.str,
  1511. user_var_event->user_var_event->name.length,
  1512. user_var_event->value,
  1513. user_var_event->length,
  1514. user_var_event->type,
  1515. user_var_event->charset_number);
  1516. if (e.write(file))
  1517. goto err;
  1518. }
  1519. }
  1520. }
  1521. /*
  1522. Write the SQL command
  1523. */
  1524. if (event_info->write(file))
  1525. goto err;
  1526. if (file == &log_file) // we are writing to the real log (disk)
  1527. {
  1528. if (flush_and_sync())
  1529. goto err;
  1530. signal_update();
  1531. rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
  1532. }
  1533. error=0;
  1534. err:
  1535. if (error)
  1536. {
  1537. if (my_errno == EFBIG)
  1538. my_message(ER_TRANS_CACHE_FULL, ER(ER_TRANS_CACHE_FULL), MYF(0));
  1539. else
  1540. my_error(ER_ERROR_ON_WRITE, MYF(0), name, errno);
  1541. write_error=1;
  1542. }
  1543. }
  1544. pthread_mutex_unlock(&LOCK_log);
  1545. DBUG_RETURN(error);
  1546. }
  1547. void MYSQL_LOG::rotate_and_purge(uint flags)
  1548. {
  1549. if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED))
  1550. pthread_mutex_lock(&LOCK_log);
  1551. if ((flags & RP_FORCE_ROTATE) ||
  1552. (my_b_tell(&log_file) >= (my_off_t) max_size))
  1553. {
  1554. new_file(0);
  1555. #ifdef HAVE_REPLICATION
  1556. if (expire_logs_days)
  1557. {
  1558. long purge_time= (long) (time(0) - expire_logs_days*24*60*60);
  1559. if (purge_time >= 0)
  1560. purge_logs_before_date(purge_time);
  1561. }
  1562. #endif
  1563. }
  1564. if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED))
  1565. pthread_mutex_unlock(&LOCK_log);
  1566. }
  1567. uint MYSQL_LOG::next_file_id()
  1568. {
  1569. uint res;
  1570. pthread_mutex_lock(&LOCK_log);
  1571. res = file_id++;
  1572. pthread_mutex_unlock(&LOCK_log);
  1573. return res;
  1574. }
  1575. /*
  1576. Write a cached log entry to the binary log
  1577. SYNOPSIS
  1578. write()
  1579. thd
  1580. cache The cache to copy to the binlog
  1581. NOTE
  1582. - We only come here if there is something in the cache.
  1583. - The thing in the cache is always a complete transaction
  1584. - 'cache' needs to be reinitialized after this functions returns.
  1585. IMPLEMENTATION
  1586. - To support transaction over replication, we wrap the transaction
  1587. with BEGIN/COMMIT or BEGIN/ROLLBACK in the binary log.
  1588. We want to write a BEGIN/ROLLBACK block when a non-transactional table
  1589. was updated in a transaction which was rolled back. This is to ensure
  1590. that the same updates are run on the slave.
  1591. */
  1592. bool MYSQL_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event)
  1593. {
  1594. DBUG_ENTER("MYSQL_LOG::write(THD *, IO_CACHE *, Log_event *)");
  1595. VOID(pthread_mutex_lock(&LOCK_log));
  1596. /* NULL would represent nothing to replicate after ROLLBACK */
  1597. DBUG_ASSERT(commit_event != NULL);
  1598. if (likely(is_open())) // Should always be true
  1599. {
  1600. uint length;
  1601. /*
  1602. Log "BEGIN" at the beginning of the transaction.
  1603. which may contain more than 1 SQL statement.
  1604. */
  1605. if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
  1606. {
  1607. Query_log_event qinfo(thd, STRING_WITH_LEN("BEGIN"), TRUE, FALSE);
  1608. /*
  1609. Imagine this is rollback due to net timeout, after all statements of
  1610. the transaction succeeded. Then we want a zero-error code in BEGIN.
  1611. In other words, if there was a really serious error code it's already
  1612. in the statement's events, there is no need to put it also in this
  1613. internally generated event, and as this event is generated late it
  1614. would lead to false alarms.
  1615. This is safer than thd->clear_error() against kills at shutdown.
  1616. */
  1617. qinfo.error_code= 0;
  1618. /*
  1619. Now this Query_log_event has artificial log_pos 0. It must be adjusted
  1620. to reflect the real position in the log. Not doing it would confuse the
  1621. slave: it would prevent this one from knowing where he is in the
  1622. master's binlog, which would result in wrong positions being shown to
  1623. the user, MASTER_POS_WAIT undue waiting etc.
  1624. */
  1625. if (qinfo.write(&log_file))
  1626. goto err;
  1627. }
  1628. /* Read from the file used to cache the queries .*/
  1629. if (reinit_io_cache(cache, READ_CACHE, 0, 0, 0))
  1630. goto err;
  1631. length=my_b_bytes_in_cache(cache);
  1632. DBUG_EXECUTE_IF("half_binlogged_transaction", length-=100;);
  1633. do
  1634. {
  1635. /* Write data to the binary log file */
  1636. if (my_b_write(&log_file, cache->read_pos, length))
  1637. goto err;
  1638. cache->read_pos=cache->read_end; // Mark buffer used up
  1639. DBUG_EXECUTE_IF("half_binlogged_transaction", goto DBUG_skip_commit;);
  1640. } while ((length=my_b_fill(cache)));
  1641. if (commit_event->write(&log_file))
  1642. goto err;
  1643. #ifndef DBUG_OFF
  1644. DBUG_skip_commit:
  1645. #endif
  1646. if (flush_and_sync())
  1647. goto err;
  1648. DBUG_EXECUTE_IF("half_binlogged_transaction", abort(););
  1649. if (cache->error) // Error on read
  1650. {
  1651. sql_print_error(ER(ER_ERROR_ON_READ), cache->file_name, errno);
  1652. write_error=1; // Don't give more errors
  1653. goto err;
  1654. }
  1655. signal_update();
  1656. /*
  1657. if commit_event is Xid_log_event, increase the number of
  1658. prepared_xids (it's decreasd in ::unlog()). Binlog cannot be rotated
  1659. if there're prepared xids in it - see the comment in new_file() for
  1660. an explanation.
  1661. If the commit_event is not Xid_log_event (then it's a Query_log_event)
  1662. rotate binlog, if necessary.
  1663. */
  1664. if (commit_event->get_type_code() == XID_EVENT)
  1665. {
  1666. pthread_mutex_lock(&LOCK_prep_xids);
  1667. prepared_xids++;
  1668. pthread_mutex_unlock(&LOCK_prep_xids);
  1669. }
  1670. else
  1671. rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
  1672. }
  1673. VOID(pthread_mutex_unlock(&LOCK_log));
  1674. DBUG_RETURN(0);
  1675. err:
  1676. if (!write_error)
  1677. {
  1678. write_error= 1;
  1679. sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
  1680. }
  1681. VOID(pthread_mutex_unlock(&LOCK_log));
  1682. DBUG_RETURN(1);
  1683. }
  1684. /*
  1685. Write to the slow query log.
  1686. */
  1687. bool MYSQL_LOG::write(THD *thd,const char *query, uint query_length,
  1688. time_t query_start_arg)
  1689. {
  1690. bool error=0;
  1691. time_t current_time;
  1692. if (!is_open())
  1693. return 0;
  1694. DBUG_ENTER("MYSQL_LOG::write");
  1695. VOID(pthread_mutex_lock(&LOCK_log));
  1696. if (is_open())
  1697. { // Safety agains reopen
  1698. int tmp_errno=0;
  1699. char buff[80],*end;
  1700. end=buff;
  1701. if (!(thd->options & OPTION_UPDATE_LOG))
  1702. {
  1703. VOID(pthread_mutex_unlock(&LOCK_log));
  1704. DBUG_RETURN(0);
  1705. }
  1706. if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT) || query_start_arg)
  1707. {
  1708. Security_context *sctx= thd->security_ctx;
  1709. current_time=time(NULL);
  1710. if (current_time != last_time)
  1711. {
  1712. last_time=current_time;
  1713. struct tm tm_tmp;
  1714. struct tm *start;
  1715. localtime_r(&current_time,&tm_tmp);
  1716. start=&tm_tmp;
  1717. /* Note that my_b_write() assumes it knows the length for this */
  1718. sprintf(buff,"# Time: %02d%02d%02d %2d:%02d:%02d\n",
  1719. start->tm_year % 100,
  1720. start->tm_mon+1,
  1721. start->tm_mday,
  1722. start->tm_hour,
  1723. start->tm_min,
  1724. start->tm_sec);
  1725. if (my_b_write(&log_file, (byte*) buff,24))
  1726. tmp_errno=errno;
  1727. }
  1728. if (my_b_printf(&log_file, "# User@Host: %s[%s] @ %s [%s]\n",
  1729. sctx->priv_user ?
  1730. sctx->priv_user : "",
  1731. sctx->user ? sctx->user : "",
  1732. sctx->host ? sctx->host : "",
  1733. sctx->ip ? sctx->ip : "") ==
  1734. (uint) -1)
  1735. tmp_errno=errno;
  1736. }
  1737. if (query_start_arg)
  1738. {
  1739. /* For slow query log */
  1740. if (my_b_printf(&log_file,
  1741. "# Query_time: %lu Lock_time: %lu Rows_sent: %lu Rows_examined: %lu\n",
  1742. (ulong) (current_time - query_start_arg),
  1743. (ulong) (thd->time_after_lock - query_start_arg),
  1744. (ulong) thd->sent_row_count,
  1745. (ulong) thd->examined_row_count) == (uint) -1)
  1746. tmp_errno=errno;
  1747. }
  1748. if (thd->db && strcmp(thd->db,db))
  1749. { // Database changed
  1750. if (my_b_printf(&log_file,"use %s;\n",thd->db) == (uint) -1)
  1751. tmp_errno=errno;
  1752. strmov(db,thd->db);
  1753. }
  1754. if (thd->last_insert_id_used_bin_log)
  1755. {
  1756. end=strmov(end,",last_insert_id=");
  1757. end=longlong10_to_str((longlong) thd->current_insert_id,end,-10);
  1758. }
  1759. // Save value if we do an insert.
  1760. if (thd->insert_id_used)
  1761. {
  1762. if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT))
  1763. {
  1764. end=strmov(end,",insert_id=");
  1765. end=longlong10_to_str((longlong) thd->last_insert_id,end,-10);
  1766. }
  1767. }
  1768. if (thd->query_start_used)
  1769. {
  1770. if (query_start_arg != thd->query_start())
  1771. {
  1772. query_start_arg=thd->query_start();
  1773. end=strmov(end,",timestamp=");
  1774. end=int10_to_str((long) query_start_arg,end,10);
  1775. }
  1776. }
  1777. if (end != buff)
  1778. {
  1779. *end++=';';
  1780. *end='\n';
  1781. if (my_b_write(&log_file, (byte*) "SET ",4) ||
  1782. my_b_write(&log_file, (byte*) buff+1,(uint) (end-buff)))
  1783. tmp_errno=errno;
  1784. }
  1785. if (!query)
  1786. {
  1787. end=strxmov(buff, "# administrator command: ",
  1788. command_name[thd->command], NullS);
  1789. query_length=(ulong) (end-buff);
  1790. query=buff;
  1791. }
  1792. if (my_b_write(&log_file, (byte*) query,query_length) ||
  1793. my_b_write(&log_file, (byte*) ";\n",2) ||
  1794. flush_io_cache(&log_file))
  1795. tmp_errno=errno;
  1796. if (tmp_errno)
  1797. {
  1798. error=1;
  1799. if (! write_error)
  1800. {
  1801. write_error=1;
  1802. sql_print_error(ER(ER_ERROR_ON_WRITE),name,error);
  1803. }
  1804. }
  1805. }
  1806. VOID(pthread_mutex_unlock(&LOCK_log));
  1807. DBUG_RETURN(error);
  1808. }
  1809. /*
  1810. Wait until we get a signal that the binary log has been updated
  1811. SYNOPSIS
  1812. wait_for_update()
  1813. thd Thread variable
  1814. is_slave If 0, the caller is the Binlog_dump thread from master;
  1815. if 1, the caller is the SQL thread from the slave. This
  1816. influences only thd->proc_info.
  1817. NOTES
  1818. One must have a lock on LOCK_log before calling this function.
  1819. This lock will be released before return! That's required by
  1820. THD::enter_cond() (see NOTES in sql_class.h).
  1821. */
  1822. void MYSQL_LOG::wait_for_update(THD* thd, bool is_slave)
  1823. {
  1824. const char *old_msg;
  1825. DBUG_ENTER("wait_for_update");
  1826. old_msg= thd->enter_cond(&update_cond, &LOCK_log,
  1827. is_slave ?
  1828. "Has read all relay log; waiting for the slave I/O "
  1829. "thread to update it" :
  1830. "Has sent all binlog to slave; waiting for binlog "
  1831. "to be updated");
  1832. pthread_cond_wait(&update_cond, &LOCK_log);
  1833. thd->exit_cond(old_msg);
  1834. DBUG_VOID_RETURN;
  1835. }
  1836. /*
  1837. Close the log file
  1838. SYNOPSIS
  1839. close()
  1840. exiting Bitmask for one or more of the following bits:
  1841. LOG_CLOSE_INDEX if we should close the index file
  1842. LOG_CLOSE_TO_BE_OPENED if we intend to call open
  1843. at once after close.
  1844. LOG_CLOSE_STOP_EVENT write a 'stop' event to the log
  1845. NOTES
  1846. One can do an open on the object at once after doing a close.
  1847. The internal structures are not freed until cleanup() is called
  1848. */
  1849. void MYSQL_LOG::close(uint exiting)
  1850. { // One can't set log_type here!
  1851. DBUG_ENTER("MYSQL_LOG::close");
  1852. DBUG_PRINT("enter",("exiting: %d", (int) exiting));
  1853. if (log_type != LOG_CLOSED && log_type != LOG_TO_BE_OPENED)
  1854. {
  1855. #ifdef HAVE_REPLICATION
  1856. if (log_type == LOG_BIN && !no_auto_events &&
  1857. (exiting & LOG_CLOSE_STOP_EVENT))
  1858. {
  1859. Stop_log_event s;
  1860. s.write(&log_file);
  1861. bytes_written+= s.data_written;
  1862. signal_update();
  1863. }
  1864. #endif /* HAVE_REPLICATION */
  1865. end_io_cache(&log_file);
  1866. /* don't pwrite in a file opened with O_APPEND - it doesn't work */
  1867. if (log_file.type == WRITE_CACHE && log_type == LOG_BIN)
  1868. {
  1869. my_off_t offset= BIN_LOG_HEADER_SIZE + FLAGS_OFFSET;
  1870. byte flags=0; // clearing LOG_EVENT_BINLOG_IN_USE_F
  1871. my_pwrite(log_file.file, &flags, 1, offset, MYF(0));
  1872. }
  1873. if (my_sync(log_file.file,MYF(MY_WME)) && ! write_error)
  1874. {
  1875. write_error=1;
  1876. sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
  1877. }
  1878. if (my_close(log_file.file,MYF(MY_WME)) && ! write_error)
  1879. {
  1880. write_error=1;
  1881. sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno);
  1882. }
  1883. }
  1884. /*
  1885. The following test is needed even if is_open() is not set, as we may have
  1886. called a not complete close earlier and the index file is still open.
  1887. */
  1888. if ((exiting & LOG_CLOSE_INDEX) && my_b_inited(&index_file))
  1889. {
  1890. end_io_cache(&index_file);
  1891. if (my_close(index_file.file, MYF(0)) < 0 && ! write_error)
  1892. {
  1893. write_error= 1;
  1894. sql_print_error(ER(ER_ERROR_ON_WRITE), index_file_name, errno);
  1895. }
  1896. }
  1897. log_type= (exiting & LOG_CLOSE_TO_BE_OPENED) ? LOG_TO_BE_OPENED : LOG_CLOSED;
  1898. safeFree(name);
  1899. DBUG_VOID_RETURN;
  1900. }
  1901. void MYSQL_LOG::set_max_size(ulong max_size_arg)
  1902. {
  1903. /*
  1904. We need to take locks, otherwise this may happen:
  1905. new_file() is called, calls open(old_max_size), then before open() starts,
  1906. set_max_size() sets max_size to max_size_arg, then open() starts and
  1907. uses the old_max_size argument, so max_size_arg has been overwritten and
  1908. it's like if the SET command was never run.
  1909. */
  1910. DBUG_ENTER("MYSQL_LOG::set_max_size");
  1911. pthread_mutex_lock(&LOCK_log);
  1912. if (is_open())
  1913. max_size= max_size_arg;
  1914. pthread_mutex_unlock(&LOCK_log);
  1915. DBUG_VOID_RETURN;
  1916. }
  1917. /*
  1918. Check if a string is a valid number
  1919. SYNOPSIS
  1920. test_if_number()
  1921. str String to test
  1922. res Store value here
  1923. allow_wildcards Set to 1 if we should ignore '%' and '_'
  1924. NOTE
  1925. For the moment the allow_wildcards argument is not used
  1926. Should be move to some other file.
  1927. RETURN VALUES
  1928. 1 String is a number
  1929. 0 Error
  1930. */
  1931. static bool test_if_number(register const char *str,
  1932. long *res, bool allow_wildcards)
  1933. {
  1934. reg2 int flag;
  1935. const char *start;
  1936. DBUG_ENTER("test_if_number");
  1937. flag=0; start=str;
  1938. while (*str++ == ' ') ;
  1939. if (*--str == '-' || *str == '+')
  1940. str++;
  1941. while (my_isdigit(files_charset_info,*str) ||
  1942. (allow_wildcards && (*str == wild_many || *str == wild_one)))
  1943. {
  1944. flag=1;
  1945. str++;
  1946. }
  1947. if (*str == '.')
  1948. {
  1949. for (str++ ;
  1950. my_isdigit(files_charset_info,*str) ||
  1951. (allow_wildcards && (*str == wild_many || *str == wild_one)) ;
  1952. str++, flag=1) ;
  1953. }
  1954. if (*str != 0 || flag == 0)
  1955. DBUG_RETURN(0);
  1956. if (res)
  1957. *res=atol(start);
  1958. DBUG_RETURN(1); /* Number ok */
  1959. } /* test_if_number */
  1960. void sql_perror(const char *message)
  1961. {
  1962. #ifdef HAVE_STRERROR
  1963. sql_print_error("%s: %s",message, strerror(errno));
  1964. #else
  1965. perror(message);
  1966. #endif
  1967. }
  1968. bool flush_error_log()
  1969. {
  1970. bool result=0;
  1971. if (opt_error_log)
  1972. {
  1973. char err_renamed[FN_REFLEN], *end;
  1974. end= strmake(err_renamed,log_error_file,FN_REFLEN-4);
  1975. strmov(end, "-old");
  1976. VOID(pthread_mutex_lock(&LOCK_error_log));
  1977. #ifdef __WIN__
  1978. char err_temp[FN_REFLEN+4];
  1979. /*
  1980. On Windows is necessary a temporary file for to rename
  1981. the current error file.
  1982. */
  1983. strxmov(err_temp, err_renamed,"-tmp",NullS);
  1984. (void) my_delete(err_temp, MYF(0));
  1985. if (freopen(err_temp,"a+",stdout))
  1986. {
  1987. freopen(err_temp,"a+",stderr);
  1988. (void) my_delete(err_renamed, MYF(0));
  1989. my_rename(log_error_file,err_renamed,MYF(0));
  1990. if (freopen(log_error_file,"a+",stdout))
  1991. freopen(log_error_file,"a+",stderr);
  1992. int fd, bytes;
  1993. char buf[IO_SIZE];
  1994. if ((fd = my_open(err_temp, O_RDONLY, MYF(0))) >= 0)
  1995. {
  1996. while ((bytes = (int) my_read(fd, (byte*) buf, IO_SIZE, MYF(0))) > 0)
  1997. my_fwrite(stderr, (byte*) buf, bytes, MYF(0));
  1998. my_close(fd, MYF(0));
  1999. }
  2000. (void) my_delete(err_temp, MYF(0));
  2001. }
  2002. else
  2003. result= 1;
  2004. #else
  2005. my_rename(log_error_file,err_renamed,MYF(0));
  2006. if (freopen(log_error_file,"a+",stdout))
  2007. freopen(log_error_file,"a+",stderr);
  2008. else
  2009. result= 1;
  2010. #endif
  2011. VOID(pthread_mutex_unlock(&LOCK_error_log));
  2012. }
  2013. return result;
  2014. }
  2015. void MYSQL_LOG::signal_update()
  2016. {
  2017. DBUG_ENTER("MYSQL_LOG::signal_update");
  2018. pthread_cond_broadcast(&update_cond);
  2019. DBUG_VOID_RETURN;
  2020. }
  2021. #ifdef __NT__
  2022. static void print_buffer_to_nt_eventlog(enum loglevel level, char *buff,
  2023. size_t length, size_t buffLen)
  2024. {
  2025. HANDLE event;
  2026. char *buffptr= buff;
  2027. DBUG_ENTER("print_buffer_to_nt_eventlog");
  2028. /* Add ending CR/LF's to string, overwrite last chars if necessary */
  2029. strmov(buffptr+min(length, buffLen-5), "\r\n\r\n");
  2030. setup_windows_event_source();
  2031. if ((event= RegisterEventSource(NULL,"MySQL")))
  2032. {
  2033. switch (level) {
  2034. case ERROR_LEVEL:
  2035. ReportEvent(event, EVENTLOG_ERROR_TYPE, 0, MSG_DEFAULT, NULL, 1, 0,
  2036. (LPCSTR*)&buffptr, NULL);
  2037. break;
  2038. case WARNING_LEVEL:
  2039. ReportEvent(event, EVENTLOG_WARNING_TYPE, 0, MSG_DEFAULT, NULL, 1, 0,
  2040. (LPCSTR*) &buffptr, NULL);
  2041. break;
  2042. case INFORMATION_LEVEL:
  2043. ReportEvent(event, EVENTLOG_INFORMATION_TYPE, 0, MSG_DEFAULT, NULL, 1,
  2044. 0, (LPCSTR*) &buffptr, NULL);
  2045. break;
  2046. }
  2047. DeregisterEventSource(event);
  2048. }
  2049. DBUG_VOID_RETURN;
  2050. }
  2051. #endif /* __NT__ */
  2052. /*
  2053. Prints a printf style message to the error log and, under NT, to the
  2054. Windows event log.
  2055. SYNOPSIS
  2056. vprint_msg_to_log()
  2057. event_type Type of event to write (Error, Warning, or Info)
  2058. format Printf style format of message
  2059. args va_list list of arguments for the message
  2060. NOTE
  2061. IMPLEMENTATION
  2062. This function prints the message into a buffer and then sends that buffer
  2063. to other functions to write that message to other logging sources.
  2064. RETURN VALUES
  2065. void
  2066. */
  2067. #ifdef EMBEDDED_LIBRARY
  2068. void vprint_msg_to_log(enum loglevel level __attribute__((unused)),
  2069. const char *format __attribute__((unused)),
  2070. va_list argsi __attribute__((unused)))
  2071. {}
  2072. #else /*!EMBEDDED_LIBRARY*/
  2073. static void print_buffer_to_file(enum loglevel level, const char *buffer)
  2074. {
  2075. time_t skr;
  2076. struct tm tm_tmp;
  2077. struct tm *start;
  2078. DBUG_ENTER("print_buffer_to_file");
  2079. DBUG_PRINT("enter",("buffer: %s", buffer));
  2080. VOID(pthread_mutex_lock(&LOCK_error_log));
  2081. skr=time(NULL);
  2082. localtime_r(&skr, &tm_tmp);
  2083. start=&tm_tmp;
  2084. fprintf(stderr, "%02d%02d%02d %2d:%02d:%02d [%s] %s\n",
  2085. start->tm_year % 100,
  2086. start->tm_mon+1,
  2087. start->tm_mday,
  2088. start->tm_hour,
  2089. start->tm_min,
  2090. start->tm_sec,
  2091. (level == ERROR_LEVEL ? "ERROR" : level == WARNING_LEVEL ?
  2092. "Warning" : "Note"),
  2093. buffer);
  2094. fflush(stderr);
  2095. VOID(pthread_mutex_unlock(&LOCK_error_log));
  2096. DBUG_VOID_RETURN;
  2097. }
  2098. void vprint_msg_to_log(enum loglevel level, const char *format, va_list args)
  2099. {
  2100. char buff[1024];
  2101. size_t length;
  2102. DBUG_ENTER("vprint_msg_to_log");
  2103. length= my_vsnprintf(buff, sizeof(buff), format, args);
  2104. print_buffer_to_file(level, buff);
  2105. #ifdef __NT__
  2106. print_buffer_to_nt_eventlog(level, buff, length, sizeof(buff));
  2107. #endif
  2108. DBUG_VOID_RETURN;
  2109. }
  2110. #endif /*EMBEDDED_LIBRARY*/
  2111. void sql_print_error(const char *format, ...)
  2112. {
  2113. va_list args;
  2114. DBUG_ENTER("sql_print_error");
  2115. va_start(args, format);
  2116. vprint_msg_to_log(ERROR_LEVEL, format, args);
  2117. va_end(args);
  2118. DBUG_VOID_RETURN;
  2119. }
  2120. void sql_print_warning(const char *format, ...)
  2121. {
  2122. va_list args;
  2123. DBUG_ENTER("sql_print_warning");
  2124. va_start(args, format);
  2125. vprint_msg_to_log(WARNING_LEVEL, format, args);
  2126. va_end(args);
  2127. DBUG_VOID_RETURN;
  2128. }
  2129. void sql_print_information(const char *format, ...)
  2130. {
  2131. va_list args;
  2132. DBUG_ENTER("sql_print_information");
  2133. va_start(args, format);
  2134. vprint_msg_to_log(INFORMATION_LEVEL, format, args);
  2135. va_end(args);
  2136. DBUG_VOID_RETURN;
  2137. }
  2138. /********* transaction coordinator log for 2pc - mmap() based solution *******/
  2139. /*
  2140. the log consists of a file, mmapped to a memory.
  2141. file is divided on pages of tc_log_page_size size.
  2142. (usable size of the first page is smaller because of log header)
  2143. there's PAGE control structure for each page
  2144. each page (or rather PAGE control structure) can be in one of three
  2145. states - active, syncing, pool.
  2146. there could be only one page in active or syncing states,
  2147. but many in pool - pool is fifo queue.
  2148. usual lifecycle of a page is pool->active->syncing->pool
  2149. "active" page - is a page where new xid's are logged.
  2150. the page stays active as long as syncing slot is taken.
  2151. "syncing" page is being synced to disk. no new xid can be added to it.
  2152. when the sync is done the page is moved to a pool and an active page
  2153. becomes "syncing".
  2154. the result of such an architecture is a natural "commit grouping" -
  2155. If commits are coming faster than the system can sync, they do not
  2156. stall. Instead, all commit that came since the last sync are
  2157. logged to the same page, and they all are synced with the next -
  2158. one - sync. Thus, thought individual commits are delayed, throughput
  2159. is not decreasing.
  2160. when a xid is added to an active page, the thread of this xid waits
  2161. for a page's condition until the page is synced. when syncing slot
  2162. becomes vacant one of these waiters is awaken to take care of syncing.
  2163. it syncs the page and signals all waiters that the page is synced.
  2164. PAGE::waiters is used to count these waiters, and a page may never
  2165. become active again until waiters==0 (that is all waiters from the
  2166. previous sync have noticed the sync was completed)
  2167. note, that the page becomes "dirty" and has to be synced only when a
  2168. new xid is added into it. Removing a xid from a page does not make it
  2169. dirty - we don't sync removals to disk.
  2170. */
  2171. ulong tc_log_page_waits= 0;
  2172. #ifdef HAVE_MMAP
  2173. #define TC_LOG_HEADER_SIZE (sizeof(tc_log_magic)+1)
  2174. static const char tc_log_magic[]={(char) 254, 0x23, 0x05, 0x74};
  2175. ulong opt_tc_log_size= TC_LOG_MIN_SIZE;
  2176. ulong tc_log_max_pages_used=0, tc_log_page_size=0, tc_log_cur_pages_used=0;
  2177. int TC_LOG_MMAP::open(const char *opt_name)
  2178. {
  2179. uint i;
  2180. bool crashed=FALSE;
  2181. PAGE *pg;
  2182. DBUG_ASSERT(total_ha_2pc > 1);
  2183. DBUG_ASSERT(opt_name && opt_name[0]);
  2184. tc_log_page_size= my_getpagesize();
  2185. DBUG_ASSERT(TC_LOG_PAGE_SIZE % tc_log_page_size == 0);
  2186. fn_format(logname,opt_name,mysql_data_home,"",MY_UNPACK_FILENAME);
  2187. if ((fd= my_open(logname, O_RDWR, MYF(0))) < 0)
  2188. {
  2189. if (my_errno != ENOENT)
  2190. goto err;
  2191. if (using_heuristic_recover())
  2192. return 1;
  2193. if ((fd= my_create(logname, CREATE_MODE, O_RDWR, MYF(MY_WME))) < 0)
  2194. goto err;
  2195. inited=1;
  2196. file_length= opt_tc_log_size;
  2197. if (my_chsize(fd, file_length, 0, MYF(MY_WME)))
  2198. goto err;
  2199. }
  2200. else
  2201. {
  2202. inited= 1;
  2203. crashed= TRUE;
  2204. sql_print_information("Recovering after a crash using %s", opt_name);
  2205. if (tc_heuristic_recover)
  2206. {
  2207. sql_print_error("Cannot perform automatic crash recovery when "
  2208. "--tc-heuristic-recover is used");
  2209. goto err;
  2210. }
  2211. file_length= my_seek(fd, 0L, MY_SEEK_END, MYF(MY_WME+MY_FAE));
  2212. if (file_length == MY_FILEPOS_ERROR || file_length % tc_log_page_size)
  2213. goto err;
  2214. }
  2215. data= (uchar *)my_mmap(0, (size_t)file_length, PROT_READ|PROT_WRITE,
  2216. MAP_NOSYNC|MAP_SHARED, fd, 0);
  2217. if (data == MAP_FAILED)
  2218. {
  2219. my_errno=errno;
  2220. goto err;
  2221. }
  2222. inited=2;
  2223. npages=(uint)file_length/tc_log_page_size;
  2224. DBUG_ASSERT(npages >= 3); // to guarantee non-empty pool
  2225. if (!(pages=(PAGE *)my_malloc(npages*sizeof(PAGE), MYF(MY_WME|MY_ZEROFILL))))
  2226. goto err;
  2227. inited=3;
  2228. for (pg=pages, i=0; i < npages; i++, pg++)
  2229. {
  2230. pg->next=pg+1;
  2231. pg->waiters=0;
  2232. pg->state=POOL;
  2233. pthread_mutex_init(&pg->lock, MY_MUTEX_INIT_FAST);
  2234. pthread_cond_init (&pg->cond, 0);
  2235. pg->start=(my_xid *)(data + i*tc_log_page_size);
  2236. pg->end=(my_xid *)(pg->start + tc_log_page_size);
  2237. pg->size=pg->free=tc_log_page_size/sizeof(my_xid);
  2238. }
  2239. pages[0].size=pages[0].free=
  2240. (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid);
  2241. pages[0].start=pages[0].end-pages[0].size;
  2242. pages[npages-1].next=0;
  2243. inited=4;
  2244. if (crashed && recover())
  2245. goto err;
  2246. memcpy(data, tc_log_magic, sizeof(tc_log_magic));
  2247. data[sizeof(tc_log_magic)]= (uchar)total_ha_2pc;
  2248. my_msync(fd, data, tc_log_page_size, MS_SYNC);
  2249. inited=5;
  2250. pthread_mutex_init(&LOCK_sync, MY_MUTEX_INIT_FAST);
  2251. pthread_mutex_init(&LOCK_active, MY_MUTEX_INIT_FAST);
  2252. pthread_mutex_init(&LOCK_pool, MY_MUTEX_INIT_FAST);
  2253. pthread_cond_init(&COND_active, 0);
  2254. pthread_cond_init(&COND_pool, 0);
  2255. inited=6;
  2256. syncing= 0;
  2257. active=pages;
  2258. pool=pages+1;
  2259. pool_last=pages+npages-1;
  2260. return 0;
  2261. err:
  2262. close();
  2263. return 1;
  2264. }
  2265. /*
  2266. there is no active page, let's got one from the pool
  2267. two strategies here:
  2268. 1. take the first from the pool
  2269. 2. if there're waiters - take the one with the most free space
  2270. TODO page merging. try to allocate adjacent page first,
  2271. so that they can be flushed both in one sync
  2272. */
  2273. void TC_LOG_MMAP::get_active_from_pool()
  2274. {
  2275. PAGE **p, **best_p=0;
  2276. int best_free;
  2277. if (syncing)
  2278. pthread_mutex_lock(&LOCK_pool);
  2279. do
  2280. {
  2281. best_p= p= &pool;
  2282. if ((*p)->waiters == 0) // can the first page be used ?
  2283. break; // yes - take it.
  2284. best_free=0; // no - trying second strategy
  2285. for (p=&(*p)->next; *p; p=&(*p)->next)
  2286. {
  2287. if ((*p)->waiters == 0 && (*p)->free > best_free)
  2288. {
  2289. best_free=(*p)->free;
  2290. best_p=p;
  2291. }
  2292. }
  2293. }
  2294. while ((*best_p == 0 || best_free == 0) && overflow());
  2295. active=*best_p;
  2296. if (active->free == active->size) // we've chosen an empty page
  2297. {
  2298. tc_log_cur_pages_used++;
  2299. set_if_bigger(tc_log_max_pages_used, tc_log_cur_pages_used);
  2300. }
  2301. if ((*best_p)->next) // unlink the page from the pool
  2302. *best_p=(*best_p)->next;
  2303. else
  2304. pool_last=*best_p;
  2305. if (syncing)
  2306. pthread_mutex_unlock(&LOCK_pool);
  2307. }
  2308. int TC_LOG_MMAP::overflow()
  2309. {
  2310. /*
  2311. simple overflow handling - just wait
  2312. TODO perhaps, increase log size ?
  2313. let's check the behaviour of tc_log_page_waits first
  2314. */
  2315. tc_log_page_waits++;
  2316. pthread_cond_wait(&COND_pool, &LOCK_pool);
  2317. return 1; // always return 1
  2318. }
  2319. /*
  2320. Record that transaction XID is committed on the persistent storage
  2321. NOTES
  2322. This function is called in the middle of two-phase commit:
  2323. First all resources prepare the transaction, then tc_log->log() is called,
  2324. then all resources commit the transaction, then tc_log->unlog() is called.
  2325. All access to active page is serialized but it's not a problem, as
  2326. we're assuming that fsync() will be a main bottleneck.
  2327. That is, parallelizing writes to log pages we'll decrease number of
  2328. threads waiting for a page, but then all these threads will be waiting
  2329. for a fsync() anyway
  2330. IMPLEMENTATION
  2331. If tc_log == MYSQL_LOG then tc_log writes transaction to binlog and
  2332. records XID in a special Xid_log_event.
  2333. If tc_log = TC_LOG_MMAP then xid is written in a special memory-mapped
  2334. log.
  2335. RETURN
  2336. 0 Error
  2337. # "cookie", a number that will be passed as an argument
  2338. to unlog() call. tc_log can define it any way it wants,
  2339. and use for whatever purposes. TC_LOG_MMAP sets it
  2340. to the position in memory where xid was logged to.
  2341. */
  2342. int TC_LOG_MMAP::log_xid(THD *thd, my_xid xid)
  2343. {
  2344. int err;
  2345. PAGE *p;
  2346. ulong cookie;
  2347. pthread_mutex_lock(&LOCK_active);
  2348. /*
  2349. if active page is full - just wait...
  2350. frankly speaking, active->free here accessed outside of mutex
  2351. protection, but it's safe, because it only means we may miss an
  2352. unlog() for the active page, and we're not waiting for it here -
  2353. unlog() does not signal COND_active.
  2354. */
  2355. while (unlikely(active && active->free == 0))
  2356. pthread_cond_wait(&COND_active, &LOCK_active);
  2357. /* no active page ? take one from the pool */
  2358. if (active == 0)
  2359. get_active_from_pool();
  2360. p=active;
  2361. pthread_mutex_lock(&p->lock);
  2362. /* searching for an empty slot */
  2363. while (*p->ptr)
  2364. {
  2365. p->ptr++;
  2366. DBUG_ASSERT(p->ptr < p->end); // because p->free > 0
  2367. }
  2368. /* found! store xid there and mark the page dirty */
  2369. cookie= (ulong)((uchar *)p->ptr - data); // can never be zero
  2370. *p->ptr++= xid;
  2371. p->free--;
  2372. p->state= DIRTY;
  2373. /* to sync or not to sync - this is the question */
  2374. pthread_mutex_unlock(&LOCK_active);
  2375. pthread_mutex_lock(&LOCK_sync);
  2376. pthread_mutex_unlock(&p->lock);
  2377. if (syncing)
  2378. { // somebody's syncing. let's wait
  2379. p->waiters++;
  2380. /*
  2381. note - it must be while (), not do ... while () here
  2382. as p->state may be not DIRTY when we come here
  2383. */
  2384. while (p->state == DIRTY && syncing)
  2385. pthread_cond_wait(&p->cond, &LOCK_sync);
  2386. p->waiters--;
  2387. err= p->state == ERROR;
  2388. if (p->state != DIRTY) // page was synced
  2389. {
  2390. if (p->waiters == 0)
  2391. pthread_cond_signal(&COND_pool); // in case somebody's waiting
  2392. pthread_mutex_unlock(&LOCK_sync);
  2393. goto done; // we're done
  2394. }
  2395. } // page was not synced! do it now
  2396. DBUG_ASSERT(active == p && syncing == 0);
  2397. pthread_mutex_lock(&LOCK_active);
  2398. syncing=p; // place is vacant - take it
  2399. active=0; // page is not active anymore
  2400. pthread_cond_broadcast(&COND_active); // in case somebody's waiting
  2401. pthread_mutex_unlock(&LOCK_active);
  2402. pthread_mutex_unlock(&LOCK_sync);
  2403. err= sync();
  2404. done:
  2405. return err ? 0 : cookie;
  2406. }
  2407. int TC_LOG_MMAP::sync()
  2408. {
  2409. int err;
  2410. DBUG_ASSERT(syncing != active);
  2411. /*
  2412. sit down and relax - this can take a while...
  2413. note - no locks are held at this point
  2414. */
  2415. err= my_msync(fd, syncing->start, 1, MS_SYNC);
  2416. /* page is synced. let's move it to the pool */
  2417. pthread_mutex_lock(&LOCK_pool);
  2418. pool_last->next=syncing;
  2419. pool_last=syncing;
  2420. syncing->next=0;
  2421. syncing->state= err ? ERROR : POOL;
  2422. pthread_cond_broadcast(&syncing->cond); // signal "sync done"
  2423. pthread_cond_signal(&COND_pool); // in case somebody's waiting
  2424. pthread_mutex_unlock(&LOCK_pool);
  2425. /* marking 'syncing' slot free */
  2426. pthread_mutex_lock(&LOCK_sync);
  2427. syncing=0;
  2428. pthread_cond_signal(&active->cond); // wake up a new syncer
  2429. pthread_mutex_unlock(&LOCK_sync);
  2430. return err;
  2431. }
  2432. /*
  2433. erase xid from the page, update page free space counters/pointers.
  2434. cookie points directly to the memory where xid was logged
  2435. */
  2436. void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid)
  2437. {
  2438. PAGE *p=pages+(cookie/tc_log_page_size);
  2439. my_xid *x=(my_xid *)(data+cookie);
  2440. DBUG_ASSERT(*x == xid);
  2441. DBUG_ASSERT(x >= p->start && x < p->end);
  2442. *x=0;
  2443. pthread_mutex_lock(&p->lock);
  2444. p->free++;
  2445. DBUG_ASSERT(p->free <= p->size);
  2446. set_if_smaller(p->ptr, x);
  2447. if (p->free == p->size) // the page is completely empty
  2448. statistic_decrement(tc_log_cur_pages_used, &LOCK_status);
  2449. if (p->waiters == 0) // the page is in pool and ready to rock
  2450. pthread_cond_signal(&COND_pool); // ping ... for overflow()
  2451. pthread_mutex_unlock(&p->lock);
  2452. }
  2453. void TC_LOG_MMAP::close()
  2454. {
  2455. uint i;
  2456. switch (inited) {
  2457. case 6:
  2458. pthread_mutex_destroy(&LOCK_sync);
  2459. pthread_mutex_destroy(&LOCK_active);
  2460. pthread_mutex_destroy(&LOCK_pool);
  2461. pthread_cond_destroy(&COND_pool);
  2462. case 5:
  2463. data[0]='A'; // garble the first (signature) byte, in case my_delete fails
  2464. case 4:
  2465. for (i=0; i < npages; i++)
  2466. {
  2467. if (pages[i].ptr == 0)
  2468. break;
  2469. pthread_mutex_destroy(&pages[i].lock);
  2470. pthread_cond_destroy(&pages[i].cond);
  2471. }
  2472. case 3:
  2473. my_free((gptr)pages, MYF(0));
  2474. case 2:
  2475. my_munmap((byte*)data, (size_t)file_length);
  2476. case 1:
  2477. my_close(fd, MYF(0));
  2478. }
  2479. if (inited>=5) // cannot do in the switch because of Windows
  2480. my_delete(logname, MYF(MY_WME));
  2481. inited=0;
  2482. }
  2483. int TC_LOG_MMAP::recover()
  2484. {
  2485. HASH xids;
  2486. PAGE *p=pages, *end_p=pages+npages;
  2487. if (memcmp(data, tc_log_magic, sizeof(tc_log_magic)))
  2488. {
  2489. sql_print_error("Bad magic header in tc log");
  2490. goto err1;
  2491. }
  2492. /*
  2493. the first byte after magic signature is set to current
  2494. number of storage engines on startup
  2495. */
  2496. if (data[sizeof(tc_log_magic)] != total_ha_2pc)
  2497. {
  2498. sql_print_error("Recovery failed! You must enable "
  2499. "exactly %d storage engines that support "
  2500. "two-phase commit protocol",
  2501. data[sizeof(tc_log_magic)]);
  2502. goto err1;
  2503. }
  2504. if (hash_init(&xids, &my_charset_bin, tc_log_page_size/3, 0,
  2505. sizeof(my_xid), 0, 0, MYF(0)))
  2506. goto err1;
  2507. for ( ; p < end_p ; p++)
  2508. {
  2509. for (my_xid *x=p->start; x < p->end; x++)
  2510. if (*x && my_hash_insert(&xids, (byte *)x))
  2511. goto err2; // OOM
  2512. }
  2513. if (ha_recover(&xids))
  2514. goto err2;
  2515. hash_free(&xids);
  2516. bzero(data, (size_t)file_length);
  2517. return 0;
  2518. err2:
  2519. hash_free(&xids);
  2520. err1:
  2521. sql_print_error("Crash recovery failed. Either correct the problem "
  2522. "(if it's, for example, out of memory error) and restart, "
  2523. "or delete tc log and start mysqld with "
  2524. "--tc-heuristic-recover={commit|rollback}");
  2525. return 1;
  2526. }
  2527. #endif
  2528. TC_LOG *tc_log;
  2529. TC_LOG_DUMMY tc_log_dummy;
  2530. TC_LOG_MMAP tc_log_mmap;
  2531. /*
  2532. Perform heuristic recovery, if --tc-heuristic-recover was used
  2533. RETURN VALUE
  2534. 0 no heuristic recovery was requested
  2535. 1 heuristic recovery was performed
  2536. NOTE
  2537. no matter whether heuristic recovery was successful or not
  2538. mysqld must exit. So, return value is the same in both cases.
  2539. */
  2540. int TC_LOG::using_heuristic_recover()
  2541. {
  2542. if (!tc_heuristic_recover)
  2543. return 0;
  2544. sql_print_information("Heuristic crash recovery mode");
  2545. if (ha_recover(0))
  2546. sql_print_error("Heuristic crash recovery failed");
  2547. sql_print_information("Please restart mysqld without --tc-heuristic-recover");
  2548. return 1;
  2549. }
  2550. /****** transaction coordinator log for 2pc - binlog() based solution ******/
  2551. #define TC_LOG_BINLOG MYSQL_LOG
  2552. /*
  2553. TODO keep in-memory list of prepared transactions
  2554. (add to list in log(), remove on unlog())
  2555. and copy it to the new binlog if rotated
  2556. but let's check the behaviour of tc_log_page_waits first!
  2557. */
  2558. int TC_LOG_BINLOG::open(const char *opt_name)
  2559. {
  2560. LOG_INFO log_info;
  2561. int error= 1;
  2562. DBUG_ASSERT(total_ha_2pc > 1);
  2563. DBUG_ASSERT(opt_name && opt_name[0]);
  2564. pthread_mutex_init(&LOCK_prep_xids, MY_MUTEX_INIT_FAST);
  2565. pthread_cond_init (&COND_prep_xids, 0);
  2566. if (!my_b_inited(&index_file))
  2567. {
  2568. /* There was a failure to open the index file, can't open the binlog */
  2569. cleanup();
  2570. return 1;
  2571. }
  2572. if (using_heuristic_recover())
  2573. {
  2574. /* generate a new binlog to mask a corrupted one */
  2575. open(opt_name, LOG_BIN, 0, WRITE_CACHE, 0, max_binlog_size, 0);
  2576. cleanup();
  2577. return 1;
  2578. }
  2579. if ((error= find_log_pos(&log_info, NullS, 1)))
  2580. {
  2581. if (error != LOG_INFO_EOF)
  2582. sql_print_error("find_log_pos() failed (error: %d)", error);
  2583. else
  2584. error= 0;
  2585. goto err;
  2586. }
  2587. {
  2588. const char *errmsg;
  2589. IO_CACHE log;
  2590. File file;
  2591. Log_event *ev=0;
  2592. Format_description_log_event fdle(BINLOG_VERSION);
  2593. char log_name[FN_REFLEN];
  2594. if (! fdle.is_valid())
  2595. goto err;
  2596. do
  2597. {
  2598. strmake(log_name, log_info.log_file_name, sizeof(log_name)-1);
  2599. } while (!(error= find_next_log(&log_info, 1)));
  2600. if (error != LOG_INFO_EOF)
  2601. {
  2602. sql_print_error("find_log_pos() failed (error: %d)", error);
  2603. goto err;
  2604. }
  2605. if ((file= open_binlog(&log, log_name, &errmsg)) < 0)
  2606. {
  2607. sql_print_error("%s", errmsg);
  2608. goto err;
  2609. }
  2610. if ((ev= Log_event::read_log_event(&log, 0, &fdle)) &&
  2611. ev->get_type_code() == FORMAT_DESCRIPTION_EVENT &&
  2612. ev->flags & LOG_EVENT_BINLOG_IN_USE_F)
  2613. {
  2614. sql_print_information("Recovering after a crash using %s", opt_name);
  2615. error= recover(&log, (Format_description_log_event *)ev);
  2616. }
  2617. else
  2618. error=0;
  2619. delete ev;
  2620. end_io_cache(&log);
  2621. my_close(file, MYF(MY_WME));
  2622. if (error)
  2623. goto err;
  2624. }
  2625. err:
  2626. return error;
  2627. }
  2628. /* this is called on shutdown, after ha_panic */
  2629. void TC_LOG_BINLOG::close()
  2630. {
  2631. DBUG_ASSERT(prepared_xids==0);
  2632. pthread_mutex_destroy(&LOCK_prep_xids);
  2633. pthread_cond_destroy (&COND_prep_xids);
  2634. }
  2635. /*
  2636. TODO group commit
  2637. RETURN
  2638. 0 - error
  2639. 1 - success
  2640. */
  2641. int TC_LOG_BINLOG::log_xid(THD *thd, my_xid xid)
  2642. {
  2643. Xid_log_event xle(thd, xid);
  2644. IO_CACHE *trans_log= (IO_CACHE*)thd->ha_data[binlog_hton.slot];
  2645. return !binlog_end_trans(thd, trans_log, &xle); // invert return value
  2646. }
  2647. void TC_LOG_BINLOG::unlog(ulong cookie, my_xid xid)
  2648. {
  2649. pthread_mutex_lock(&LOCK_prep_xids);
  2650. if (--prepared_xids == 0)
  2651. pthread_cond_signal(&COND_prep_xids);
  2652. pthread_mutex_unlock(&LOCK_prep_xids);
  2653. rotate_and_purge(0); // as ::write() did not rotate
  2654. }
  2655. int TC_LOG_BINLOG::recover(IO_CACHE *log, Format_description_log_event *fdle)
  2656. {
  2657. Log_event *ev;
  2658. HASH xids;
  2659. MEM_ROOT mem_root;
  2660. if (! fdle->is_valid() ||
  2661. hash_init(&xids, &my_charset_bin, TC_LOG_PAGE_SIZE/3, 0,
  2662. sizeof(my_xid), 0, 0, MYF(0)))
  2663. goto err1;
  2664. init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE);
  2665. fdle->flags&= ~LOG_EVENT_BINLOG_IN_USE_F; // abort on the first error
  2666. while ((ev= Log_event::read_log_event(log,0,fdle)) && ev->is_valid())
  2667. {
  2668. if (ev->get_type_code() == XID_EVENT)
  2669. {
  2670. Xid_log_event *xev=(Xid_log_event *)ev;
  2671. byte *x=(byte *)memdup_root(&mem_root, (char *)& xev->xid,
  2672. sizeof(xev->xid));
  2673. if (! x)
  2674. goto err2;
  2675. my_hash_insert(&xids, x);
  2676. }
  2677. delete ev;
  2678. }
  2679. if (ha_recover(&xids))
  2680. goto err2;
  2681. free_root(&mem_root, MYF(0));
  2682. hash_free(&xids);
  2683. return 0;
  2684. err2:
  2685. free_root(&mem_root, MYF(0));
  2686. hash_free(&xids);
  2687. err1:
  2688. sql_print_error("Crash recovery failed. Either correct the problem "
  2689. "(if it's, for example, out of memory error) and restart, "
  2690. "or delete (or rename) binary log and start mysqld with "
  2691. "--tc-heuristic-recover={commit|rollback}");
  2692. return 1;
  2693. }