MySQL通过TABLE对象进行表的读写等操作,对于构建TABLE对象所需的表定义相关信息,MySQL会通过Dictionary_client与DD模块进行交互。DD模块通过多级缓存的结构提供了高效而安全的DD信息访问方式,具体介绍见http://mysql.taobao.org/monthly/2021/08/02/。本文旨在讨论TABLE对象及其用到的DD模块中TableImpl信息的生命周期,包括他们的构建、缓存、清理和移除。 ​

相关数据结构: TABLE结构描述表的相关信息,其中表定义相关的一些DD信息,如包含的字段等,记录在TABLE_SHARE中,handler是该表所使用的存储引擎接口,两个TABLE指针串起了正在操作这个TABLE对象的THD所控制的所有TABLE对象,即THD::opened_tables。另外,TABLE结构中还有字段信息、保存操作过程中读写的数据的内存区域等,与本文主题无关。

  1. struct TABLE {
  2. TABLE_SHARE *s{nullptr};
  3. handler *file{nullptr};
  4. TABLE *next{nullptr}, *prev{nullptr};
  5. private:
  6. TABLE *cache_next{nullptr}, **cache_prev{nullptr};
  7. /*
  8. Give table_cache_element access to the above two members to allow
  9. using them for linking TABLE objects in a list.
  10. */
  11. friend class table_cache_element;
  12. public:
  13. THD *in_use{nullptr}; /* Which thread uses this */
  14. Field **field{nullptr}; /* Pointer to fields */
  15. bool m_needs_reopen{false};
  16. }

table_cache_element是table cache中的一个元素,它表示了一张表在线程对应的table cache中构建的所有TABLE实例,其中有一些位于thd->opened_tables中正在使用(used_tables),也有一些已经被释放,缓存供后续使用(free_tables)。这些表共用一个TABLE_SHARE对象维护dd信息等。

  1. /**
  2. Element that represents the table in the specific table cache.
  3. Plays for table cache instance role similar to role of TABLE_SHARE
  4. for table definition cache.
  5. It is an implementation detail of table_cache and is present
  6. in the header file only to allow inlining of some methods.
  7. */
  8. class table_cache_element {
  9. TABLE_list used_tables;
  10. TABLE_list free_tables;
  11. TABLE_SHARE *share;
  12. };

table_cache维护了相关的几个THD所使用的所有table_cache_element,即所有正在使用或曾经打开过的TABLE对象。m_unused_tables是所有table_cache_element中free_tables的并集。

  1. class table_cache {
  2. /**
  3. The hash of table_cache_element objects, each table/table share that
  4. has any TABLE object in the table_cache has a table_cache_element from
  5. which the list of free TABLE objects in this table cache AND the list
  6. of used TABLE objects in this table cache is stored.
  7. We use table_cache_element::share::table_cache_key as key for this hash.
  8. */
  9. std::unordered_map<std::string, std::unique_ptr<table_cache_element>> m_cache;
  10. /**
  11. List that contains all TABLE instances for tables in this particular
  12. table cache that are in not use by any thread. Recently used TABLE
  13. instances are appended to the end of the list. Thus the beginning of
  14. the list contains which have been least recently used.
  15. */
  16. TABLE *m_unused_tables;
  17. /**
  18. Total number of TABLE instances for tables in this particular table
  19. cache (both in use by threads and not in use).
  20. This value summed over all table caches is accessible to users as
  21. Open_tables status variable.
  22. */
  23. uint m_table_count;
  24. };

table_cache_manager是所有table cache的集合,该对象有一个全局单例。需要操作table cache保存或者借用空闲TABLE对象时,根据THD ID访问对应的table cache并进行相应操作。

  1. /**
  2. Container class for all table cache instances in the system.
  3. */
  4. class table_cache_manager {
  5. /**
  6. An array of table_cache instances.
  7. Only the first table_cache_instances elements in it are used.
  8. */
  9. table_cache m_table_cache[MAX_table_cacheS];
  10. };
  11. extern table_cache_manager table_cache_manager;

