Debian Codegraph @

event/class.go

raw symbols SCIP
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 event
32
33 import (
34 "github.com/percona/go-mysql/log"
35 )
36
37 const (
38 // MaxExampleBytes defines to how many bytes truncate a query.
39 MaxExampleBytes = 2 * 1024 * 10
40
41 // TruncatedExampleSuffix is added to truncated query.
42 TruncatedExampleSuffix = "..."
43 )
44
45 // A Class represents all events with the same fingerprint and class ID.
46 // This is only enforced by convention, so be careful not to mix events from
47 // different classes.
48 type Class struct {
49 Id string // 32-character hex checksum of fingerprint
50 User string
51 Host string
52 Db string
53 Server string
54 LabelsKey []string
55 LabelsValue []string
56 Fingerprint string // canonical form of query: values replaced with "?"
57 Metrics *Metrics // statistics for each metric, e.g. max Query_time
58 TotalQueries uint // total number of queries in class
59 UniqueQueries uint // unique number of queries in class
60 Example *Example `json:",omitempty"` // sample query with max Query_time
61 NumQueriesWithErrors float32
62 ErrorsCode []uint64
63 ErrorsCount []uint64
64 // --
65 outliers uint
66 lastDb string
67 errorsMap map[uint64]uint64 // ErrorsCode: ErrorsCount
68 sample bool
69 }
70
71 // A Example is a real query and its database, timestamp, and Query_time.
72 // If the query is larger than MaxExampleBytes, it is truncated and TruncatedExampleSuffix
73 // is appended.
74 type Example struct {
75 QueryTime float64 // Query_time
76 Db string // Schema: <db> or USE <db>
77 Query string // truncated to MaxExampleBytes
78 Size int `json:",omitempty"` // Original size of query.
79 Ts string `json:",omitempty"` // in MySQL time zone
80 }
81
82 // NewClass returns a new Class for the class ID and fingerprint.
83 // If sample is true, the query with the greatest Query_time is saved.
84 func NewClass(id, user, host, db, server, fingerprint string, sample bool) *Class {
85 class := &Class{
86 Id: id,
87 User: user,
88 Host: host,
89 Db: db,
90 Server: server,
91 LabelsKey: []string{},
92 LabelsValue: []string{},
93 Fingerprint: fingerprint,
94 Metrics: NewMetrics(),
95 TotalQueries: 0,
96 Example: &Example{},
97 sample: sample,
98 errorsMap: map[uint64]uint64{},
99 }
100 return class
101 }
102
103 // AddEvent adds an event to the query class.
104 func (c *Class) AddEvent(e *log.Event, outlier bool) {
105 if outlier {
106 c.outliers++
107 } else {
108 c.TotalQueries++
109 }
110
111 c.Metrics.AddEvent(e, outlier)
112
113 // Add labels
114 c.LabelsKey = append(c.LabelsKey, e.LabelsKey...)
115 c.LabelsValue = append(c.LabelsValue, e.LabelsValue...)
116
117 // Add Errors
118 if lastErrno, ok := e.NumberMetrics["Last_errno"]; ok && lastErrno > 0 {
119 c.errorsMap[uint64(lastErrno)]++
120 c.NumQueriesWithErrors++
121 }
122
123 // Save last db seen for this query. This helps ensure the sample query
124 // has a db.
125 if e.Db != "" {
126 c.lastDb = e.Db
127 }
128 if c.sample {
129 if n, ok := e.TimeMetrics["Query_time"]; ok {
130 if float64(n) > c.Example.QueryTime {
131 c.Example.QueryTime = float64(n)
132 c.Example.Size = len(e.Query)
133 if e.Db != "" {
134 c.Example.Db = e.Db
135 } else {
136 c.Example.Db = c.lastDb
137 }
138 if len(e.Query) > MaxExampleBytes {
139 c.Example.Query = e.Query[0:MaxExampleBytes-len(TruncatedExampleSuffix)] + TruncatedExampleSuffix
140 } else {
141 c.Example.Query = e.Query
142 }
143 if !e.Ts.IsZero() {
144 // todo use time.RFC3339Nano instead
145 c.Example.Ts = e.Ts.UTC().Format("2006-01-02 15:04:05")
146 }
147 }
148 }
149 }
150 }
151
152 // AddClass adds a Class to the current class. This is used with Performance
153 // Schema which returns pre-aggregated classes instead of events.
154 func (c *Class) AddClass(newClass *Class) {
155 c.UniqueQueries++
156 c.TotalQueries += newClass.TotalQueries
157 c.Example = nil
158
159 for newMetric, newStats := range newClass.Metrics.TimeMetrics {
160 stats, ok := c.Metrics.TimeMetrics[newMetric]
161 if !ok {
162 m := *newStats
163 c.Metrics.TimeMetrics[newMetric] = &m
164 } else {
165 stats.Cnt++
166 stats.Sum += newStats.Sum
167 if Float64Value(newStats.Min) < Float64Value(stats.Min) || stats.Min == nil {
168 stats.Min = newStats.Min
169 }
170 if Float64Value(newStats.Max) > Float64Value(stats.Max) || stats.Max == nil {
171 stats.Max = newStats.Max
172 }
173 }
174 }
175
176 for newMetric, newStats := range newClass.Metrics.NumberMetrics {
177 stats, ok := c.Metrics.NumberMetrics[newMetric]
178 if !ok {
179 m := *newStats
180 c.Metrics.NumberMetrics[newMetric] = &m
181 } else {
182 stats.Cnt++
183 stats.Sum += newStats.Sum
184 if Uint64Value(newStats.Min) < Uint64Value(stats.Min) || stats.Min == nil {
185 stats.Min = newStats.Min
186 }
187 if Uint64Value(newStats.Max) > Uint64Value(stats.Max) || stats.Max == nil {
188 stats.Max = newStats.Max
189 }
190 }
191 }
192
193 for newMetric, newStats := range newClass.Metrics.BoolMetrics {
194 stats, ok := c.Metrics.BoolMetrics[newMetric]
195 if !ok {
196 m := *newStats
197 c.Metrics.BoolMetrics[newMetric] = &m
198 } else {
199 stats.Cnt++
200 stats.Sum += newStats.Sum
201 }
202 }
203 }
204
205 // Finalize calculates all metric statistics. Call this function when done
206 // adding events to the class.
207 func (c *Class) Finalize(rateLimit uint) {
208 if rateLimit == 0 {
209 rateLimit = 1
210 }
211
212 for code, count := range c.errorsMap {
213 c.ErrorsCode = append(c.ErrorsCode, code)
214 c.ErrorsCount = append(c.ErrorsCount, count)
215 }
216
217 c.TotalQueries = (c.TotalQueries * rateLimit) + c.outliers
218 c.Metrics.Finalize(rateLimit, c.TotalQueries)
219 if c.Example.QueryTime == 0 {
220 c.Example = nil
221 }
222 }