Progress is the bytes a backend process has read (rchar in /proc/PID/io), so every backend works unchanged; reads of successive processes add up. Speed is smoothed with an exponential moving average. - The display redraws every 80 ms, appears only after 250 ms, and erases itself completely when stopped. - Backend output goes through Writer, which prints whole lines above the display. - An unterminated line that stays put, or a backend opening /dev/tty, is treated as a password prompt and stops the drawing.
327 lines
8.4 KiB
Go
327 lines
8.4 KiB
Go
package progress
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"src.panahifar.ir/ahp/archive-utils/internal/proc"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
const (
|
|
interval = 80 * time.Millisecond // redraw rate, as in zap
|
|
// showAfter keeps quick operations from flashing a display.
|
|
showAfter = 250 * time.Millisecond
|
|
// promptAfter is how long an unterminated backend line may wait before it
|
|
// is treated as a prompt and shown.
|
|
promptAfter = 150 * time.Millisecond
|
|
// smoothing weighs each new speed sample (exponential moving average).
|
|
smoothing = 0.15
|
|
)
|
|
|
|
// Monitor shows a live display while a backend runs. It measures progress as
|
|
// the bytes the watched backend process has read (rchar in /proc/PID/io)
|
|
// against an expected total, so it works with any backend unchanged.
|
|
//
|
|
// Backend output must go through Writer, which erases the display, prints
|
|
// complete lines and redraws, so messages and the display never mix. A nil
|
|
// *Monitor is valid and does nothing; Streams then returns plain streams.
|
|
type Monitor struct {
|
|
mu sync.Mutex
|
|
out io.Writer
|
|
columns func() int
|
|
frame frame
|
|
delay time.Duration
|
|
|
|
start time.Time
|
|
pid int // process being watched; 0 if none
|
|
base int64 // bytes read by processes watched earlier
|
|
current int64 // bytes read by pid so far
|
|
sampled time.Time
|
|
prev int64 // done at the previous sample
|
|
|
|
drawn int // lines currently on screen
|
|
pending []byte // backend output without a final newline yet
|
|
lastOut time.Time
|
|
paused bool // a backend is prompting; stop drawing for good
|
|
stopping chan struct{}
|
|
stopped sync.WaitGroup
|
|
|
|
// Replaceable in tests.
|
|
bytesRead func(pid int) (int64, bool)
|
|
usesTTY func(pid int) bool
|
|
}
|
|
|
|
// Enabled reports whether a display can be drawn on f: f is a terminal that
|
|
// is not "dumb" and is at least MinWidth columns wide.
|
|
func Enabled(f *os.File) bool {
|
|
if term := os.Getenv("TERM"); term == "" || term == "dumb" {
|
|
return false
|
|
}
|
|
return terminalWidth(f) >= MinWidth
|
|
}
|
|
|
|
// Start begins a display on f for operation op ("extract" or "create") on
|
|
// label. total is the expected number of bytes. An empty label shows
|
|
// "scanning…" until Ready is called.
|
|
func Start(f *os.File, op, label string, total int64, color bool) *Monitor {
|
|
m := newMonitor(f, func() int { return terminalWidth(f) }, op, label, total, color, showAfter)
|
|
m.run()
|
|
return m
|
|
}
|
|
|
|
func newMonitor(out io.Writer, columns func() int, op, label string, total int64, color bool, delay time.Duration) *Monitor {
|
|
return &Monitor{
|
|
out: out,
|
|
columns: columns,
|
|
frame: frame{op: op, label: label, total: total, color: color},
|
|
delay: delay,
|
|
start: time.Now(),
|
|
stopping: make(chan struct{}),
|
|
bytesRead: readRchar,
|
|
usesTTY: opensTerminal,
|
|
}
|
|
}
|
|
|
|
func (m *Monitor) run() {
|
|
m.stopped.Add(1)
|
|
go func() {
|
|
defer m.stopped.Done()
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-m.stopping:
|
|
return
|
|
case now := <-ticker.C:
|
|
m.tick(now)
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
// Ready names what is being processed and sets the expected number of bytes,
|
|
// for a display started with an empty label (shown as "scanning…").
|
|
func (m *Monitor) Ready(label string, total int64) {
|
|
if m == nil {
|
|
return
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.frame.label, m.frame.total = label, total
|
|
}
|
|
|
|
// Watch makes pid the process whose reads are counted. Bytes read by the
|
|
// previously watched process are kept, so successive backend runs add up.
|
|
func (m *Monitor) Watch(pid int) {
|
|
if m == nil {
|
|
return
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.base += m.current
|
|
m.current, m.pid = 0, pid
|
|
}
|
|
|
|
// Stage selects which process of a pipeline is watched.
|
|
type Stage int
|
|
|
|
const (
|
|
FirstStage Stage = iota // the process that reads the input files
|
|
LastStage // e.g. the compressor after tar
|
|
)
|
|
|
|
// Streams returns pipeline streams that route backend output through the
|
|
// display and watch the given stage of the pipeline. stdout is the pipeline's
|
|
// data output; if it is os.Stderr (backend chatter), it goes through the
|
|
// display too.
|
|
func (m *Monitor) Streams(stdin io.Reader, stdout io.Writer, stage Stage) proc.IO {
|
|
if m == nil {
|
|
return proc.IO{Stdin: stdin, Stdout: stdout}
|
|
}
|
|
w := Writer{m}
|
|
if stdout == os.Stderr {
|
|
stdout = w
|
|
}
|
|
watch := func(pids []int) {
|
|
if stage == LastStage {
|
|
m.Watch(pids[len(pids)-1])
|
|
} else {
|
|
m.Watch(pids[0])
|
|
}
|
|
}
|
|
return proc.IO{Stdin: stdin, Stdout: stdout, Stderr: w, Started: watch}
|
|
}
|
|
|
|
// Stop erases the display and flushes pending backend output. The terminal is
|
|
// left exactly as if no display had been shown.
|
|
func (m *Monitor) Stop() {
|
|
if m == nil {
|
|
return
|
|
}
|
|
close(m.stopping)
|
|
m.stopped.Wait()
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.erase()
|
|
if len(m.pending) > 0 {
|
|
m.out.Write(m.pending)
|
|
m.pending = nil
|
|
}
|
|
}
|
|
|
|
func (m *Monitor) tick(now time.Time) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.paused {
|
|
return
|
|
}
|
|
if m.pid != 0 {
|
|
if n, ok := m.bytesRead(m.pid); ok {
|
|
m.current = n
|
|
}
|
|
// A backend that opens the terminal is asking for a password. Stop
|
|
// drawing so the prompt is not overwritten.
|
|
// The display is abandoned, not erased: the prompt may already be on
|
|
// screen after it, and the cursor will move once it is answered.
|
|
if m.usesTTY(m.pid) {
|
|
m.paused = true
|
|
m.drawn = 0
|
|
return
|
|
}
|
|
}
|
|
m.sample(now)
|
|
// An unterminated line that stays put is a prompt: show it, stop drawing.
|
|
if len(m.pending) > 0 && now.Sub(m.lastOut) >= promptAfter {
|
|
m.erase()
|
|
m.out.Write(m.pending)
|
|
m.pending = nil
|
|
m.paused = true
|
|
return
|
|
}
|
|
if now.Sub(m.start) < m.delay {
|
|
return
|
|
}
|
|
m.frame.tick++
|
|
m.draw()
|
|
}
|
|
|
|
// sample updates the processed byte count and the smoothed speed.
|
|
func (m *Monitor) sample(now time.Time) {
|
|
done := m.base + m.current
|
|
if !m.sampled.IsZero() {
|
|
if dt := now.Sub(m.sampled).Seconds(); dt > 0 {
|
|
instant := float64(done-m.prev) / dt
|
|
if m.frame.speed == 0 {
|
|
m.frame.speed = instant
|
|
} else {
|
|
m.frame.speed = smoothing*instant + (1-smoothing)*m.frame.speed
|
|
}
|
|
}
|
|
}
|
|
m.sampled, m.prev, m.frame.done = now, done, done
|
|
}
|
|
|
|
// draw replaces the display with the current frame. Must hold m.mu.
|
|
func (m *Monitor) draw() {
|
|
m.frame.columns = m.columns()
|
|
if m.frame.columns < MinWidth {
|
|
m.erase()
|
|
return
|
|
}
|
|
lines := render(m.frame)
|
|
var b strings.Builder
|
|
b.WriteString(eraseSeq(m.drawn))
|
|
b.WriteString(strings.Join(lines, "\n"))
|
|
io.WriteString(m.out, b.String())
|
|
m.drawn = len(lines)
|
|
}
|
|
|
|
// erase removes the display; the cursor ends where the display began.
|
|
func (m *Monitor) erase() {
|
|
if m.drawn > 0 {
|
|
io.WriteString(m.out, eraseSeq(m.drawn))
|
|
m.drawn = 0
|
|
}
|
|
}
|
|
|
|
// eraseSeq clears n lines, ending at the start of the first. The cursor is
|
|
// assumed to be on the last of them.
|
|
func eraseSeq(n int) string {
|
|
if n == 0 {
|
|
return ""
|
|
}
|
|
return "\r\x1b[2K" + strings.Repeat("\x1b[1A\x1b[2K", n-1)
|
|
}
|
|
|
|
// Writer passes backend output to the terminal without mixing it with the
|
|
// display: complete lines are printed above a redrawn display.
|
|
type Writer struct{ m *Monitor }
|
|
|
|
func (w Writer) Write(p []byte) (int, error) {
|
|
m := w.m
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.pending = append(m.pending, p...)
|
|
m.lastOut = time.Now()
|
|
if i := bytes.LastIndexByte(m.pending, '\n'); i >= 0 {
|
|
visible := m.drawn > 0
|
|
m.erase()
|
|
m.out.Write(m.pending[:i+1])
|
|
m.pending = append([]byte(nil), m.pending[i+1:]...)
|
|
if visible && !m.paused {
|
|
m.draw()
|
|
}
|
|
}
|
|
return len(p), nil
|
|
}
|
|
|
|
// readRchar returns the bytes a process has read so far, from /proc/PID/io.
|
|
func readRchar(pid int) (int64, bool) {
|
|
data, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/io")
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
for line := range strings.SplitSeq(string(data), "\n") {
|
|
if v, ok := strings.CutPrefix(line, "rchar: "); ok {
|
|
n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
|
|
return n, err == nil
|
|
}
|
|
}
|
|
return 0, false
|
|
}
|
|
|
|
// opensTerminal reports whether a process has opened a terminal device
|
|
// beyond its standard streams, as password prompts do (/dev/tty).
|
|
func opensTerminal(pid int) bool {
|
|
dir := "/proc/" + strconv.Itoa(pid) + "/fd"
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, e := range entries {
|
|
if fd, err := strconv.Atoi(e.Name()); err != nil || fd <= 2 {
|
|
continue
|
|
}
|
|
target, err := os.Readlink(dir + "/" + e.Name())
|
|
if err == nil && (target == "/dev/tty" || strings.HasPrefix(target, "/dev/pts/")) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func terminalWidth(f *os.File) int {
|
|
ws, err := unix.IoctlGetWinsize(int(f.Fd()), unix.TIOCGWINSZ)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return int(ws.Col)
|
|
}
|