hatoku_hton.cc 84.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

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

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.
53
  This software is covered by US Patent No. 8,489,638.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

PATENT RIGHTS GRANT:

  "THIS IMPLEMENTATION" means the copyrightable works distributed by
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
Rich Prohaska's avatar
Rich Prohaska committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/* -*- mode: C; c-basic-offset: 4 -*- */
#define MYSQL_SERVER 1
#include "hatoku_defines.h"
#include <db.h>

#include "stdint.h"
#if defined(_WIN32)
#include "misc.h"
#endif
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "toku_os.h"
#include "toku_time.h"
#include "partitioned_counter.h"

/* We define DTRACE after mysql_priv.h in case it disabled dtrace in the main server */
#ifdef HAVE_DTRACE
#define _DTRACE_VERSION 1
#else
#endif

#include <mysql/plugin.h>
#include "hatoku_hton.h"
#include "ha_tokudb.h"

#undef PACKAGE
#undef VERSION
#undef HAVE_DTRACE
#undef _DTRACE_VERSION

#define TOKU_METADB_NAME "tokudb_meta"

typedef struct savepoint_info {
    DB_TXN* txn;
    tokudb_trx_data* trx;
    bool in_sub_stmt;
} *SP_INFO, SP_INFO_T;

static uchar *tokudb_get_key(TOKUDB_SHARE * share, size_t * length, my_bool not_used __attribute__ ((unused))) {
    *length = share->table_name_length;
    return (uchar *) share->table_name;
}

static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root);

136

Rich Prohaska's avatar
Rich Prohaska committed
137 138 139 140 141
static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer);
static void tokudb_cleanup_log_files(void);
static int tokudb_end(handlerton * hton, ha_panic_function type);
static bool tokudb_flush_logs(handlerton * hton);
static bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * print, enum ha_stat_type);
142
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
143
static void tokudb_handle_fatal_signal(handlerton *hton, THD *thd, int sig);
144
#endif
Rich Prohaska's avatar
Rich Prohaska committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
static int tokudb_close_connection(handlerton * hton, THD * thd);
static int tokudb_commit(handlerton * hton, THD * thd, bool all);
static int tokudb_rollback(handlerton * hton, THD * thd, bool all);
#if TOKU_INCLUDE_XA
static int tokudb_xa_prepare(handlerton* hton, THD* thd, bool all);
static int tokudb_xa_recover(handlerton* hton, XID*  xid_list, uint  len);
static int tokudb_commit_by_xid(handlerton* hton, XID* xid);
static int tokudb_rollback_by_xid(handlerton* hton, XID*  xid);
#endif

static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_discover(handlerton *hton, THD* thd, const char *db, const char *name, uchar **frmblob, size_t *frmlen);
static int tokudb_discover2(handlerton *hton, THD* thd, const char *db, const char *name, bool translate_name,uchar **frmblob, size_t *frmlen);
handlerton *tokudb_hton;

const char *ha_tokudb_ext = ".tokudb";
char *tokudb_data_dir;
ulong tokudb_debug;
DB_ENV *db_env;
DB* metadata_db;
HASH tokudb_open_tables;
pthread_mutex_t tokudb_mutex;
pthread_mutex_t tokudb_meta_mutex;

171
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
172 173
static my_bool tokudb_gdb_on_fatal;
static char *tokudb_gdb_path;
174
#endif
175

Rich Prohaska's avatar
Rich Prohaska committed
176 177 178 179 180
static PARTITIONED_COUNTER tokudb_primary_key_bytes_inserted;
void toku_hton_update_primary_key_bytes_inserted(uint64_t row_size) {
    increment_partitioned_counter(tokudb_primary_key_bytes_inserted, row_size);
}

181
static void tokudb_lock_timeout_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key, uint64_t blocking_txnid);
Rich Prohaska's avatar
Rich Prohaska committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
static ulong tokudb_cleaner_period;
static ulong tokudb_cleaner_iterations;

#define ASSERT_MSGLEN 1024

void toku_hton_assert_fail(const char* expr_as_string, const char * fun, const char * file, int line, int caller_errno) {
    char msg[ASSERT_MSGLEN];
    if (db_env) {
        snprintf(msg, ASSERT_MSGLEN, "Handlerton: %s ", expr_as_string);
        db_env->crash(db_env, msg, fun, file, line,caller_errno);
    }
    else {
        snprintf(msg, ASSERT_MSGLEN, "Handlerton assertion failed, no env, %s, %d, %s, %s (errno=%d)\n", file, line, fun, expr_as_string, caller_errno);
        perror(msg);
        fflush(stderr);
    }
    abort();
}

//my_bool tokudb_shared_data = false;
static uint32_t tokudb_init_flags = 
    DB_CREATE | DB_THREAD | DB_PRIVATE | 
    DB_INIT_LOCK | 
    DB_INIT_MPOOL |
    DB_INIT_TXN | 
    DB_INIT_LOG |
    DB_RECOVER;
static uint32_t tokudb_env_flags = 0;
// static uint32_t tokudb_lock_type = DB_LOCK_DEFAULT;
// static ulong tokudb_log_buffer_size = 0;
// static ulong tokudb_log_file_size = 0;
static my_bool tokudb_directio = FALSE;
static my_bool tokudb_checkpoint_on_flush_logs = FALSE;
static ulonglong tokudb_cache_size = 0;
static ulonglong tokudb_max_lock_memory = 0;
static char *tokudb_home;
static char *tokudb_tmp_dir;
static char *tokudb_log_dir;
// static long tokudb_lock_scan_time = 0;
// static ulong tokudb_region_size = 0;
// static ulong tokudb_cache_parts = 1;
const char *tokudb_hton_name = "TokuDB";
static uint32_t tokudb_checkpointing_period;
static uint32_t tokudb_fsync_log_period;
uint32_t tokudb_write_status_frequency;
uint32_t tokudb_read_status_frequency;
#ifdef TOKUDB_VERSION
char *tokudb_version = (char*) TOKUDB_VERSION;
#else
char *tokudb_version;
#endif
static int tokudb_fs_reserve_percent;  // file system reserve as a percentage of total disk space

#if defined(_WIN32)
extern "C" {
#include "ydb.h"
}
#endif

// A flag set if the handlerton is in an initialized, usable state,
// plus a reader-write lock to protect it without serializing reads.
// Since we don't have static initializers for the opaque rwlock type,
// use constructor and destructor functions to create and destroy
// the lock before and after main(), respectively.
static int tokudb_hton_initialized;
static rw_lock_t tokudb_hton_initialized_lock;

static void create_tokudb_hton_intialized_lock(void)  __attribute__((constructor));
250
static void create_tokudb_hton_intialized_lock(void) {
Rich Prohaska's avatar
Rich Prohaska committed
251 252 253
    my_rwlock_init(&tokudb_hton_initialized_lock, 0);
}

254 255
static void destroy_tokudb_hton_initialized_lock(void) __attribute__((destructor));
static void destroy_tokudb_hton_initialized_lock(void) {
Rich Prohaska's avatar
Rich Prohaska committed
256 257 258 259 260 261 262
    rwlock_destroy(&tokudb_hton_initialized_lock);
}

static SHOW_VAR *toku_global_status_variables = NULL;
static uint64_t toku_global_status_max_rows;
static TOKU_ENGINE_STATUS_ROW_S* toku_global_status_rows = NULL;

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
static void handle_ydb_error(int error) {
    switch (error) {
    case TOKUDB_HUGE_PAGES_ENABLED:
        fprintf(stderr, "************************************************************\n");
        fprintf(stderr, "                                                            \n");
        fprintf(stderr, "                        @@@@@@@@@@@                         \n");
        fprintf(stderr, "                      @@'         '@@                       \n");
        fprintf(stderr, "                     @@    _     _  @@                      \n");
        fprintf(stderr, "                     |    (.)   (.)  |                      \n");
        fprintf(stderr, "                     |             ` |                      \n");
        fprintf(stderr, "                     |        >    ' |                      \n");
        fprintf(stderr, "                     |     .----.    |                      \n");
        fprintf(stderr, "                     ..   |.----.|  ..                      \n");
        fprintf(stderr, "                      ..  '      ' ..                       \n");
        fprintf(stderr, "                        .._______,.                         \n");
        fprintf(stderr, "                                                            \n");
        fprintf(stderr, " %s will not run with transparent huge pages enabled.       \n", tokudb_hton_name);
        fprintf(stderr, " Please disable them to continue.                           \n");
        fprintf(stderr, " (echo never > /sys/kernel/mm/transparent_hugepage/enabled) \n");
        fprintf(stderr, "                                                            \n");
        fprintf(stderr, "************************************************************\n");
        fflush(stderr);
        break;
    }
}
288

