-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
286 lines (255 loc) · 7.11 KB
/
main.go
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
53
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
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
136
137
138
139
140
141
142
143
144
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
171
172
173
174
175
176
177
178
179
180
181
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
"context"
"database/sql"
"encoding/csv"
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
)
const (
defaultDriver = "mysql"
defaultDBName = "performance_schema"
defaultQueryMysql565 = `select
COUNT_STAR AS cnt,
SUM_TIMER_WAIT/1e12 AS sum,
MIN_TIMER_WAIT/1e12 AS min,
AVG_TIMER_WAIT/1e12 AS avg,
MAX_TIMER_WAIT/1e12 AS max,
SUM_LOCK_TIME/1e12 AS sumLock,
SUM_ROWS_SENT AS sumRows,
ifnull((SUM_ROWS_SENT / nullif(COUNT_STAR,0)),0) AS avgRows,
DIGEST_TEXT AS digest
from events_statements_summary_by_digest
order by SUM_TIMER_WAIT desc`
defaultQueryMysql569 = `select
COUNT_STAR AS cnt,
SUM_TIMER_WAIT/1e12 AS sum,
MIN_TIMER_WAIT/1e12 AS min,
AVG_TIMER_WAIT/1e12 AS avg,
MAX_TIMER_WAIT/1e12 AS max,
SUM_LOCK_TIME/1e12 AS sumLock,
SUM_ROWS_SENT AS sumRows,
ifnull((SUM_ROWS_SENT / nullif(COUNT_STAR,0)),0) AS avgRows,
SCHEMA_NAME AS db,
DIGEST_TEXT AS digest
from events_statements_summary_by_digest
where SCHEMA_NAME <> ?
order by SUM_TIMER_WAIT desc`
defaultQueryMysql80 = `select
COUNT_STAR AS cnt,
SUM_TIMER_WAIT/1e12 AS sum,
MIN_TIMER_WAIT/1e12 AS min,
AVG_TIMER_WAIT/1e12 AS avg,
MAX_TIMER_WAIT/1e12 AS max,
SUM_LOCK_TIME/1e12 AS sumLock,
SUM_ROWS_SENT AS sumRows,
ifnull((SUM_ROWS_SENT / nullif(COUNT_STAR,0)),0) AS avgRows,
SCHEMA_NAME AS db,
QUERY_SAMPLE_TEXT AS query
from events_statements_summary_by_digest
where SCHEMA_NAME <> ?
order by SUM_TIMER_WAIT desc`
defaultQueryPgsql94 = `SELECT
s.calls AS cnt,
s.total_time AS sum,
s.rows AS sumRows,
COALESCE((s.rows / NULLIF(s.calls,0)),0) AS avgRows,
d.datname AS db,
s.query
FROM pg_stat_statements s
LEFT JOIN pg_database d ON s.dbid = d.oid
ORDER BY s.total_time DESC`
defaultQueryPgsql95 = `SELECT
s.calls AS cnt,
s.total_time AS sum,
s.min_time AS min,
s.mean_time AS avg,
s.max_time AS max,
s.rows AS sumRows,
COALESCE((s.rows / NULLIF(s.calls,0)),0) AS avgRows,
d.datname AS db,
s.query
FROM pg_stat_statements s
LEFT JOIN pg_database d ON s.dbid = d.oid
ORDER BY s.total_time DESC`
defaultQueryPgsql13 = `SELECT
s.calls AS cnt,
s.total_exec_time AS sum,
s.min_exec_time AS min,
s.mean_exec_time AS avg,
s.max_exec_time AS max,
s.rows AS sumRows,
COALESCE((s.rows / NULLIF(s.calls,0)),0) AS avgRows,
d.datname AS db,
s.query
FROM pg_stat_statements s
LEFT JOIN pg_database d ON s.dbid = d.oid
ORDER BY s.total_exec_time DESC`
)
var (
isVerbose bool
)
// Output はDBからPerformanceSchemaを読み込んでTSV形式で出力
func Output(ctx context.Context, w io.Writer, driver, dsn string, queries []string, params ...string) error {
db, err := sql.Open(driver, dsn)
if err != nil {
return fmt.Errorf("failed to open: %w", err)
}
defer db.Close()
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
var args []interface{}
for _, p := range params {
args = append(args, p)
}
var rows *sql.Rows
for _, query := range queries {
rows, err = db.QueryContext(ctx, query, args...)
// success
if err == nil {
break
}
if isVerbose {
fmt.Fprintf(os.Stderr, `failed to query "%s": %v\n`, query, err)
}
}
if err != nil {
return fmt.Errorf("failed to query: %w", err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return fmt.Errorf("failed to get columns: %w", err)
}
cw := csv.NewWriter(w)
cw.Comma = '\t'
defer cw.Flush()
if err := cw.Write(cols); err != nil {
return fmt.Errorf("failed to write columns: %w", err)
}
tsv := make([]string, len(cols))
values := make([]interface{}, len(cols))
for i := range values {
values[i] = &tsv[i]
}
for rows.Next() {
err := rows.Scan(values...)
if err != nil {
return fmt.Errorf("failed to scan rows: %w", err)
}
if err := cw.Write(tsv); err != nil {
return fmt.Errorf("failed to write values: %w", err)
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("db error: %w", err)
}
if err := cw.Error(); err != nil {
return fmt.Errorf("csv error: %w", err)
}
return nil
}
func main() {
var user, passwd, host, sock, driver, ssl, query string
var port int
var params []string
flag.StringVar(&user, "user", "", "Username")
flag.StringVar(&user, "u", "", "Username (shorthand)")
flag.StringVar(&passwd, "password", "", "Password")
flag.StringVar(&passwd, "p", "", "Password (shorthand)")
flag.StringVar(&host, "host", "", "Host")
flag.StringVar(&host, "h", "", "Host (shorthand)")
flag.IntVar(&port, "port", 0, "Port")
flag.IntVar(&port, "P", 0, "Port (shorthand)")
flag.StringVar(&driver, "driver", defaultDriver, "driver")
flag.StringVar(&driver, "D", defaultDriver, "driver (shorthand)")
flag.StringVar(&sock, "socket", "", "Socket path")
flag.StringVar(&sock, "S", "", "Socket path (shorthand)")
flag.StringVar(&ssl, "ssl", "disable", "sslmode(TLS) option")
flag.StringVar(&ssl, "s", "disable", "sslmode(TLS) (shorthand)")
flag.StringVar(&query, "execute", "", "execute command")
flag.StringVar(&query, "e", "", "execute command (shorthand)")
flag.BoolVar(&isVerbose, "verbose", false, "verbose output")
flag.BoolVar(&isVerbose, "v", false, "verbose output (shorthand)")
flag.Parse()
dbname := flag.Arg(0)
var dsn string
var queries []string
switch driver {
case "mysql":
mysqlConfig := mysql.NewConfig()
mysqlConfig.User = user
mysqlConfig.Passwd = passwd
if port == 0 {
port = 3306
}
if host != "" {
mysqlConfig.Net = "tcp"
mysqlConfig.Addr = fmt.Sprintf("%s:%d", host, port)
} else if sock != "" {
mysqlConfig.Net = "unix"
mysqlConfig.Addr = sock
}
if dbname == "" {
dbname = defaultDBName
}
mysqlConfig.DBName = dbname
if ssl != "disable" {
mysqlConfig.TLSConfig = ssl
}
dsn = mysqlConfig.FormatDSN()
if query == "" {
queries = append(queries, defaultQueryMysql80)
queries = append(queries, defaultQueryMysql569)
queries = append(queries, defaultQueryMysql565)
params = append(params, dbname)
} else {
queries = append(queries, query)
}
case "postgres":
var dsnParams []string
if user != "" {
dsnParams = append(dsnParams, fmt.Sprintf("user=%s", user))
}
if passwd != "" {
dsnParams = append(dsnParams, fmt.Sprintf("password=%s", passwd))
}
if host != "" {
dsnParams = append(dsnParams, fmt.Sprintf("host=%s", host))
} else if sock != "" {
dsnParams = append(dsnParams, fmt.Sprintf("host=%s", sock))
}
if port != 0 {
dsnParams = append(dsnParams, fmt.Sprintf("port=%d", port))
}
if dbname != "" {
dsnParams = append(dsnParams, fmt.Sprintf("dbname=%s", dbname))
}
dsnParams = append(dsnParams, fmt.Sprintf("sslmode=%s", ssl))
if len(dsnParams) > 0 {
dsn = strings.Join(dsnParams, " ")
} else {
dsn = "postgres://"
}
if query == "" {
queries = append(queries, defaultQueryPgsql13)
queries = append(queries, defaultQueryPgsql95)
queries = append(queries, defaultQueryPgsql94)
} else {
queries = append(queries, query)
}
default:
fmt.Fprintf(os.Stderr, "unknown driver: %s\n", driver)
os.Exit(1)
}
if err := Output(context.Background(), os.Stdout, driver, dsn, queries, params...); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}