Documentation
¶
Overview ¶
Package progress reports what a command is doing while it runs.
The work is a tree of spans, one level for each kind of unit: the command, its steps, the batches of a staggered action, the targets a step works on, the calls made for a target, and the waits in between. A span travels in the context.Context the work is done under, so the span a call starts nests under the target it is made for without being handed down. Every change to a span is sent, as one Event of plain data, to the sinks of the Bus the context carries, in one total order. A counter, a live tree, an agent's progress notifications, an event log and a test are sinks; this package draws nothing itself, and writes only the event log, Log.
Without a Bus in the context, Start returns the context unchanged and a nil *Span, and every method of a nil *Span does nothing, so work that nobody watches pays only for the lookup.
The vocabulary is closed: an event carries the fields of Fields and nothing else, so an argument vector, a script, standard input or a header has nowhere to go. Text that came from elsewhere, an error or a remote line, is passed through Sanitize before any sink sees it.
The events map one to one onto a trace: the trace id is 16 bytes, a span id is 8, and each Bus draws the base of its span ids at random, so that runs sharing one trace do not share span ids. A Bus may continue a trace another program began, as ParseTraceContext reads it from a W3C traceparent.
Index ¶
- Constants
- func Sanitize(s string, max int) string
- func Suspend(ctx context.Context) (resume func())
- func Tee(ctx context.Context, w io.Writer, st Stream, parse func(Stream, string)) io.Writer
- func WithBus(ctx context.Context, b *Bus) context.Context
- type Bus
- type Class
- type Classifier
- type Count
- type Event
- type Fields
- type Flags
- type Kind
- type LineSink
- type Log
- type LogOptions
- type Option
- func Batch(i, n int) Option
- func Cache(s string) Option
- func Exit(code int) Option
- func HTTP(method, path string) Option
- func HTTPStatus(code int) Option
- func Host(s string) Option
- func Limit(n int) Option
- func Message(s string) Option
- func Node(s string) Option
- func Queued() Option
- func Role(s string) Option
- func Source(s string) Option
- func Timeout(d time.Duration) Option
- func Total(n int) Option
- func WithFlags(f Flags) Option
- type Options
- type Sink
- type Span
- type SpanID
- type State
- type Status
- type Stream
- type Suspender
- type Tally
- type TraceContext
- type TraceID
- type TraceSink
- type Type
Constants ¶
const ( // MaxText bounds the text of a line of output. MaxText = 512 // MaxErr bounds the error a span ended with. MaxErr = 1024 // MaxField bounds a span's name, its Message and every other text // field but Node, which is a node set a display folds and is never // cut. MaxField = 256 )
The bounds of the text an event carries, in bytes. Sanitize cuts to them.
const LogVersion = 1
LogVersion is the version of the event log's schema, the "v" of every line. It changes when what a key or a value means does, not when a key or a value is added: a reader leaves out the keys and the values it does not know.
Variables ¶
This section is empty.
Functions ¶
func Sanitize ¶
Sanitize makes text from elsewhere, a remote line or an error, safe to show on one line of a terminal, in at most max bytes; max of zero or less sets no bound.
A carriage return is first applied the way a terminal shows it: it goes back to the start of the line and what follows overwrites what was there, so "50%\r100%" reads "100%", "abcdef\r12" reads "12cdef", and a line that ends in "\r\n" loses nothing. What is left is escaped by termtext.EscapeCell, the one escaper, which shows every other control character, an escape sequence's introducer, a bidirectional control, a newline and bytes that are not UTF-8 as a visible escape such as \x1b. The result is cut on a rune boundary.
func Suspend ¶
Suspend takes every display off the terminal, for a question to be asked there, and returns once they are all off. Calling the function it returns puts them back; calling that again does nothing. Suspensions may nest, and without a Bus in ctx nothing happens.
func Tee ¶
Tee returns a writer that writes to w, and cuts what it writes into lines on the way.
Each complete line goes to parse, when it is not nil, with its "\n" and a "\r" before it taken off, from the goroutine that writes; the tees of a command's two streams may call it at the same time. A parser sees only lines that ended: a line cut off by the end of the output, or longer than 64 KiB, is none it is given.
When the innermost span in ctx has ShowLines and a sink wants lines, they also go to the sinks as TypeLine events, sanitised and rate limited: a burst of 20, then one each 100ms. A line that finds no place waits for the next one, in place of the line that waited before it, which is counted as dropped; so the newest line is never lost, and is sent when its place comes, whether another line comes or not. A line that does not end is sent in pieces of 4 KiB, and what is left of it when the span ends is sent before the End.
Tee returns w itself when nothing needs the lines. The lines never fail a write: what Write returns is what w returned.
Types ¶
type Bus ¶
type Bus struct {
// contains filtered or unexported fields
}
Bus hands the events of one command's spans to its sinks. It is safe for concurrent use: every event is numbered and delivered under one lock, so each sink sees the same order.
func (*Bus) Close ¶
func (b *Bus) Close()
Close ends every span still open as canceled, "not finished", the innermost first, and resumes a display still suspended. Nothing is sent after Close; the sinks are not closed, which is for whoever made them to do once Close has returned. Closing a closed Bus does nothing.
func (*Bus) TraceContext ¶
func (b *Bus) TraceContext() TraceContext
TraceContext returns the trace the Bus's spans belong to, and where it came from.
type Class ¶
type Class uint8
Class says in a word why a span failed, for a display to group failures by. Classify tells it from the error.
const ( // ClassNone is a span that did not fail. ClassNone Class = iota // ClassTarget is a target that answered and said no, such as a // command that exited non-zero. ClassTarget // ClassTransport is a host that could not be reached or kept. ClassTransport // ClassTimeout is work that ran out of time. ClassTimeout // ClassAuth is an account that was refused. ClassAuth // ClassPin is a certificate that does not match the one pinned. ClassPin // ClassUsage is a request refused before anything was contacted. ClassUsage // ClassCanceled is work that was interrupted. ClassCanceled )
func Classify ¶
Classify tells why work failed from its error. The first rule that applies wins:
- the first error in the chain that is a Classifier, unless it answers ClassNone;
- context.Canceled is ClassCanceled;
- context.DeadlineExceeded, or an error that reports Timeout, such as a network timeout, is ClassTimeout;
- what fallback says of the error, the program's own rule, such as one that reads the exit code the error asks for; a nil fallback says ClassTarget.
A nil error is ClassNone, and fallback is not asked.
An error that sums up the failures of many targets is best a Classifier of its own, since the first of its targets' errors that says a class is no more the whole's than any other.
type Classifier ¶
type Classifier interface {
ProgressClass() Class
}
Classifier is an error that says its own Class, such as a certificate that does not match its pin or an account a service processor refused. ClassNone leaves the error to the rules of Classify.
type Count ¶
type Count struct {
Span SpanID
Name string
Flags Flags
// Total is the span's Total, the targets it expects.
Total int
// Done counts the targets that ended below, however they ended, and
// the Total of every batch or Fold step below that was left out.
// Failed, Canceled and Skipped count those that ended so.
Done, Failed, Canceled, Skipped int
// Running counts the targets below that are running. Queued counts
// those that wait for their turn, and the Total of every batch below
// that waits for its own.
Running, Queued int
// Targets counts the targets that started below, queued or running.
Targets int
// Batch is the place, "i/n", of the batch below that ran last, or of
// the span itself when it is a batch.
Batch string
// Waits counts the waits open below, such as a pause between batches.
Waits int
}
Count is where the targets below a step or a batch that counts them stand.
type Event ¶
type Event struct {
// Seq numbers the events of a Bus from 1, with no gaps: the order in
// which every sink sees them.
Seq uint64
Time time.Time
Type Type
// Span is the span the event is about, and Parent the span it was
// started under; zero for the root. A TypeSuspend or TypeResume names
// the span it was asked for under, if any.
Span, Parent SpanID
Kind Kind
// Name says what the span is, in few words: "ssh", "redfish",
// "reset the machines", or a target's name.
Name string
Flags Flags
// State is the span's state once the event has happened.
State State
// Fields are the span's fields once the event has happened.
Fields
// Status, Class and Err say how a TypeEnd ended; Err is one line.
Status Status
Class Class
Err string
// Stream and Text are the line of a TypeLine, sanitised.
Stream Stream
Text string
// Dropped counts the lines the sinks were not sent: on a TypeLine,
// those left out since the span's previous line, and on a TypeEnd, all
// the span's.
Dropped int
}
Event is one change to a span, or a suspension of the displays. It is plain data: no errors, buffers or maps, so a sink may keep it as it is.
type Fields ¶
type Fields struct {
// Node is what a display folds finished targets by: the node, the
// service processor, the role, the name or the port. It may be a node
// set, such as the nodes of a batch.
Node string
// Host is the address the work goes to, and Role its host role.
Host, Role string
// Total is how many targets to expect below a step or a batch. It
// only ever grows: a smaller Total given later is ignored.
Total int
// Limit is how many of those targets are worked on at once.
Limit int
// Batch is "i/n", the place of a batch among its step's.
Batch string
// Message is one short line for a display, such as the question a
// confirmation asks.
Message string
// Method and Path are the request of a Redfish call, and HTTPStatus
// its answer.
Method, Path string
HTTPStatus int
// Cache says where a lookup was answered from: "hit", "miss",
// "memory" or "disk".
Cache string
// Source is the kind of source a secret or a credential was read
// from, such as "age", "sops", "prompt" or "command"; never the value.
Source string
// Timeout is the bound of a call, or the length of a wait.
Timeout time.Duration
// Exit is the exit code of a remote command, nil when there was none.
Exit *int
}
Fields is the whole vocabulary a span can say about itself. There is no bag of free-form attributes: a value without a field here cannot reach a sink, and so reaches no log or exporter either.
type Flags ¶
type Flags uint8
Flags tell a display how to show a span.
const ( // Hidden is plumbing, drawn only when it fails or takes long. A span // started under a Hidden one is Hidden too. Hidden Flags = 1 << iota // Fold marks a step whose finished targets a display folds into node // sets. A Fold step with no Fold step above it is where a counter // counts: its Total is what the counter expects. Fold // ShowLines lets the output of the calls below be shown as it // arrives, for exec, where the output is the product. A span started // under one shows lines too. ShowLines // DryRun marks the command of a dry run, and a call a dry run only // recorded. It is not passed down. DryRun )
type Kind ¶
type Kind uint8
Kind is the level of the tree a span is on.
const ( // KindCommand is the command being run, the root of the tree. KindCommand Kind = iota + 1 // KindStep is a named phase of a command, such as "reset the // machines". A step with Fold is where a pool's targets are counted. KindStep // KindBatch is one of the batches a staggered action runs in turn. KindBatch // KindTarget is one node, service processor, role, name or port that // a step works on. KindTarget // KindCall is one request made for a target: an ssh command, a // Redfish request, a copy, a lookup. KindCall // KindWait is time spent waiting on purpose: the confirmation, the // pause between batches. KindWait )
type LineSink ¶
type LineSink interface {
WantsLines() bool
}
LineSink is a Sink that may ask for the lines of output, which are only produced when a sink asks. The Bus asks once, when it is made.
type Log ¶
type Log struct {
// contains filtered or unexported fields
}
Log is a sink that writes the events of a Bus as JSON, one line each: an event log, for a bug report, a test, or a converter to another tracing system.
The first line is the run, the trace its events belong to, where the trace came from when another program handed it on, and the program and its version that wrote it, as LogOptions name them:
{"v":1,"type":"trace","run":"5d0c…a1f3","trace":"4bf9…4736","parent":"00f067aa0ba902b7","traceFlags":"01","traceState":"rojo=00f067aa0ba902b7","version":"v0.4.0"}
and every line after it one event, with the run and the trace again, its Seq, Time and Type, the span's id and its parent's as 16 hexadecimal digits, its Kind, Name, Flags and State, the Fields it has, and how it ended:
{"v":1,"run":"5d0c…a1f3","trace":"4bf9…4736","seq":7,"time":"2026-09-26T12:00:03.000000000Z","type":"end","span":"9f3c…0007","parent":"9f3c…0002","kind":"target","name":"exe0002","state":"ended","node":"exe0002","host":"exe0002.hpc.example.org","status":"failed","class":"transport","err":"…"}
The run tells the lines of one Log from those of others appending to the same file, which may share the trace. A Timeout is in seconds. A key whose value is zero or empty is left out. A line of output is written without its text, which never leaves the process: the event says only which stream it came from and how many lines before it were not sent; and since the log asks for no lines, there are line events only while a display asks for them.
The lines are written by a goroutine of the log's own, never under the Bus's lock, in pieces of whole lines, so that the lines of runs appending to one file at once do not cut into each other: once 64 KiB wait, as a step, a batch or the command ends, and a second after a line came at the latest, so that a log followed as it grows, or one of a run killed, falls little behind. A write that fails stops the log, and so does a writer that falls 8 MiB behind, a pipe whose reader has stopped: the log never holds the work up. Close writes what is left, waiting five seconds at most, and says why the log stops short when it does.
func NewLog ¶
func NewLog(w io.Writer, o LogOptions) *Log
NewLog returns a Log that writes to w, and starts the goroutine that writes; Close stops it.
func (*Log) Begin ¶
func (l *Log) Begin(tc TraceContext)
Begin writes the trace the events belong to, the log's first line.
func (*Log) Close ¶
Close writes what is left of the log, once the Bus is closed, waiting CloseWait at most, and returns the first error the log met: nothing after it was written. The writer is not closed; that is for whoever opened it to do. Closing a closed Log only says so again.
func (*Log) WantsLines ¶
WantsLines says that the log asks for no lines of output: it never writes their text.
type LogOptions ¶
type LogOptions struct {
// Program names the program that writes the log, which its first line
// names as "program"; empty leaves the key out.
Program string
// Version is the version of the program that writes the log, which its
// first line names.
Version string
// Run names the run on every line; empty draws 16 hexadecimal digits
// at random.
Run string
// FlushEvery is how long a line is kept at most before it is written;
// zero is a second.
FlushEvery time.Duration
// CloseWait is how long Close waits for what is left to be written;
// zero is five seconds.
CloseWait time.Duration
}
LogOptions configure a Log.
type Option ¶
type Option func(*options)
Option sets what a span says about itself when it starts, changes or ends.
type Options ¶
type Options struct {
// Sinks receive every event, in the order given.
Sinks []Sink
// Now is the clock the events are stamped with; nil is time.Now.
Now func() time.Time
// Trace is the trace the spans belong to; zero draws one at random.
Trace TraceID
// Parent, TraceFlags and TraceState say where Trace came from when
// another program handed it on, as ParseTraceContext reads them: the
// span of that program's the work runs under, the trace flags and
// the tracestate. They are recorded, for an event log, and change
// nothing else; without a Trace they are ignored.
Parent SpanID
TraceFlags byte
TraceState string
// PanicLog receives the stack of a sink that panicked, the front
// end's diagnostics; nil is the process's standard error.
PanicLog io.Writer
// Program names the program in the line that says a sink panicked,
// "clusterctl: …", so that it is not read as a line of the work's;
// empty leaves the name out.
Program string
// Classify is the fallback of the classes End gives the errors of
// spans, asked for an error that none of Classify's first three rules
// fits, such as a program's rule for its exit codes; nil is
// ClassTarget.
Classify func(error) Class
}
Options configure a Bus.
type Sink ¶
type Sink interface {
Handle(Event)
}
Sink receives the events of a Bus, one at a time, in Seq order, while the Bus is locked. It only updates memory, never blocks and never calls the Bus back; drawing happens on the sink's own time. A sink that panics is removed from the Bus.
type Span ¶
type Span struct {
// contains filtered or unexported fields
}
Span is one unit of work. A nil *Span is one nobody watches, and every method of it does nothing. The methods are safe for concurrent use.
func Start ¶
Start begins a span under the innermost one ctx carries, and returns a context that carries the new span along with it. The span is running unless Queued is given. Without a Bus in ctx, once it is closed, or under a span that has ended, Start returns ctx itself and a nil span: what a worker starts after its target was ended for it, by the end of its step or of the command, belongs to nothing still open, and would outlive the span its ending ended.
func (*Span) End ¶
End ends a span with the outcome of its work: ok for a nil error, otherwise failed or canceled as Classify tells from err, with the Bus's Options.Classify as its fallback, and err's text becomes the span's one-line Err. The options set the fields that are known only at the end, such as Exit. Only the first End or Skip of a span counts. Spans started under it that are still open end first, as canceled, "not finished".
func (*Span) Run ¶
func (s *Span) Run()
Run marks a queued span as running, when its work takes its place in a pool. It does nothing to a span that is running or ended.
type SpanID ¶
type SpanID uint64
SpanID names a span. It is never zero, and unique within a trace; Seq, not the id, orders the events.
type Status ¶
type Status uint8
Status says how a span ended.
const ( // StatusOK is work that succeeded. StatusOK Status = iota + 1 // StatusFailed is work that failed. StatusFailed // StatusCanceled is work that was interrupted, or never started // because of an interrupt. StatusCanceled // StatusSkipped is work left out on purpose, such as a call a dry run // does not send or a batch after one that failed. StatusSkipped )
type Suspender ¶
type Suspender interface {
Suspend()
Resume()
}
Suspender is a Sink that draws on the terminal, and takes itself off it while something else asks a question there. Suspend and Resume are called outside the Bus lock, and Suspend returns once the terminal is clear: they are the only calls in which a sink may write to the terminal itself.
type Tally ¶
type Tally struct {
// contains filtered or unexported fields
}
Tally keeps count of the targets of a Bus's work, from its events, the way a display shows how far the work has got.
A step with Fold and a batch count the targets below them. A target that ends counts once in every such span above it, however it ended; a batch or a Fold step left out, skipped or canceled before any target of its own started, counts in the same spans as its Total. So a count reaches its Total once all the work it expects has ended, after an interrupt too, and never passes it: progresstest.Check holds every source to that.
The spans that count with none above them are the roots of the tally, what a counter shows: "power on" as a whole, not each of its batches.
A Tally is given every event of a Bus in order, as a sink is, and forgets a span once it has ended. It is not safe for concurrent use; a sink feeds it from Handle, under the Bus lock.
func (*Tally) Add ¶
Add counts e in. When e ends a span that counts, Add returns where its targets stood as it ended.
type TraceContext ¶
type TraceContext struct {
Trace TraceID
// Parent is the other program's span the work runs under; zero when
// the trace began with the Bus.
Parent SpanID
// Flags are the trace flags the other program gave, whose lowest bit
// says that it samples the trace.
Flags byte
// State is the tracestate the other program gave, the part of the
// trace context each tracing system keeps for itself, as it was given.
State string
}
TraceContext says which trace the spans of a Bus belong to and, when another program handed the trace on, where in it they belong: under a span of that program's, with the trace flags and the tracestate it gave. A Bus records where its trace came from, for an event log, and changes nothing else by it: a trace the other program does not sample is shown and logged all the same.
func ParseTraceContext ¶
func ParseTraceContext(traceparent, tracestate string) (tc TraceContext, ok bool)
ParseTraceContext reads the trace context another program handed on, as a traceparent and a tracestate in the W3C Trace Context format, such as the TRACEPARENT and TRACESTATE a CI job runs clusterctl with.
A traceparent is four fields of lowercase hexadecimal digits split by dashes: the version, the trace id, the parent's span id and the trace flags, as in 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. Version 00 is exactly that; a later version may add fields after a further dash, which are left out. Version ff, a trace or span id of zeros, a letter in upper case and anything else that does not fit make the traceparent invalid, and an invalid one is no trace context at all: ok is false, and the tracestate is not looked at. The tracestate is kept as it was given when it is at most 512 bytes of printable ASCII, and left out otherwise.
type TraceSink ¶
type TraceSink interface {
Begin(TraceContext)
}
TraceSink is a Sink that records the trace its events belong to, as an event log does. The Bus tells it once, when it is made, before any event.
type Type ¶
type Type uint8
Type is what an event reports.
const ( // TypeStart is a span that begins, queued or running. TypeStart Type = iota + 1 // TypeRun is a queued span whose work has started. TypeRun // TypeUpdate is a span whose Total or Message changed. TypeUpdate // TypeLine is a line of output from the work of a call. TypeLine // TypeEnd is a span that ended; Status says how. TypeEnd // TypeSuspend asks every display to take itself off the terminal, // since something is about to ask a question there. TypeSuspend // TypeResume ends a TypeSuspend. TypeResume )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package display shows the progress of a command on its standard error, from the events of its progress.Bus: the live tree, a few rows at the bottom of a terminal that show the work under way and what of it failed; the counter, one line there that says how far the work has got; plain lines, one for each thing worth a line, for a log as much as a terminal; and the summary a display leaves behind once the command has ended.
|
Package display shows the progress of a command on its standard error, from the events of its progress.Bus: the live tree, a few rows at the bottom of a terminal that show the work under way and what of it failed; the counter, one line there that says how far the work has got; plain lines, one for each thing worth a line, for a log as much as a terminal; and the summary a display leaves behind once the command has ended. |
|
Package progresstest captures the progress events of a test, draws them as a tree that does not depend on the order concurrent work happened in, and checks that they keep the promises the progress package makes to every sink.
|
Package progresstest captures the progress events of a test, draws them as a tree that does not depend on the order concurrent work happened in, and checks that they keep the promises the progress package makes to every sink. |