Rich Prohaska's avatar
Rich Prohaska committed
289 290 291
static int tokudb_init_func(void *p) {
    TOKUDB_DBUG_ENTER("tokudb_init_func");
    int r;
292

Rich Prohaska's avatar
Rich Prohaska committed
293 294 295
#if defined(_WIN64)
        r = toku_ydb_init();
        if (r) {
296
            fprintf(stderr, "got error %d\n", r);
Rich Prohaska's avatar
Rich Prohaska committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
            goto error;
        }
#endif

    // 3938: lock the handlerton's initialized status flag for writing
    r = rw_wrlock(&tokudb_hton_initialized_lock);
    assert(r == 0);

    db_env = NULL;
    metadata_db = NULL;

    tokudb_hton = (handlerton *) p;

    pthread_mutex_init(&tokudb_mutex, MY_MUTEX_INIT_FAST);
    pthread_mutex_init(&tokudb_meta_mutex, MY_MUTEX_INIT_FAST);
    (void) my_hash_init(&tokudb_open_tables, table_alias_charset, 32, 0, 0, (my_hash_get_key) tokudb_get_key, 0, 0);

    tokudb_hton->state = SHOW_OPTION_YES;
    // tokudb_hton->flags= HTON_CAN_RECREATE;  // QQQ this came from skeleton
    tokudb_hton->flags = HTON_CLOSE_CURSORS_AT_COMMIT;

#if TOKU_INCLUDE_OTHER_DB_TYPE
    // we have historically been a dynamic storage engine, so we set db_type according.
    // however, extended keys is triggered off of the db_type, so tokudb adds another type so that extended keys works
    tokudb_hton->db_type = DB_TYPE_UNKNOWN;
    tokudb_hton->other_db_type = DB_TYPE_TOKUDB;
#else
    tokudb_hton->db_type = DB_TYPE_TOKUDB;
#endif

    tokudb_hton->create = tokudb_create_handler;
    tokudb_hton->close_connection = tokudb_close_connection;

    tokudb_hton->savepoint_offset = sizeof(SP_INFO_T);
    tokudb_hton->savepoint_set = tokudb_savepoint;
    tokudb_hton->savepoint_rollback = tokudb_rollback_to_savepoint;
    tokudb_hton->savepoint_release = tokudb_release_savepoint;

    tokudb_hton->discover = tokudb_discover;
#if defined(MYSQL_HANDLERTON_INCLUDE_DISCOVER2)
    tokudb_hton->discover2 = tokudb_discover2;
#endif
    tokudb_hton->commit = tokudb_commit;
    tokudb_hton->rollback = tokudb_rollback;
#if TOKU_INCLUDE_XA
    tokudb_hton->prepare=tokudb_xa_prepare;
    tokudb_hton->recover=tokudb_xa_recover;
    tokudb_hton->commit_by_xid=tokudb_commit_by_xid;
    tokudb_hton->rollback_by_xid=tokudb_rollback_by_xid;
#endif

    tokudb_hton->panic = tokudb_end;
    tokudb_hton->flush_logs = tokudb_flush_logs;
    tokudb_hton->show_status = tokudb_show_status;
351
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
352
    tokudb_hton->handle_fatal_signal = tokudb_handle_fatal_signal;
353
#endif
Rich Prohaska's avatar
Rich Prohaska committed
354 355 356
    if (!tokudb_home)
        tokudb_home = mysql_real_data_home;
    DBUG_PRINT("info", ("tokudb_home: %s", tokudb_home));
Rich Prohaska's avatar
Rich Prohaska committed
357

Rich Prohaska's avatar
Rich Prohaska committed
358 359
    if ((r = db_env_create(&db_env, 0))) {
        DBUG_PRINT("info", ("db_env_create %d\n", r));
360
        handle_ydb_error(r);
Rich Prohaska's avatar
Rich Prohaska committed
361 362 363 364 365 366 367 368 369 370 371 372 373
        goto error;
    }

    DBUG_PRINT("info", ("tokudb_env_flags: 0x%x\n", tokudb_env_flags));
    r = db_env->set_flags(db_env, tokudb_env_flags, 1);
    if (r) { // QQQ
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
            TOKUDB_TRACE("%s:WARNING: flags=%x r=%d\n", __FUNCTION__, tokudb_env_flags, r); 
        // goto error;
    }

    // config error handling
    db_env->set_errcall(db_env, tokudb_print_error);
374
    db_env->set_errpfx(db_env, tokudb_hton_name);
Rich Prohaska's avatar
Rich Prohaska committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

    //
    // set default comparison functions
    //
    r = db_env->set_default_bt_compare(db_env, tokudb_cmp_dbt_key);
    if (r) {
        DBUG_PRINT("info", ("set_default_bt_compare%d\n", r));
        goto error; 
    }

    {
    char *tmp_dir = tokudb_tmp_dir;
    char *data_dir = tokudb_data_dir;
    if (data_dir == 0) {
        data_dir = mysql_data_home;
    }
    if (tmp_dir == 0) {
        tmp_dir = data_dir;
    }
    DBUG_PRINT("info", ("tokudb_data_dir: %s\n", data_dir));
    db_env->set_data_dir(db_env, data_dir);

    DBUG_PRINT("info", ("tokudb_tmp_dir: %s\n", tmp_dir));
    db_env->set_tmp_dir(db_env, tmp_dir);
    }

    if (tokudb_log_dir) {
        DBUG_PRINT("info", ("tokudb_log_dir: %s\n", tokudb_log_dir));
        db_env->set_lg_dir(db_env, tokudb_log_dir);
    }

    // config the cache table size to min(1/2 of physical memory, 1/8 of the process address space)
    if (tokudb_cache_size == 0) {
        uint64_t physmem, maxdata;
        physmem = toku_os_get_phys_memory_size();
        tokudb_cache_size = physmem / 2;
        r = toku_os_get_max_process_data_size(&maxdata);
        if (r == 0) {
            if (tokudb_cache_size > maxdata / 8)
                tokudb_cache_size = maxdata / 8;
        }
    }
    if (tokudb_cache_size) {
        DBUG_PRINT("info", ("tokudb_cache_size: %lld\n", tokudb_cache_size));
        r = db_env->set_cachesize(db_env, (uint32_t)(tokudb_cache_size >> 30), (uint32_t)(tokudb_cache_size % (1024L * 1024L * 1024L)), 1);
        if (r) {
            DBUG_PRINT("info", ("set_cachesize %d\n", r));
            goto error; 
        }
    }
    if (tokudb_max_lock_memory == 0) {
        tokudb_max_lock_memory = tokudb_cache_size/8;
    }
    if (tokudb_max_lock_memory) {
        DBUG_PRINT("info", ("tokudb_max_lock_memory: %lld\n", tokudb_max_lock_memory));
        r = db_env->set_lk_max_memory(db_env, tokudb_max_lock_memory);
        if (r) {
            DBUG_PRINT("info", ("set_lk_max_memory %d\n", r));
            goto error; 
        }
    }
    
    uint32_t gbytes, bytes; int parts;
    r = db_env->get_cachesize(db_env, &gbytes, &bytes, &parts);
    if (r == 0) 
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
            TOKUDB_TRACE("%s:tokudb_cache_size=%lld\n", __FUNCTION__, ((unsigned long long) gbytes << 30) + bytes);

    if (db_env->set_redzone) {
        r = db_env->set_redzone(db_env, tokudb_fs_reserve_percent);
        if (r && (tokudb_debug & TOKUDB_DEBUG_INIT))
            TOKUDB_TRACE("%s:%d r=%d\n", __FUNCTION__, __LINE__, r);
    }

    if (tokudb_debug & TOKUDB_DEBUG_INIT) TOKUDB_TRACE("%s:env open:flags=%x\n", __FUNCTION__, tokudb_init_flags);

    r = db_env->set_generate_row_callback_for_put(db_env,generate_row_for_put);
    assert(r == 0);
    r = db_env->set_generate_row_callback_for_del(db_env,generate_row_for_del);
    assert(r == 0);
    db_env->set_update(db_env, tokudb_update_fun);
    db_env_set_direct_io(tokudb_directio == TRUE);
    db_env->change_fsync_log_period(db_env, tokudb_fsync_log_period);
458
    db_env->set_lock_timeout_callback(db_env, tokudb_lock_timeout_callback);
459
    db_env->set_loader_memory_size(db_env, tokudb_get_loader_memory_size_callback);
460

Rich Prohaska's avatar
Rich Prohaska committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    r = db_env->open(db_env, tokudb_home, tokudb_init_flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);

    if (tokudb_debug & TOKUDB_DEBUG_INIT) TOKUDB_TRACE("%s:env opened:return=%d\n", __FUNCTION__, r);

    if (r) {
        DBUG_PRINT("info", ("env->open %d\n", r));
        goto error;
    }

    r = db_env->checkpointing_set_period(db_env, tokudb_checkpointing_period);
    assert(r == 0);
    r = db_env->cleaner_set_period(db_env, tokudb_cleaner_period);
    assert(r == 0);
    r = db_env->cleaner_set_iterations(db_env, tokudb_cleaner_iterations);
    assert(r == 0);

477
    r = db_env->set_lock_timeout(db_env, DEFAULT_TOKUDB_LOCK_TIMEOUT, tokudb_get_lock_wait_time_callback);
Rich Prohaska's avatar
Rich Prohaska committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    assert(r == 0);

    r = db_env->get_engine_status_num_rows (db_env, &toku_global_status_max_rows);
    assert(r == 0);

    {
        const myf mem_flags = MY_FAE|MY_WME|MY_ZEROFILL|MY_ALLOW_ZERO_PTR|MY_FREE_ON_ERROR;
        toku_global_status_variables = (SHOW_VAR*)my_malloc(sizeof(*toku_global_status_variables)*toku_global_status_max_rows, mem_flags);
        toku_global_status_rows = (TOKU_ENGINE_STATUS_ROW_S*)my_malloc(sizeof(*toku_global_status_rows)*toku_global_status_max_rows, mem_flags);
    }

    r = db_create(&metadata_db, db_env, 0);
    if (r) {
        DBUG_PRINT("info", ("failed to create metadata db %d\n", r));
        goto error;
    }
    

    r= metadata_db->open(metadata_db, NULL, TOKU_METADB_NAME, NULL, DB_BTREE, DB_THREAD, 0);
    if (r) {
        if (r != ENOENT) {
            sql_print_error("Got error %d when trying to open metadata_db", r);
            goto error;
        }
        r = metadata_db->close(metadata_db,0);
        assert(r == 0);
        r = db_create(&metadata_db, db_env, 0);
        if (r) {
            DBUG_PRINT("info", ("failed to create metadata db %d\n", r));
            goto error;
        }

        r= metadata_db->open(metadata_db, NULL, TOKU_METADB_NAME, NULL, DB_BTREE, DB_THREAD | DB_CREATE | DB_EXCL, my_umask);
        if (r) {
            goto error;
        }
    }



    tokudb_primary_key_bytes_inserted = create_partitioned_counter();

    //3938: succeeded, set the init status flag and unlock
    tokudb_hton_initialized = 1;
    rw_unlock(&tokudb_hton_initialized_lock);
    DBUG_RETURN(false);

error:
    if (metadata_db) {
        int rr = metadata_db->close(metadata_db, 0);
        assert(rr==0);
    }
    if (db_env) {
        int rr= db_env->close(db_env, 0);
        assert(rr==0);
        db_env = 0;
    }

    // 3938: failed to initialized, drop the flag and lock
    tokudb_hton_initialized = 0;
    rw_unlock(&tokudb_hton_initialized_lock);
    DBUG_RETURN(true);
}

static int tokudb_done_func(void *p) {
    TOKUDB_DBUG_ENTER("tokudb_done_func");
Rich Prohaska's avatar
Rich Prohaska committed
544 545 546 547
    my_free(toku_global_status_variables);
    toku_global_status_variables = NULL;
    my_free(toku_global_status_rows);
    toku_global_status_rows = NULL;
Rich Prohaska's avatar
Rich Prohaska committed
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    my_hash_free(&tokudb_open_tables);
    pthread_mutex_destroy(&tokudb_mutex);
    pthread_mutex_destroy(&tokudb_meta_mutex);
#if defined(_WIN64)
    toku_ydb_destroy();
#endif
    TOKUDB_DBUG_RETURN(0);
}

static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root) {
    return new(mem_root) ha_tokudb(hton, table);
}

int tokudb_end(handlerton * hton, ha_panic_function type) {
    TOKUDB_DBUG_ENTER("tokudb_end");
    int error = 0;
    
    // 3938: if we finalize the storage engine plugin, it is no longer
    // initialized. grab a writer lock for the duration of the
    // call, so we can drop the flag and destroy the mutexes
    // in isolation.
    rw_wrlock(&tokudb_hton_initialized_lock);
    assert(tokudb_hton_initialized);

    if (metadata_db) {
        int r = metadata_db->close(metadata_db, 0);
        assert(r == 0);
    }
    if (db_env) {
        if (tokudb_init_flags & DB_INIT_LOG)
            tokudb_cleanup_log_files();
        error = db_env->close(db_env, 0);       // Error is logged
        assert(error==0);
        db_env = NULL;
    }

    // 3938: drop the initialized flag and unlock
    tokudb_hton_initialized = 0;
    rw_unlock(&tokudb_hton_initialized_lock);

    TOKUDB_DBUG_RETURN(error);
}