DD信息创建:create table create table时会通过open_table调用check_if_table_exists判断表是否存在,以便在表存在时报错。这里会产生一次空读,这次空读会完整读穿DD模块直至底层存储引擎,不过由于此时相关DD信息尚未构建,暂时略去。之后在rea_create_base_table时才会构建DD信息并保存到存储引擎InnoDB。 ​

  1. static bool rea_create_base_table(...) {
  2. // 构造dd::Table对象,并用create_info中的信息填充
  3. std::unique_ptr<dd::Table> table_def_res =
  4. dd::create_table(thd, sch_obj, table_name, create_info, create_fields,
  5. key_info, keys, keys_onoff, fk_key_info, fk_keys, file);
  6. if (do_not_store_in_dd) {
  7. ......
  8. } else {
  9. // Storage_adapter::store(m_thd, object) 保存在Storage_adapter(innoDB)中。然后调用register_uncommitted_object将table_def_res的clone()保存在Dictionary_client的m_registry_uncommitted中。
  10. bool result = thd->dd_client()->store(table_def_res.get());
  11. ......
  12. // 获取Dictionary_client的m_registry_uncommitted中dd::Table的clone() 【为啥不直接用table_def_res,反正存进去的也是clone】
  13. if (thd->dd_client()->acquire_for_modification(db, table_name, &table_def))
  14. DBUG_RETURN(true);
  15. }
  16. ...... (根据前面的table_def信息构造TABLE_SHARE并让存储引擎完成实际的table create,与本文主题无关)
  17. }

前面的rea_create_base_table中,表定义信息被保存到了Dictionary_clientm_registry_uncommitted中,即保存在多级缓存中的局部缓存中,并保存在了存储引擎,但是并不会放置到共享缓存Shared_dictionary_cache层中。接下来,事务提交过程会在将dd表信息落盘的同时清理之前放入缓存的表信息:

  1. bool trans_commit_implicit(THD *thd, bool ignore_global_read_lock) {
  2. ......
  3. // 调用各个dd数据类型的remove_uncommitted_objects清理dd cache中的Abstract_table、Schema、Tablespace等各种缓存
  4. thd->dd_client()->commit_modified_objects();
  5. }
  6. void Dictionary_client::remove_uncommitted_objects(
  7. bool commit_to_shared_cache) {
  8. if (commit_to_shared_cache) {
  9. typename Multi_map_base<typename T::Cache_partition>::Const_iterator it;
  10. // 防止Shared_dictionary_cache中残留有新建的表的信息,为m_registry_uncommitted中的每一个表信息调用invalidate,以清理Shared_dictionary_cache中相应的表信息(如果有)
  11. for (it = m_registry_uncommitted.begin<typename T::Cache_partition>();
  12. it != m_registry_uncommitted.end<typename T::Cache_partition>();
  13. it++) {
  14. typename T::Cache_partition *uncommitted_object =
  15. const_cast<typename T::Cache_partition *>(it->second->object());
  16. DBUG_ASSERT(uncommitted_object != nullptr);
  17. // 防止Shared_dictionary_cache中残留有新建的表的信息
  18. invalidate(uncommitted_object);
  19. }
  20. // 仅对于bootstrap过程中initialize的dd表(mysql.tables等),将uncommitted cache中的表信息转移到Shared_dictionary_cache和m_registry_committed中
  21. if (m_thd->is_dd_system_thread() &&
  22. bootstrap::DD_bootstrap_ctx::instance().get_stage() <
  23. bootstrap::Stage::FINISHED) {
  24. // We must do this in two iterations to handle situations where two
  25. // uncommitted objects swap names.
  26. for (it = m_registry_uncommitted.begin<typename T::Cache_partition>();
  27. it != m_registry_uncommitted.end<typename T::Cache_partition>();
  28. it++) {
  29. typename T::Cache_partition *uncommitted_object =
  30. const_cast<typename T::Cache_partition *>(it->second->object());
  31. DBUG_ASSERT(uncommitted_object != nullptr);
  32. Cache_element<typename T::Cache_partition> *element = NULL;
  33. // In put, the reference counter is stepped up, so this is safe.
  34. Shared_dictionary_cache::instance()->put(
  35. static_cast<const typename T::Cache_partition *>(
  36. uncommitted_object->clone()),
  37. &element);
  38. m_registry_committed.put(element);
  39. // Sign up for auto release.
  40. m_current_releaser->auto_release(element);
  41. }
  42. }
  43. } // commit_to_shared_cache
  44. // 清理需要清理的m_registry_uncommitted和m_registry_dropped中的信息
  45. m_registry_uncommitted.erase<typename T::Cache_partition>();
  46. m_registry_dropped.erase<typename T::Cache_partition>();
  47. }

