6c10ef40362e53c7ba5d73c38a603efaa1c0fcd3
[pstop.git] / performance_schema / file_summary_by_instance / file_summary_by_instance_row.go
1 // This file contains the library routines for managing the
2 // file_summary_by_instance table.
3 package file_summary_by_instance
4
5 import (
6         "database/sql"
7         "fmt"
8         "log"
9         "regexp"
10         "sort"
11         //      "strconv"
12         "time"
13
14         "github.com/sjmudd/pstop/lib"
15 )
16
17 /*
18 CREATE TABLE `file_summary_by_instance` (
19   `FILE_NAME` varchar(512) NOT NULL,
20   `EVENT_NAME` varchar(128) NOT NULL,                           // not collected
21   `OBJECT_INSTANCE_BEGIN` bigint(20) unsigned NOT NULL,         // not collected
22   `COUNT_STAR` bigint(20) unsigned NOT NULL,
23   `SUM_TIMER_WAIT` bigint(20) unsigned NOT NULL,
24   `MIN_TIMER_WAIT` bigint(20) unsigned NOT NULL,
25   `AVG_TIMER_WAIT` bigint(20) unsigned NOT NULL,
26   `MAX_TIMER_WAIT` bigint(20) unsigned NOT NULL,
27   `COUNT_READ` bigint(20) unsigned NOT NULL,
28   `SUM_TIMER_READ` bigint(20) unsigned NOT NULL,
29   `MIN_TIMER_READ` bigint(20) unsigned NOT NULL,
30   `AVG_TIMER_READ` bigint(20) unsigned NOT NULL,
31   `MAX_TIMER_READ` bigint(20) unsigned NOT NULL,
32   `SUM_NUMBER_OF_BYTES_READ` bigint(20) NOT NULL,
33   `COUNT_WRITE` bigint(20) unsigned NOT NULL,
34   `SUM_TIMER_WRITE` bigint(20) unsigned NOT NULL,
35   `MIN_TIMER_WRITE` bigint(20) unsigned NOT NULL,
36   `AVG_TIMER_WRITE` bigint(20) unsigned NOT NULL,
37   `MAX_TIMER_WRITE` bigint(20) unsigned NOT NULL,
38   `SUM_NUMBER_OF_BYTES_WRITE` bigint(20) NOT NULL,
39   `COUNT_MISC` bigint(20) unsigned NOT NULL,
40   `SUM_TIMER_MISC` bigint(20) unsigned NOT NULL,
41   `MIN_TIMER_MISC` bigint(20) unsigned NOT NULL,
42   `AVG_TIMER_MISC` bigint(20) unsigned NOT NULL,
43   `MAX_TIMER_MISC` bigint(20) unsigned NOT NULL
44 ) ENGINE=PERFORMANCE_SCHEMA DEFAULT CHARSET=utf8
45 1 row in set (0.00 sec)
46 */
47
48 //     foo/../bar --> foo/bar   perl: $new =~ s{[^/]+/\.\./}{/};
49 //     /./        --> /         perl: $new =~ s{/\./}{};
50 //     //         --> /         perl: $new =~ s{//}{/};
51 const (
52         re_encoded = `@(\d{4})` // FIXME - add me to catch @0024 --> $ for example
53 )
54
55 var (
56         re_one_or_the_other    *regexp.Regexp = regexp.MustCompile(`/(\.)?/`)
57         re_slash_dot_dot_slash *regexp.Regexp = regexp.MustCompile(`[^/]+/\.\./`)
58         re_table_file          *regexp.Regexp = regexp.MustCompile(`/([^/]+)/([^/]+)\.(frm|ibd|MYD|MYI|CSM|CSV|par)$`)
59         re_temp_table          *regexp.Regexp = regexp.MustCompile(`#sql-[0-9_]+`)
60         re_part_table          *regexp.Regexp = regexp.MustCompile(`(.+)#P#p(\d+|MAX)`)
61         re_ibdata              *regexp.Regexp = regexp.MustCompile(`/ibdata\d+$`)
62         re_redo_log            *regexp.Regexp = regexp.MustCompile(`/ib_logfile\d+$`)
63         re_binlog              *regexp.Regexp = regexp.MustCompile(`/binlog\.(\d{6}|index)$`)
64         re_db_opt              *regexp.Regexp = regexp.MustCompile(`/db\.opt$`)
65         re_slowlog             *regexp.Regexp = regexp.MustCompile(`/slowlog$`)
66         re_auto_cnf            *regexp.Regexp = regexp.MustCompile(`/auto\.cnf$`)
67         re_pid_file            *regexp.Regexp = regexp.MustCompile(`/[^/]+\.pid$`)
68         re_error_msg           *regexp.Regexp = regexp.MustCompile(`/share/[^/]+/errmsg\.sys$`)
69         re_charset             *regexp.Regexp = regexp.MustCompile(`/share/charsets/Index\.xml$`)
70 )
71
72 type file_summary_by_instance_row struct {
73         FILE_NAME string
74
75         COUNT_STAR  uint64
76         COUNT_READ  uint64
77         COUNT_WRITE uint64
78         COUNT_MISC  uint64
79
80         SUM_TIMER_WAIT  uint64
81         SUM_TIMER_READ  uint64
82         SUM_TIMER_WRITE uint64
83         SUM_TIMER_MISC  uint64
84
85         SUM_NUMBER_OF_BYTES_READ  uint64
86         SUM_NUMBER_OF_BYTES_WRITE uint64
87 }
88
89 // represents a table or set of rows
90 type file_summary_by_instance_rows []file_summary_by_instance_row
91
92 // Return the name using the FILE_NAME attribute.
93 func (r *file_summary_by_instance_row) name() string {
94         return r.FILE_NAME
95 }
96
97 // Return a formatted pretty name for the row.
98 func (r *file_summary_by_instance_row) pretty_name() string {
99         s := r.name()
100         if len(s) > 30 {
101                 s = s[:29]
102         }
103         return fmt.Sprintf("%-30s", s)
104 }
105
106 func (r *file_summary_by_instance_row) headings() string {
107         return fmt.Sprintf("%-30s %10s %6s|%6s %6s %6s|%8s %8s|%8s %6s %6s %6s",
108                 "Table Name",
109                 "Latency",
110                 "%",
111                 "Read",
112                 "Write",
113                 "Misc",
114                 "Rd bytes",
115                 "Wr bytes",
116                 "Ops",
117                 "R Ops",
118                 "W Ops",
119                 "M Ops")
120 }
121
122 // generate a printable result
123 func (row *file_summary_by_instance_row) row_content(totals file_summary_by_instance_row) string {
124         var name string
125
126         // We assume that if COUNT_STAR = 0 then there's no data at all...
127         // when we have no data we really don't want to show the name either.
128         if row.COUNT_STAR == 0 {
129                 name = ""
130         } else {
131                 name = row.pretty_name()
132         }
133
134         return fmt.Sprintf("%-30s %10s %6s|%6s %6s %6s|%8s %8s|%8s %6s %6s %6s",
135                 name,
136                 lib.FormatTime(row.SUM_TIMER_WAIT),
137                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_WAIT, totals.SUM_TIMER_WAIT)),
138                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_READ, row.SUM_TIMER_WAIT)),
139                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_WRITE, row.SUM_TIMER_WAIT)),
140                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_MISC, row.SUM_TIMER_WAIT)),
141                 lib.FormatAmount(row.SUM_NUMBER_OF_BYTES_READ),
142                 lib.FormatAmount(row.SUM_NUMBER_OF_BYTES_WRITE),
143                 lib.FormatAmount(row.COUNT_STAR),
144                 lib.FormatPct(lib.MyDivide(row.COUNT_READ, row.COUNT_STAR)),
145                 lib.FormatPct(lib.MyDivide(row.COUNT_WRITE, row.COUNT_STAR)),
146                 lib.FormatPct(lib.MyDivide(row.COUNT_MISC, row.COUNT_STAR)))
147 }
148
149 func (this *file_summary_by_instance_row) add(other file_summary_by_instance_row) {
150         this.COUNT_STAR += other.COUNT_STAR
151         this.COUNT_READ += other.COUNT_READ
152         this.COUNT_WRITE += other.COUNT_WRITE
153         this.COUNT_MISC += other.COUNT_MISC
154
155         this.SUM_TIMER_WAIT += other.SUM_TIMER_WAIT
156         this.SUM_TIMER_READ += other.SUM_TIMER_READ
157         this.SUM_TIMER_WRITE += other.SUM_TIMER_WRITE
158         this.SUM_TIMER_MISC += other.SUM_TIMER_MISC
159
160         this.SUM_NUMBER_OF_BYTES_READ += other.SUM_NUMBER_OF_BYTES_READ
161         this.SUM_NUMBER_OF_BYTES_WRITE += other.SUM_NUMBER_OF_BYTES_WRITE
162 }
163
164 func (this *file_summary_by_instance_row) subtract(other file_summary_by_instance_row) {
165         this.COUNT_STAR -= other.COUNT_STAR
166         this.COUNT_READ -= other.COUNT_READ
167         this.COUNT_WRITE -= other.COUNT_WRITE
168         this.COUNT_MISC -= other.COUNT_MISC
169
170         this.SUM_TIMER_WAIT -= other.SUM_TIMER_WAIT
171         this.SUM_TIMER_READ -= other.SUM_TIMER_READ
172         this.SUM_TIMER_WRITE -= other.SUM_TIMER_WRITE
173         this.SUM_TIMER_MISC -= other.SUM_TIMER_MISC
174
175         this.SUM_NUMBER_OF_BYTES_READ -= other.SUM_NUMBER_OF_BYTES_READ
176         this.SUM_NUMBER_OF_BYTES_WRITE -= other.SUM_NUMBER_OF_BYTES_WRITE
177 }
178
179 // return the totals of a slice of rows
180 func (t file_summary_by_instance_rows) totals() file_summary_by_instance_row {
181         var totals file_summary_by_instance_row
182         totals.FILE_NAME = "TOTALS"
183
184         for i := range t {
185                 totals.add(t[i])
186         }
187
188         return totals
189 }
190
191 // clean up the given path reducing redundant stuff and return the clean path
192 func cleanup_path(path string) string {
193
194         for {
195                 orig_path := path
196                 path = re_one_or_the_other.ReplaceAllString(path, "/")
197                 path = re_slash_dot_dot_slash.ReplaceAllString(path, "/")
198                 if orig_path == path { // no change so give up
199                         break
200                 }
201         }
202
203         return path
204 }
205
206 // From the original FILE_NAME we want to generate a simpler name to use.
207 // This simpler name may also merge several different filenames into one.
208 func (t file_summary_by_instance_row) simple_name(global_variables map[string]string) string {
209
210         path := t.FILE_NAME
211
212         if cached_result, err := get_from_cache(path); err == nil {
213                 return cached_result
214         }
215
216         // FIXME and make this work.
217         //      re4 := regexp.MustCompile(re_encoded)
218         //      if m4 := re4.FindStringSubmatch(path); m4 != nil {
219         //              if value, err := strconv.ParseInt(m4[1], 16, 16); err != nil {
220         //                      // missing replace @.... with char(value) in path
221         //
222         //              }
223         //      }
224
225         // this should probably be ordered from most expected regexp to least
226         if m1 := re_table_file.FindStringSubmatch(path); m1 != nil {
227                 // we may match temporary tables so check for them
228                 if m2 := re_temp_table.FindStringSubmatch(m1[2]); m2 != nil {
229                         return save_to_cache(path, "<temp_table>")
230                 }
231
232                 // we may match partitioned tables so check for them
233                 if m3 := re_part_table.FindStringSubmatch(m1[2]); m3 != nil {
234                         return save_to_cache(path, m1[1]+"."+m3[1]) // <schema>.<table> (less partition info)
235                 }
236
237                 return save_to_cache(path, m1[1]+"."+m1[2]) // <schema>.<table>
238         }
239         if re_ibdata.MatchString(path) == true {
240                 return save_to_cache(path, "<ibdata>")
241         }
242         if re_redo_log.MatchString(path) == true {
243                 return save_to_cache(path, "<redo_log>")
244         }
245         if re_binlog.MatchString(path) == true {
246                 return save_to_cache(path, "<binlog>")
247         }
248         if re_db_opt.MatchString(path) == true {
249                 return save_to_cache(path, "<db_opt>")
250         }
251         if re_slowlog.MatchString(path) == true {
252                 return save_to_cache(path, "<slow_log>")
253         }
254         if re_auto_cnf.MatchString(path) == true {
255                 return save_to_cache(path, "<auto_cnf>")
256         }
257         // relay logs are a bit complicated. If a full path then easy to
258         // identify,but if a relative path we may need to add $datadir,
259         // but also if as I do we have a ../blah/somewhere/path then we
260         // need to make it match too.
261         if len(global_variables["relay_log"]) > 0 {
262                 relay_log := global_variables["relay_log"]
263                 if relay_log[0] != '/' { // relative path
264                         relay_log = cleanup_path(global_variables["datadir"] + relay_log) // datadir always ends in /
265                 }
266                 re_relay_log := relay_log + `\.(\d{6}|index)$`
267                 if regexp.MustCompile(re_relay_log).MatchString(path) == true {
268                         return save_to_cache(path, "<relay_log>")
269                 }
270         }
271         if re_pid_file.MatchString(path) == true {
272                 return save_to_cache(path, "<pid_file>")
273         }
274         if re_error_msg.MatchString(path) == true {
275                 return save_to_cache(path, "<errmsg>")
276         }
277         if re_charset.MatchString(path) == true {
278                 return save_to_cache(path, "<charset>")
279         }
280         return save_to_cache(path, path)
281 }
282
283 // Convert the imported "table" to a merged one with merged data.
284 // Combine all entries with the same "FILE_NAME" by adding their values.
285 func merge_by_table_name(orig file_summary_by_instance_rows, global_variables map[string]string) file_summary_by_instance_rows {
286         start := time.Now()
287         t := make(file_summary_by_instance_rows, 0, len(orig))
288
289         m := make(map[string]file_summary_by_instance_row)
290
291         // iterate over source table
292         for i := range orig {
293                 var file_name string
294                 var new_row file_summary_by_instance_row
295                 orig_row := orig[i]
296
297                 if orig_row.COUNT_STAR > 0 {
298                         file_name = orig_row.simple_name(global_variables)
299
300                         // check if we have an entry in the map
301                         if _, found := m[file_name]; found {
302                                 new_row = m[file_name]
303                         } else {
304                                 new_row.FILE_NAME = file_name
305                         }
306                         new_row.add(orig_row)
307                         m[file_name] = new_row // update the map with the new value
308                 }
309         }
310
311         // add the map contents back into the table
312         for _, row := range m {
313                 t = append(t, row)
314         }
315
316         lib.Logger.Println("merge_by_table_name() took:", time.Duration(time.Since(start)).String())
317         return t
318 }
319
320 // Select the raw data from the database into file_summary_by_instance_rows
321 // - filter out empty values
322 // - merge rows with the same name into a single row
323 // - change FILE_NAME into a more descriptive value.
324 func select_fsbi_rows(dbh *sql.DB) file_summary_by_instance_rows {
325         var t file_summary_by_instance_rows
326         start := time.Now()
327
328         sql := "SELECT FILE_NAME, COUNT_STAR, SUM_TIMER_WAIT, COUNT_READ, SUM_TIMER_READ, SUM_NUMBER_OF_BYTES_READ, COUNT_WRITE, SUM_TIMER_WRITE, SUM_NUMBER_OF_BYTES_WRITE, COUNT_MISC, SUM_TIMER_MISC FROM file_summary_by_instance"
329
330         rows, err := dbh.Query(sql)
331         if err != nil {
332                 log.Fatal(err)
333         }
334         defer rows.Close()
335
336         for rows.Next() {
337                 var r file_summary_by_instance_row
338
339                 if err := rows.Scan(&r.FILE_NAME, &r.COUNT_STAR, &r.SUM_TIMER_WAIT, &r.COUNT_READ, &r.SUM_TIMER_READ, &r.SUM_NUMBER_OF_BYTES_READ, &r.COUNT_WRITE, &r.SUM_TIMER_WRITE, &r.SUM_NUMBER_OF_BYTES_WRITE, &r.COUNT_MISC, &r.SUM_TIMER_MISC); err != nil {
340                         log.Fatal(err)
341                 }
342                 t = append(t, r)
343         }
344         if err := rows.Err(); err != nil {
345                 log.Fatal(err)
346         }
347         lib.Logger.Println("select_fsbi_rows() took:", time.Duration(time.Since(start)).String())
348
349         return t
350 }
351
352 // remove the initial values from those rows where there's a match
353 // - if we find a row we can't match ignore it
354 func (this *file_summary_by_instance_rows) subtract(initial file_summary_by_instance_rows) {
355         i_by_name := make(map[string]int)
356
357         // iterate over rows by name
358         for i := range initial {
359                 i_by_name[initial[i].name()] = i
360         }
361
362         for i := range *this {
363                 if _, ok := i_by_name[(*this)[i].name()]; ok {
364                         initial_i := i_by_name[(*this)[i].name()]
365                         (*this)[i].subtract(initial[initial_i])
366                 }
367         }
368 }
369
370 func (t file_summary_by_instance_rows) Len() int      { return len(t) }
371 func (t file_summary_by_instance_rows) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
372 func (t file_summary_by_instance_rows) Less(i, j int) bool {
373         return (t[i].SUM_TIMER_WAIT > t[j].SUM_TIMER_WAIT) ||
374                 ((t[i].SUM_TIMER_WAIT == t[j].SUM_TIMER_WAIT) && (t[i].FILE_NAME < t[j].FILE_NAME))
375 }
376
377 func (t *file_summary_by_instance_rows) sort() {
378         sort.Sort(t)
379 }
380
381 // if the data in t2 is "newer", "has more values" than t then it needs refreshing.
382 // check this by comparing totals.
383 func (t file_summary_by_instance_rows) needs_refresh(t2 file_summary_by_instance_rows) bool {
384         my_totals := t.totals()
385         t2_totals := t2.totals()
386
387         return my_totals.SUM_TIMER_WAIT > t2_totals.SUM_TIMER_WAIT
388 }