| 1 | /* |
| 2 | Copyright (c) 2019, Percona LLC. |
| 3 | All rights reserved. |
| 4 | |
| 5 | Redistribution and use in source and binary forms, with or without |
| 6 | modification, are permitted provided that the following conditions are met: |
| 7 | |
| 8 | * Redistributions of source code must retain the above copyright notice, this |
| 9 | list of conditions and the following disclaimer. |
| 10 | |
| 11 | * Redistributions in binary form must reproduce the above copyright notice, |
| 12 | this list of conditions and the following disclaimer in the documentation |
| 13 | and/or other materials provided with the distribution. |
| 14 | |
| 15 | * Neither the name of the copyright holder nor the names of its |
| 16 | contributors may be used to endorse or promote products derived from |
| 17 | this software without specific prior written permission. |
| 18 | |
| 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | */ |
| 30 | |
| 31 | // Package slow implements a MySQL slow log parser. |
| 32 | package slow |
| 33 | |
| 34 | import ( |
| 35 | "bufio" |
| 36 | "fmt" |
| 37 | "io" |
| 38 | stdlog "log" |
| 39 | "os" |
| 40 | "regexp" |
| 41 | "strconv" |
| 42 | "strings" |
| 43 | "time" |
| 44 | |
| 45 | "github.com/percona/go-mysql/log" |
| 46 | ) |
| 47 | |
| 48 | // Regular expressions to match important lines in slow log. |
| 49 | var ( |
| 50 | timeRe = regexp.MustCompile(`Time: (\S+\s{1,2}\S+)`) |
| 51 | timeNewRe = regexp.MustCompile(`Time:\s+(\d{4}-\d{2}-\d{2}\S+)`) |
| 52 | userRe = regexp.MustCompile(`User@Host: ([^\[]+|\[[^[]+\]).*?@ (\S*) \[(.*)\]`) |
| 53 | schema = regexp.MustCompile(`Schema: +(.*?) +Last_errno:`) |
| 54 | headerRe = regexp.MustCompile(`^#\s+[A-Z]`) |
| 55 | metricsRe = regexp.MustCompile(`(\w+): (\S+|\z)`) |
| 56 | adminRe = regexp.MustCompile(`command: (.+)`) |
| 57 | setRe = regexp.MustCompile(`^SET (?:last_insert_id|insert_id|timestamp)`) |
| 58 | useRe = regexp.MustCompile(`^(?i)use `) |
| 59 | ) |
| 60 | |
| 61 | // A SlowLogParser parses a MySQL slow log. It implements the LogParser interface. |
| 62 | type SlowLogParser struct { |
| 63 | file *os.File |
| 64 | opt log.Options |
| 65 | // -- |
| 66 | stopChan chan bool |
| 67 | eventChan chan *log.Event |
| 68 | inHeader bool |
| 69 | inQuery bool |
| 70 | headerLines uint |
| 71 | queryLines uint64 |
| 72 | bytesRead uint64 |
| 73 | lineOffset uint64 |
| 74 | endOffset uint64 |
| 75 | stopped bool |
| 76 | event *log.Event |
| 77 | } |
| 78 | |
| 79 | // NewSlowLogParser returns a new SlowLogParser that reads from the open file. |
| 80 | func NewSlowLogParser(file *os.File, opt log.Options) *SlowLogParser { |
| 81 | if opt.DefaultLocation == nil { |
| 82 | // Old MySQL format assumes time is taken from SYSTEM. |
| 83 | opt.DefaultLocation = time.Local |
| 84 | } |
| 85 | p := &SlowLogParser{ |
| 86 | file: file, |
| 87 | opt: opt, |
| 88 | // -- |
| 89 | stopChan: make(chan bool, 1), |
| 90 | eventChan: make(chan *log.Event), |
| 91 | inHeader: false, |
| 92 | inQuery: false, |
| 93 | headerLines: 0, |
| 94 | queryLines: 0, |
| 95 | lineOffset: 0, |
| 96 | bytesRead: opt.StartOffset, |
| 97 | event: log.NewEvent(), |
| 98 | } |
| 99 | return p |
| 100 | } |
| 101 | |
| 102 | // logf logs with configured logger. |
| 103 | func (p *SlowLogParser) logf(format string, v ...interface{}) { |
| 104 | if !p.opt.Debug { |
| 105 | return |
| 106 | } |
| 107 | if p.opt.Debugf != nil { |
| 108 | p.opt.Debugf(format, v...) |
| 109 | return |
| 110 | } |
| 111 | stdlog.Printf(format, v...) |
| 112 | } |
| 113 | |
| 114 | // EventChan returns the unbuffered event channel on which the caller can |
| 115 | // receive events. |
| 116 | func (p *SlowLogParser) EventChan() <-chan *log.Event { |
| 117 | return p.eventChan |
| 118 | } |
| 119 | |
| 120 | // Stop stops the parser before parsing the next event or while blocked on |
| 121 | // sending the current event to the event channel. |
| 122 | func (p *SlowLogParser) Stop() { |
| 123 | p.logf("stopping") |
| 124 | p.stopChan <- true |
| 125 | return |
| 126 | } |
| 127 | |
| 128 | // Start starts the parser. Events are sent to the unbuffered event channel. |
| 129 | // Parsing stops on EOF, error, or call to Stop. The event channel is closed |
| 130 | // when parsing stops. The file is not closed. |
| 131 | func (p *SlowLogParser) Start() error { |
| 132 | p.logf("parsing %q", p.file.Name()) |
| 133 | |
| 134 | // Seek to the offset, if any. |
| 135 | // @todo error if start off > file size |
| 136 | if p.opt.StartOffset > 0 { |
| 137 | if _, err := p.file.Seek(int64(p.opt.StartOffset), os.SEEK_SET); err != nil { |
| 138 | return err |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | defer close(p.eventChan) |
| 143 | |
| 144 | r := bufio.NewReader(p.file) |
| 145 | |
| 146 | SCANNER_LOOP: |
| 147 | for !p.stopped { |
| 148 | select { |
| 149 | case <-p.stopChan: |
| 150 | p.stopped = true |
| 151 | break SCANNER_LOOP |
| 152 | default: |
| 153 | } |
| 154 | |
| 155 | line, err := r.ReadString('\n') |
| 156 | if err != nil { |
| 157 | if err != io.EOF { |
| 158 | return err |
| 159 | } |
| 160 | break SCANNER_LOOP |
| 161 | } |
| 162 | |
| 163 | lineLen := uint64(len(line)) |
| 164 | p.bytesRead += lineLen |
| 165 | p.lineOffset = p.bytesRead - lineLen |
| 166 | p.logf("+%d line: %s", p.lineOffset, line) |
| 167 | |
| 168 | // Filter out meta lines: |
| 169 | // /usr/local/bin/mysqld, Version: 5.6.15-62.0-tokudb-7.1.0-tokudb-log (binary). started with: |
| 170 | // Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock |
| 171 | // Time Id Command Argument |
| 172 | if lineLen >= 20 && ((line[0] == '/' && line[lineLen-6:lineLen] == "with:\n") || |
| 173 | (line[0:5] == "Time ") || |
| 174 | (line[0:4] == "Tcp ") || |
| 175 | (line[0:4] == "TCP ")) { |
| 176 | p.logf("meta") |
| 177 | continue |
| 178 | } |
| 179 | |
| 180 | // PMM-1834: Filter out empty comments and MariaDB explain: |
| 181 | if line == "#\n" || strings.HasPrefix(line, "# explain:") { |
| 182 | continue |
| 183 | } |
| 184 | |
| 185 | // Remove \n. |
| 186 | line = line[0 : lineLen-1] |
| 187 | |
| 188 | if p.inHeader { |
| 189 | p.parseHeader(line) |
| 190 | } else if p.inQuery { |
| 191 | p.parseQuery(line) |
| 192 | } else if headerRe.MatchString(line) { |
| 193 | p.inHeader = true |
| 194 | p.inQuery = false |
| 195 | p.parseHeader(line) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | if !p.stopped && p.queryLines > 0 { |
| 200 | p.endOffset = p.bytesRead |
| 201 | p.sendEvent(false, false) |
| 202 | } |
| 203 | |
| 204 | p.logf("done") |
| 205 | return nil |
| 206 | } |
| 207 | |
| 208 | // -------------------------------------------------------------------------- |
| 209 | |
| 210 | func (p *SlowLogParser) parseHeader(line string) { |
| 211 | p.logf("header") |
| 212 | |
| 213 | if !headerRe.MatchString(line) { |
| 214 | p.inHeader = false |
| 215 | p.inQuery = true |
| 216 | p.parseQuery(line) |
| 217 | return |
| 218 | } |
| 219 | |
| 220 | if p.headerLines == 0 { |
| 221 | p.event.Offset = p.lineOffset |
| 222 | } |
| 223 | p.headerLines++ |
| 224 | |
| 225 | if strings.HasPrefix(line, "# Time") { |
| 226 | p.logf("time") |
| 227 | m := timeRe.FindStringSubmatch(line) |
| 228 | if len(m) == 2 { |
| 229 | p.event.Ts, _ = time.ParseInLocation("060102 15:04:05", m[1], p.opt.DefaultLocation) |
| 230 | } else { |
| 231 | m = timeNewRe.FindStringSubmatch(line) |
| 232 | if len(m) == 2 { |
| 233 | p.event.Ts, _ = time.ParseInLocation(time.RFC3339Nano, m[1], p.opt.DefaultLocation) |
| 234 | } else { |
| 235 | return |
| 236 | } |
| 237 | } |
| 238 | if userRe.MatchString(line) { |
| 239 | p.logf("user (bad format)") |
| 240 | m := userRe.FindStringSubmatch(line) |
| 241 | p.event.User = m[1] |
| 242 | p.event.Host = m[2] |
| 243 | } |
| 244 | } else if strings.HasPrefix(line, "# User") { |
| 245 | p.logf("user") |
| 246 | m := userRe.FindStringSubmatch(line) |
| 247 | if len(m) < 3 { |
| 248 | return |
| 249 | } |
| 250 | p.event.User = m[1] |
| 251 | p.event.Host = m[2] |
| 252 | } else if strings.HasPrefix(line, "# admin") { |
| 253 | p.parseAdmin(line) |
| 254 | } else { |
| 255 | p.logf("metrics") |
| 256 | submatch := schema.FindStringSubmatch(line) |
| 257 | if len(submatch) == 2 { |
| 258 | p.event.Db = submatch[1] |
| 259 | } |
| 260 | |
| 261 | m := metricsRe.FindAllStringSubmatch(line, -1) |
| 262 | for _, smv := range m { |
| 263 | // [String, Metric, Value], e.g. ["Query_time: 2", "Query_time", "2"] |
| 264 | if strings.HasSuffix(smv[1], "_time") || strings.HasSuffix(smv[1], "_wait") { |
| 265 | // microsecond value |
| 266 | val, _ := strconv.ParseFloat(smv[2], 64) |
| 267 | p.event.TimeMetrics[smv[1]] = val |
| 268 | } else if smv[2] == "Yes" || smv[2] == "No" { |
| 269 | // boolean value |
| 270 | if smv[2] == "Yes" { |
| 271 | p.event.BoolMetrics[smv[1]] = true |
| 272 | } else { |
| 273 | p.event.BoolMetrics[smv[1]] = false |
| 274 | } |
| 275 | } else if smv[1] == "Schema" { |
| 276 | p.event.Db = smv[2] |
| 277 | } else if smv[1] == "Log_slow_rate_type" { |
| 278 | p.event.RateType = smv[2] |
| 279 | } else if smv[1] == "Log_slow_rate_limit" { |
| 280 | val, _ := strconv.ParseUint(smv[2], 10, 64) |
| 281 | p.event.RateLimit = uint(val) |
| 282 | } else { |
| 283 | // integer value |
| 284 | val, _ := strconv.ParseUint(smv[2], 10, 64) |
| 285 | p.event.NumberMetrics[smv[1]] = val |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func (p *SlowLogParser) parseQuery(line string) { |
| 292 | p.logf("query") |
| 293 | |
| 294 | if strings.HasPrefix(line, "# admin") { |
| 295 | p.parseAdmin(line) |
| 296 | return |
| 297 | } else if headerRe.MatchString(line) { |
| 298 | p.logf("next event") |
| 299 | p.inHeader = true |
| 300 | p.inQuery = false |
| 301 | p.endOffset = p.lineOffset |
| 302 | p.sendEvent(true, false) |
| 303 | p.parseHeader(line) |
| 304 | return |
| 305 | } |
| 306 | |
| 307 | isUse := useRe.FindString(line) |
| 308 | if p.queryLines == 0 && isUse != "" { |
| 309 | p.logf("use db") |
| 310 | db := strings.TrimPrefix(line, isUse) |
| 311 | db = strings.TrimRight(db, ";") |
| 312 | db = strings.Trim(db, "`") |
| 313 | p.event.Db = db |
| 314 | // Set the 'use' as the query itself. |
| 315 | // In case we are on a group of lines like in test 23, lines 6~8, the |
| 316 | // query will be replaced by the real query "select field...." |
| 317 | // In case we are on a group of lines like in test23, lines 27~28, the |
| 318 | // query will be "use dbnameb" since the user executed a use command |
| 319 | p.event.Query = line |
| 320 | } else if setRe.MatchString(line) { |
| 321 | p.logf("set var") |
| 322 | // @todo ignore or use these lines? |
| 323 | } else { |
| 324 | p.logf("query") |
| 325 | if p.queryLines > 0 { |
| 326 | p.event.Query += "\n" + line |
| 327 | } else { |
| 328 | p.event.Query = line |
| 329 | } |
| 330 | p.queryLines++ |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | func (p *SlowLogParser) parseAdmin(line string) { |
| 335 | p.logf("admin") |
| 336 | p.event.Admin = true |
| 337 | m := adminRe.FindStringSubmatch(line) |
| 338 | p.event.Query = m[1] |
| 339 | p.event.Query = strings.TrimSuffix(p.event.Query, ";") // makes FilterAdminCommand work |
| 340 | |
| 341 | // admin commands should be the last line of the event. |
| 342 | if filtered := p.opt.FilterAdminCommand[p.event.Query]; !filtered { |
| 343 | p.logf("not filtered") |
| 344 | p.endOffset = p.bytesRead |
| 345 | p.sendEvent(false, false) |
| 346 | } else { |
| 347 | p.inHeader = false |
| 348 | p.inQuery = false |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | func (p *SlowLogParser) sendEvent(inHeader bool, inQuery bool) { |
| 353 | p.logf("send event") |
| 354 | |
| 355 | p.event.OffsetEnd = p.endOffset |
| 356 | |
| 357 | // Make a new event and reset our metadata. |
| 358 | defer func() { |
| 359 | p.event = log.NewEvent() |
| 360 | p.headerLines = 0 |
| 361 | p.queryLines = 0 |
| 362 | p.inHeader = inHeader |
| 363 | p.inQuery = inQuery |
| 364 | }() |
| 365 | |
| 366 | if _, ok := p.event.TimeMetrics["Query_time"]; !ok { |
| 367 | if p.headerLines == 0 { |
| 368 | panic(fmt.Sprintf("No Query_time in event at %d: %#v", p.lineOffset, p.event)) |
| 369 | } |
| 370 | // Started parsing in header after Query_time. Throw away event. |
| 371 | return |
| 372 | } |
| 373 | |
| 374 | // Clean up the event. |
| 375 | p.event.Db = strings.TrimSuffix(p.event.Db, ";\n") |
| 376 | p.event.Query = strings.TrimSuffix(p.event.Query, ";") |
| 377 | |
| 378 | // Send the event. This will block. |
| 379 | select { |
| 380 | case p.eventChan <- p.event: |
| 381 | case <-p.stopChan: |
| 382 | p.stopped = true |
| 383 | } |
| 384 | } |