以上,create user table的过程中不会遗留任何类型的DD cache信息,因为对所有类型的cache均调用了remove_uncommitted_objects函数,保证临时产生的dd::Table对象不会残留在缓存中,而仅仅是进行了落盘。但这并不代表建表过程完全不会污染内存缓存信息,比如,建表过程中创建tablespace所调用的fil_space_create会将表空间信息保存在全局变量fil_system对应的Fil_shard中。 ​

DD信息读取和TABLE对象构建:open_table

所有的DML、DQL在访问表数据之前都要先访问表的Table_Impl等DD信息,以便读取、解析或写入相关的数据。这一访问过程在开表过程中构造TABLE_SHARE时实现。

  1. TABLE_SHARE *get_TABLE_SHARE(THD *thd, const char *db, const char *table_name,
  2. const char *key, size_t key_length, bool open_view,
  3. bool open_secondary) {
  4. ......
  5. /*
  6. Read table definition from the cache. If the share is being opened,
  7. wait for the appropriate condition. The share may be destroyed if
  8. open fails, so after cond_wait, we must repeat searching the
  9. hash table.
  10. */
  11. for (;;) {
  12. auto it = table_def_cache->find(string(key, key_length));
  13. // table_def_cache中找不到,确认加了schema的MDL锁之后建立新的TABLE_SHARE
  14. if (it == table_def_cache->end()) {
  15. if (thd->mdl_context.owns_equal_or_stronger_lock(
  16. MDL_key::SCHEMA, db, "", MDL_INTENTION_EXCLUSIVE)) {
  17. break;
  18. }
  19. mysql_mutex_unlock(&LOCK_open);
  20. if (dd::mdl_lock_schema(thd, db, MDL_TRANSACTION)) {
  21. // Lock LOCK_open again to preserve function contract
  22. mysql_mutex_lock(&LOCK_open);
  23. DBUG_RETURN(nullptr);
  24. }
  25. mysql_mutex_lock(&LOCK_open);
  26. // Need to re-try the find after getting the mutex again
  27. continue;
  28. }
  29. share = it->second.get();
  30. // m_open_in_progress说明有其他线程创建了TABLE_SHARE并放进table_def_cache,但此时尚未完成信息填充,于是等待创建线程填充信息完成后通过COND_open通知,然后再次进入循环查询。
  31. if (!share->m_open_in_progress)
  32. DBUG_RETURN(process_found_TABLE_SHARE(thd, share, open_view));
  33. DEBUG_SYNC(thd, "get_share_before_COND_open_wait");
  34. mysql_cond_wait(&COND_open, &LOCK_open);
  35. }
  36. /*
  37. 申请新的TABLE_SHARE
  38. */
  39. if (!(share = alloc_TABLE_SHARE(db, table_name, key, key_length,
  40. open_secondary))) {
  41. DBUG_RETURN(NULL);
  42. }
  43. /*
  44. We assign a new table id under the protection of LOCK_open.
  45. We do this instead of creating a new mutex
  46. and using it for the sole purpose of serializing accesses to a
  47. static variable, we assign the table id here. We assign it to the
  48. share before inserting it into the table_def_cache to be really
  49. sure that it cannot be read from the cache without having a table
  50. id assigned.
  51. CAVEAT. This means that the table cannot be used for
  52. binlogging/replication purposes, unless get_TABLE_SHARE() has been
  53. called directly or indirectly.
  54. */
  55. assign_new_table_id(share);
  56. // 将TABLE_SHARE放入table_def_cache,此时另一个线程如果进入前面的循环,他就已经能读到了,但由于信息还未完成填充,所以还不能用。
  57. table_def_cache->emplace(to_string(share->table_cache_key),
  58. unique_ptr<TABLE_SHARE, TABLE_SHARE_deleter>(share));
  59. /*
  60. We must increase ref_count prior to releasing LOCK_open
  61. to keep the share from being deleted in tdc_remove_table()
  62. and TABLE_SHARE::wait_for_old_version. We must also set
  63. m_open_in_progress to indicate allocated but incomplete share.
  64. */
  65. share->increment_ref_count(); // Mark in use
  66. share->m_open_in_progress = true; // Mark being opened
  67. /*
  68. Temporarily release LOCK_open before opening the table definition,
  69. which can be done without mutex protection.
  70. */
  71. mysql_mutex_unlock(&LOCK_open);
  72. #if defined(ENABLED_DEBUG_SYNC)
  73. if (!thd->is_attachable_ro_transaction_active())
  74. DEBUG_SYNC(thd, "get_share_before_open");
  75. #endif
  76. {
  77. // We must make sure the schema is released and unlocked in the right order.
  78. dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
  79. const dd::Schema *sch = nullptr;
  80. const dd::Abstract_table *abstract_table = nullptr;
  81. if (thd->dd_client()->acquire(share->db.str, &sch) ||
  82. thd->dd_client()->acquire(share->db.str, share->table_name.str,
  83. &abstract_table)) {
  84. }
  85. ......
  86. // 通过刚刚读到的abstract_table 填充TABLE_SHARE中的一些细节信息
  87. }
  88. /*
  89. Get back LOCK_open before continuing. Notify all waiters that the
  90. opening is finished, even if there was a failure while opening.
  91. */
  92. // 设置m_open_in_progress表示信息已完成填充,并通过COND_open通知可能在等待的其他线程。
  93. mysql_mutex_lock(&LOCK_open);
  94. share->m_open_in_progress = false;
  95. mysql_cond_broadcast(&COND_open);
  96. ......
  97. DBUG_RETURN(share);
  98. }