static int tokudb_close_connection(handlerton * hton, THD * thd) {
    int error = 0;
    tokudb_trx_data* trx = NULL;
    trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
    if (trx && trx->checkpoint_lock_taken) {
        error = db_env->checkpointing_resume(db_env);
    }
Rich Prohaska's avatar
Rich Prohaska committed
598
    my_free(trx);
Rich Prohaska's avatar
Rich Prohaska committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    return error;
}

bool tokudb_flush_logs(handlerton * hton) {
    TOKUDB_DBUG_ENTER("tokudb_flush_logs");
    int error;
    bool result = 0;

    if (tokudb_checkpoint_on_flush_logs) {
        //
        // take the checkpoint
        //
        error = db_env->txn_checkpoint(db_env, 0, 0, 0);
        if (error) {
            my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);
            result = 1;
            goto exit;
        }
    }
    else {
        error = db_env->log_flush(db_env, NULL);
        assert(error == 0);
    }

    result = 0;
exit:
    TOKUDB_DBUG_RETURN(result);
}


typedef struct txn_progress_info {
    char status[200];
    THD* thd;
} *TXN_PROGRESS_INFO;

634
static void txn_progress_func(TOKU_TXN_PROGRESS progress, void* extra) {
Rich Prohaska's avatar
Rich Prohaska committed
635
    TXN_PROGRESS_INFO progress_info = (TXN_PROGRESS_INFO)extra;
636 637 638 639 640 641 642 643
    int r = sprintf(progress_info->status, 
                    "%sprocessing %s of transaction, %" PRId64 " out of %" PRId64,
                    progress->stalled_on_checkpoint ? "Writing committed changes to disk, " : "",
                    progress->is_commit ? "commit" : "abort",
                    progress->entries_processed, 
                    progress->entries_total
                    ); 
    assert(r >= 0);
Rich Prohaska's avatar
Rich Prohaska committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    thd_proc_info(progress_info->thd, progress_info->status);
}

static void commit_txn_with_progress(DB_TXN* txn, uint32_t flags, THD* thd) {
    int r;
    struct txn_progress_info info;
    info.thd = thd;
    r = txn->commit_with_progress(txn, flags, txn_progress_func, &info);
    if (r != 0) {
        sql_print_error("tried committing transaction %p and got error code %d", txn, r);
    }
    assert(r == 0);
}

static void abort_txn_with_progress(DB_TXN* txn, THD* thd) {
    int r;
    struct txn_progress_info info;
    info.thd = thd;
    r = txn->abort_with_progress(txn, txn_progress_func, &info);
    if (r != 0) {
        sql_print_error("tried aborting transaction %p and got error code %d", txn, r);
    }
    assert(r == 0);
}

static int tokudb_commit(handlerton * hton, THD * thd, bool all) {
    TOKUDB_DBUG_ENTER("tokudb_commit");
    DBUG_PRINT("trans", ("ending transaction %s", all ? "all" : "stmt"));
    uint32_t syncflag = THDVAR(thd, commit_sync) ? 0 : DB_TXN_NOSYNC;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
675 676
    DB_TXN *this_txn = *txn;
    if (this_txn) {
Rich Prohaska's avatar
Rich Prohaska committed
677
        if (tokudb_debug & TOKUDB_DEBUG_TXN) {
Rich Prohaska's avatar
Rich Prohaska committed
678
            TOKUDB_TRACE("commit %u %p\n", all, this_txn);
Rich Prohaska's avatar
Rich Prohaska committed
679 680 681
        }
        // test hook to induce a crash on a debug build
        DBUG_EXECUTE_IF("tokudb_crash_commit_before", DBUG_SUICIDE(););
682
        commit_txn_with_progress(this_txn, syncflag, thd);
Rich Prohaska's avatar
Rich Prohaska committed
683 684
        // test hook to induce a crash on a debug build
        DBUG_EXECUTE_IF("tokudb_crash_commit_after", DBUG_SUICIDE(););
685
        if (this_txn == trx->sp_level) {
Rich Prohaska's avatar
Rich Prohaska committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
            trx->sp_level = 0;
        }
        *txn = 0;
        trx->sub_sp_level = NULL;
    } 
    else if (tokudb_debug & TOKUDB_DEBUG_TXN) {
        TOKUDB_TRACE("nothing to commit %d\n", all);
    }
    reset_stmt_progress(&trx->stmt_progress);
    TOKUDB_DBUG_RETURN(0);
}

static int tokudb_rollback(handlerton * hton, THD * thd, bool all) {
    TOKUDB_DBUG_ENTER("tokudb_rollback");
    DBUG_PRINT("trans", ("aborting transaction %s", all ? "all" : "stmt"));
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
703 704
    DB_TXN *this_txn = *txn;
    if (this_txn) {
Rich Prohaska's avatar
Rich Prohaska committed
705
        if (tokudb_debug & TOKUDB_DEBUG_TXN) {
Rich Prohaska's avatar
Rich Prohaska committed
706
            TOKUDB_TRACE("rollback %u %p\n", all, this_txn);
Rich Prohaska's avatar
Rich Prohaska committed
707
        }
708
        abort_txn_with_progress(this_txn, thd);
Rich Prohaska's avatar
Rich Prohaska committed
709
        if (this_txn == trx->sp_level) {
Rich Prohaska's avatar
Rich Prohaska committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
            trx->sp_level = 0;
        }
        *txn = 0;
        trx->sub_sp_level = NULL;
    } 
    else {
        if (tokudb_debug & TOKUDB_DEBUG_TXN) {
            TOKUDB_TRACE("abort0\n");
        }
    }
    reset_stmt_progress(&trx->stmt_progress);
    TOKUDB_DBUG_RETURN(0);
}

#if TOKU_INCLUDE_XA

static int tokudb_xa_prepare(handlerton* hton, THD* thd, bool all) {
    TOKUDB_DBUG_ENTER("tokudb_xa_prepare");
    int r = 0;
    DBUG_PRINT("trans", ("preparing transaction %s", all ? "all" : "stmt"));
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    DB_TXN* txn = all ? trx->all : trx->stmt;
    if (txn) {
        if (tokudb_debug & TOKUDB_DEBUG_TXN) {
            TOKUDB_TRACE("doing txn prepare:%d:%p\n", all, txn);
        }
        // a TOKU_XA_XID is identical to a MYSQL_XID
        TOKU_XA_XID thd_xid;
        thd_get_xid(thd, (MYSQL_XID*) &thd_xid);
        // test hook to induce a crash on a debug build
        DBUG_EXECUTE_IF("tokudb_crash_prepare_before", DBUG_SUICIDE(););
        r = txn->xa_prepare(txn, &thd_xid);
        // test hook to induce a crash on a debug build
        DBUG_EXECUTE_IF("tokudb_crash_prepare_after", DBUG_SUICIDE(););
    } 
    else if (tokudb_debug & TOKUDB_DEBUG_TXN) {
        TOKUDB_TRACE("nothing to prepare %d\n", all);
    }
    TOKUDB_DBUG_RETURN(r);
}

static int tokudb_xa_recover(handlerton* hton, XID*  xid_list, uint  len) {
    TOKUDB_DBUG_ENTER("tokudb_xa_recover");
    int r = 0;
    if (len == 0 || xid_list == NULL) {
        TOKUDB_DBUG_RETURN(0);
    }
    long num_returned = 0;
    r = db_env->txn_xa_recover(
        db_env,
        (TOKU_XA_XID*)xid_list,
        len,
        &num_returned,
        DB_NEXT
        );
    assert(r == 0);
    TOKUDB_DBUG_RETURN((int)num_returned);
}

static int tokudb_commit_by_xid(handlerton* hton, XID* xid) {
    TOKUDB_DBUG_ENTER("tokudb_commit_by_xid");
    int r = 0;
    DB_TXN* txn = NULL;
    TOKU_XA_XID* toku_xid = (TOKU_XA_XID*)xid;

    r = db_env->get_txn_from_xid(db_env, toku_xid, &txn);
    if (r) { goto cleanup; }

    r = txn->commit(txn, 0);
    if (r) { goto cleanup; }

    r = 0;
cleanup:
    TOKUDB_DBUG_RETURN(r);
}

static int tokudb_rollback_by_xid(handlerton* hton, XID*  xid) {
    TOKUDB_DBUG_ENTER("tokudb_rollback_by_xid");
    int r = 0;
    DB_TXN* txn = NULL;
    TOKU_XA_XID* toku_xid = (TOKU_XA_XID*)xid;

    r = db_env->get_txn_from_xid(db_env, toku_xid, &txn);
    if (r) { goto cleanup; }

    r = txn->abort(txn);
    if (r) { goto cleanup; }

    r = 0;
cleanup:
    TOKUDB_DBUG_RETURN(r);
}

#endif

static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint) {
    TOKUDB_DBUG_ENTER("tokudb_savepoint");
    int error;
    SP_INFO save_info = (SP_INFO)savepoint;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    if (thd->in_sub_stmt) {
        assert(trx->stmt);
Rich Prohaska's avatar
Rich Prohaska committed
812
        error = txn_begin(db_env, trx->sub_sp_level, &(save_info->txn), DB_INHERIT_ISOLATION, thd);
Rich Prohaska's avatar
Rich Prohaska committed
813 814 815 816 817 818 819
        if (error) {
            goto cleanup;
        }
        trx->sub_sp_level = save_info->txn;
        save_info->in_sub_stmt = true;
    }
    else {
Rich Prohaska's avatar
Rich Prohaska committed
820
        error = txn_begin(db_env, trx->sp_level, &(save_info->txn), DB_INHERIT_ISOLATION, thd);
Rich Prohaska's avatar
Rich Prohaska committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
        if (error) {
            goto cleanup;
        }
        trx->sp_level = save_info->txn;
        save_info->in_sub_stmt = false;
    }
    save_info->trx = trx;
    error = 0;
cleanup:
    TOKUDB_DBUG_RETURN(error);
}

static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint) {
    TOKUDB_DBUG_ENTER("tokudb_rollback_to_savepoint");
    int error;
    SP_INFO save_info = (SP_INFO)savepoint;
    DB_TXN* parent = NULL;
    DB_TXN* txn_to_rollback = save_info->txn;

    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    parent = txn_to_rollback->parent;
    if (!(error = txn_to_rollback->abort(txn_to_rollback))) {
        if (save_info->in_sub_stmt) {
            trx->sub_sp_level = parent;
        }
        else {
            trx->sp_level = parent;
        }
        error = tokudb_savepoint(hton, thd, savepoint);
    }
    TOKUDB_DBUG_RETURN(error);
}

