generated from bool64/go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogress.go
400 lines (322 loc) · 8.03 KB
/
progress.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Package progress provides helpers to print progress status.
package progress
import (
"fmt"
"io"
"runtime"
"sync/atomic"
"time"
)
// Status describes current progress.
type Status struct {
Task string `json:"task"`
DonePercent float64 `json:"done_percent"`
LinesCompleted int64 `json:"lines_completed"`
BytesCompleted int64 `json:"bytes_completed"`
SpeedMBPS float64 `json:"speed_mbps"`
SpeedLPS float64 `json:"speed_lps"`
Elapsed time.Duration `json:"-"`
Remaining time.Duration `json:"-"`
Metrics []Metric `json:"-"`
}
// Progress reports reading performance.
type Progress struct {
Interval time.Duration
Print func(status Status)
ShowHeapStats bool
ShowLinesStats bool
// IncrementalSpeed shows speed and remaining estimate based on performance between two status updates.
IncrementalSpeed bool
done chan bool
task Task
lines func() int64
current func() int64
tot func() int64
prnt func(s Status)
start time.Time
prevStatus Status
continuedLines int64
continuedBytes int64
metrics []Metric
}
// Type describes metric value.
type Type string
// Type values.
const (
Bytes = Type("bytes")
Duration = Type("duration")
Gauge = Type("gauge")
)
// Metric is an operation metric.
type Metric struct {
Name string
Type Type
Value func() int64
}
// DefaultStatus renders Status as a string.
func DefaultStatus(s Status) string {
if s.Task != "" {
s.Task += ": "
}
ms := runtime.MemStats{}
runtime.ReadMemStats(&ms)
heapMB := ms.HeapInuse / (1024 * 1024)
res := fmt.Sprintf(s.Task+"%.1f%% bytes read, %d lines processed, %.1f l/s, %.1f MB/s, elapsed %s, remaining %s, heap %d MB",
s.DonePercent, s.LinesCompleted, s.SpeedLPS, s.SpeedMBPS,
s.Elapsed.Round(10*time.Millisecond).String(), s.Remaining.String(), heapMB)
return res
}
// MetricsStatus renders Status metrics as a string.
func MetricsStatus(s Status) string {
metrics := ""
for _, m := range s.Metrics {
switch m.Type {
case Bytes:
spdMBPS := float64(m.Value()) / (s.Elapsed.Seconds() * 1024 * 1024)
metrics += fmt.Sprintf("%s: %.1f MB/s, ", m.Name, spdMBPS)
case Duration:
metrics += m.Name + ": " + time.Duration(m.Value()).String() + ", "
case Gauge:
metrics += fmt.Sprintf("%s: %d, ", m.Name, m.Value())
}
}
if metrics != "" {
metrics = metrics[:len(metrics)-2]
}
return metrics
}
// Task describes a long-running process.
type Task struct {
TotalBytes func() int64
CurrentBytes func() int64
CurrentLines func() int64
Task string
Continue bool
PrintOnStart bool
}
// Start spawns background progress reporter.
func (p *Progress) Start(options ...func(t *Task)) {
p.done = make(chan bool)
task := Task{}
for _, o := range options {
o(&task)
}
if task.Continue {
if p.current != nil {
p.continuedBytes += p.current()
}
if p.lines != nil {
p.continuedLines += p.lines()
}
}
p.task = task
p.current = task.CurrentBytes
p.lines = task.CurrentLines
p.tot = task.TotalBytes
interval := p.Interval
if interval == 0 {
interval = time.Second
}
p.prnt = p.Print
if p.prnt == nil {
p.prnt = func(s Status) {
println(DefaultStatus(s))
}
}
if !task.Continue || p.start.IsZero() {
p.start = time.Now()
p.continuedBytes = 0
p.continuedLines = 0
}
p.startPrinter(interval)
}
func (p *Progress) startPrinter(interval time.Duration) {
done := p.done
t := time.NewTicker(interval)
go func() {
for {
select {
case <-t.C:
p.printStatus(false)
case <-done:
t.Stop()
return
}
}
}()
if p.task.PrintOnStart {
go func() {
time.Sleep(time.Millisecond)
p.printStatus(false)
}()
}
}
// AddMetrics adds more metrics to progress status message.
func (p *Progress) AddMetrics(metrics ...Metric) {
p.metrics = append(p.metrics, metrics...)
}
// Reset drops continued counters.
func (p *Progress) Reset() {
p.start = time.Time{}
p.continuedLines = 0
p.continuedBytes = 0
p.metrics = nil
}
func (p *Progress) speedStatus(s *Status) {
if !p.IncrementalSpeed {
s.SpeedMBPS = (float64(s.BytesCompleted) / s.Elapsed.Seconds()) / (1024 * 1024)
s.SpeedLPS = float64(s.LinesCompleted) / s.Elapsed.Seconds()
if s.DonePercent > 0 {
s.Remaining = time.Duration(float64(100*s.Elapsed)/s.DonePercent) - s.Elapsed
s.Remaining = s.Remaining.Truncate(time.Second)
} else {
s.Remaining = 0
}
return
}
lc := s.LinesCompleted - p.prevStatus.LinesCompleted
bc := s.BytesCompleted - p.prevStatus.BytesCompleted
dc := s.DonePercent - p.prevStatus.DonePercent
ela := s.Elapsed - p.prevStatus.Elapsed
if ela != 0 {
if lc > 0 {
s.SpeedLPS = float64(lc) / ela.Seconds()
}
if bc > 0 {
s.SpeedMBPS = (float64(bc) / ela.Seconds()) / (1024 * 1024)
}
}
if dc > 0 {
s.Remaining = time.Duration((100.0 - s.DonePercent) * float64(ela) / dc)
s.Remaining = s.Remaining.Truncate(time.Second)
} else {
s.Remaining = 0
}
p.prevStatus = *s
}
func (p *Progress) printStatus(last bool) {
s := Status{}
s.Task = p.task.Task
s.LinesCompleted = p.Lines()
s.BytesCompleted = p.Bytes()
s.Metrics = p.metrics
s.Elapsed = time.Since(p.start)
s.DonePercent = 100 * float64(s.BytesCompleted) / float64(p.tot())
p.speedStatus(&s)
if s.Remaining > 100*time.Millisecond || s.Remaining == 0 || last {
p.prnt(s)
}
}
// Stop stops progress reporting.
func (p *Progress) Stop() {
p.printStatus(true)
if !p.task.Continue {
p.metrics = nil
}
close(p.done)
}
// Bytes returns current number of bytes.
func (p *Progress) Bytes() int64 {
if p.current != nil {
return p.continuedBytes + p.current()
}
return p.continuedBytes
}
// Lines returns current number of lines.
func (p *Progress) Lines() int64 {
if p.lines != nil {
return p.continuedLines + p.lines()
}
return p.continuedLines
}
// NewCountingReader wraps an io.Reader with counters of bytes and lines.
func NewCountingReader(r io.Reader) *CountingReader {
cr := &CountingReader{
Reader: r,
}
cr.lines = new(int64)
cr.bytes = new(int64)
return cr
}
// CountingReader wraps io.Reader to count bytes.
type CountingReader struct {
Reader io.Reader
sharedCounters
}
type sharedCounters struct {
lines *int64
bytes *int64
localBytes int64
localLines int64
}
func (cr *sharedCounters) SetLines(lines *int64) {
cr.lines = lines
}
func (cr *sharedCounters) SetBytes(bytes *int64) {
cr.bytes = bytes
}
func (cr *sharedCounters) count(n int, p []byte, err error) {
cr.localBytes += int64(n)
if (err != nil || cr.localBytes > 100000) && cr.bytes != nil {
atomic.AddInt64(cr.bytes, cr.localBytes)
cr.localBytes = 0
}
if cr.lines == nil {
return
}
for i := 0; i < n; i++ {
if p[i] == '\n' {
cr.localLines++
}
}
if err != nil || cr.localLines > 1000 {
atomic.AddInt64(cr.lines, cr.localLines)
cr.localLines = 0
}
}
// Read reads and counts bytes.
func (cr *CountingReader) Read(p []byte) (n int, err error) {
n, err = cr.Reader.Read(p)
cr.count(n, p, err)
return n, err
}
func (cr *sharedCounters) Close() {
if cr.localBytes > 0 && cr.bytes != nil {
atomic.AddInt64(cr.bytes, cr.localBytes)
cr.localBytes = 0
}
if cr.localLines > 0 && cr.lines != nil {
atomic.AddInt64(cr.lines, cr.localLines)
cr.localLines = 0
}
}
// Bytes returns number of processed bytes.
func (cr *sharedCounters) Bytes() int64 {
return atomic.LoadInt64(cr.bytes)
}
// Lines returns number of processed lines.
func (cr *sharedCounters) Lines() int64 {
return atomic.LoadInt64(cr.lines)
}
// NewCountingWriter wraps an io.Writer with counters of bytes and lines.
func NewCountingWriter(w io.Writer) *CountingWriter {
cw := &CountingWriter{Writer: w}
cw.lines = new(int64)
cw.bytes = new(int64)
return cw
}
// CountingWriter wraps io.Writer to count bytes.
type CountingWriter struct {
Writer io.Writer
sharedCounters
}
// Write writes and counts bytes.
func (cr *CountingWriter) Write(p []byte) (n int, err error) {
n, err = cr.Writer.Write(p)
cr.count(n, p, err)
return n, err
}
// MetricsExposer provides metric counters.
type MetricsExposer interface {
Metrics() []Metric
}