/
logstats.go
233 lines (211 loc) · 6.34 KB
/
logstats.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tabletserver
import (
"encoding/json"
"fmt"
"html/template"
"net/url"
"strings"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/streamlog"
"github.com/youtube/vitess/go/vt/callerid"
"github.com/youtube/vitess/go/vt/callinfo"
"golang.org/x/net/context"
)
// StatsLogger is the main stream logger object
var StatsLogger = streamlog.New("TabletServer", 50)
const (
// QuerySourceRowcache means query result is found in rowcache.
QuerySourceRowcache = 1 << iota
// QuerySourceConsolidator means query result is found in consolidator.
QuerySourceConsolidator
// QuerySourceMySQL means query result is returned from MySQL.
QuerySourceMySQL
)
// LogStats records the stats for a single query
type LogStats struct {
Method string
PlanType string
OriginalSQL string
BindVariables map[string]interface{}
rewrittenSqls []string
RowsAffected int
NumberOfQueries int
StartTime time.Time
EndTime time.Time
MysqlResponseTime time.Duration
WaitingForConnection time.Duration
CacheHits int64
CacheAbsent int64
CacheMisses int64
CacheInvalidations int64
QuerySources byte
Rows [][]sqltypes.Value
TransactionID int64
ctx context.Context
Error *TabletError
}
func newLogStats(methodName string, ctx context.Context) *LogStats {
return &LogStats{
Method: methodName,
StartTime: time.Now(),
ctx: ctx,
}
}
// Send finalizes a record and sends it
func (stats *LogStats) Send() {
stats.EndTime = time.Now()
StatsLogger.Send(stats)
}
// ImmediateCaller returns the immediate caller stored in LogStats.ctx
func (stats *LogStats) ImmediateCaller() string {
return callerid.GetUsername(callerid.ImmediateCallerIDFromContext(stats.ctx))
}
// EffectiveCaller returns the effective caller stored in LogStats.ctx
func (stats *LogStats) EffectiveCaller() string {
return callerid.GetPrincipal(callerid.EffectiveCallerIDFromContext(stats.ctx))
}
// EventTime returns the time the event was created.
func (stats *LogStats) EventTime() time.Time {
return stats.EndTime
}
// AddRewrittenSQL adds a single sql statement to the rewritten list
func (stats *LogStats) AddRewrittenSQL(sql string, start time.Time) {
stats.QuerySources |= QuerySourceMySQL
stats.NumberOfQueries++
stats.rewrittenSqls = append(stats.rewrittenSqls, sql)
stats.MysqlResponseTime += time.Now().Sub(start)
}
// TotalTime returns how long this query has been running
func (stats *LogStats) TotalTime() time.Duration {
return stats.EndTime.Sub(stats.StartTime)
}
// RewrittenSQL returns a semicolon separated list of SQL statements
// that were executed.
func (stats *LogStats) RewrittenSQL() string {
return strings.Join(stats.rewrittenSqls, "; ")
}
// SizeOfResponse returns the approximate size of the response in
// bytes (this does not take in account BSON encoding). It will return
// 0 for streaming requests.
func (stats *LogStats) SizeOfResponse() int {
if stats.Rows == nil {
return 0
}
size := 0
for _, row := range stats.Rows {
for _, field := range row {
size += field.Len()
}
}
return size
}
// FmtBindVariables returns the map of bind variables as JSON. For
// values that are strings or byte slices it only reports their type
// and length.
func (stats *LogStats) FmtBindVariables(full bool) string {
var out map[string]interface{}
if full {
out = stats.BindVariables
} else {
// NOTE(szopa): I am getting rid of potentially large bind
// variables.
out = make(map[string]interface{})
for k, v := range stats.BindVariables {
switch val := v.(type) {
case string:
out[k] = fmt.Sprintf("string %v", len(val))
case []byte:
out[k] = fmt.Sprintf("bytes %v", len(val))
default:
out[k] = v
}
}
}
b, err := json.Marshal(out)
if err != nil {
log.Warningf("could not marshal %q", stats.BindVariables)
return ""
}
return string(b)
}
// FmtQuerySources returns a comma separated list of query
// sources. If there were no query sources, it returns the string
// "none".
func (stats *LogStats) FmtQuerySources() string {
if stats.QuerySources == 0 {
return "none"
}
sources := make([]string, 3)
n := 0
if stats.QuerySources&QuerySourceMySQL != 0 {
sources[n] = "mysql"
n++
}
if stats.QuerySources&QuerySourceRowcache != 0 {
sources[n] = "rowcache"
n++
}
if stats.QuerySources&QuerySourceConsolidator != 0 {
sources[n] = "consolidator"
n++
}
return strings.Join(sources[:n], ",")
}
// ContextHTML returns the HTML version of the context that was used, or "".
// This is a method on LogStats instead of a field so that it doesn't need
// to be passed by value everywhere.
func (stats *LogStats) ContextHTML() template.HTML {
return callinfo.HTMLFromContext(stats.ctx)
}
// ErrorStr returns the error string or ""
func (stats *LogStats) ErrorStr() string {
if stats.Error != nil {
return stats.Error.Error()
}
return ""
}
// RemoteAddrUsername returns some parts of CallInfo if set
func (stats *LogStats) RemoteAddrUsername() (string, string) {
ci, ok := callinfo.FromContext(stats.ctx)
if !ok {
return "", ""
}
return ci.RemoteAddr(), ci.Username()
}
// Format returns a tab separated list of logged fields.
func (stats *LogStats) Format(params url.Values) string {
_, fullBindParams := params["full"]
// TODO: remove username here we fully enforce immediate caller id
remoteAddr, username := stats.RemoteAddrUsername()
return fmt.Sprintf(
"%v\t%v\t%v\t'%v'\t'%v'\t%v\t%v\t%.6f\t%v\t%q\t%v\t%v\t%q\t%v\t%.6f\t%.6f\t%v\t%v\t%v\t%v\t%v\t%v\t%q\t\n",
stats.Method,
remoteAddr,
username,
stats.ImmediateCaller(),
stats.EffectiveCaller(),
stats.StartTime.Format(time.StampMicro),
stats.EndTime.Format(time.StampMicro),
stats.TotalTime().Seconds(),
stats.PlanType,
stats.OriginalSQL,
stats.FmtBindVariables(fullBindParams),
stats.NumberOfQueries,
stats.RewrittenSQL(),
stats.FmtQuerySources(),
stats.MysqlResponseTime.Seconds(),
stats.WaitingForConnection.Seconds(),
stats.RowsAffected,
stats.SizeOfResponse(),
stats.CacheHits,
stats.CacheMisses,
stats.CacheAbsent,
stats.CacheInvalidations,
stats.ErrorStr(),
)
}