Adjust to highlight headings and totals
[pstop.git] / p_s / 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         "time"
12
13         "github.com/sjmudd/pstop/key_value_cache"
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         re_dollar              *regexp.Regexp = regexp.MustCompile(`@0024`) // FIXME - add me to catch @0024 --> $ (specific case)
71
72         cache key_value_cache.KeyValueCache
73 )
74
75 type file_summary_by_instance_row struct {
76         FILE_NAME string
77
78         COUNT_STAR  uint64
79         COUNT_READ  uint64
80         COUNT_WRITE uint64
81         COUNT_MISC  uint64
82
83         SUM_TIMER_WAIT  uint64
84         SUM_TIMER_READ  uint64
85         SUM_TIMER_WRITE uint64
86         SUM_TIMER_MISC  uint64
87
88         SUM_NUMBER_OF_BYTES_READ  uint64
89         SUM_NUMBER_OF_BYTES_WRITE uint64
90 }
91
92 // represents a table or set of rows
93 type file_summary_by_instance_rows []file_summary_by_instance_row
94
95 // Return the name using the FILE_NAME attribute.
96 func (r *file_summary_by_instance_row) name() string {
97         return r.FILE_NAME
98 }
99
100 // Return a formatted pretty name for the row.
101 func (r *file_summary_by_instance_row) pretty_name() string {
102         s := r.name()
103         if len(s) > 30 {
104                 s = s[:29]
105         }
106         return s
107 }
108
109 func (r *file_summary_by_instance_row) headings() string {
110         return fmt.Sprintf("%-30s %10s %6s|%6s %6s %6s|%8s %8s|%8s %6s %6s %6s",
111                 "Table Name",
112                 "Latency",
113                 "%",
114                 "Read",
115                 "Write",
116                 "Misc",
117                 "Rd bytes",
118                 "Wr bytes",
119                 "Ops",
120                 "R Ops",
121                 "W Ops",
122                 "M Ops")
123 }
124
125 // generate a printable result
126 func (row *file_summary_by_instance_row) row_content(totals file_summary_by_instance_row) string {
127         var name string = row.pretty_name()
128
129         // We assume that if COUNT_STAR = 0 then there's no data at all...
130         // when we have no data we really don't want to show the name either.
131         if row.COUNT_STAR == 0 && name != "Totals" {
132                 name = ""
133         }
134
135         return fmt.Sprintf("%-30s %10s %6s|%6s %6s %6s|%8s %8s|%8s %6s %6s %6s",
136                 name,
137                 lib.FormatTime(row.SUM_TIMER_WAIT),
138                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_WAIT, totals.SUM_TIMER_WAIT)),
139                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_READ, row.SUM_TIMER_WAIT)),
140                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_WRITE, row.SUM_TIMER_WAIT)),
141                 lib.FormatPct(lib.MyDivide(row.SUM_TIMER_MISC, row.SUM_TIMER_WAIT)),
142                 lib.FormatAmount(row.SUM_NUMBER_OF_BYTES_READ),
143                 lib.FormatAmount(row.SUM_NUMBER_OF_BYTES_WRITE),
144                 lib.FormatAmount(row.COUNT_STAR),
145                 lib.FormatPct(lib.MyDivide(row.COUNT_READ, row.COUNT_STAR)),
146                 lib.FormatPct(lib.MyDivide(row.COUNT_WRITE, row.COUNT_STAR)),
147                 lib.FormatPct(lib.MyDivide(row.COUNT_MISC, row.COUNT_STAR)))
148 }
149
150 func (this *file_summary_by_instance_row) add(other file_summary_by_instance_row) {
151         this.COUNT_STAR += other.COUNT_STAR
152         this.COUNT_READ += other.COUNT_READ
153         this.COUNT_WRITE += other.COUNT_WRITE
154         this.COUNT_MISC += other.COUNT_MISC
155
156         this.SUM_TIMER_WAIT += other.SUM_TIMER_WAIT
157         this.SUM_TIMER_READ += other.SUM_TIMER_READ
158         this.SUM_TIMER_WRITE += other.SUM_TIMER_WRITE
159         this.SUM_TIMER_MISC += other.SUM_TIMER_MISC
160
161         this.SUM_NUMBER_OF_BYTES_READ += other.SUM_NUMBER_OF_BYTES_READ
162         this.SUM_NUMBER_OF_BYTES_WRITE += other.SUM_NUMBER_OF_BYTES_WRITE
163 }
164
165 func (this *file_summary_by_instance_row) subtract(other file_summary_by_instance_row) {
166         this.COUNT_STAR -= other.COUNT_STAR
167         this.COUNT_READ -= other.COUNT_READ
168         this.COUNT_WRITE -= other.COUNT_WRITE
169         this.COUNT_MISC -= other.COUNT_MISC
170
171         this.SUM_TIMER_WAIT -= other.SUM_TIMER_WAIT
172         this.SUM_TIMER_READ -= other.SUM_TIMER_READ
173         this.SUM_TIMER_WRITE -= other.SUM_TIMER_WRITE
174         this.SUM_TIMER_MISC -= other.SUM_TIMER_MISC
175
176         this.SUM_NUMBER_OF_BYTES_READ -= other.SUM_NUMBER_OF_BYTES_READ
177         this.SUM_NUMBER_OF_BYTES_WRITE -= other.SUM_NUMBER_OF_BYTES_WRITE
178 }
179
180 // return the totals of a slice of rows
181 func (t file_summary_by_instance_rows) totals() file_summary_by_instance_row {
182         var totals file_summary_by_instance_row
183         totals.FILE_NAME = "Totals"
184
185         for i := range t {
186                 totals.add(t[i])
187         }
188
189         return totals
190 }
191
192 // clean up the given path reducing redundant stuff and return the clean path
193 func cleanup_path(path string) string {
194
195         for {
196                 orig_path := path
197                 path = re_one_or_the_other.ReplaceAllString(path, "/")
198                 path = re_slash_dot_dot_slash.ReplaceAllString(path, "/")
199                 if orig_path == path { // no change so give up
200                         break
201                 }
202         }
203
204         return path
205 }
206
207 // From the original FILE_NAME we want to generate a simpler name to use.
208 // This simpler name may also merge several different filenames into one.
209 func (t file_summary_by_instance_row) simple_name(global_variables map[string]string) string {
210
211         path := t.FILE_NAME
212
213         if cached_result, err := cache.Get(path); err == nil {
214                 return cached_result
215         }
216
217         // @0024 --> $ (should do this more generically)
218         path = re_dollar.ReplaceAllLiteralString(path, "$")
219
220         // this should probably be ordered from most expected regexp to least
221         if m1 := re_table_file.FindStringSubmatch(path); m1 != nil {
222                 // we may match temporary tables so check for them
223                 if m2 := re_temp_table.FindStringSubmatch(m1[2]); m2 != nil {
224                         return cache.Put(path, "<temp_table>")
225                 }
226
227                 // we may match partitioned tables so check for them
228                 if m3 := re_part_table.FindStringSubmatch(m1[2]); m3 != nil {
229                         return cache.Put(path, m1[1]+"."+m3[1]) // <schema>.<table> (less partition info)
230                 }
231
232                 return cache.Put(path, m1[1]+"."+m1[2]) // <schema>.<table>
233         }
234         if re_ibdata.MatchString(path) == true {
235                 return cache.Put(path, "<ibdata>")
236         }
237         if re_redo_log.MatchString(path) == true {
238                 return cache.Put(path, "<redo_log>")
239         }
240         if re_binlog.MatchString(path) == true {
241                 return cache.Put(path, "<binlog>")
242         }
243         if re_db_opt.MatchString(path) == true {
244                 return cache.Put(path, "<db_opt>")
245         }
246         if re_slowlog.MatchString(path) == true {
247                 return cache.Put(path, "<slow_log>")
248         }
249         if re_auto_cnf.MatchString(path) == true {
250                 return cache.Put(path, "<auto_cnf>")
251         }
252         // relay logs are a bit complicated. If a full path then easy to
253         // identify,but if a relative path we may need to add $datadir,
254         // but also if as I do we have a ../blah/somewhere/path then we
255         // need to make it match too.
256         if len(global_variables["relay_log"]) > 0 {
257                 relay_log := global_variables["relay_log"]
258                 if relay_log[0] != '/' { // relative path
259                         relay_log = cleanup_path(global_variables["datadir"] + relay_log) // datadir always ends in /
260                 }
261                 re_relay_log := relay_log + `\.(\d{6}|index)$`
262                 if regexp.MustCompile(re_relay_log).MatchString(path) == true {
263                         return cache.Put(path, "<relay_log>")
264                 }
265         }
266         if re_pid_file.MatchString(path) == true {
267                 return cache.Put(path, "<pid_file>")
268         }
269         if re_error_msg.MatchString(path) == true {
270                 return cache.Put(path, "<errmsg>")
271         }
272         if re_charset.MatchString(path) == true {
273                 return cache.Put(path, "<charset>")
274         }
275         // clean up datadir to <datadir>
276         if len(global_variables["datadir"]) > 0 {
277                 re_datadir := regexp.MustCompile("^" + global_variables["datadir"])
278                 path = re_datadir.ReplaceAllLiteralString(path, "<datadir>/")
279         }
280
281         return cache.Put(path, path)
282 }
283
284 // Convert the imported "table" to a merged one with merged data.
285 // Combine all entries with the same "FILE_NAME" by adding their values.
286 func merge_by_table_name(orig file_summary_by_instance_rows, global_variables map[string]string) file_summary_by_instance_rows {
287         start := time.Now()
288         t := make(file_summary_by_instance_rows, 0, len(orig))
289
290         m := make(map[string]file_summary_by_instance_row)
291
292         // iterate over source table
293         for i := range orig {
294                 var file_name string
295                 var new_row file_summary_by_instance_row
296                 orig_row := orig[i]
297
298                 if orig_row.COUNT_STAR > 0 {
299                         file_name = orig_row.simple_name(global_variables)
300
301                         // check if we have an entry in the map
302                         if _, found := m[file_name]; found {
303                                 new_row = m[file_name]
304                         } else {
305                                 new_row.FILE_NAME = file_name
306                         }
307                         new_row.add(orig_row)
308                         m[file_name] = new_row // update the map with the new value
309                 }
310         }
311
312         // add the map contents back into the table
313         for _, row := range m {
314                 t = append(t, row)
315         }
316
317         lib.Logger.Println("merge_by_table_name() took:", time.Duration(time.Since(start)).String())
318         return t
319 }
320
321 // Select the raw data from the database into file_summary_by_instance_rows
322 // - filter out empty values
323 // - merge rows with the same name into a single row
324 // - change FILE_NAME into a more descriptive value.
325 func select_fsbi_rows(dbh *sql.DB) file_summary_by_instance_rows {
326         var t file_summary_by_instance_rows
327         start := time.Now()
328
329         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"
330
331         rows, err := dbh.Query(sql)
332         if err != nil {
333                 log.Fatal(err)
334         }
335         defer rows.Close()
336
337         for rows.Next() {
338                 var r file_summary_by_instance_row
339
340                 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 {
341                         log.Fatal(err)
342                 }
343                 t = append(t, r)
344         }
345         if err := rows.Err(); err != nil {
346                 log.Fatal(err)
347         }
348         lib.Logger.Println("select_fsbi_rows() took:", time.Duration(time.Since(start)).String())
349
350         return t
351 }
352
353 // remove the initial values from those rows where there's a match
354 // - if we find a row we can't match ignore it
355 func (this *file_summary_by_instance_rows) subtract(initial file_summary_by_instance_rows) {
356         i_by_name := make(map[string]int)
357
358         // iterate over rows by name
359         for i := range initial {
360                 i_by_name[initial[i].name()] = i
361         }
362
363         for i := range *this {
364                 if _, ok := i_by_name[(*this)[i].name()]; ok {
365                         initial_i := i_by_name[(*this)[i].name()]
366                         (*this)[i].subtract(initial[initial_i])
367                 }
368         }
369 }
370
371 func (t file_summary_by_instance_rows) Len() int      { return len(t) }
372 func (t file_summary_by_instance_rows) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
373 func (t file_summary_by_instance_rows) Less(i, j int) bool {
374         return (t[i].SUM_TIMER_WAIT > t[j].SUM_TIMER_WAIT) ||
375                 ((t[i].SUM_TIMER_WAIT == t[j].SUM_TIMER_WAIT) && (t[i].FILE_NAME < t[j].FILE_NAME))
376 }
377
378 func (t *file_summary_by_instance_rows) sort() {
379         sort.Sort(t)
380 }
381
382 // if the data in t2 is "newer", "has more values" than t then it needs refreshing.
383 // check this by comparing totals.
384 func (t file_summary_by_instance_rows) needs_refresh(t2 file_summary_by_instance_rows) bool {
385         my_totals := t.totals()
386         t2_totals := t2.totals()
387
388         return my_totals.SUM_TIMER_WAIT > t2_totals.SUM_TIMER_WAIT
389 }