Documentation
¶
Overview ¶
Package sys provides read-only file mapping, CLI flag hygiene checks, keyed text redaction, run identifiers, and deterministic virtual and test clocks.
It groups zero-copy read-only file views ([Map]), flag validation (CheckArgs, ParseGoTest), keyed hostname/token redaction (Redactor, NewRedactor), run ID formatting (ID), step-driven virtual clocks (VirtualClock, NewVirtualClock), and synthetic monotonic clocks (TestClock).
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
dir, err := os.MkdirTemp("", "filemap")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
name := filepath.Join(dir, "weights.bin")
if err := os.WriteFile(name, []byte("weights"), 0o644); err != nil {
log.Fatal(err)
}
f, err := sys.Open(name)
if err != nil {
log.Fatal(err)
}
defer f.Close()
fmt.Printf("%d bytes: %s\n", f.Len(), f.Bytes())
}
Output: 7 bytes: weights
Example (Clocktest) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
// NTP slews CLOCK_MONOTONIC by -90 ppm; the device clock ticks in 32 ns.
c := sys.TestClock{SlewPPM: -90, TickNs: 32}
const t = 500_000_000 // 0.5 s
fmt.Println(c.Raw(t), c.Mono(t), c.Device(t+31))
}
Output: 500000000 499955000 500000000
Example (Redact) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
r := sys.NewRedactor([]byte("example key 0123"), []string{"gpu-node-17"}, nil)
out := r.Replace([]byte(`{"span":"step","peer":"10.1.2.3","note":"ran on gpu-node-17"}`))
fmt.Printf("%s\n", out)
fmt.Println(r.Scan(out))
}
Output: {"span":"step","peer":"[ipv4-b1ef73dc]","note":"ran on [site-963ee284]"} map[]
Example (Runid) ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
settings, err := sys.SumJSON(map[string]any{"chunk_tokens": 512})
if err != nil {
fmt.Println(err)
return
}
a := sys.ID{Commit: strings.Repeat("a", 40), Settings: settings, Arch: "sm_89"}
b := a
b.Settings, _ = sys.SumJSON(map[string]any{"chunk_tokens": 1024})
fmt.Println(a.Digest() == b.Digest())
for _, c := range sys.Diff(a, b) {
fmt.Println(c.Field)
}
}
Output: false settings
Example (Virtualclock) ¶
This example bounds a wait for a flag that is never set. With a 1µs step and a 1ms budget the wait gives up after the same number of polls on any host.
package main
import (
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
c := sys.NewVirtualClock(time.Microsecond)
ready := func() bool { return false }
budget := uint64(time.Millisecond)
polls := 0
for start := c.Now(); !ready(); polls++ {
if c.Now()-start > budget {
break
}
}
fmt.Println("gave up after", polls, "polls at", c.Elapsed())
}
Output: gave up after 1000 polls at 1.002ms
Index ¶
- func Build() (commit string, modified bool)
- func HostValues() []string
- func Load(ctx context.Context, t Target, k Kind, pkg string) (map[string]Set, error)
- func LoadKey(file string) ([]byte, error)
- func ParseGoTest(args []string) (GoTest, []Problem)
- func ReadDenyFile(file string) ([]string, error)
- func Sum(r io.Reader) (string, error)
- func SumJSON(v any) (string, error)
- func Wall() func() uint64
- type Change
- type File
- type GoTest
- type Hit
- type Host
- type ID
- type Kind
- type Problem
- type RateStep
- type Redactor
- type Set
- type Target
- type TestClock
- type VirtualClock
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Build ¶
Build returns the VCS revision the running binary was built from and whether its tree had uncommitted changes. The revision is empty when the build recorded none. A modified tree's revision does not identify the source; set ID.TreeHash too.
func HostValues ¶
func HostValues() []string
HostValues returns the literal values of this host that identify it: its name, short and full, and the current user's name and home directory, from the system and from USER, LOGNAME and HOME.
func Load ¶
Load returns the flags of the binary of kind k built from pkg for t, keyed by import path; pkg may be a pattern such as ./x/... that names several packages. A package with no test files has no test binary and no Test set. A Command's set holds every flag its source registers, on flag.CommandLine or on any FlagSet. A Test set holds the flags registered on flag.CommandLine by the package, its tests, the testing package and every non-standard package they import.
func LoadKey ¶
LoadKey returns the key in file, a hex string of at least 16 bytes. If file does not exist, LoadKey creates it with a new random 32-byte key, readable only by its owner, so later runs share the key and the tokens for equal values stay equal. If file is "", the key is random and lasts only as long as the caller keeps it.
func ParseGoTest ¶
ParseGoTest splits args, the arguments after "go test", and reports the flags placed where go test fails on them: an unknown flag before the package list, which go test reads as a path.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
// A test flag before the package list is a mistake go test reports
// only on the GPU host, as a missing package.
_, probs := sys.ParseGoTest(strings.Fields("-count=1 -update-census ./x/cudasass"))
for _, p := range probs {
fmt.Println(p)
}
g, _ := sys.ParseGoTest(strings.Fields("-count=1 ./x/cudasass -update-census -args -v"))
fmt.Printf("packages %q, to the binary %q, after -args %q\n", g.Packages, g.Binary, g.Args)
}
Output: -update-census: unknown to go test before the package list, where go test cannot parse it; move it after the packages or after -args packages ["./x/cudasass"], to the binary ["-update-census"], after -args ["-v"]
func ReadDenyFile ¶
ReadDenyFile returns the deny terms in file, one per line. Blank lines and lines beginning with # are skipped.
Types ¶
type Change ¶
A Change is one field that differs between two IDs.
type File ¶
type File struct {
// contains filtered or unexported fields
}
A File is a read-only view of a whole file's contents. The zero value is not usable; construct one with Open.
func Open ¶
Open maps the named file read-only. An empty file or a directory is an error: neither can be mapped.
func (*File) Bytes ¶
Bytes returns the file's contents. The slice must not be written, and it is invalid after Close. Bytes returns nil after Close.
type GoTest ¶
type GoTest struct {
Flags []string // go test's own, build and test flags, with their values
Packages []string // the package list
Binary []string // flags after the package list that go test passes to every test binary
Args []string // everything after -args
Tags string // the -tags value, if any
Dir string // the -C value, if any
}
A GoTest is a go test command line split as go test splits it.
type Host ¶
type Host struct {
OS string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
CPUs int `json:"cpus,omitempty"`
}
Host identifies the class of machine a run used.
func CurrentHost ¶
func CurrentHost() Host
CurrentHost returns the host class of the running process.
type ID ¶
type ID struct {
Commit string `json:"commit,omitempty"` // source revision
TreeHash string `json:"tree_hash,omitempty"` // source tree built, including uncommitted changes
Weights string `json:"weights,omitempty"` // model weights
Config string `json:"config,omitempty"` // model configuration
Settings string `json:"settings,omitempty"` // run settings, such as server flags
Plan string `json:"plan,omitempty"` // execution plan, such as a launch schedule
Modules []string `json:"modules,omitempty"` // loaded device module images, in any order
Arch string `json:"arch,omitempty"` // device architecture, such as "sm_89"
Driver string `json:"driver,omitempty"` // driver version
Host Host `json:"host"`
}
An ID identifies the inputs of one run. Digest fields hold lowercase hex SHA-256 digests; Commit and TreeHash hold a 40- or 64-digit git object name. An empty field is unknown.
func (ID) Digest ¶
Digest returns a hex SHA-256 over every field of id. The order of Modules does not affect it.
func (ID) Missing ¶
Missing returns the names of the fields of id that are unknown.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
id := sys.ID{Arch: "sm_89", Driver: "580.173.02"}
fmt.Println(id.Missing())
}
Output: [commit tree_hash weights config settings plan modules host.os host.arch host.cpus]
type Problem ¶
type Problem struct {
Flag string // the argument, such as -update
Package string // the package whose binary rejects it, if any
Reason string
}
A Problem is a flag a command line uses wrongly.
func CheckArgs ¶
CheckArgs reports the flags in args that s does not define. A value following a non-boolean flag is skipped, and so is everything after the first argument that is not a flag, or after "--", where a flag package stops parsing.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
s := sys.Set{"json": true, "out": false}
fmt.Println(sys.CheckArgs(s, []string{"-json", "-out", "facts.json", "-compile=false"}))
}
Output: [-compile=false: flag provided but not defined]
func CheckGoTest ¶
CheckGoTest checks a go test command line, the arguments after "go test", run in t.Dir: the placements ParseGoTest reports, then the flags go test passes to each package's test binary against that binary's flags. A package flag go test takes for itself, such as -n or -v, is reported unless it follows -args. Packages are resolved with t, and the line's -tags and -C apply.
type Redactor ¶
type Redactor struct {
// contains filtered or unexported fields
}
A Redactor replaces identifiers with keyed hashes and scans for what must not leave the site. A Redactor is not safe for concurrent use.
func NewRedactor ¶
New returns a Redactor whose tokens are keyed by key. Site values are literal strings from this host, such as its name and the paths of its files, that must not leave it; values shorter than three bytes are ignored. Deny terms are never replaced: Scan reports them, matching case-insensitively. A Redactor used only to Scan needs no key.
func (*Redactor) Replace ¶
Replace returns data with every identifier and site value replaced by a token of the form [class-xxxxxxxx], a keyed hash of the value, so equal values get equal tokens. Replacing a token leaves it unchanged.
func (*Redactor) Scan ¶
Scan counts what must not appear in data, by class: identifiers that Replace would replace, secrets such as private keys and API tokens, site values, and deny terms. Deny terms match as case-insensitive substrings. Site values of six or more bytes do too, wider than replace's whole-word rule; shorter ones (a user name such as "dev") match whole words only, or every "device" would fail the scan.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
r := sys.NewRedactor(nil, nil, []string{"ProjectRedwood"})
fmt.Println(r.Scan([]byte("codename projectredwood\n-----BEGIN OPENSSH PRIVATE KEY-----")))
}
Output: map[deny:1 secret:1]
func (*Redactor) ScanTree ¶
ScanTree scans every file and file name under dir, and returns the hits sorted by file and class, and the number of files. A file whose name holds a hit is reported as "(file name withheld)". Every file under dir must be a regular file.
func (*Redactor) SiteValues ¶
SiteValues returns the site values r replaces, after New dropped short and duplicate values, longest first.
type Set ¶
A Set is the flags a binary defines, by name. The value reports whether the flag is a boolean, which may be given without a value.
type Target ¶
type Target struct {
Dir string // directory go list runs in, inside the module
GOOS string // empty means the host's
GOARCH string // empty means the host's
Env []string // more environment, such as CGO_ENABLED=0 or GOFLAGS=-tags=cuda
Tags string // the -tags build flag, if any
}
A Target is the build a binary's flags are read for.
type TestClock ¶
type TestClock struct {
// RawBase, MonoBase and DeviceBase are the readings at t = 0.
RawBase, MonoBase, DeviceBase uint64
// SlewPPM is CLOCK_MONOTONIC's constant rate offset from the raw
// clock in parts per million, such as an NTP frequency correction.
SlewPPM float64
// DecayPPM is a further rate offset at t = 0 that decays as
// exp(-t/DecayTauNs), as the kernel slews out a pending NTP offset.
// It applies only when DecayTauNs > 0.
DecayPPM float64
DecayTauNs float64
// Steps change CLOCK_MONOTONIC's rate offset at given times, as an
// NTP frequency update does.
Steps []RateStep
// DevicePPM is the device clock's rate offset from the raw clock.
DevicePPM float64
// TickNs is the device clock's quantum: readings are rounded down to
// a multiple of it. When 0, readings are not quantized.
TickNs uint64
}
Clock is a synthetic CLOCK_MONOTONIC_RAW, CLOCK_MONOTONIC and device clock. Its methods take the true time t in nanoseconds from the clock's origin, which may be negative, and are pure functions of it.
The zero Clock is usable: all three clocks read t.
func (TestClock) Mono ¶
Mono returns the CLOCK_MONOTONIC reading at t: MonoBase plus t plus the integral of the rate offset from 0 to t, rounded to the nearest nanosecond.
func (TestClock) SlewAt ¶
SlewAt returns CLOCK_MONOTONIC's rate offset from the raw clock at t, in parts per million.
func (TestClock) WithStep ¶
WithStep returns a copy of c with a rate step of ppm at atNs added.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/sys"
)
func main() {
// An NTP frequency update at 1 s moves the slew from -90 to -20 ppm.
c := sys.TestClock{SlewPPM: -90}.WithStep(1_000_000_000, 70)
fmt.Println(c.SlewAt(0), c.SlewAt(2_000_000_000), c.Mono(2_000_000_000))
}
Output: -90 -20 1999890000
type VirtualClock ¶
type VirtualClock struct {
// contains filtered or unexported fields
}
A Clock is a virtual clock. It is safe for concurrent use: every read, from any goroutine, advances the one shared time.
func NewVirtualClock ¶
func NewVirtualClock(step time.Duration) *VirtualClock
New returns a clock at time zero that advances by step on each read. It panics if step is not positive, which is a programming error.
func (*VirtualClock) Advance ¶
func (c *VirtualClock) Advance(d time.Duration)
Advance moves the clock forward by d without counting as a read. Negative d is ignored: the clock never goes back.
func (*VirtualClock) Elapsed ¶
func (c *VirtualClock) Elapsed() time.Duration
Elapsed returns the clock's time without advancing it.
func (*VirtualClock) Now ¶
func (c *VirtualClock) Now() uint64
Now advances the clock by its step and returns the new time in nanoseconds.
func (*VirtualClock) Step ¶
func (c *VirtualClock) Step() time.Duration
Step returns the amount each read advances the clock.