git-lfs/tq/meter.go

285 lines
6.3 KiB
Go
Raw Normal View History

package tq
import (
"fmt"
"math"
"os"
"path/filepath"
2016-02-23 19:00:45 +00:00
"sync"
"sync/atomic"
"time"
"github.com/git-lfs/git-lfs/v3/config"
"github.com/git-lfs/git-lfs/v3/tasklog"
"github.com/git-lfs/git-lfs/v3/tools"
"github.com/git-lfs/git-lfs/v3/tools/humanize"
"github.com/git-lfs/git-lfs/v3/tr"
)
// Meter provides a progress bar type output for the TransferQueue. It
2015-07-27 20:55:23 +00:00
// is given an estimated file count and size up front and tracks the number of
// files and bytes transferred as well as the number of files and bytes that
// get skipped because the transfer is unnecessary.
type Meter struct {
finishedFiles int64 // int64s must come first for struct alignment
transferringFiles int64
estimatedBytes int64
lastBytes int64
currentBytes int64
sampleCount uint64
avgBytes float64
lastAvg time.Time
estimatedFiles int32
paused uint32
fileIndex map[string]int64 // Maps a file name to its transfer number
2016-02-23 19:00:45 +00:00
fileIndexMutex *sync.Mutex
updates chan *tasklog.Update
cfg *config.Configuration
DryRun bool
Logger *tools.SyncWriter
Direction Direction
}
type env interface {
Get(key string) (val string, ok bool)
}
func (m *Meter) LoggerFromEnv(os env) *tools.SyncWriter {
name, _ := os.Get("GIT_LFS_PROGRESS")
if len(name) < 1 {
return nil
}
return m.LoggerToFile(name)
}
func (m *Meter) LoggerToFile(name string) *tools.SyncWriter {
printErr := func(err string) {
avoid extra message format parsing where possible Because the tr.Tr.Get() family of methods insert arguments into printf(3)-style format strings after translating the format string, we can in a few cases drop a surrounding call to fmt.Sprintf() or a similar method, as those now take no arguments and so are redundant. Moreover, this will help us avoid situations where either the translated string or the argument values interpolated by tr.Tr.Get() produce an output string which itself happens to contain character sequences that resemble Go format specifiers (e.g., "%s", "%d", etc.) In such cases passing the string at runtime to a method such as fmt.Fprintf() will result in the output containing a warning such as "%!s(MISSING)", which is not ideal. Note that in one case, in lfs/attribute.go, we can now also simplify the format string to use standard format specifiers instead of double-escaped ones (e.g., "%%q") since we can just allow tr.Tr.Get() to do the interpolation. We also take the opportunity to remove explicit leading or trailing newlines from translation messages wherever it is possible to convert the surrounding call to fmt.Print(), fmt.Fprint(), fmt.Println(), or fmt.Fprintln(). Finally, in the commands/run.go file, we can replace two calls to fmt.Fprintf() with fmt.Println() because they are just printing output to os.Stdout, not os.Stderr, and in the lfs/extension.go file, we can make better use of fmt.Errorf(). Note that at least one of these messages is not yet actually passed as a translation string, but we will address that issue in a subsequent commit.
2022-01-27 02:00:03 +00:00
fmt.Fprintln(os.Stderr, tr.Tr.Get("Error creating progress logger: %s", err))
}
if !filepath.IsAbs(name) {
printErr(tr.Tr.Get("GIT_LFS_PROGRESS must be an absolute path"))
return nil
}
if err := tools.MkdirAll(filepath.Dir(name), m.cfg); err != nil {
printErr(err.Error())
return nil
}
file, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
printErr(err.Error())
return nil
}
return tools.NewSyncWriter(file)
}
// NewMeter creates a new Meter.
func NewMeter(cfg *config.Configuration) *Meter {
m := &Meter{
fileIndex: make(map[string]int64),
2016-02-23 19:00:45 +00:00
fileIndexMutex: &sync.Mutex{},
updates: make(chan *tasklog.Update),
cfg: cfg,
}
return m
}
2016-12-07 23:54:24 +00:00
// Start begins sending status updates to the optional log file, and stdout.
2017-12-07 21:44:19 +00:00
func (m *Meter) Start() {
if m == nil {
return
}
2017-12-07 21:44:19 +00:00
atomic.StoreUint32(&m.paused, 0)
}
2017-01-26 16:31:12 +00:00
// Pause stops sending status updates temporarily, until Start() is called again.
2017-12-07 21:44:19 +00:00
func (m *Meter) Pause() {
if m == nil {
return
}
2017-12-07 21:44:19 +00:00
atomic.StoreUint32(&m.paused, 1)
2017-01-24 21:11:38 +00:00
}
// Add tells the progress meter that a single file of the given size will
// possibly be transferred. If a file doesn't need to be transferred for some
// reason, be sure to call Skip(int64) with the same size.
2017-12-07 21:44:19 +00:00
func (m *Meter) Add(size int64) {
if m == nil {
return
}
defer m.update(false)
2017-12-07 21:44:19 +00:00
atomic.AddInt32(&m.estimatedFiles, 1)
atomic.AddInt64(&m.estimatedBytes, size)
}
2015-07-27 20:55:23 +00:00
// Skip tells the progress meter that a file of size `size` is being skipped
// because the transfer is unnecessary.
2017-12-07 21:44:19 +00:00
func (m *Meter) Skip(size int64) {
if m == nil {
return
}
defer m.update(false)
2018-01-06 02:01:50 +00:00
atomic.AddInt64(&m.finishedFiles, 1)
atomic.AddInt64(&m.currentBytes, size)
}
// StartTransfer tells the progress meter that a transferring file is being
// added to the TransferQueue.
2017-12-07 21:44:19 +00:00
func (m *Meter) StartTransfer(name string) {
if m == nil {
return
}
defer m.update(false)
2017-12-07 21:44:19 +00:00
idx := atomic.AddInt64(&m.transferringFiles, 1)
m.fileIndexMutex.Lock()
m.fileIndex[name] = idx
m.fileIndexMutex.Unlock()
}
2015-07-27 20:55:23 +00:00
// TransferBytes increments the number of bytes transferred
2017-12-07 21:44:19 +00:00
func (m *Meter) TransferBytes(direction, name string, read, total int64, current int) {
if m == nil {
return
}
defer m.update(false)
now := time.Now()
since := now.Sub(m.lastAvg)
2017-12-07 21:44:19 +00:00
atomic.AddInt64(&m.currentBytes, int64(current))
atomic.AddInt64(&m.lastBytes, int64(current))
if since > time.Second {
m.lastAvg = now
bps := float64(m.lastBytes) / since.Seconds()
m.avgBytes = (m.avgBytes*float64(m.sampleCount) + bps) / (float64(m.sampleCount) + 1.0)
atomic.StoreInt64(&m.lastBytes, 0)
atomic.AddUint64(&m.sampleCount, 1)
}
2017-12-07 21:44:19 +00:00
m.logBytes(direction, name, read, total)
2015-07-27 20:55:23 +00:00
}
// FinishTransfer increments the finished transfer count
2017-12-07 21:44:19 +00:00
func (m *Meter) FinishTransfer(name string) {
if m == nil {
return
}
defer m.update(false)
2017-12-07 21:44:19 +00:00
atomic.AddInt64(&m.finishedFiles, 1)
m.fileIndexMutex.Lock()
delete(m.fileIndex, name)
m.fileIndexMutex.Unlock()
}
// Flush sends the latest progress update, while leaving the meter active.
func (m *Meter) Flush() {
if m == nil {
return
}
m.update(true)
}
// Finish shuts down the Meter.
2017-12-07 21:44:19 +00:00
func (m *Meter) Finish() {
if m == nil {
return
}
m.update(false)
2017-12-07 21:44:19 +00:00
close(m.updates)
}
2017-12-07 21:44:19 +00:00
func (m *Meter) Updates() <-chan *tasklog.Update {
if m == nil {
return nil
}
2017-12-07 21:44:19 +00:00
return m.updates
}
2017-12-07 21:44:19 +00:00
func (m *Meter) Throttled() bool {
return true
}
func (m *Meter) update(force bool) {
2017-12-07 21:44:19 +00:00
if m.skipUpdate() {
return
}
2017-12-07 21:44:19 +00:00
m.updates <- &tasklog.Update{
S: m.str(),
At: time.Now(),
Force: force,
}
}
2017-12-07 21:44:19 +00:00
func (m *Meter) skipUpdate() bool {
return m.DryRun ||
2018-01-06 02:01:50 +00:00
m.estimatedFiles == 0 ||
2017-12-07 21:44:19 +00:00
atomic.LoadUint32(&m.paused) == 1
}
2017-12-07 21:44:19 +00:00
func (m *Meter) str() string {
2018-01-06 02:01:50 +00:00
// (Uploading|Downloading) LFS objects: 100% (10/10) 100 MiB | 10 MiB/s
percentage := 100 * float64(m.finishedFiles) / float64(m.estimatedFiles)
return fmt.Sprintf("%s: %3.f%% (%d/%d), %s | %s",
m.Direction.Progress(),
2018-01-06 02:01:50 +00:00
percentage,
m.finishedFiles, m.estimatedFiles,
humanize.FormatBytes(clamp(m.currentBytes)),
humanize.FormatByteRate(clampf(m.avgBytes), time.Second))
}
// clamp clamps the given "x" within the acceptable domain of the uint64 integer
// type, so as to prevent over- and underflow.
func clamp(x int64) uint64 {
if x < 0 {
return 0
}
if x > math.MaxInt64 {
return math.MaxUint64
}
return uint64(x)
}
func clampf(x float64) uint64 {
if x < 0 {
return 0
}
if x > math.MaxUint64 {
return math.MaxUint64
}
return uint64(x)
}
2017-12-07 21:44:19 +00:00
func (m *Meter) logBytes(direction, name string, read, total int64) {
m.fileIndexMutex.Lock()
idx := m.fileIndex[name]
logger := m.Logger
2017-12-07 21:44:19 +00:00
m.fileIndexMutex.Unlock()
if logger == nil {
return
}
2017-12-07 21:44:19 +00:00
line := fmt.Sprintf("%s %d/%d %d/%d %s\n", direction, idx, m.estimatedFiles, read, total, name)
if err := m.Logger.Write([]byte(line)); err != nil {
m.fileIndexMutex.Lock()
m.Logger = nil
m.fileIndexMutex.Unlock()
}
}