static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint) {
    TOKUDB_DBUG_ENTER("tokudb_release_savepoint");
    int error;

    SP_INFO save_info = (SP_INFO)savepoint;
    DB_TXN* parent = NULL;
    DB_TXN* txn_to_commit = save_info->txn;

    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
    parent = txn_to_commit->parent;
    if (!(error = txn_to_commit->commit(txn_to_commit, 0))) {
        if (save_info->in_sub_stmt) {
            trx->sub_sp_level = parent;
        }
        else {
            trx->sp_level = parent;
        }
        save_info->txn = NULL;
    }
    TOKUDB_DBUG_RETURN(error);
}

static int tokudb_discover(handlerton *hton, THD* thd, const char *db, const char *name, uchar **frmblob, size_t *frmlen) {
    return tokudb_discover2(hton, thd, db, name, true, frmblob, frmlen);
}

static int tokudb_discover2(handlerton *hton, THD* thd, const char *db, const char *name, bool translate_name,
                            uchar **frmblob, size_t *frmlen) {
    TOKUDB_DBUG_ENTER("tokudb_discover");
    int error;
    DB* status_db = NULL;
    DB_TXN* txn = NULL;
    char path[FN_REFLEN + 1];
    HA_METADATA_KEY curr_key = hatoku_frm_data;
    DBT key, value;    
    memset(&key, 0, sizeof(key));
    memset(&value, 0, sizeof(&value));
    
Rich Prohaska's avatar
Rich Prohaska committed
892
    error = txn_begin(db_env, 0, &txn, 0, thd);
Rich Prohaska's avatar
Rich Prohaska committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    if (error) { goto cleanup; }

    build_table_filename(path, sizeof(path) - 1, db, name, "", translate_name ? 0 : FN_IS_TMP);
    error = open_status_dictionary(&status_db, path, txn);
    if (error) { goto cleanup; }

    key.data = &curr_key;
    key.size = sizeof(curr_key);

    error = status_db->getf_set(
        status_db, 
        txn,
        0,
        &key, 
        smart_dbt_callback_verify_frm,
        &value
        );
    if (error) {
        goto cleanup;
    }

    *frmblob = (uchar *)value.data;
    *frmlen = value.size;

    error = 0;
cleanup:
    if (status_db) {
        status_db->close(status_db,0);
    }
    if (txn) {
        commit_txn(txn, 0);
    }
    TOKUDB_DBUG_RETURN(error);    
}


Rich Prohaska's avatar
Rich Prohaska committed
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
#define STATPRINT(legend, val) if (legend != NULL && val != NULL) stat_print(thd,   \
                                          tokudb_hton_name, \
                                          strlen(tokudb_hton_name), \
                                          legend, \
                                          strlen(legend), \
                                          val, \
                                          strlen(val))

extern sys_var *intern_find_sys_var(const char *str, uint length, bool no_error);

static bool tokudb_show_engine_status(THD * thd, stat_print_fn * stat_print) {
    TOKUDB_DBUG_ENTER("tokudb_show_engine_status");
    int error;
    uint64_t panic;
    const int panic_string_len = 1024;
    char panic_string[panic_string_len] = {'\0'};
    uint64_t num_rows;
    uint64_t max_rows;
    fs_redzone_state redzone_state;
    const int bufsiz = 1024;
    char buf[bufsiz];

#if MYSQL_VERSION_ID < 50500
    {
        sys_var * version = intern_find_sys_var("version", 0, false);
        snprintf(buf, bufsiz, "%s", version->value_ptr(thd, (enum_var_type)0, (LEX_STRING*)NULL));
        STATPRINT("Version", buf);
Rich Prohaska's avatar
Rich Prohaska committed
956
    }
Rich Prohaska's avatar
Rich Prohaska committed
957 958 959 960
#endif
    error = db_env->get_engine_status_num_rows (db_env, &max_rows);
    TOKU_ENGINE_STATUS_ROW_S mystat[max_rows];
    error = db_env->get_engine_status (db_env, mystat, max_rows, &num_rows, &redzone_state, &panic, panic_string, panic_string_len, TOKU_ENGINE_STATUS);
Rich Prohaska's avatar
Rich Prohaska committed
961

Rich Prohaska's avatar
Rich Prohaska committed
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    if (strlen(panic_string)) {
        STATPRINT("Environment panic string", panic_string);
    }
    if (error == 0) {
        if (panic) {
            snprintf(buf, bufsiz, "%" PRIu64, panic);
            STATPRINT("Environment panic", buf);
        }
        
        if(redzone_state == FS_BLOCKED) {
            STATPRINT("*** URGENT WARNING ***", "FILE SYSTEM IS COMPLETELY FULL");
            snprintf(buf, bufsiz, "FILE SYSTEM IS COMPLETELY FULL");
        }
        else if (redzone_state == FS_GREEN) {
            snprintf(buf, bufsiz, "more than %d percent of total file system space", 2*tokudb_fs_reserve_percent);
        }
        else if (redzone_state == FS_YELLOW) {
            snprintf(buf, bufsiz, "*** WARNING *** FILE SYSTEM IS GETTING FULL (less than %d percent free)", 2*tokudb_fs_reserve_percent);
        } 
        else if (redzone_state == FS_RED){
            snprintf(buf, bufsiz, "*** WARNING *** FILE SYSTEM IS GETTING VERY FULL (less than %d percent free): INSERTS ARE PROHIBITED", tokudb_fs_reserve_percent);
        }
        else {
            snprintf(buf, bufsiz, "information unavailable, unknown redzone state %d", redzone_state);
        }
        STATPRINT ("disk free space", buf);

        for (uint64_t row = 0; row < num_rows; row++) {
            switch (mystat[row].type) {
            case FS_STATE:
                snprintf(buf, bufsiz, "%"PRIu64"", mystat[row].value.num);
                break;
            case UINT64:
                snprintf(buf, bufsiz, "%"PRIu64"", mystat[row].value.num);
                break;
            case CHARSTR:
                snprintf(buf, bufsiz, "%s", mystat[row].value.str);
                break;
            case UNIXTIME:
                {
                    time_t t = mystat[row].value.num;
                    char tbuf[26];
                    snprintf(buf, bufsiz, "%.24s", ctime_r(&t, tbuf));
                }
                break;
            case TOKUTIME:
                {
                    double t = tokutime_to_seconds(mystat[row].value.num);
                    snprintf(buf, bufsiz, "%.6f", t);
                }
                break;
            case PARCOUNT:
                {
                    uint64_t v = read_partitioned_counter(mystat[row].value.parcount);
                    snprintf(buf, bufsiz, "%" PRIu64, v);
                }
                break;
            default:
                snprintf(buf, bufsiz, "UNKNOWN STATUS TYPE: %d", mystat[row].type);
                break;                
            }
            STATPRINT(mystat[row].legend, buf);
        }
        uint64_t bytes_inserted = read_partitioned_counter(tokudb_primary_key_bytes_inserted);
        snprintf(buf, bufsiz, "%" PRIu64, bytes_inserted);
        STATPRINT("handlerton: primary key bytes inserted", buf);
    }  
    if (error) { my_errno = error; }
    TOKUDB_DBUG_RETURN(error);
Rich Prohaska's avatar
Rich Prohaska committed
1031 1032
}

Rich Prohaska's avatar
Rich Prohaska committed
1033
static void tokudb_checkpoint_lock(THD * thd) {
Rich Prohaska's avatar
Rich Prohaska committed
1034
    int error;
Rich Prohaska's avatar
Rich Prohaska committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    tokudb_trx_data* trx = NULL;
    char status_msg[200]; //buffer of 200 should be a good upper bound.
    trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
    if (!trx) {
        error = create_tokudb_trx_data_instance(&trx);
        //
        // can only fail due to memory allocation, so ok to assert
        //
        assert(!error);
        thd_data_set(thd, tokudb_hton->slot, trx);
Rich Prohaska's avatar
Rich Prohaska committed
1045
    }
Rich Prohaska's avatar
Rich Prohaska committed
1046 1047
    
    if (trx->checkpoint_lock_taken) {
Rich Prohaska's avatar
Rich Prohaska committed
1048 1049
        goto cleanup;
    }
Rich Prohaska's avatar
Rich Prohaska committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    //
    // This can only fail if environment is not created, which is not possible
    // in handlerton
    //
    sprintf(status_msg, "Trying to grab checkpointing lock.");
    thd_proc_info(thd, status_msg);
    error = db_env->checkpointing_postpone(db_env);
    assert(!error);

    trx->checkpoint_lock_taken = true;
cleanup:
    return;
}

static void tokudb_checkpoint_unlock(THD * thd) {
    int error;
    char status_msg[200]; //buffer of 200 should be a good upper bound.
    tokudb_trx_data* trx = NULL;
    trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
    if (!trx) {
        error = 0;
        goto  cleanup;
Rich Prohaska's avatar
Rich Prohaska committed
1072
    }
Rich Prohaska's avatar
Rich Prohaska committed
1073
    if (!trx->checkpoint_lock_taken) {
Rich Prohaska's avatar
Rich Prohaska committed
1074
        error = 0;
Rich Prohaska's avatar
Rich Prohaska committed
1075
        goto  cleanup;
Rich Prohaska's avatar
Rich Prohaska committed
1076
    }
Rich Prohaska's avatar
Rich Prohaska committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    //
    // at this point, we know the checkpoint lock has been taken
    //
    sprintf(status_msg, "Trying to release checkpointing lock.");
    thd_proc_info(thd, status_msg);
    error = db_env->checkpointing_resume(db_env);
    assert(!error);

    trx->checkpoint_lock_taken = false;
    
Rich Prohaska's avatar
Rich Prohaska committed
1087
cleanup:
Rich Prohaska's avatar
Rich Prohaska committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    return;
}

static bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * stat_print, enum ha_stat_type stat_type) {
    switch (stat_type) {
    case HA_ENGINE_STATUS:
        return tokudb_show_engine_status(thd, stat_print);
        break;
    default:
        break;
Rich Prohaska's avatar
Rich Prohaska committed
1098
    }
Rich Prohaska's avatar
Rich Prohaska committed
1099 1100 1101 1102
    return false;
}

#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
1103
static void tokudb_handle_fatal_signal(handlerton *hton __attribute__ ((__unused__)), THD *thd __attribute__ ((__unused__)), int sig) {
Rich Prohaska's avatar
Rich Prohaska committed
1104 1105
    if (tokudb_gdb_on_fatal) {
        db_env_try_gdb_stack_trace(tokudb_gdb_path);
Rich Prohaska's avatar
Rich Prohaska committed
1106
    }
Rich Prohaska's avatar
Rich Prohaska committed
1107 1108 1109 1110 1111
}
#endif

static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer) {
    sql_print_error("%s:  %s", db_errpfx, buffer);
Rich Prohaska's avatar
Rich Prohaska committed
1112 1113
}

