├── LICENSE ├── README.md ├── db.go ├── go.mod ├── layout.go ├── layout_mysql.go ├── layout_tidb.go ├── main.go ├── stat.go ├── stat_test.go ├── widget.go ├── widget_iostat.go ├── widget_overview.go └── widget_processlist.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sqltop -------------------------------------------------------------------------------- /db.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | type DBType int 11 | 12 | const ( 13 | TypeUnknown DBType = iota 14 | TypeMySQL 15 | TypeTiDB 16 | ) 17 | 18 | func (t DBType) String() string { 19 | switch t { 20 | case TypeMySQL: 21 | return "MySQL" 22 | case TypeTiDB: 23 | return "TiDB" 24 | default: 25 | return "Unknown" 26 | } 27 | } 28 | 29 | type DataSource struct { 30 | db *sql.DB 31 | dsn string 32 | user, pwd, host string 33 | port int 34 | 35 | dbType DBType 36 | } 37 | 38 | const ( 39 | MaxRetryNum = 10 40 | ) 41 | 42 | var ( 43 | globalDS *DataSource 44 | ) 45 | 46 | func newDataSource(user, pwd, host string, port int) *DataSource { 47 | return &DataSource{ 48 | user: user, 49 | pwd: pwd, 50 | host: host, 51 | port: port, 52 | } 53 | } 54 | 55 | func InitDB() error { 56 | cfg := Config() 57 | globalDS = newDataSource(cfg.DBUser, cfg.DBPwd, cfg.Host, cfg.Port) 58 | if err := globalDS.Connect(); err != nil { 59 | return err 60 | } 61 | err := globalDS.Ping() 62 | if err != nil { 63 | return err 64 | } 65 | t, err := globalDS.getDBType() 66 | if err != nil { 67 | return err 68 | } 69 | globalDS.dbType = t 70 | return nil 71 | } 72 | 73 | func DB() *DataSource { 74 | return globalDS 75 | } 76 | 77 | func (ds *DataSource) Type() DBType { 78 | return ds.dbType 79 | } 80 | 81 | func (ds *DataSource) Ping() error { 82 | if ds.db == nil { 83 | err := ds.Connect() 84 | if err != nil { 85 | return err 86 | } 87 | } 88 | return ds.db.Ping() 89 | } 90 | 91 | func (ds *DataSource) getDBType() (DBType, error) { 92 | r, err := ds.Query(`SHOW VARIABLES LIKE "version"`) 93 | if err != nil { 94 | return TypeUnknown, err 95 | } 96 | defer r.Close() 97 | 98 | if r.Next() { 99 | var varName, versionText string 100 | err = r.Scan(&varName, &versionText) 101 | if err != nil { 102 | return TypeUnknown, err 103 | } 104 | 105 | if strings.Contains(versionText, "TiDB") { 106 | return TypeTiDB, nil 107 | } 108 | return TypeMySQL, nil 109 | } 110 | return TypeUnknown, fmt.Errorf("unsupported DB") 111 | } 112 | 113 | func (ds *DataSource) Close() error { 114 | if ds.db != nil { 115 | if err := ds.db.Close(); err != nil { 116 | return err 117 | } 118 | ds.db = nil 119 | } 120 | return nil 121 | } 122 | 123 | func (ds *DataSource) Connect() error { 124 | dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/INFORMATION_SCHEMA", ds.user, ds.pwd, ds.host, ds.port) 125 | var err error 126 | ds.db, err = sql.Open("mysql", dsn) 127 | ds.db.SetMaxIdleConns(10) 128 | ds.db.SetMaxOpenConns(10) 129 | 130 | if err != nil { 131 | return err 132 | } 133 | return nil 134 | } 135 | 136 | // make sure call Connect() before calling Query() 137 | func (ds *DataSource) Query(query string, args ...interface{}) (*sql.Rows, error) { 138 | var err error 139 | var ret *sql.Rows 140 | 141 | if ds.db == nil { 142 | err := ds.Connect() 143 | if err != nil { 144 | return nil, err 145 | } 146 | } 147 | 148 | for i := 0; i < MaxRetryNum; i++ { 149 | ret, err = ds.db.Query(query, args...) 150 | if err != nil { 151 | time.Sleep(500 * time.Millisecond) 152 | ds.db.Close() 153 | if err := ds.Connect(); err != nil { 154 | return nil, err 155 | } 156 | } else { 157 | return ret, nil 158 | } 159 | } 160 | // excees max retry, but still got error 161 | return nil, err 162 | } 163 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ngaut/sqltop 2 | 3 | go 1.13 4 | 5 | require ( 6 | code.cloudfoundry.org/bytefmt v0.0.0-20190819182555-854d396b647c 7 | github.com/gizak/termui/v3 v3.1.0 8 | github.com/go-sql-driver/mysql v1.4.1 9 | github.com/onsi/ginkgo v1.10.2 // indirect 10 | github.com/onsi/gomega v1.7.0 // indirect 11 | github.com/spf13/pflag v1.0.3 12 | github.com/stretchr/testify v1.4.0 13 | google.golang.org/appengine v1.6.4 // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /layout.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type Layout interface { 4 | Render() 5 | Refresh() error 6 | OnResize(payload interface{}) 7 | } 8 | -------------------------------------------------------------------------------- /layout_mysql.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | ui "github.com/gizak/termui/v3" 7 | "github.com/gizak/termui/v3/widgets" 8 | ) 9 | 10 | type mysqlLayout struct { 11 | rootGrid *ui.Grid 12 | 13 | processListWidget Widget 14 | overviewWidget Widget 15 | 16 | processList *widgets.Paragraph 17 | overview *widgets.Paragraph 18 | } 19 | 20 | func newMysqlLayout(overviewWidget Widget, processListWidget Widget) Layout { 21 | termWidth, termHeight := ui.TerminalDimensions() 22 | parent := ui.NewGrid() 23 | parent.SetRect(1, 3, termWidth-1, termHeight) 24 | parent.Border = true 25 | 26 | o := widgets.NewParagraph() 27 | o.Text = fmt.Sprintf("sqltop v0.2 [%s]\n", DB().Type()) 28 | o.Border = false 29 | 30 | o.SetRect(1, 1, termWidth-1, 2) 31 | 32 | p := widgets.NewParagraph() 33 | p.Border = false 34 | 35 | parent.Set( 36 | ui.NewRow(1.0, p), 37 | ) 38 | 39 | ret := &mysqlLayout{ 40 | rootGrid: parent, 41 | processList: p, 42 | overview: o, 43 | 44 | processListWidget: processListWidget, 45 | overviewWidget: overviewWidget, 46 | } 47 | 48 | return ret 49 | } 50 | 51 | func (l *mysqlLayout) Refresh() error { 52 | l.overview.Text = fmt.Sprintf("sqltop v0.2\t Mode: %s, %s\n", DB().Type(), l.overviewWidget.GetText()) 53 | l.processList.Text = l.processListWidget.GetText() 54 | return nil 55 | } 56 | 57 | func (l *mysqlLayout) Render() { 58 | ui.Render(l.overview) 59 | ui.Render(l.rootGrid) 60 | } 61 | 62 | func (l *mysqlLayout) OnResize(payload interface{}) { 63 | resize := payload.(ui.Resize) 64 | l.rootGrid.SetRect(1, 3, resize.Width-1, resize.Height) 65 | l.overview.SetRect(1, 1, resize.Width-1, 2) 66 | l.Render() 67 | } 68 | -------------------------------------------------------------------------------- /layout_tidb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | ui "github.com/gizak/termui/v3" 7 | "github.com/gizak/termui/v3/widgets" 8 | ) 9 | 10 | type tidbLayout struct { 11 | rootGrid *ui.Grid 12 | 13 | processListWidget Widget 14 | overviewWidget Widget 15 | iostatWidget Widget 16 | 17 | overview *widgets.Paragraph 18 | processList *widgets.Paragraph 19 | iostat *widgets.Paragraph 20 | } 21 | 22 | func newTiDBLayout(overviewWidget, processListWidget, iostatWidget Widget) Layout { 23 | termWidth, termHeight := ui.TerminalDimensions() 24 | parent := ui.NewGrid() 25 | parent.SetRect(1, 3, termWidth-1, termHeight) 26 | parent.Border = true 27 | 28 | // overview 29 | o := widgets.NewParagraph() 30 | o.Text = fmt.Sprintf("sqltop v0.2 [%s]\n", DB().Type()) 31 | o.Border = false 32 | o.SetRect(1, 1, termWidth-1, 2) 33 | 34 | // process list 35 | p := widgets.NewParagraph() 36 | p.Border = false 37 | 38 | // iostat 39 | i := widgets.NewParagraph() 40 | i.Border = false 41 | 42 | parent.Set( 43 | ui.NewRow(0.3, i), 44 | ui.NewRow(0.7, p), 45 | ) 46 | 47 | ret := &tidbLayout{ 48 | rootGrid: parent, 49 | processList: p, 50 | overview: o, 51 | iostat: i, 52 | 53 | processListWidget: processListWidget, 54 | overviewWidget: overviewWidget, 55 | iostatWidget: iostatWidget, 56 | } 57 | 58 | return ret 59 | } 60 | 61 | func (l *tidbLayout) Refresh() error { 62 | l.overview.Text = fmt.Sprintf("sqltop v0.2\t Mode: %s, %s\n", DB().Type(), l.overviewWidget.GetText()) 63 | l.processList.Text = l.processListWidget.GetText() 64 | l.iostat.Text = l.iostatWidget.GetText() 65 | return nil 66 | } 67 | 68 | func (l *tidbLayout) Render() { 69 | ui.Render(l.overview) 70 | ui.Render(l.rootGrid) 71 | } 72 | 73 | func (l *tidbLayout) OnResize(payload interface{}) { 74 | resize := payload.(ui.Resize) 75 | l.rootGrid.SetRect(1, 3, resize.Width-1, resize.Height) 76 | l.overview.SetRect(1, 1, resize.Width-1, 2) 77 | l.Render() 78 | } 79 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "os/exec" 7 | "time" 8 | 9 | ui "github.com/gizak/termui/v3" 10 | flag "github.com/spf13/pflag" 11 | 12 | _ "github.com/go-sql-driver/mysql" 13 | ) 14 | 15 | const version = "0.1" 16 | 17 | type Conf struct { 18 | Host string 19 | DBPwd string 20 | DBUser string 21 | Port int 22 | NumProcessToShow int 23 | } 24 | 25 | var ( 26 | host = flag.StringP("host", "h", "127.0.0.1", "host") 27 | pwd = flag.StringP("password", "p", "", "pwd") 28 | user = flag.StringP("user", "u", "root", "user") 29 | port = flag.IntP("port", "P", 3306, "port") 30 | count = flag.IntP("count", "n", 50, "Number of process to show") 31 | 32 | cfg *Conf 33 | ) 34 | 35 | func Config() *Conf { 36 | return cfg 37 | } 38 | 39 | func InitConfig() { 40 | flag.Parse() 41 | cfg = &Conf{} 42 | 43 | cfg.DBUser = *user 44 | cfg.DBPwd = *pwd 45 | cfg.Host = *host 46 | cfg.Port = *port 47 | cfg.NumProcessToShow = *count 48 | } 49 | 50 | func main() { 51 | InitConfig() 52 | log.SetFlags(log.Ldate | log.Ltime | log.Llongfile) 53 | 54 | if err := ui.Init(); err != nil { 55 | log.Print(err) 56 | os.Exit(-1) 57 | } 58 | 59 | if err := InitDB(); err != nil { 60 | cleanExit(err) 61 | } 62 | defer func() { 63 | ui.Close() 64 | err := DB().Close() 65 | if err != nil { 66 | cleanExit(err) 67 | } 68 | }() 69 | 70 | go refreshWorker() 71 | 72 | // if backend is MySQL 73 | if DB().Type() == TypeMySQL { 74 | refreshUI(newMysqlLayout(newOverviewWidget(), newProcessListWidget())) 75 | } else { 76 | refreshUI(newTiDBLayout(newOverviewWidget(), newProcessListWidget(), newIOStatWidget())) 77 | } 78 | 79 | } 80 | 81 | func cleanExit(err error) { 82 | ui.Close() 83 | exec.Command("clear").Run() 84 | if err != nil { 85 | log.Print(err) 86 | } 87 | os.Exit(0) 88 | } 89 | 90 | // refreshUI periodically refreshes the screen. 91 | func refreshUI(layout Layout) { 92 | redraw := make(chan struct{}) 93 | go func() { 94 | for { 95 | redraw <- struct{}{} 96 | 97 | // update data for UI 98 | if err := layout.Refresh(); err != nil { 99 | cleanExit(err) 100 | } 101 | // update every 1 seconds 102 | time.Sleep(1 * time.Second) 103 | } 104 | }() 105 | 106 | evt := ui.PollEvents() 107 | for { 108 | select { 109 | case e := <-evt: 110 | if e.Type == ui.KeyboardEvent && (e.ID == "q" || e.ID == "") { 111 | cleanExit(nil) 112 | } 113 | if e.ID == "" { 114 | layout.OnResize(e.Payload.(ui.Resize)) 115 | } 116 | 117 | case <-redraw: 118 | layout.Render() 119 | } 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /stat.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "strings" 7 | "sync" 8 | "time" 9 | 10 | "code.cloudfoundry.org/bytefmt" 11 | ) 12 | 13 | var ( 14 | stat *sync.Map 15 | once sync.Once 16 | ) 17 | 18 | var ( 19 | kProcessListSQL = `SELECT 20 | ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO 21 | FROM 22 | PROCESSLIST 23 | WHERE 24 | COMMAND != 'Sleep' 25 | ORDER BY TIME DESC LIMIT %d` 26 | 27 | kIOStatSQL = `SELECT 28 | table_name, index_name, SUM(written_bytes) AS w, SUM(read_bytes) AS r 29 | FROM 30 | TIKV_REGION_STATUS 31 | WHERE 32 | db_name != "INFORMATION_SCHEMA" AND db_name != "PERFORMANCE_SCHEMA" AND db_name != "mysql" 33 | GROUP BY table_name, index_name ORDER BY w DESC LIMIT 10` 34 | ) 35 | 36 | // stat keys 37 | const ( 38 | TOTAL_PROCESSES = "total_processes" 39 | USING_DBS = "using_dbs" 40 | TOTAL_READ = "total_read" 41 | TOTAL_WRITE = "total_write" 42 | TABLES_IO_STATUS = "table_io_status" 43 | PROCESS_LIST = "process_list" 44 | ) 45 | 46 | func Stat() *sync.Map { 47 | once.Do(func() { 48 | stat = &sync.Map{} 49 | }) 50 | return stat 51 | } 52 | 53 | type ProcessRecord struct { 54 | id, time int 55 | user, host, command string 56 | dbName, state, sqlText sql.NullString 57 | } 58 | 59 | type TableRegionStatus struct { 60 | tableName, indexName sql.NullString 61 | wbytes uint64 62 | rbytes uint64 63 | } 64 | 65 | func (r TableRegionStatus) String() string { 66 | return fmt.Sprintf("Table: %-20s Index: %-20s Write: %-10s Read: %-10s", 67 | r.tableName.String, r.indexName.String, bytefmt.ByteSize(r.wbytes), bytefmt.ByteSize(r.rbytes)) 68 | } 69 | 70 | func refresh() { 71 | // update process info 72 | if err := refreshProcessList(); err != nil { 73 | cleanExit(err) 74 | } 75 | 76 | // TiDB only-feature 77 | if DB().Type() == TypeTiDB { 78 | if err := refreshIOStat(); err != nil { 79 | cleanExit(err) 80 | } 81 | } 82 | } 83 | 84 | func refreshProcessList() error { 85 | q := fmt.Sprintf(kProcessListSQL, Config().NumProcessToShow) 86 | rows, err := DB().Query(q) 87 | if err != nil { 88 | return err 89 | } 90 | defer rows.Close() 91 | 92 | totalProcesses := 0 93 | usingDBs := make(map[string]struct{}) 94 | 95 | var records []ProcessRecord 96 | for rows.Next() { 97 | var r ProcessRecord 98 | err := rows.Scan(&r.id, &r.user, &r.host, &r.dbName, &r.command, &r.time, &r.state, &r.sqlText) 99 | if err != nil { 100 | return err 101 | } 102 | if r.dbName.Valid { 103 | usingDBs[strings.ToLower(r.dbName.String)] = struct{}{} 104 | } 105 | records = append(records, r) 106 | totalProcesses++ 107 | } 108 | err = rows.Err() 109 | if err != nil { 110 | return err 111 | } 112 | 113 | Stat().Store(TOTAL_PROCESSES, totalProcesses) 114 | Stat().Store(USING_DBS, len(usingDBs)) 115 | Stat().Store(PROCESS_LIST, records) 116 | 117 | return nil 118 | } 119 | 120 | func refreshIOStat() error { 121 | rows, err := DB().Query(kIOStatSQL) 122 | if err != nil { 123 | return err 124 | } 125 | defer rows.Close() 126 | var records TableRegionStatusList 127 | var totalRead, totalWrite uint64 128 | for rows.Next() { 129 | var r TableRegionStatus 130 | err := rows.Scan(&r.tableName, &r.indexName, &r.wbytes, &r.rbytes) 131 | if err != nil { 132 | return err 133 | } 134 | records = append(records, r) 135 | 136 | totalRead += r.rbytes 137 | totalWrite += r.wbytes 138 | } 139 | err = rows.Err() 140 | if err != nil { 141 | return err 142 | } 143 | 144 | Stat().Store(TOTAL_READ, totalRead) 145 | Stat().Store(TOTAL_WRITE, totalWrite) 146 | Stat().Store(TABLES_IO_STATUS, records) 147 | 148 | return nil 149 | } 150 | 151 | func refreshWorker() { 152 | for { 153 | refresh() 154 | time.Sleep(1 * time.Second) 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /stat_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/suite" 7 | ) 8 | 9 | type StatTestSuite struct { 10 | suite.Suite 11 | } 12 | 13 | func (suite *StatTestSuite) SetupTest() { 14 | // FIXME: hard-coded test env 15 | cfg = &Conf{ 16 | Host: "127.0.01", 17 | Port: 4001, 18 | DBUser: "root", 19 | DBPwd: "", 20 | NumProcessToShow: 10, 21 | } 22 | InitDB() 23 | } 24 | 25 | func (suite *StatTestSuite) TestRefreshProcessList() { 26 | err := refreshProcessList() 27 | suite.Nil(err) 28 | 29 | processList, ok := Stat().Load(PROCESS_LIST) 30 | suite.Equal(true, ok) 31 | suite.Greater(len(processList.([]ProcessRecord)), 0) 32 | 33 | usingDBs, ok := Stat().Load(USING_DBS) 34 | suite.Equal(true, ok) 35 | suite.Greater(usingDBs.(int), 0) 36 | } 37 | 38 | /* TODO 39 | func (suite *StatTestSuite) TestIOStat() { 40 | err := refreshIOStat() 41 | 42 | suite.Nil(err) 43 | 44 | if list, ok := Stat().Load(TABLES_IO_STATUS); ok { 45 | for _, r := range list.([]TableRegionStatus) { 46 | fmt.Println(r) 47 | } 48 | } 49 | } 50 | */ 51 | 52 | func TestSuiteTestSuite(t *testing.T) { 53 | suite.Run(t, new(StatTestSuite)) 54 | } 55 | -------------------------------------------------------------------------------- /widget.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type Widget interface { 4 | GetText() string 5 | } 6 | -------------------------------------------------------------------------------- /widget_iostat.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strings" 7 | ) 8 | 9 | type IOStatWidget struct{} 10 | 11 | type TableRegionStatusList []TableRegionStatus 12 | 13 | func (c TableRegionStatusList) Len() int { 14 | return len(c) 15 | } 16 | func (c TableRegionStatusList) Swap(i, j int) { 17 | c[i], c[j] = c[j], c[i] 18 | } 19 | func (c TableRegionStatusList) Less(i, j int) bool { 20 | if c[i].wbytes < c[j].wbytes { 21 | return true 22 | } else if c[i].wbytes == c[j].wbytes { 23 | if c[i].rbytes < c[j].rbytes { 24 | return true 25 | } else if c[i].rbytes == c[j].rbytes { 26 | switch strings.Compare(c[i].String(), c[j].String()) { 27 | case 1: 28 | return true 29 | case -1: 30 | return false 31 | } 32 | } 33 | } 34 | return false 35 | } 36 | 37 | func newIOStatWidget() Widget { 38 | return &IOStatWidget{} 39 | } 40 | 41 | func (c *IOStatWidget) GetText() string { 42 | var sb strings.Builder 43 | fmt.Fprintf(&sb, "Top hotspots\n") 44 | if list, ok := Stat().Load(TABLES_IO_STATUS); ok { 45 | sort.Sort(list.(TableRegionStatusList)) 46 | for _, r := range list.(TableRegionStatusList) { 47 | fmt.Fprintf(&sb, "%s\n", r) 48 | } 49 | } 50 | sb.WriteString("\n") 51 | return sb.String() 52 | } 53 | -------------------------------------------------------------------------------- /widget_overview.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "code.cloudfoundry.org/bytefmt" 8 | ) 9 | 10 | type OverviewWidget struct{} 11 | 12 | func newOverviewWidget() Widget { 13 | return &OverviewWidget{} 14 | } 15 | 16 | func (c *OverviewWidget) GetText() string { 17 | var sb strings.Builder 18 | if totalProcess, ok := Stat().Load(TOTAL_PROCESSES); ok { 19 | fmt.Fprintf(&sb, "Processes: %d total, Running: %d", totalProcess, totalProcess) 20 | } 21 | if usingDBs, ok := Stat().Load(USING_DBS); ok { 22 | fmt.Fprintf(&sb, ", Using DB: %d", usingDBs) 23 | } 24 | if DB().Type() == TypeTiDB { 25 | if totalRead, ok := Stat().Load(TOTAL_READ); ok { 26 | fmt.Fprintf(&sb, ", Recent total read: %s", bytefmt.ByteSize(totalRead.(uint64))) 27 | } 28 | if totalWrite, ok := Stat().Load(TOTAL_WRITE); ok { 29 | fmt.Fprintf(&sb, ", Recent total write: %s", bytefmt.ByteSize(totalWrite.(uint64))) 30 | } 31 | } 32 | return sb.String() 33 | } 34 | -------------------------------------------------------------------------------- /widget_processlist.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "strings" 7 | ) 8 | 9 | var ( 10 | re = regexp.MustCompile(`\r?\n`) 11 | ) 12 | 13 | type ProcessListWidget struct{} 14 | 15 | func newProcessListWidget() Widget { 16 | return &ProcessListWidget{} 17 | } 18 | 19 | func (c *ProcessListWidget) GetText() string { 20 | var sb strings.Builder 21 | fmt.Fprintf(&sb, "Top %d order by time desc:\n", Config().NumProcessToShow) 22 | fmt.Fprintf(&sb, "%-6s %-20s %-20s %-20s %-7s %-6s %-8s %-15s\n", 23 | "ID", "USER", "HOST", "DB", "COMMAND", "TIME", "STATE", "SQL") 24 | 25 | if r, ok := Stat().Load(PROCESS_LIST); ok { 26 | records := r.([]ProcessRecord) 27 | for _, r := range records { 28 | var sqlText string 29 | if r.sqlText.Valid { 30 | sqlText = r.sqlText.String 31 | if len(sqlText) > 128 { 32 | sqlText = sqlText[:128] 33 | sqlText = re.ReplaceAllString(sqlText, " ") 34 | } 35 | } 36 | fmt.Fprintf(&sb, "%-6d %-20s %-20s %-20s %-7s %-6d %-8s %-15s\n", 37 | r.id, r.user, r.host, r.dbName.String, r.command, r.time, r.state.String, sqlText) 38 | } 39 | } 40 | return sb.String() 41 | } 42 | --------------------------------------------------------------------------------