以上,get_TABLE_SHARE过程中会通过thd->dd_client()->acquire()获取Table_Impl信息并保存到abstract_table中。同时TABLE_SHARE会被缓存在table_def_cache中,以避免重复构建TABLE_SHARE的开销。TABLE_SHARE为所有TABLE对象所共有,直到TABLE被删除或因开表过多需要关掉时才会释放。

  1. bool Dictionary_client::acquire(const K &key, const T **object,
  2. bool *local_committed,
  3. bool *local_uncommitted) {
  4. ......
  5. // 首先尝试是否有线程本地的uncommited cache,一般存在于create过程中
  6. acquire_uncommitted(key, &uncommitted_object, &dropped);
  7. if (uncommitted_object || dropped) {
  8. ......
  9. return false;
  10. }
  11. // 本地的uncommited cache中没有时,访问本地commited cache,一般存在于当前THD正在处理表操作时
  12. m_registry_committed.get(key, &element);
  13. if (element) {
  14. ......
  15. return false;
  16. }
  17. // The element is not present locally.
  18. *local_committed = false;
  19. // 查找共享缓存或存储系统中是否有表信息
  20. if (Shared_dictionary_cache::instance()->get(m_thd, key, &element)) {
  21. DBUG_ASSERT(m_thd->is_system_thread() || m_thd->killed ||
  22. m_thd->is_error());
  23. return true;
  24. }
  25. // Add the element to the local registry and assign the output object.
  26. if (element) {
  27. ......
  28. }
  29. return false;
  30. }
  31. // 查找共享缓存对应dd信息类型的字典,找不到时会查找存储引擎,并保存在相应字典中。
  32. bool Shared_dictionary_cache::get(THD *thd, const K &key,
  33. Cache_element<T> **element) {
  34. bool error = false;
  35. DBUG_ASSERT(element);
  36. if (m_map<T>()->get(key, element)) {
  37. // Handle cache miss.
  38. const T *new_object = NULL;
  39. error = get_uncached(thd, key, ISO_READ_COMMITTED, &new_object);
  40. // Add the new object, and assign the output element, even in the case of
  41. // a miss error (needed to remove the missed key).
  42. m_map<T>()->put(&key, new_object, element);
  43. }
  44. return error;
  45. }
  46. // 访问存储引擎查找dd信息
  47. bool Shared_dictionary_cache::get_uncached(THD *thd, const K &key,
  48. enum_tx_isolation isolation,
  49. const T **object) const {
  50. DBUG_ASSERT(object);
  51. bool error = Storage_adapter::get(thd, key, isolation, false, object);
  52. DBUG_ASSERT(!error || thd->is_system_thread() || thd->killed ||
  53. thd->is_error());
  54. return error;
  55. }