Rich Prohaska's avatar
Rich Prohaska committed
1114 1115 1116
static void tokudb_cleanup_log_files(void) {
    TOKUDB_DBUG_ENTER("tokudb_cleanup_log_files");
    char **names;
Rich Prohaska's avatar
Rich Prohaska committed
1117 1118
    int error;

Rich Prohaska's avatar
Rich Prohaska committed
1119 1120 1121 1122 1123 1124 1125
    if ((error = db_env->txn_checkpoint(db_env, 0, 0, 0)))
        my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);

    if ((error = db_env->log_archive(db_env, &names, 0)) != 0) {
        DBUG_PRINT("error", ("log_archive failed (error %d)", error));
        db_env->err(db_env, error, "log_archive");
        DBUG_VOID_RETURN;
Rich Prohaska's avatar
Rich Prohaska committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    }

    if (names) {
        char **np;
        for (np = names; *np; ++np) {
#if 1
            if (tokudb_debug)
                TOKUDB_TRACE("%s:cleanup:%s\n", __FUNCTION__, *np);
#else
            my_delete(*np, MYF(MY_WME));
#endif
        }

        free(names);
    }

    DBUG_VOID_RETURN;
}

// options flags
//   PLUGIN_VAR_THDLOCAL  Variable is per-connection
//   PLUGIN_VAR_READONLY  Server variable is read only
//   PLUGIN_VAR_NOSYSVAR  Not a server variable
//   PLUGIN_VAR_NOCMDOPT  Not a command line option
//   PLUGIN_VAR_NOCMDARG  No argument for cmd line
//   PLUGIN_VAR_RQCMDARG  Argument required for cmd line
//   PLUGIN_VAR_OPCMDARG  Argument optional for cmd line
//   PLUGIN_VAR_MEMALLOC  String needs memory allocated


// system variables
static void tokudb_cleaner_period_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
    ulong * cleaner_period = (ulong *) var;
    *cleaner_period = *(const ulonglong *) save;
    int r = db_env->cleaner_set_period(db_env, *cleaner_period);
    assert(r == 0);
}

#define DEFAULT_CLEANER_PERIOD 1

static MYSQL_SYSVAR_ULONG(cleaner_period, tokudb_cleaner_period,
    0, "TokuDB cleaner_period", 
    NULL, tokudb_cleaner_period_update, DEFAULT_CLEANER_PERIOD,
    0, ~0UL, 0);

static void tokudb_cleaner_iterations_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
    ulong * cleaner_iterations = (ulong *) var;
    *cleaner_iterations = *(const ulonglong *) save;
    int r = db_env->cleaner_set_iterations(db_env, *cleaner_iterations);
    assert(r == 0);
}

#define DEFAULT_CLEANER_ITERATIONS 5

static MYSQL_SYSVAR_ULONG(cleaner_iterations, tokudb_cleaner_iterations,
    0, "TokuDB cleaner_iterations", 
    NULL, tokudb_cleaner_iterations_update, DEFAULT_CLEANER_ITERATIONS,
    0, ~0UL, 0);

static void tokudb_checkpointing_period_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
    uint * checkpointing_period = (uint *) var;
    *checkpointing_period = *(const ulonglong *) save;
    int r = db_env->checkpointing_set_period(db_env, *checkpointing_period);
    assert(r == 0);
}

static MYSQL_SYSVAR_UINT(checkpointing_period, tokudb_checkpointing_period, 
    0, "TokuDB Checkpointing period", 
    NULL, tokudb_checkpointing_period_update, 60, 
    0, ~0U, 0);

static MYSQL_SYSVAR_BOOL(directio, tokudb_directio,
    PLUGIN_VAR_READONLY,
    "TokuDB Enable Direct I/O ",
    NULL, NULL, FALSE);
static MYSQL_SYSVAR_BOOL(checkpoint_on_flush_logs, tokudb_checkpoint_on_flush_logs,
    0,
    "TokuDB Checkpoint on Flush Logs ",
    NULL, NULL, FALSE);

static MYSQL_SYSVAR_ULONGLONG(cache_size, tokudb_cache_size,
    PLUGIN_VAR_READONLY, "TokuDB cache table size", NULL, NULL, 0,
    0, ~0ULL, 0);

static MYSQL_SYSVAR_ULONGLONG(max_lock_memory, tokudb_max_lock_memory, PLUGIN_VAR_READONLY, "TokuDB max memory for locks", NULL, NULL, 0, 0, ~0ULL, 0);
static MYSQL_SYSVAR_ULONG(debug, tokudb_debug, 0, "TokuDB Debug", NULL, NULL, 0, 0, ~0UL, 0);

static MYSQL_SYSVAR_STR(log_dir, tokudb_log_dir, PLUGIN_VAR_READONLY, "TokuDB Log Directory", NULL, NULL, NULL);

static MYSQL_SYSVAR_STR(data_dir, tokudb_data_dir, PLUGIN_VAR_READONLY, "TokuDB Data Directory", NULL, NULL, NULL);

static MYSQL_SYSVAR_STR(version, tokudb_version, PLUGIN_VAR_READONLY, "TokuDB Version", NULL, NULL, NULL);

static MYSQL_SYSVAR_UINT(init_flags, tokudb_init_flags, PLUGIN_VAR_READONLY, "Sets TokuDB DB_ENV->open flags", NULL, NULL, tokudb_init_flags, 0, ~0U, 0);

static MYSQL_SYSVAR_UINT(write_status_frequency, tokudb_write_status_frequency, 0, "TokuDB frequency that show processlist updates status of writes", NULL, NULL, 1000, 0, ~0U, 0);
static MYSQL_SYSVAR_UINT(read_status_frequency, tokudb_read_status_frequency, 0, "TokuDB frequency that show processlist updates status of reads", NULL, NULL, 10000, 0, ~0U, 0);
static MYSQL_SYSVAR_INT(fs_reserve_percent, tokudb_fs_reserve_percent, PLUGIN_VAR_READONLY, "TokuDB file system space reserve (percent free required)", NULL, NULL, 5, 0, 100, 0);
static MYSQL_SYSVAR_STR(tmp_dir, tokudb_tmp_dir, PLUGIN_VAR_READONLY, "Tokudb Tmp Dir", NULL, NULL, NULL);

1226
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
1227 1228
static MYSQL_SYSVAR_STR(gdb_path, tokudb_gdb_path, PLUGIN_VAR_READONLY|PLUGIN_VAR_RQCMDARG, "TokuDB path to gdb for extra debug info on fatal signal", NULL, NULL, "/usr/bin/gdb");
static MYSQL_SYSVAR_BOOL(gdb_on_fatal, tokudb_gdb_on_fatal, 0, "TokuDB enable gdb debug info on fatal signal", NULL, NULL, true);
1229
#endif
1230

Rich Prohaska's avatar
Rich Prohaska committed
1231 1232 1233 1234 1235 1236 1237 1238
static void tokudb_fsync_log_period_update(THD *thd, struct st_mysql_sys_var *sys_var, void *var, const void *save) {
    uint32 *period = (uint32 *) var;
    *period = *(const ulonglong *) save;
    db_env->change_fsync_log_period(db_env, *period);
}

static MYSQL_SYSVAR_UINT(fsync_log_period, tokudb_fsync_log_period, 0, "TokuDB fsync log period", NULL, tokudb_fsync_log_period_update, 0, 0, ~0U, 0);

1239

Rich Prohaska's avatar
Rich Prohaska committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
static struct st_mysql_sys_var *tokudb_system_variables[] = {
    MYSQL_SYSVAR(cache_size),
    MYSQL_SYSVAR(max_lock_memory),
    MYSQL_SYSVAR(data_dir),
    MYSQL_SYSVAR(log_dir),
    MYSQL_SYSVAR(debug),
    MYSQL_SYSVAR(commit_sync),
    MYSQL_SYSVAR(lock_timeout),
    MYSQL_SYSVAR(cleaner_period),
    MYSQL_SYSVAR(cleaner_iterations),
    MYSQL_SYSVAR(pk_insert_mode),
    MYSQL_SYSVAR(load_save_space),
    MYSQL_SYSVAR(disable_slow_alter),
    MYSQL_SYSVAR(disable_hot_alter),
    MYSQL_SYSVAR(create_index_online),
    MYSQL_SYSVAR(disable_prefetching),
    MYSQL_SYSVAR(version),
    MYSQL_SYSVAR(init_flags),
    MYSQL_SYSVAR(checkpointing_period),
    MYSQL_SYSVAR(prelock_empty),
    MYSQL_SYSVAR(checkpoint_lock),
    MYSQL_SYSVAR(write_status_frequency),
    MYSQL_SYSVAR(read_status_frequency),
    MYSQL_SYSVAR(fs_reserve_percent),
    MYSQL_SYSVAR(tmp_dir),
    MYSQL_SYSVAR(block_size),
    MYSQL_SYSVAR(read_block_size),
    MYSQL_SYSVAR(read_buf_size),
    MYSQL_SYSVAR(row_format),
    MYSQL_SYSVAR(directio),
    MYSQL_SYSVAR(checkpoint_on_flush_logs),
#if TOKU_INCLUDE_UPSERT
    MYSQL_SYSVAR(disable_slow_update),
    MYSQL_SYSVAR(disable_slow_upsert),
#endif
    MYSQL_SYSVAR(analyze_time),
    MYSQL_SYSVAR(fsync_log_period),
1277
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
1278 1279
    MYSQL_SYSVAR(gdb_path),
    MYSQL_SYSVAR(gdb_on_fatal),
1280
#endif
1281 1282
    MYSQL_SYSVAR(last_lock_timeout),
    MYSQL_SYSVAR(lock_timeout_debug),
1283
    MYSQL_SYSVAR(loader_memory_size),
1284
    MYSQL_SYSVAR(hide_default_row_format),
Rich Prohaska's avatar
Rich Prohaska committed
1285 1286 1287 1288 1289
    NULL
};

struct st_mysql_storage_engine tokudb_storage_engine = { MYSQL_HANDLERTON_INTERFACE_VERSION };

1290
static struct st_mysql_information_schema tokudb_file_map_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
Rich Prohaska's avatar
Rich Prohaska committed
1291

