summaryrefslogtreecommitdiffstats
path: root/metrics/metrics.go
blob: 9715a3747e8efc4dea8f8f0a0fcf2514de0c556e (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package metrics provides simple metrics tracking features.
package metrics

import (
	"fmt"
	"io"
	"math"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gohugoio/hugo/common/types"
	"github.com/gohugoio/hugo/compare"
	"github.com/gohugoio/hugo/identity"
)

// The Provider interface defines an interface for measuring metrics.
type Provider interface {
	// MeasureSince adds a measurement for key to the metric store.
	// Used with defer and time.Now().
	MeasureSince(key string, start time.Time)

	// WriteMetrics will write a summary of the metrics to w.
	WriteMetrics(w io.Writer)

	// TrackValue tracks the value for diff calculations etc.
	TrackValue(key string, value any, cached bool)

	// Reset clears the metric store.
	Reset()
}

type diff struct {
	baseline any
	count    int
	simSum   int
}

func (d *diff) add(v any) *diff {
	if types.IsNil(d.baseline) {
		d.baseline = v
		d.count = 1
		d.simSum = 100 // If we get only one it is very cache friendly.
		return d
	}
	adder := howSimilar(v, d.baseline)
	d.simSum += adder
	d.count++

	return d
}

// Store provides storage for a set of metrics.
type Store struct {
	calculateHints bool
	metrics        map[string][]time.Duration
	mu             sync.Mutex
	diffs          map[string]*diff
	diffmu         sync.Mutex
	cached         map[string]int
	cachedmu       sync.Mutex
}

// NewProvider returns a new instance of a metric store.
func NewProvider(calculateHints bool) Provider {
	return &Store{
		calculateHints: calculateHints,
		metrics:        make(map[string][]time.Duration),
		diffs:          make(map[string]*diff),
		cached:         make(map[string]int),
	}
}

// Reset clears the metrics store.
func (s *Store) Reset() {
	s.mu.Lock()
	s.metrics = make(map[string][]time.Duration)
	s.mu.Unlock()

	s.diffmu.Lock()
	s.diffs = make(map[string]*diff)
	s.diffmu.Unlock()

	s.cachedmu.Lock()
	s.cached = make(map[string]int)
	s.cachedmu.Unlock()
}

// TrackValue tracks the value for diff calculations etc.
func (s *Store) TrackValue(key string, value any, cached bool) {
	if !s.calculateHints {
		return
	}

	s.diffmu.Lock()
	d, found := s.diffs[key]

	if !found {
		d = &diff{}
		s.diffs[key] = d
	}

	d.add(value)
	s.diffmu.Unlock()

	if cached {
		s.cachedmu.Lock()
		s.cached[key] = s.cached[key] + 1
		s.cachedmu.Unlock()
	}
}

// MeasureSince adds a measurement for key to the metric store.
func (s *Store) MeasureSince(key string, start time.Time) {
	s.mu.Lock()
	s.metrics[key] = append(s.metrics[key], time.Since(start))
	s.mu.Unlock()
}

// WriteMetrics writes a summary of the metrics to w.
func (s *Store) WriteMetrics(w io.Writer) {
	s.mu.Lock()

	results := make([]result, len(s.metrics))

	var i int
	for k, v := range s.metrics {
		var sum time.Duration
		var max time.Duration

		diff, found := s.diffs[k]

		cacheFactor := 0
		if found {
			cacheFactor = int(math.Floor(float64(diff.simSum) / float64(diff.count)))
		}

		for _, d := range v {
			sum += d
			if d > max {
				max = d
			}
		}

		avg := time.Duration(int(sum) / len(v))
		cacheCount := s.cached[k]

		results[i] = result{key: k, count: len(v), max: max, sum: sum, avg: avg, cacheCount: cacheCount, cacheFactor: cacheFactor}
		i++
	}

	s.mu.Unlock()

	if s.calculateHints {
		fmt.Fprintf(w, "  %13s  %12s  %12s  %9s  %7s  %6s  %5s  %s\n", "cumulative", "average", "maximum", "cache", "percent", "cached", "total", "")
		fmt.Fprintf(w, "  %13s  %12s  %12s  %9s  %7s  %6s  %5s  %s\n", "duration", "duration", "duration", "potential", "cached", "count", "count", "template")
		fmt.Fprintf(w, "  %13s  %12s  %12s  %9s  %7s  %6s  %5s  %s\n", "----------", "--------", "--------", "---------", "-------", "------", "-----", "--------")
	} else {
		fmt.Fprintf(w, "  %13s  %12s  %12s  %5s  %s\n", "cumulative", "average", "maximum", "", "")
		fmt.Fprintf(w, "  %13s  %12s  %12s  %5s  %s\n", "duration", "duration", "duration", "count", "template")
		fmt.Fprintf(w, "  %13s  %12s  %12s  %5s  %s\n", "----------", "--------", "--------", "-----", "--------")

	}

	sort.Sort(bySum(results))
	for _, v := range results {
		if s.calculateHints {
			fmt.Fprintf(w, "  %13s  %12s  %12s  %9d  %7.f  %6d  %5d  %s\n", v.sum, v.avg, v.max, v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key)
		} else {
			fmt.Fprintf(w, "  %13s  %12s  %12s  %5d  %s\n", v.sum, v.avg, v.max, v.count, v.key)
		}
	}
}

// A result represents the calculated results for a given metric.
type result struct {
	key         string
	count       int
	cacheCount  int
	cacheFactor int
	sum         time.Duration
	max         time.Duration
	avg         time.Duration
}

type bySum []result

func (b bySum) Len() int           { return len(b) }
func (b bySum) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
func (b bySum) Less