Your SlideShare is downloading. ×
Mysql展示功能与源码对应
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Mysql展示功能与源码对应

2,548
views

Published on

Mysql客户端的一些展示命令与源码 …

Mysql客户端的一些展示命令与源码

Mysqld服务端的展示命令与源码

Mysql复制状态信息的查看命令与源码

Innodb monitor信息展示与源码

Published in: Education, Technology

0 Comments
9 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,548
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
158
Comments
0
Likes
9
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • com_status 函数只展示 status 命令的一部份信息
  • sql/sql_show.cc 中的 mysqld_list_processes 函数
  • void mysqld_list_processes(THD *thd,const char *user, bool verbose) { Item *field; List<Item> field_list; I_List<thread_info> thread_infos; ulong max_query_length= (verbose ? thd->variables.max_allowed_packet : PROCESS_LIST_WIDTH); Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_list_processes"); // 先定义 id,user,Host,db,Command,Time,State,Info 字段信息到 field_list 变量中 , 并通过 protocol->send_fields 发送到客户端 field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS)); field_list.push_back(new Item_empty_string("User",16)); field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN)); field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN)); field->maybe_null=1; field_list.push_back(new Item_empty_string("Command",16)); field_list.push_back(field= new Item_return_int("Time",7, MYSQL_TYPE_LONG)); field->unsigned_flag= 0; field_list.push_back(field=new Item_empty_string("State",30)); field->maybe_null=1; field_list.push_back(field=new Item_empty_string("Info",max_query_length)); field->maybe_null=1; if (protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_VOID_RETURN; // 在读取各线程的信息之前,先锁定总的线程个数 , 不允许发生变化 VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list if (!thd->killed) { I_List_iterator<THD> it(threads); THD *tmp; while ((tmp=it++)) { // 获取一个线程的信息保存到 thd_info 中 Security_context *tmp_sctx= tmp->security_ctx; struct st_my_thread_var *mysys_var; if ((tmp->vio_ok() || tmp->system_thread) && (!user || (tmp_sctx->user && !strcmp(tmp_sctx->user, user)))) { thread_info *thd_info= new thread_info; thd_info->thread_id=tmp->thread_id; thd_info->user= thd->strdup(tmp_sctx->user ? tmp_sctx->user : (tmp->system_thread ? "system user" : "unauthenticated user")); if (tmp->peer_port && (tmp_sctx->host || tmp_sctx->ip) && thd->security_ctx->host_or_ip[0]) { if ((thd_info->host= (char*) thd->alloc(LIST_PROCESS_HOST_LEN+1))) my_snprintf((char *) thd_info->host, LIST_PROCESS_HOST_LEN, "%s:%u", tmp_sctx->host_or_ip, tmp->peer_port); } else thd_info->host= thd->strdup(tmp_sctx->host_or_ip[0] ? tmp_sctx->host_or_ip : tmp_sctx->host ? tmp_sctx->host : ""); if ((thd_info->db=tmp->db)) // Safe test thd_info->db=thd->strdup(thd_info->db); thd_info->command=(int) tmp->command; if ((mysys_var= tmp->mysys_var)) pthread_mutex_lock(&mysys_var->mutex); thd_info->proc_info= (char*) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0); #ifndef EMBEDDED_LIBRARY thd_info->state_info= (char*) (tmp->locked ? "Locked" : tmp->net.reading_or_writing ? (tmp->net.reading_or_writing == 2 ? "Writing to net" : thd_info->command == COM_SLEEP ? "" : "Reading from net") : tmp->proc_info ? tmp->proc_info : tmp->mysys_var && tmp->mysys_var->current_cond ? "Waiting on cond" : NullS); #else thd_info->state_info= (char*)"Writing to net"; #endif if (mysys_var) pthread_mutex_unlock(&mysys_var->mutex); thd_info->start_time= tmp->start_time; thd_info->query=0; /* Lock THD mutex that protects its data when looking at it. */ pthread_mutex_lock(&tmp->LOCK_thd_data); if (tmp->query()) { uint length= min(max_query_length, tmp->query_length()); thd_info->query= (char*) thd->strmake(tmp->query(),length); } pthread_mutex_unlock(&tmp->LOCK_thd_data); // 将一个线程的 thd_info 添加到 thread_infos 链表变量里 thread_infos.append(thd_info); } } } VOID(pthread_mutex_unlock(&LOCK_thread_count)); // 向客户端传送 thread_infos 链表中的数据 thread_info *thd_info; time_t now= my_time(0); while ((thd_info=thread_infos.get())) { protocol->prepare_for_resend(); protocol->store((ulonglong) thd_info->thread_id); protocol->store(thd_info->user, system_charset_info); protocol->store(thd_info->host, system_charset_info); protocol->store(thd_info->db, system_charset_info); if (thd_info->proc_info) protocol->store(thd_info->proc_info, system_charset_info); else protocol->store(command_name[thd_info->command].str, system_charset_info); if (thd_info->start_time) protocol->store_long ((longlong) (now - thd_info->start_time)); else protocol->store_null(); protocol->store(thd_info->state_info, system_charset_info); protocol->store(thd_info->query, system_charset_info); // 一条 item, 即向客户端写一次,如果有任何错误,则立刻退出循环,不必再向客户端写 if (protocol->write()) break; /* purecov: inspected */ } my_eof(thd); DBUG_VOID_RETURN; }
  • Mysql 的作者遍布全世界 root@(none) 01:45:16>SHOW AUTHORS; +--------------------------------+---------------------------------------+----------------------------------------------------------------------+ | Name | Location | Comment | +--------------------------------+---------------------------------------+----------------------------------------------------------------------+ | Brian (Krow) Aker | Seattle, WA, USA | Architecture, archive, federated, bunch of little stuff :) | | Venu Anuganti | | Client/server protocol (4.1) | | David Axmark | Uppsala, Sweden | Small stuff long time ago, Monty ripped it out! | | Alexander (Bar) Barkov | Izhevsk, Russia | Unicode and character sets (4.1) | | Omer BarNir | Sunnyvale, CA, USA | Testing (sometimes) and general QA stuff | | Guilhem Bichot | Bordeaux, France | Replication (since 4.0) | | John Birrell | | Emulation of pthread_mutex() for OS/2 | | Andreas F. Bobak | | AGGREGATE extension to user-defined functions | | Alexey Botchkov (Holyfoot) | Izhevsk, Russia | GIS extensions (4.1), embedded server (4.1), precision math (5.0) | | Reggie Burnett | Nashville, TN, USA | Windows development, Connectors | | Oleksandr Byelkin | Lugansk, Ukraine | Query Cache (4.0), Subqueries (4.1), Views (5.0) | | Kent Boortz | Orebro, Sweden | Test platform, and general build stuff | | Tim Bunce | | mysqlhotcopy | | Yves Carlier | | mysqlaccess | | Joshua Chamas | Cupertino, CA, USA | Concurrent insert, extended date syntax | | Petr Chardin | Moscow, Russia | Instance Manager (5.0), Server log tables (5.1) | | Wei-Jou Chen | | Chinese (Big5) character set | | Albert Chin-A-Young | | Tru64 port, large file support, better TCP wrappers support | | Jorge del Conde | Mexico City, Mexico | Windows development | | Antony T. Curtis | Norwalk, CA, USA | Parser, port to OS/2, storage engines and some random stuff | | Yuri Dario | | OS/2 port | | Andrei Elkin | Espoo, Finland | Replication | | Patrick Galbraith | Sharon, NH | Federated Engine, mysqlslap | | Sergei Golubchik | Kerpen, Germany | Full-text search, precision math | | Lenz Grimmer | Hamburg, Germany | Production (build and release) engineering | | Nikolay Grishakin | Austin, TX, USA | Testing - Server | | Wei He | | Chinese (GBK) character set | | Eric Herman | Amsterdam, Netherlands | Bug fixing - federated | | Andrey Hristov | Walldorf, Germany | Event scheduler (5.1) | | Alexander (Alexi) Ivanov | St. Petersburg, Russia | Replication | | Alexander (Salle) Keremidarski | Sofia, Bulgaria | Bug fixing | | Mats Kindahl | Storvreta, Sweden | Replication | | Serge Kozlov | Velikie Luki, Russia | Testing - Cluster | | Hakan Kü?üky?lmaz | Walldorf, Germany | Testing - Server | | Greg (Groggy) Lehey | Uchunga, SA, Australia | Backup | | Matthias Leich | Berlin, Germany | Testing - Server | | Dmitri Lenev | Moscow, Russia | Time zones support (4.1), Triggers (5.0) | | Arjen Lentz | Brisbane, Australia | Documentation (2001-2004), Dutch error messages, LOG2() | | Marc Liyanage | | Created Mac OS X packages | | Zarko Mocnik | | Sorting for Slovenian language | | Per-Erik Martin | Uppsala, Sweden | Stored Procedures (5.0) | | Alexis Mikhailov | | User-defined functions | | Sinisa Milivojevic | Larnaca, Cyprus | UNION (4.0), Subqueries in FROM clause (4.1), many other features | | Jonathan (Jeb) Miller | Kyle, TX, USA | Testing - Cluster, Replication | | Elliot Murphy | Cocoa, FL, USA | Replication and backup | | Kristian Nielsen | Copenhagen, Denmark | General build stuff | | Pekka Nouisiainen | Stockholm, Sweden | NDB Cluster: BLOB support, character set support, ordered indexes | | Alexander Nozdrin | Moscow, Russia | Bug fixing (Stored Procedures, 5.0) | | Per Eric Olsson | | Testing of dynamic record format | | Jonas Oreland | Stockholm, Sweden | NDB Cluster, Online Backup, lots of other things | | Konstantin Osipov | Moscow, Russia | Prepared statements (4.1), Cursors (5.0) | | Alexander (Sasha) Pachev | Provo, UT, USA | Statement-based replication, SHOW CREATE TABLE, mysql-bench | | Irena Pancirov | | Port to Windows with Borland compiler | | Jan Pazdziora | | Czech sorting order | | Benjamin Pflugmann | | Extended MERGE storage engine to handle INSERT | | Igor Romanenko | | mysqldump | | Mikael Ronstr?m | Stockholm, Sweden | NDB Cluster, Partitioning (5.1), Optimizations | | T?nu Samuel | | VIO interface, other miscellaneous features | | Carsten Segieth (Pino) | Fredersdorf, Germany | Testing - Server | | Martin Sk?ld | Stockholm, Sweden | NDB Cluster: Unique indexes, integration into MySQL | | Timothy Smith | Auckland, New Zealand | Dynamic character sets, parts of the build system, libmysqld | | Miguel Solorzano | Florianopolis, Santa Catarina, Brazil | Windows development, Windows NT service | | Punita Srivastava | Austin, TX, USA | Testing - Merlin | | Alexey Stroganov (Ranger) | Lugansk, Ukraine | Testing - Benchmarks | | Ingo Strüwing | Berlin, Germany | Bug fixing | | Magnus Svensson | ?regrund, Sweden | NDB Cluster: Integration into MySQL, test framework | | Zeev Suraski | | FROM_UNIXTIME(), ENCRYPT() | | TAMITO | | The _MB character set macros and UJIS and SJIS character sets | | Jani Tolonen | Helsinki, Finland | mysqlimport, extensions to command-line clients, PROCEDURE ANALYSE() | | Lars Thalmann | Stockholm, Sweden | Replication and cluster development | | Tomas Ulin | Stockholm, Sweden | NDB Cluster: Configuration, installation | | Gianmassimo Vigazzola | | Initial Windows port | | Sergey Vojtovich | Izhevsk, Russia | Plugins infrastructure (5.1) | | Matt Wagner | Northfield, MN, USA | Bug fixing | | Jim Winstead Jr. | Los Angeles, CA, USA | Bug fixing | | Michael (Monty) Widenius | Tusby, Finland | Lead developer and main author | | Peter Zaitsev | Tacoma, WA, USA | SHA1(), AES_ENCRYPT(), AES_DECRYPT(), bug fixing | +--------------------------------+---------------------------------------+----------------------------------------------------------------------+
  • root@(none) 01:45:40>show contributors; +-------------------+---------------------+-------------------------------------+ | Name | Location | Comment | +-------------------+---------------------+-------------------------------------+ | Ronald Bradford | Brisbane, Australia | EFF contribution for UC2006 Auction | | Sheeri Kritzer | Boston, Mass. USA | EFF contribution for UC2006 Auction | | Mark Shuttleworth | London, UK. | EFF contribution for UC2006 Auction | +-------------------+---------------------+-------------------------------------+ 3 rows in set (0.01 sec)
  • 查看创建表脚本示例: root@test 03:26:51>show create table spG *************************** 1. row *************************** Table: sp Create Table: CREATE TABLE `sp` ( `a` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=gbk 1 row in set (0.00 sec) 查看创建视图脚本示例: root@test 03:11:26>show create view t2G *************************** 1. row *************************** View: t2 Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `t2` AS select `sp`.`a` AS `a` from `sp` character_set_client: gbk collation_connection: gbk_chinese_ci 1 row in set (0.00 sec)
  • root@test 03:11:33>show create database test; +----------+--------------------------------------------------------------+ | Database | Create Database | +----------+--------------------------------------------------------------+ | test | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET gbk */ | +----------+--------------------------------------------------------------+ 1 row in set (0.00 sec)
  • root@test 03:26:59>show privileges; +-------------------------+---------------------------------------+-------------------------------------------------------+ | Privilege | Context | Comment | +-------------------------+---------------------------------------+-------------------------------------------------------+ | Alter | Tables | To alter the table | | Alter routine | Functions,Procedures | To alter or drop stored functions/procedures | | Create | Databases,Tables,Indexes | To create new databases and tables | | Create routine | Databases | To use CREATE FUNCTION/PROCEDURE | | Create temporary tables | Databases | To use CREATE TEMPORARY TABLE | | Create view | Tables | To create new views | | Create user | Server Admin | To create new users | | Delete | Tables | To delete existing rows | | Drop | Databases,Tables | To drop databases, tables, and views | | Event | Server Admin | To create, alter, drop and execute events | | Execute | Functions,Procedures | To execute stored routines | | File | File access on server | To read and write files on the server | | Grant option | Databases,Tables,Functions,Procedures | To give to other users those privileges you possess | | Index | Tables | To create or drop indexes | | Insert | Tables | To insert data into tables | | Lock tables | Databases | To use LOCK TABLES (together with SELECT privilege) | | Process | Server Admin | To view the plain text of currently executing queries | | References | Databases,Tables | To have references on tables | | Reload | Server Admin | To reload or refresh tables, logs and privileges | | Replication client | Server Admin | To ask where the slave or master servers are | | Replication slave | Server Admin | To read binary log events from the master | | Select | Tables | To retrieve rows from table | | Show databases | Server Admin | To see all databases with SHOW DATABASES | | Show view | Tables | To see views with SHOW CREATE VIEW | | Shutdown | Server Admin | To shut down the server | | Super | Server Admin | To use KILL thread, SET GLOBAL, CHANGE MASTER, etc. | | Trigger | Tables | To use triggers | | Update | Tables | To update existing rows | | Usage | Server Admin | No privileges - allow connect only | +-------------------------+---------------------------------------+-------------------------------------------------------+
  • sql/Table.h /* Make sure that the order of schema_tables and enum_schema_tables are the same. */ enum enum_schema_tables { SCH_CHARSETS= 0, SCH_COLLATIONS, SCH_COLLATION_CHARACTER_SET_APPLICABILITY, SCH_COLUMNS, SCH_COLUMN_PRIVILEGES, SCH_ENGINES, SCH_EVENTS, SCH_FILES, SCH_GLOBAL_STATUS, SCH_GLOBAL_VARIABLES, SCH_KEY_COLUMN_USAGE, SCH_OPEN_TABLES, SCH_PARTITIONS, SCH_PLUGINS, SCH_PROCESSLIST, SCH_PROFILES, SCH_REFERENTIAL_CONSTRAINTS, SCH_PROCEDURES, SCH_SCHEMATA, SCH_SCHEMA_PRIVILEGES, SCH_SESSION_STATUS, SCH_SESSION_VARIABLES, SCH_STATISTICS, SCH_STATUS, SCH_TABLES, SCH_TABLE_CONSTRAINTS, SCH_TABLE_NAMES, SCH_TABLE_PRIVILEGES, SCH_TRIGGERS, SCH_USER_PRIVILEGES, SCH_VARIABLES, SCH_VIEWS }; 参考: http://forge.mysql.com/wiki/INFORMATION_SCHEMA_storage_engine
  • 如何把一台 mysql 做成多台 master 的 slave?
  • 各个版本的 mysql 所展示的 show innodb status 会有差异 5.1.45-log Source distribution Innodb plugin
  • Create table innodb_tablespace_monitor; Create table innodb_lock_monitor; create table innodb_table_monitor(a int) engine=innodb; 参考网址: http://zhaolinjnu.blog.sohu.com/119143540.html http://dev.mysql.com/doc/refman/5.0/en/innodb-monitors.html#innodb-tablespace-monitor
  • /*********************************************************************//** Calculates new estimates for table and index statistics. The statistics are used in query optimization. */ UNIV_INTERN void dict_update_statistics_low( /*=======================*/ dict_table_t* table, /*!< in/out: table */ ibool has_dict_mutex __attribute__((unused))) /*!< in: TRUE if the caller has the dictionary mutex */ { dict_index_t* index; ulint size; ulint sum_of_index_sizes = 0; if (table->ibd_file_missing) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: cannot calculate statistics for table %s
    " "InnoDB: because the .ibd file is missing. For help," " please refer to
    " "InnoDB: " REFMAN "innodb-troubleshooting.html
    ", table->name); return; } /* If we have set a high innodb_force_recovery level, do not calculate statistics, as a badly corrupted index can cause a crash in it. */ if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) { return; } /* Find out the sizes of the indexes and how many different values for the key they approximately have */ // 先查找第一个索引,至少有一个索引 index = dict_table_get_first_index(table); if (index == NULL) { /* Table definition is corrupt */ return; } while (index) { // 取得当前索引大小精确值 size = btr_get_size(index, BTR_TOTAL_SIZE); index->stat_index_size = size; sum_of_index_sizes += size; // 取得当前索引叶子结点页数 size = btr_get_size(index, BTR_N_LEAF_PAGES); if (size == 0) { /* The root node of the tree is a leaf */ size = 1; } index->stat_n_leaf_pages = size; // 预测不同的索引键值个数 btr_estimate_number_of_different_key_vals(index); // 查找下一个索引 index = dict_table_get_next_index(index); } // 第一个索引,总是 cluster_index, 怪不得其它索引称为第二索引 index = dict_table_get_first_index(table); dict_index_stat_mutex_enter(index); // 表的行数,从索引的统计数据里获取 table->stat_n_rows = index->stat_n_diff_key_vals[ dict_index_get_n_unique(index)]; dict_index_stat_mutex_exit(index); // 主索引大小 cluster index table->stat_clustered_index_size = index->stat_index_size; // 其它索引总共大小 = 索引总大小 -cluster_index_size table->stat_sum_of_other_index_sizes = sum_of_index_sizes - index->stat_index_size; table->stat_initialized = TRUE; table->stat_modified_counter = 0; }
  • Transcript

    • 1. MySQL 展示功能与源码对应 丹臣 / 赵林 2010-10-12
    • 2. 提 纲
      • Mysql 客户端的一些展示命令与源码
      • Mysqld 服务端的展示命令与源码
      • Mysql 复制状态信息的查看命令与源码
      • Innodb monitor 信息展示与源码
    • 3. 客户端 status 命令
    • 4. 客户端 status 命令 client/Mysql.cc 源文件 …
    • 5. 客户端 status 命令 这部份信息来自于哪里? Sql_parse.cc 源程序中的 dispatch_command 函数
    • 6. 服务端常用的一些命令
      • show processlist
      • show authors
      • show contributors
      • show create table / view
      • show create database
      • show privileges
      • 神奇的 information_schema
    • 7. Show processlist
    • 8. show processlist
      • 三个步骤:
      • 1. 先定义 id,user,Host,db,Command,Time,State,Info 字段信息到 field_list 变量中 , 并通过 protocol->send_fields 发送到客户端
      • 2. 锁定线程总数,遍历所有线程,将所有线程的信息填入 thread_infos 链表变量中
      • 向客户端传送 thread_infos 链表中的数据 , 通过 protocol->write() 完成写操作
      • 实际中遇到的问题:
      • 如果一个 mysql 线程很多,那么大部份的 sleep 线程将干扰查看 processlist 列表
    • 9. Show authors
    • 10. show contributors
    • 11. show create table / view
    • 12. show create database
    • 13. show privileges
    • 14. information_schema 中的对象
    • 15. schema_information 中的对象
    • 16. st_schema_table 结构体定义
    • 17. show table status Table 的各种信息,都在 tables_fields_info[] 数组里定义义 ,Name,Engine,Version,Row_format,Rows,Avg_row_lenght,Data_length 等等
    • 18. show table status 再看 ST_SCHEMA_TABLE schema_tables[] 关于 tables 的定义 表的名字: TABLES 表结构的定义: tables_fields_info 表的创建函数: create_schema_table 填冲数据函数: by function get_all_tables and get_schema_tables_record
    • 19. MySQL 复制的常用命令
      • show slave status;
      • show master status;
    • 20. show slave status sql/Slave.cc 源文件 如何把一台 mysql 做成多台 master 的 slave?
    • 21. show master status sql/Sql_repl.cc 源文件
    • 22. Show innodb status
    • 23. show innodb status srv_printf_innodb_monitor INNODB MONITOR OUTPUT srv_print_master_thread_info(file) 注解: BACKGROUND THREAD sync_print(file) 注解: SEMAPHORES lock_print_info_summary() 汇总事务信息 lock_print_info_all_transactions() 每个事务的信息 注解: TRANSACTIONS os_aio_print(file); 注解: FILE I/O ibuf_print(file) // insert buffer ha_print_info(file…) //hash table 注解: INSERT BUFFER AND ADAPTIVE HASH INDEX log_print(file) 注解: LOG buf_print_io(file) 注解: BUFFER POOL AND MEMORY ROW OPERATIONS( 根据全局变量值计算 ) sync_array_print_info sync_print_wait_info 源文件位置: storage/innodb_plugin/srv/srv0srv.c trx_sys_struct trx_purge_struct log_struct buf_pool_struct ibuf_struct hash_table_struct os_aio_array_struct /** The asynchronous i/o array structure */ /** Synchronization array */ sync_array_struct
    • 24. Innodb monitor 信息展示与源码 …… . srv/Srv0srv.c 源文件中的 srv_monitor_thread 主函数 INNODB TABLESPACE and TABLE MONITOR OUTPUT dict_table_print_low, dict_update_statistics_low, dict_col_print_low, dtype_print
    • 25. 收集表与索引统计数据
    • 26. Follow me
      • 团队 blog:http://www.taobaodba.com
      • 个人 blog:http://zhaolinjnu.blog.sohu.com
      • Twitter:http://twitter.com/zhaolinjnu
      • 新浪微博: http://t.sina.com.cn/zhaolinjnu
      • Email:zhaolinjnu@163.com