1292
static ST_FIELD_INFO tokudb_file_map_field_info[] = {
Rich Prohaska's avatar
Rich Prohaska committed
1293 1294
    {"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
1295 1296 1297
    {"database", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"table", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"dictionary", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
Rich Prohaska's avatar
Rich Prohaska committed
1298 1299 1300
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

1301
static int tokudb_file_map(TABLE *table, THD *thd) {
Rich Prohaska's avatar
Rich Prohaska committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
    int error;
    DB_TXN* txn = NULL;
    DBC* tmp_cursor = NULL;
    DBT curr_key;
    DBT curr_val;
    memset(&curr_key, 0, sizeof curr_key); 
    memset(&curr_val, 0, sizeof curr_val);
    error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
    if (error) {
        goto cleanup;
    }
    error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
    if (error) {
        goto cleanup;
    }
    while (error == 0) {
1318
        error = tmp_cursor->c_get(tmp_cursor, &curr_key, &curr_val, DB_NEXT);
Rich Prohaska's avatar
Rich Prohaska committed
1319 1320 1321 1322
        if (!error) {
            // We store the NULL terminator in the directory so it's included in the size.
            // See #5789
            // Recalculate and check just to be safe.
1323 1324
            const char *dname = (const char *) curr_key.data;
            size_t dname_len = strlen(dname);
Rich Prohaska's avatar
Rich Prohaska committed
1325
            assert(dname_len == curr_key.size - 1);
1326 1327 1328 1329
            table->field[0]->store(dname, dname_len, system_charset_info);

            const char *iname = (const char *) curr_val.data;
            size_t iname_len = strlen(iname);
Rich Prohaska's avatar
Rich Prohaska committed
1330
            assert(iname_len == curr_val.size - 1);
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
            table->field[1]->store(iname, iname_len, system_charset_info);

            // denormalize the dname
            const char *database_name = NULL;
            size_t database_len = 0;
            const char *table_name = NULL;
            size_t table_len = 0;
            const char *dictionary_name = NULL;
            size_t dictionary_len = 0;
            database_name = strchr(dname, '/');
            if (database_name) {
                database_name += 1;
                table_name = strchr(database_name, '/');
                if (table_name) {
                    database_len = table_name - database_name;
                    table_name += 1;
                    dictionary_name = strchr(table_name, '-');
                    if (dictionary_name) {
                        table_len = dictionary_name - table_name;
                        dictionary_name += 1;
                        dictionary_len = strlen(dictionary_name);
                    }
                }
            }
            table->field[2]->store(database_name, database_len, system_charset_info);
            table->field[3]->store(table_name, table_len, system_charset_info);
            table->field[4]->store(dictionary_name, dictionary_len, system_charset_info);

Rich Prohaska's avatar
Rich Prohaska committed
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
            error = schema_table_store_record(thd, table);
        }
    }
    if (error == DB_NOTFOUND) {
        error = 0;
    }
cleanup:
    if (tmp_cursor) {
        int r = tmp_cursor->c_close(tmp_cursor);
        assert(r == 0);
    }
    if (txn) {
        commit_txn(txn, 0);
    }
    return error;
}

#if MYSQL_VERSION_ID >= 50600
1377
static int tokudb_file_map_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
Rich Prohaska's avatar
Rich Prohaska committed
1378
#else
1379
static int tokudb_file_map_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
Rich Prohaska's avatar
Rich Prohaska committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
#endif
    int error;
    TABLE *table = tables->table;

    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
1390
        error = tokudb_file_map(table, thd);
Rich Prohaska's avatar
Rich Prohaska committed
1391 1392 1393 1394 1395 1396
    }

    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

1397
static int tokudb_file_map_init(void *p) {
Rich Prohaska's avatar
Rich Prohaska committed
1398
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
1399 1400
    schema->fields_info = tokudb_file_map_field_info;
    schema->fill_table = tokudb_file_map_fill_table;
Rich Prohaska's avatar
Rich Prohaska committed
1401 1402 1403
    return 0;
}

1404
static int tokudb_file_map_done(void *p) {
Rich Prohaska's avatar
Rich Prohaska committed
1405 1406 1407 1408 1409
    return 0;
}

static struct st_mysql_information_schema tokudb_fractal_tree_info_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };

Rich Prohaska's avatar
Rich Prohaska committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
static ST_FIELD_INFO tokudb_fractal_tree_info_field_info[] = {
    {"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"bt_num_blocks_allocated", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"bt_num_blocks_in_use", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"bt_size_allocated", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"bt_size_in_use", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

Rich Prohaska's avatar
Rich Prohaska committed
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
static int tokudb_report_fractal_tree_info_for_db(const DBT *dname, const DBT *iname, TABLE *table, THD *thd) {
    int error;
    DB *db;
    uint64_t bt_num_blocks_allocated;
    uint64_t bt_num_blocks_in_use;
    uint64_t bt_size_allocated;
    uint64_t bt_size_in_use;

    error = db_create(&db, db_env, 0);
    if (error) {
        goto exit;
    }
    error = db->open(db, NULL, (char *)dname->data, NULL, DB_BTREE, 0, 0666);
    if (error) {
        goto exit;
    }
    error = db->get_fractal_tree_info64(db,
                                        &bt_num_blocks_allocated, &bt_num_blocks_in_use,
                                        &bt_size_allocated, &bt_size_in_use);
    {
        int close_error = db->close(db, 0);
        if (!error) {
            error = close_error;
        }
    }
    if (error) {
        goto exit;
    }

    // We store the NULL terminator in the directory so it's included in the size.
    // See #5789
    // Recalculate and check just to be safe.
    {
        size_t dname_len = strlen((const char *)dname->data);
        size_t iname_len = strlen((const char *)iname->data);
        assert(dname_len == dname->size - 1);
        assert(iname_len == iname->size - 1);
        table->field[0]->store(
            (char *)dname->data,
            dname_len,
            system_charset_info
            );
        table->field[1]->store(
            (char *)iname->data,
            iname_len,
            system_charset_info
            );
    }
    table->field[2]->store(bt_num_blocks_allocated, false);
    table->field[3]->store(bt_num_blocks_in_use, false);
    table->field[4]->store(bt_size_allocated, false);
    table->field[5]->store(bt_size_in_use, false);

    error = schema_table_store_record(thd, table);

exit:
    return error;
}
Rich Prohaska's avatar
Rich Prohaska committed
1478

Rich Prohaska's avatar
Rich Prohaska committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
static int tokudb_fractal_tree_info(TABLE *table, THD *thd) {
    int error;
    DB_TXN* txn = NULL;
    DBC* tmp_cursor = NULL;
    DBT curr_key;
    DBT curr_val;
    memset(&curr_key, 0, sizeof curr_key);
    memset(&curr_val, 0, sizeof curr_val);
    error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
    if (error) {
        goto cleanup;
    }
    error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
    if (error) {
        goto cleanup;
    }
    while (error == 0) {
        error = tmp_cursor->c_get(
            tmp_cursor,
            &curr_key,
            &curr_val,
            DB_NEXT
            );
        if (!error) {
            error = tokudb_report_fractal_tree_info_for_db(&curr_key, &curr_val, table, thd);
        }
    }
    if (error == DB_NOTFOUND) {
        error = 0;
    }
cleanup:
    if (tmp_cursor) {
        int r = tmp_cursor->c_close(tmp_cursor);
        assert(r == 0);
    }
    if (txn) {
        commit_txn(txn, 0);
    }
    return error;
}
Rich Prohaska's avatar
Rich Prohaska committed
1519 1520

#if MYSQL_VERSION_ID >= 50600
Rich Prohaska's avatar
Rich Prohaska committed
1521
static int tokudb_fractal_tree_info_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
Rich Prohaska's avatar
Rich Prohaska committed
1522
#else
Rich Prohaska's avatar
Rich Prohaska committed
1523
static int tokudb_fractal_tree_info_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
Rich Prohaska's avatar
Rich Prohaska committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
#endif
    int error;
    TABLE *table = tables->table;

    // 3938: Get a read lock on the status flag, since we must
    // read it before safely proceeding
    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
1536
        error = tokudb_fractal_tree_info(table, thd);
Rich Prohaska's avatar
Rich Prohaska committed
1537 1538 1539 1540 1541 1542 1543
    }

    //3938: unlock the status flag lock
    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

Rich Prohaska's avatar
Rich Prohaska committed
1544 1545 1546 1547 1548 1549
static int tokudb_fractal_tree_info_init(void *p) {
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
    schema->fields_info = tokudb_fractal_tree_info_field_info;
    schema->fill_table = tokudb_fractal_tree_info_fill_table;
    return 0;
}
Rich Prohaska's avatar
Rich Prohaska committed
1550

Rich Prohaska's avatar
Rich Prohaska committed
1551 1552 1553
static int tokudb_fractal_tree_info_done(void *p) {
    return 0;
}
Rich Prohaska's avatar
Rich Prohaska committed
1554

Rich Prohaska's avatar
Rich Prohaska committed
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
static struct st_mysql_information_schema tokudb_fractal_tree_block_map_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };

static ST_FIELD_INFO tokudb_fractal_tree_block_map_field_info[] = {
    {"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"checkpoint_count", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"blocknum", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"offset", 0, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL, NULL, SKIP_OPEN_TABLE },
    {"size", 0, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL, NULL, SKIP_OPEN_TABLE },
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

struct tokudb_report_fractal_tree_block_map_iterator_extra {
    int64_t num_rows;
    int64_t i;
    uint64_t *checkpoint_counts;
    int64_t *blocknums;
    int64_t *diskoffs;
    int64_t *sizes;
};

// This iterator is called while holding the blocktable lock.  We should be as quick as possible.
// We don't want to do one call to get the number of rows, release the blocktable lock, and then do another call to get all the rows because the number of rows may change if we don't hold the lock.
// As a compromise, we'll do some mallocs inside the lock on the first call, but everything else should be fast.
static int tokudb_report_fractal_tree_block_map_iterator(uint64_t checkpoint_count,
                                                          int64_t num_rows,
                                                          int64_t blocknum,
                                                          int64_t diskoff,
                                                          int64_t size,
                                                          void *iter_extra) {
    struct tokudb_report_fractal_tree_block_map_iterator_extra *e = static_cast<struct tokudb_report_fractal_tree_block_map_iterator_extra *>(iter_extra);

    assert(num_rows > 0);
    if (e->num_rows == 0) {
        e->checkpoint_counts = (uint64_t *) my_malloc(num_rows * (sizeof *e->checkpoint_counts), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
        e->blocknums = (int64_t *) my_malloc(num_rows * (sizeof *e->blocknums), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
        e->diskoffs = (int64_t *) my_malloc(num_rows * (sizeof *e->diskoffs), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
        e->sizes = (int64_t *) my_malloc(num_rows * (sizeof *e->sizes), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
        e->num_rows = num_rows;
Rich Prohaska's avatar
Rich Prohaska committed
1594 1595
    }

Rich Prohaska's avatar
Rich Prohaska committed
1596 1597 1598 1599 1600 1601 1602
    e->checkpoint_counts[e->i] = checkpoint_count;
    e->blocknums[e->i] = blocknum;
    e->diskoffs[e->i] = diskoff;
    e->sizes[e->i] = size;
    ++(e->i);

    return 0;
Rich Prohaska's avatar
Rich Prohaska committed
1603 1604
}

Rich Prohaska's avatar
Rich Prohaska committed
1605
static int tokudb_report_fractal_tree_block_map_for_db(const DBT *dname, const DBT *iname, TABLE *table, THD *thd) {
Rich Prohaska's avatar
Rich Prohaska committed
1606
    int error;
Rich Prohaska's avatar
Rich Prohaska committed
1607 1608
    DB *db;
    struct tokudb_report_fractal_tree_block_map_iterator_extra e = {}; // avoid struct initializers so that we can compile with older gcc versions
Rich Prohaska's avatar
Rich Prohaska committed
1609

Rich Prohaska's avatar
Rich Prohaska committed
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
    error = db_create(&db, db_env, 0);
    if (error) {
        goto exit;
    }
    error = db->open(db, NULL, (char *)dname->data, NULL, DB_BTREE, 0, 0666);
    if (error) {
        goto exit;
    }
    error = db->iterate_fractal_tree_block_map(db, tokudb_report_fractal_tree_block_map_iterator, &e);
    {
        int close_error = db->close(db, 0);
        if (!error) {
            error = close_error;
        }
    }
    if (error) {
        goto exit;
    }
Rich Prohaska's avatar
Rich Prohaska committed
1628

Rich Prohaska's avatar
Rich Prohaska committed
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    // If not, we should have gotten an error and skipped this section of code
    assert(e.i == e.num_rows);
    for (int64_t i = 0; error == 0 && i < e.num_rows; ++i) {
        // We store the NULL terminator in the directory so it's included in the size.
        // See #5789
        // Recalculate and check just to be safe.
        size_t dname_len = strlen((const char *)dname->data);
        size_t iname_len = strlen((const char *)iname->data);
        assert(dname_len == dname->size - 1);
        assert(iname_len == iname->size - 1);
        table->field[0]->store(
            (char *)dname->data,
            dname_len,
            system_charset_info
            );
        table->field[1]->store(
            (char *)iname->data,
            iname_len,
            system_charset_info
            );
        table->field[2]->store(e.checkpoint_counts[i], false);
        table->field[3]->store(e.blocknums[i], false);
        static const int64_t freelist_null = -1;
        static const int64_t diskoff_unused = -2;
        if (e.diskoffs[i] == diskoff_unused || e.diskoffs[i] == freelist_null) {
            table->field[4]->set_null();
        } else {
            table->field[4]->set_notnull();
            table->field[4]->store(e.diskoffs[i], false);
        }
        static const int64_t size_is_free = -1;
        if (e.sizes[i] == size_is_free) {
            table->field[5]->set_null();
        } else {
            table->field[5]->set_notnull();
            table->field[5]->store(e.sizes[i], false);
        }

        error = schema_table_store_record(thd, table);
Rich Prohaska's avatar
Rich Prohaska committed
1668 1669
    }

Rich Prohaska's avatar
Rich Prohaska committed
1670 1671
exit:
    if (e.checkpoint_counts != NULL) {
Rich Prohaska's avatar
Rich Prohaska committed
1672
        my_free(e.checkpoint_counts);
Rich Prohaska's avatar
Rich Prohaska committed
1673 1674 1675
        e.checkpoint_counts = NULL;
    }
    if (e.blocknums != NULL) {
Rich Prohaska's avatar
Rich Prohaska committed
1676
        my_free(e.blocknums);
Rich Prohaska's avatar
Rich Prohaska committed
1677 1678 1679
        e.blocknums = NULL;
    }
    if (e.diskoffs != NULL) {
Rich Prohaska's avatar
Rich Prohaska committed
1680
        my_free(e.diskoffs);
Rich Prohaska's avatar
Rich Prohaska committed
1681 1682 1683
        e.diskoffs = NULL;
    }
    if (e.sizes != NULL) {
Rich Prohaska's avatar
Rich Prohaska committed
1684
        my_free(e.sizes);
Rich Prohaska's avatar
Rich Prohaska committed
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
        e.sizes = NULL;
    }
    return error;
}

static int tokudb_fractal_tree_block_map(TABLE *table, THD *thd) {
    int error;
    DB_TXN* txn = NULL;
    DBC* tmp_cursor = NULL;
    DBT curr_key;
    DBT curr_val;
    memset(&curr_key, 0, sizeof curr_key);
    memset(&curr_val, 0, sizeof curr_val);
    error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
    if (error) {
        goto cleanup;
    }
    error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
    if (error) {
        goto cleanup;
    }
    while (error == 0) {
        error = tmp_cursor->c_get(
            tmp_cursor,
            &curr_key,
            &curr_val,
            DB_NEXT
            );
        if (!error) {
            error = tokudb_report_fractal_tree_block_map_for_db(&curr_key, &curr_val, table, thd);
        }
    }
    if (error == DB_NOTFOUND) {
        error = 0;
    }
cleanup:
    if (tmp_cursor) {
        int r = tmp_cursor->c_close(tmp_cursor);
        assert(r == 0);
    }
    if (txn) {
        commit_txn(txn, 0);
    }
Rich Prohaska's avatar
Rich Prohaska committed
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
    return error;
}

#if MYSQL_VERSION_ID >= 50600
static int tokudb_fractal_tree_block_map_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_fractal_tree_block_map_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
    int error;
    TABLE *table = tables->table;

    // 3938: Get a read lock on the status flag, since we must
    // read it before safely proceeding
    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
        error = tokudb_fractal_tree_block_map(table, thd);
    }

    //3938: unlock the status flag lock
    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

static int tokudb_fractal_tree_block_map_init(void *p) {
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
    schema->fields_info = tokudb_fractal_tree_block_map_field_info;
    schema->fill_table = tokudb_fractal_tree_block_map_fill_table;
    return 0;
}

static int tokudb_fractal_tree_block_map_done(void *p) {
    return 0;
}

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
static void tokudb_pretty_key(const DB *db, const DBT *key, const char *default_key, String *out) {
    if (key->data == NULL) {
        out->append(default_key);
    } else {
        bool do_hexdump = true;
        if (do_hexdump) {
            // hexdump the key
            const unsigned char *data = reinterpret_cast<const unsigned char *>(key->data);
            for (size_t i = 0; i < key->size; i++) {
                char str[3];
                snprintf(str, sizeof str, "%2.2x", data[i]);
                out->append(str);
            }
        }
    }
}

static void tokudb_pretty_left_key(const DB *db, const DBT *key, String *out) {
    tokudb_pretty_key(db, key, "-infinity", out);
}

static void tokudb_pretty_right_key(const DB *db, const DBT *key, String *out) {
    tokudb_pretty_key(db, key, "+infinity", out);
}

static const char *tokudb_get_index_name(DB *db) {
    if (db != NULL) {
        return db->get_dname(db);
    } else {
        return "$ydb_internal";
    }
}

1799 1800 1801 1802 1803 1804 1805
static int tokudb_equal_key(const DBT *left_key, const DBT *right_key) {
    if (left_key->data == NULL || right_key->data == NULL || left_key->size != right_key->size)
        return 0;
    else
        return memcmp(left_key->data, right_key->data, left_key->size) == 0;
}

1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
static void tokudb_lock_timeout_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key, uint64_t blocking_txnid) {
    THD *thd = current_thd;
    if (!thd)
        return;
    ulong lock_timeout_debug = THDVAR(thd, lock_timeout_debug);
    if (lock_timeout_debug != 0) {
        // generate a JSON document with the lock timeout info
        String log_str;
        log_str.append("{");
        log_str.append("\"mysql_thread_id\":");
        log_str.append_ulonglong(thd->thread_id);
1817 1818 1819
        log_str.append(", \"dbname\":");
        log_str.append("\""); log_str.append(tokudb_get_index_name(db)); log_str.append("\"");
        log_str.append(", \"requesting_txnid\":");
1820 1821
        log_str.append_ulonglong(requesting_txnid);
        log_str.append(", \"blocking_txnid\":");
1822 1823 1824 1825 1826
        log_str.append_ulonglong(blocking_txnid);
        if (tokudb_equal_key(left_key, right_key)) {
            String key_str;
            tokudb_pretty_key(db, left_key, "?", &key_str);
            log_str.append(", \"key\":");
1827
            log_str.append("\""); log_str.append(key_str); log_str.append("\"");
1828 1829 1830
        } else {
            String left_str;
            tokudb_pretty_left_key(db, left_key, &left_str);
1831 1832
            log_str.append(", \"key_left\":");
            log_str.append("\""); log_str.append(left_str); log_str.append("\"");
1833 1834
            String right_str;
            tokudb_pretty_right_key(db, right_key, &right_str);
1835 1836
            log_str.append(", \"key_right\":");
            log_str.append("\""); log_str.append(right_str); log_str.append("\"");
1837
        }
1838
        log_str.append("}");
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
        // set last_lock_timeout
        if (lock_timeout_debug & 1) {
            char *old_lock_timeout = THDVAR(thd, last_lock_timeout);
            char *new_lock_timeout = my_strdup(log_str.c_ptr(), MY_FAE);
            THDVAR(thd, last_lock_timeout) = new_lock_timeout;
            my_free(old_lock_timeout);
        }
        // dump to stderr
        if (lock_timeout_debug & 2) {
            fprintf(stderr, "tokudb_lock_timeout: %s\n", log_str.c_ptr());
        }
    }
}

static struct st_mysql_information_schema tokudb_trx_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };

static ST_FIELD_INFO tokudb_trx_field_info[] = {
    {"trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"trx_mysql_thread_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

struct tokudb_trx_extra {
    THD *thd;
    TABLE *table;
};

static int tokudb_trx_callback(uint64_t txn_id, uint64_t client_id, iterate_row_locks_callback iterate_locks, void *locks_extra, void *extra) {
    struct tokudb_trx_extra *e = reinterpret_cast<struct tokudb_trx_extra *>(extra);
    THD *thd = e->thd;
    TABLE *table = e->table;
    table->field[0]->store(txn_id, false);
    table->field[1]->store(client_id, false);
    int error = schema_table_store_record(thd, table);
    return error;
}

#if MYSQL_VERSION_ID >= 50600
static int tokudb_trx_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_trx_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
    int error;
    
    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
        struct tokudb_trx_extra e = { thd, tables->table };
        error = db_env->iterate_live_transactions(db_env, tokudb_trx_callback, &e);
    }

    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

static int tokudb_trx_init(void *p) {
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
    schema->fields_info = tokudb_trx_field_info;
    schema->fill_table = tokudb_trx_fill_table;
    return 0;
}

static int tokudb_trx_done(void *p) {
    return 0;
}

static struct st_mysql_information_schema tokudb_lock_waits_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };

static ST_FIELD_INFO tokudb_lock_waits_field_info[] = {
    {"requesting_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"blocking_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"lock_waits_dname", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
1914 1915
    {"lock_waits_key_left", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"lock_waits_key_right", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
    {"lock_waits_start_time", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

struct tokudb_lock_waits_extra {
    THD *thd;
    TABLE *table;
};

static int tokudb_lock_waits_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key, 
                                      uint64_t blocking_txnid, uint64_t start_time, void *extra) {
    struct tokudb_lock_waits_extra *e = reinterpret_cast<struct tokudb_lock_waits_extra *>(extra);
    THD *thd = e->thd;
    TABLE *table = e->table;
    table->field[0]->store(requesting_txnid, false);
    table->field[1]->store(blocking_txnid, false);
    const char *dname = tokudb_get_index_name(db);
    size_t dname_length = strlen(dname);
    table->field[2]->store(dname, dname_length, system_charset_info);
    String left_str;
    tokudb_pretty_left_key(db, left_key, &left_str);
    table->field[3]->store(left_str.ptr(), left_str.length(), system_charset_info);
    String right_str;
    tokudb_pretty_right_key(db, right_key, &right_str);
    table->field[4]->store(right_str.ptr(), right_str.length(), system_charset_info);
    table->field[5]->store(start_time, false);
    int error = schema_table_store_record(thd, table);
    return error;
}

#if MYSQL_VERSION_ID >= 50600
static int tokudb_lock_waits_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_lock_waits_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
    int error;
    
    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
        struct tokudb_lock_waits_extra e = { thd, tables->table };
        error = db_env->iterate_pending_lock_requests(db_env, tokudb_lock_waits_callback, &e);
    }

    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

static int tokudb_lock_waits_init(void *p) {
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
    schema->fields_info = tokudb_lock_waits_field_info;
    schema->fill_table = tokudb_lock_waits_fill_table;
    return 0;
}

static int tokudb_lock_waits_done(void *p) {
    return 0;
}

static struct st_mysql_information_schema tokudb_locks_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };

static ST_FIELD_INFO tokudb_locks_field_info[] = {
    {"locks_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"locks_mysql_thread_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"locks_dname", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
1984 1985
    {"locks_key_left", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
    {"locks_key_right", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    {NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};

struct tokudb_locks_extra {
    THD *thd;
    TABLE *table;
};

static int tokudb_locks_callback(uint64_t txn_id, uint64_t client_id, iterate_row_locks_callback iterate_locks, void *locks_extra, void *extra) {
    struct tokudb_locks_extra *e = reinterpret_cast<struct tokudb_locks_extra *>(extra);
    THD *thd = e->thd;
    TABLE *table = e->table;
    int error = 0;
    DB *db;
    DBT left_key, right_key;
    while (error == 0 && iterate_locks(&db, &left_key, &right_key, locks_extra) == 0) {
        table->field[0]->store(txn_id, false);
        table->field[1]->store(client_id, false);

        const char *dname = tokudb_get_index_name(db);
        size_t dname_length = strlen(dname);
        table->field[2]->store(dname, dname_length, system_charset_info);

        String left_str;
        tokudb_pretty_left_key(db, &left_key, &left_str);
        table->field[3]->store(left_str.ptr(), left_str.length(), system_charset_info);

        String right_str;
        tokudb_pretty_right_key(db, &right_key, &right_str);
        table->field[4]->store(right_str.ptr(), right_str.length(), system_charset_info);

        error = schema_table_store_record(thd, table);
    }
    return error;
}

#if MYSQL_VERSION_ID >= 50600
static int tokudb_locks_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_locks_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
    int error;
    
    rw_rdlock(&tokudb_hton_initialized_lock);

    if (!tokudb_hton_initialized) {
        my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
        error = -1;
    } else {
        struct tokudb_locks_extra e = { thd, tables->table };
        error = db_env->iterate_live_transactions(db_env, tokudb_locks_callback, &e);
    }

    rw_unlock(&tokudb_hton_initialized_lock);
    return error;
}

static int tokudb_locks_init(void *p) {
    ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
    schema->fields_info = tokudb_locks_field_info;
    schema->fill_table = tokudb_locks_fill_table;
    return 0;
}

static int tokudb_locks_done(void *p) {
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
enum { TOKUDB_PLUGIN_VERSION = 0x0400 };
#define TOKUDB_PLUGIN_VERSION_STR "1024"

// Retrieves variables for information_schema.global_status.
// Names (columnname) are automatically converted to upper case, and prefixed with "TOKUDB_"
static int show_tokudb_vars(THD *thd, SHOW_VAR *var, char *buff) {
    TOKUDB_DBUG_ENTER("show_tokudb_vars");

    int error;
    uint64_t panic;
    const int panic_string_len = 1024;
    char panic_string[panic_string_len] = {'\0'};
    fs_redzone_state redzone_state;

    uint64_t num_rows;
    error = db_env->get_engine_status (db_env, toku_global_status_rows, toku_global_status_max_rows, &num_rows, &redzone_state, &panic, panic_string, panic_string_len, TOKU_GLOBAL_STATUS);
    //TODO: Maybe do something with the panic output?
    if (error == 0) {
        assert(num_rows <= toku_global_status_max_rows);
        //TODO: Maybe enable some of the items here: (copied from engine status

        //TODO: (optionally) add redzone state, panic, panic string, etc. Right now it's being ignored.

        for (uint64_t row = 0; row < num_rows; row++) {
            SHOW_VAR &status_var = toku_global_status_variables[row];
            TOKU_ENGINE_STATUS_ROW_S &status_row = toku_global_status_rows[row];

            status_var.name = status_row.columnname;
            switch (status_row.type) {
            case FS_STATE:
            case UINT64:
                status_var.type = SHOW_LONGLONG;
                status_var.value = (char*)&status_row.value.num;
                break;
            case CHARSTR:
                status_var.type = SHOW_CHAR;
                status_var.value = (char*)status_row.value.str;
                break;
            case UNIXTIME:
                {
                    status_var.type = SHOW_CHAR;
                    time_t t = status_row.value.num;
                    char tbuf[26];
                    // Reuse the memory in status_row. (It belongs to us).
                    snprintf(status_row.value.datebuf, sizeof(status_row.value.datebuf), "%.24s", ctime_r(&t, tbuf));
                    status_var.value = (char*)&status_row.value.datebuf[0];
                }
                break;
            case TOKUTIME:
                {
                    status_var.type = SHOW_DOUBLE;
                    double t = tokutime_to_seconds(status_row.value.num);
                    // Reuse the memory in status_row. (It belongs to us).
                    status_row.value.dnum = t;
                    status_var.value = (char*)&status_row.value.dnum;
                }
                break;
            case PARCOUNT:
                {
                    status_var.type = SHOW_LONGLONG;
                    uint64_t v = read_partitioned_counter(status_row.value.parcount);
                    // Reuse the memory in status_row. (It belongs to us).
                    status_row.value.num = v;
                    status_var.value = (char*)&status_row.value.num;
                }
                break;
            default:
                {
                    status_var.type = SHOW_CHAR;
                    // Reuse the memory in status_row.datebuf. (It belongs to us).
                    // UNKNOWN TYPE: %d fits in 26 bytes (sizeof datebuf) for any integer.
                    snprintf(status_row.value.datebuf, sizeof(status_row.value.datebuf), "UNKNOWN TYPE: %d", status_row.type);
                    status_var.value = (char*)&status_row.value.datebuf[0];
                }
                break;
            }
        }
        // Sentinel value at end.
        toku_global_status_variables[num_rows].type = SHOW_LONG;
        toku_global_status_variables[num_rows].value = (char*)NullS;
        toku_global_status_variables[num_rows].name = (char*)NullS;

        var->type= SHOW_ARRAY;
        var->value= (char *) toku_global_status_variables;
    }
    if (error) { my_errno = error; }
    TOKUDB_DBUG_RETURN(error);
}

static SHOW_VAR toku_global_status_variables_export[]= {
    {"Tokudb", (char*)&show_tokudb_vars, SHOW_FUNC},
    {NullS, NullS, SHOW_LONG}
};

mysql_declare_plugin(tokudb) 
{
    MYSQL_STORAGE_ENGINE_PLUGIN, 
    &tokudb_storage_engine, 
    tokudb_hton_name, 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_init_func,          /* plugin init */
    tokudb_done_func,          /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    toku_global_status_variables_export,  /* status variables */
    tokudb_system_variables,   /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_trx_information_schema,
    "TokuDB_trx", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_trx_init,     /* plugin init */
    tokudb_trx_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_lock_waits_information_schema,
    "TokuDB_lock_waits", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_lock_waits_init,     /* plugin init */
    tokudb_lock_waits_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_locks_information_schema,
    "TokuDB_locks", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_locks_init,     /* plugin init */
    tokudb_locks_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
Rich Prohaska's avatar
Rich Prohaska committed
2217 2218
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
2219
    &tokudb_file_map_information_schema, 
Rich Prohaska's avatar
Rich Prohaska committed
2220 2221 2222 2223
    "TokuDB_file_map", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
2224 2225
    tokudb_file_map_init,     /* plugin init */
    tokudb_file_map_done,     /* plugin deinit */
Rich Prohaska's avatar
Rich Prohaska committed
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_fractal_tree_info_information_schema, 
    "TokuDB_fractal_tree_info", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_fractal_tree_info_init,     /* plugin init */
    tokudb_fractal_tree_info_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_fractal_tree_block_map_information_schema, 
    "TokuDB_fractal_tree_block_map", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_fractal_tree_block_map_init,     /* plugin init */
    tokudb_fractal_tree_block_map_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    NULL,                      /* config options */
#if MYSQL_VERSION_ID >= 50521
    0,                         /* flags */
#endif
}
mysql_declare_plugin_end;

#ifdef MARIA_PLUGIN_INTERFACE_VERSION

maria_declare_plugin(tokudb) 
{
    MYSQL_STORAGE_ENGINE_PLUGIN, 
    &tokudb_storage_engine, 
    tokudb_hton_name, 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_init_func,          /* plugin init */
    tokudb_done_func,          /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    toku_global_status_variables_export,  /* status variables */
    tokudb_system_variables,   /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_trx_information_schema,
    "TokuDB_trx", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_trx_init,     /* plugin init */
    tokudb_trx_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_lock_waits_information_schema,
    "TokuDB_lock_waits", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_lock_waits_init,     /* plugin init */
    tokudb_lock_waits_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_locks_information_schema,
    "TokuDB_locks", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_locks_init,     /* plugin init */
    tokudb_locks_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
Rich Prohaska's avatar
Rich Prohaska committed
2332 2333 2334
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
2335
    &tokudb_file_map_information_schema, 
Rich Prohaska's avatar
Rich Prohaska committed
2336 2337 2338 2339
    "TokuDB_file_map", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
2340 2341
    tokudb_file_map_init,     /* plugin init */
    tokudb_file_map_done,     /* plugin deinit */
Rich Prohaska's avatar
Rich Prohaska committed
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_fractal_tree_info_information_schema, 
    "TokuDB_fractal_tree_info", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_fractal_tree_info_init,     /* plugin init */
    tokudb_fractal_tree_info_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
},
{
    MYSQL_INFORMATION_SCHEMA_PLUGIN, 
    &tokudb_fractal_tree_block_map_information_schema, 
    "TokuDB_fractal_tree_block_map", 
    "Tokutek Inc", 
    "Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
    PLUGIN_LICENSE_GPL,
    tokudb_fractal_tree_block_map_init,     /* plugin init */
    tokudb_fractal_tree_block_map_done,     /* plugin deinit */
    TOKUDB_PLUGIN_VERSION,     /* 4.0.0 */
    NULL,                      /* status variables */
    NULL,                      /* system variables */
    TOKUDB_PLUGIN_VERSION_STR, /* string version */
    MariaDB_PLUGIN_MATURITY_STABLE /* maturity */
}
maria_declare_plugin_end;

#endif