/
slow_query.go
171 lines (156 loc) · 4.8 KB
/
slow_query.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
package profiler
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/goccy/echo-tools/gist"
"github.com/goccy/echo-tools/notifier"
"github.com/labstack/echo/v4"
)
const (
slowQueryLogFileFormat = "2006_01_02_15_04_05"
slowQueryLogEndpoint = "/debug/slowQueryLog"
)
type MySQLSlowQueryLogProfiler struct {
echo *echo.Echo
hostAddr string
db *sql.DB
slowQueryLogFileName string
botName string
discordWebhookURL string
githubToken string
}
type MySQLSlowQueryLogProfilerOption func(*MySQLSlowQueryLogProfiler)
func MySQLSlowQueryLogDiscordNotifierOption(botName, webhookURL, githubToken string) MySQLSlowQueryLogProfilerOption {
return func(p *MySQLSlowQueryLogProfiler) {
p.botName = botName
p.discordWebhookURL = webhookURL
p.githubToken = githubToken
}
}
func NewMySQLSlowQueryLogProfiler(e *echo.Echo, hostAddr string, db *sql.DB, opts ...MySQLSlowQueryLogProfilerOption) *MySQLSlowQueryLogProfiler {
slowQueryLogFileName := fmt.Sprintf(
"%s_slow_query.log",
time.Now().Format(slowQueryLogFileFormat),
)
p := &MySQLSlowQueryLogProfiler{
echo: e,
hostAddr: hostAddr,
db: db,
slowQueryLogFileName: slowQueryLogFileName,
}
e.POST(slowQueryLogEndpoint, echo.WrapHandler(&MySQLSlowQueryLogHandler{}))
for _, opt := range opts {
opt(p)
}
return p
}
func (p *MySQLSlowQueryLogProfiler) Start() error {
log.Printf("slow query log: %s", p.slowQueryLogFileName)
if _, err := p.db.Exec(
fmt.Sprintf(
"SET GLOBAL slow_query_log_file = `%s`",
p.slowQueryLogFileName,
),
); err != nil {
return fmt.Errorf("failed to set slow query log file: %w", err)
}
if _, err := p.db.Exec("SET GLOBAL long_query_time = 0"); err != nil {
return fmt.Errorf("failed to set long_query_time: %w", err)
}
return nil
}
func (p *MySQLSlowQueryLogProfiler) requestURL() string {
addr := strings.TrimLeft(p.hostAddr, "http://")
return fmt.Sprintf("http://%s%s", addr, slowQueryLogEndpoint)
}
type MySQLSlowQueryLogRequest struct {
FileName string `json:"filename"`
BotName string `json:"botName"`
GitHubToken string `json:"githubToken"`
DiscordWebhookURL string `json:"discordWebhookURL"`
}
func (p *MySQLSlowQueryLogProfiler) Stop() error {
b, err := json.Marshal(&MySQLSlowQueryLogRequest{
FileName: p.slowQueryLogFileName,
BotName: p.botName,
GitHubToken: p.githubToken,
DiscordWebhookURL: p.discordWebhookURL,
})
if err != nil {
return fmt.Errorf("failed to encode slow query log: %w", err)
}
url := p.requestURL()
req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
httpClient := new(http.Client)
if _, err := httpClient.Do(req); err != nil {
return fmt.Errorf("failed to post %s: %w", url, err)
}
return nil
}
type MySQLSlowQueryLogHandler struct{}
func (h *MySQLSlowQueryLogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.handle(r.Context(), r.Body); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err.Error())
}
}
var (
queryDigestCommandTmpl = `sudo pt-query-digest /var/lib/mysql/%s > %s`
)
func (h *MySQLSlowQueryLogHandler) handle(ctx context.Context, body io.Reader) error {
var req MySQLSlowQueryLogRequest
if err := json.NewDecoder(body).Decode(&req); err != nil {
return fmt.Errorf("failed to decode slow query log request: %w", err)
}
if req.FileName == "" {
return fmt.Errorf("failed to find slow-query-log filename")
}
tempDir := os.TempDir()
digestFile := filepath.Join(tempDir, fmt.Sprintf("digest_%s", req.FileName))
cmd := exec.Command(
"sh", "-c", fmt.Sprintf(queryDigestCommandTmpl, req.FileName, digestFile),
)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to exec pt-query-digest: %s: %w", string(out), err)
}
if req.GitHubToken == "" || req.DiscordWebhookURL == "" {
log.Println("github token or discord webhook url is not found")
return nil
}
client, err := gist.NewClient(ctx, req.GitHubToken)
if err != nil {
return fmt.Errorf("failed to create gist client: %w", err)
}
url, err := client.UploadFile(ctx, req.FileName, digestFile)
if err != nil {
return fmt.Errorf("failed to upload slow-query-log: %w", err)
}
botName := req.BotName
if botName == "" {
botName = "bot"
}
discordClient := notifier.NewDiscordClient(req.DiscordWebhookURL)
if err := discordClient.Post(¬ifier.DiscordMessage{
Username: botName,
Content: fmt.Sprintf("slow-query-log digest: %s", url),
}); err != nil {
return fmt.Errorf("failed to post message to discord: %w", err)
}
return nil
}