一般而言,在第一次访问表的Table_Impl信息时(包括create table后、宕机重启后等情况下),Table_Impl信息不在dd cache中,于是acquire函数会通过访问Storage_adapter获取并保存到Shared_multi_mapcommitted registry 中。这里还会有set_missed机制防止多线程同时访问存储引擎 前面提到的月报文章中已有介绍。之后自己或其他工作线程再需要访问dd信息时(如新的SQL需要开表或show create时),就可以从共享缓存Shared_multi_map中得到TableImpl信息。 ​

获取TableImpl并构建和缓存TABLE_SHARE后,mysql需要获取TABLE对象以完成开表操作。这一获取操作有两种方式: 1、该TABLE对象已经在thd->open_tables中,根据匹配的TABLE对象持有的锁等级选择best_table

  1. for (table = thd->open_tables; table; table = table->next) {
  2. // find best_table
  3. }
  4. table_list->table = best_table

2、thd->open_tables中不存在时,相应TABLE对象已经在thd对应的table_cache中一定不存在used_tables中,但当free_tables中存在时:从table_cache中读取,并加入el->used_tables

  1. table = tc->get_table(thd, key, key_length, &share);
  2. TABLE *tableTABLE\_SHAREcache::get_table(THD *thd, const char *key, size_t key_length,
  3. TABLE_SHARE **share) {
  4. ......
  5. const auto el_it = m_cache.find(key_str);
  6. if (el_it == m_cache.end()) return NULL;
  7. tableTABLE\_SHAREcache_element *el = el_it->second.get();
  8. if ((table = el->free_tables.front())) {
  9. DBUG_ASSERT(!table->in_use);
  10. el->free_tables.remove(table);
  11. el->used_tables.push_front(table);
  12. table->in_use = thd;
  13. }
  14. return table;
  15. }

3、get_table发现该TABLE对象不在table_cache中,通过open_table_from_share构建对象,然后tc->add_used_table放入used table cache ​

获取到TABLE对象后,该对象也已经缓存在table_cache的used_tables中,接下来通过将thd->set_open_tables(table)对象记录在thd->open_tables中,保证前面提到的,thd->open_tables中不存在时,相应TABLE对象已经在thd对应的table_cache中一定不存在于used_tables中 这一约束成立。 ​

清理:close_table 关表操作一般发生于完成一些操作后需要释放资源时,mysql_execute_command结束后close_thread_tables(thd);关闭所有thd->open_tables,然后清理相应的table cache:一般而言都是把table cache中in use的TABLE对象置为free,当缓存对象数过多时,也会进行清理(free_unused_tables_if_necessary)。 ​

删除:drop table drop table时会清空前面提到的一切数据,包括清空表相关的table cache、释放TABLE_SHARE并从table_def_cache中移除、删除DD信息并清理dd信息的多级缓存等。 ​

首先是清空dd cache。相关函数为table_cache_manager::free_table。该函数会遍历所有table_cache并删除相匹配的item,同时降低TABLE_SHARE的引用计数。其调用栈如下:

  1. #0 tableTABLE\_SHAREcache_manager::free_table
  2. #1 0x0000000003338b39 in remove_table
  3. #2 0x0000000003338dc0 in tdc_remove_table
  4. #3 0x00000000034b3d32 in drop_base_table
  5. #4 0x00000000034b523d in mysql_rm_table_no_locks
  6. #5 0x00000000034b105f in mysql_rm_table

TABLE_SHARE的引用计数降为0(即所有TABLE对象释放完毕)后就可以释放了。 ​ tdc_remove_table函数清理完table_cache和table_def_cache后,dd::drop_table函数负责调用dd::cache::Dictionary_client::drop<dd::Table>清理dd cache和删除DD信息,主要分为两步操作: 1、Storage_adapter::drop从存储引擎删除持久化的DD信息 2、invalidate(object);将DD信息标记为已删除,这样本线程一旦再需要访问或验证成功删除时,就不会产生读穿透至存储引擎的情况。

以上,给予MySQL 8.0.13我们分析的TABLE信息和相关的DD信息的正常流程下的生命周期,至于其他流程,包括超过容量之后的淘汰、TABLE的reopen机制等,我们以后再行研究。