From 1eb4aef77d9076ae6ca5680fa9678cb8fb2ba2a7 Mon Sep 17 00:00:00 2001 From: CMGS Date: Tue, 3 Nov 2026 01:12:00 +0800 Subject: [PATCH] review: an own-line Go comment starts uppercase /code sets the case by position: own-line uppercase like godoc, trailing lowercase. Comments only: a comment naming the declaration below it, and a product name, keep their case. e2e is left out. --- mcp/tools.go | 2 +- sandboxd/egress/ca.go | 6 +++--- sandboxd/egress/intercept.go | 6 +++--- sandboxd/egress/proxy.go | 6 +++--- sandboxd/engine/installca.go | 4 ++-- sandboxd/engine/portconn.go | 2 +- sandboxd/engine/volume.go | 2 +- sandboxd/outbound/dial.go | 2 +- sandboxd/outbound/outbound.go | 2 +- sandboxd/pool/archive.go | 20 ++++++++++---------- sandboxd/pool/capture.go | 2 +- sandboxd/pool/checkpoint.go | 12 ++++++------ sandboxd/pool/claim.go | 20 ++++++++++---------- sandboxd/pool/env.go | 2 +- sandboxd/pool/hibernate.go | 20 ++++++++++---------- sandboxd/pool/liveness.go | 10 +++++----- sandboxd/pool/reconcile.go | 28 ++++++++++++++-------------- sandboxd/pool/refill.go | 14 +++++++------- sandboxd/pool/remove.go | 4 ++-- sandboxd/pool/setpools.go | 8 ++++---- sandboxd/pool/stats.go | 2 +- sandboxd/pool/telemetry.go | 2 +- sandboxd/pool/template.go | 6 +++--- sandboxd/pool/volume.go | 14 +++++++------- sandboxd/server/exec.go | 2 +- sandboxd/server/preview.go | 10 +++++----- sandboxd/server/relay.go | 6 +++--- sandboxd/store/dir/dir.go | 8 ++++---- sandboxd/store/peer/peer.go | 4 ++-- sandboxd/store/peer/probe.go | 4 ++-- sandboxd/store/peer/transport.go | 4 ++-- sandboxd/store/s3/s3.go | 8 ++++---- sdk/go/port.go | 2 +- sdk/go/proc.go | 2 +- sdk/go/sandbox.go | 4 ++-- sdk/go/upgrade.go | 2 +- 36 files changed, 126 insertions(+), 126 deletions(-) diff --git a/mcp/tools.go b/mcp/tools.go index 70921fe7c..209682d7b 100644 --- a/mcp/tools.go +++ b/mcp/tools.go @@ -109,7 +109,7 @@ func toolCreateSandbox(ctx context.Context, s *server, raw jsontext.Value) (stri if args.TTLSeconds < 0 { return "", fmt.Errorf("ttl_seconds must not be negative, got %d", args.TTLSeconds) } - // an agent session outlives the node's 5-minute default, and nothing renews a lease + // An agent session outlives the node's 5-minute default, and nothing renews a lease ttl := cmp.Or(time.Duration(args.TTLSeconds)*time.Second, defaultToolTTL) opts := []sandbox.Option{sandbox.WithTimeout(ttl)} if args.Net != "" { diff --git a/sandboxd/egress/ca.go b/sandboxd/egress/ca.go index bced95d2b..fc6e414c6 100644 --- a/sandboxd/egress/ca.go +++ b/sandboxd/egress/ca.go @@ -57,7 +57,7 @@ func LoadCA(rootCertPEM, interCertPEM, interKeyPEM []byte) (*CA, error) { if err = inter.CheckSignatureFrom(root); err != nil { return nil, fmt.Errorf("intermediate not signed by root: %w", err) } - // reject a self-signed intermediate: it would put the root key on the node. + // Reject a self-signed intermediate: it would put the root key on the node. if inter.CheckSignatureFrom(inter) == nil { return nil, fmt.Errorf("intermediate must not be a self-signed root") } @@ -68,7 +68,7 @@ func LoadCA(rootCertPEM, interCertPEM, interKeyPEM []byte) (*CA, error) { if err != nil { return nil, fmt.Errorf("generate leaf key: %w", err) } - // fingerprint the whole file: CertPEM bakes it verbatim. + // Fingerprint the whole file: CertPEM bakes it verbatim. sum := sha256.Sum256(rootCertPEM) return &CA{ rootPEM: rootCertPEM, @@ -93,7 +93,7 @@ func (c *CA) SignLeaf(host string) (*tls.Certificate, error) { return nil, err } now := time.Now() - // guests reject a chain whose leaf outlives its intermediate. + // Guests reject a chain whose leaf outlives its intermediate. notAfter := now.Add(leafValidity) if notAfter.After(c.interCert.NotAfter) { notAfter = c.interCert.NotAfter diff --git a/sandboxd/egress/intercept.go b/sandboxd/egress/intercept.go index 787197fb0..5124fb981 100644 --- a/sandboxd/egress/intercept.go +++ b/sandboxd/egress/intercept.go @@ -48,7 +48,7 @@ func (p *Proxy) serveIntercept(w http.ResponseWriter, r *http.Request, host stri if _, err := io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { return } - // a guest that never sends a ClientHello would pin this goroutine until the sandbox dies. + // A guest that never sends a ClientHello would pin this goroutine until the sandbox dies. _ = client.SetDeadline(time.Now().Add(interceptTimeout)) tlsConn := tls.Server(utils.WithBuffered(client, brw.Reader), cfg) if err := tlsConn.HandshakeContext(r.Context()); err != nil { @@ -67,7 +67,7 @@ func (p *Proxy) serveIntercept(w http.ResponseWriter, r *http.Request, host stri func (p *Proxy) leafFor(host string) (*tls.Certificate, error) { p.leafMu.Lock() defer p.leafMu.Unlock() - // a leaf clamped to the intermediate's own end has nothing to renew into + // A leaf clamped to the intermediate's own end has nothing to renew into if crt, ok := p.leaves[host]; ok && (time.Now().Before(crt.Leaf.NotAfter.Add(-leafRenewBefore)) || !crt.Leaf.NotAfter.Before(p.ca.interCert.NotAfter)) { return crt, nil } @@ -97,7 +97,7 @@ func (h *interceptHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { p.relay(w, r, ev, rule, route, true, func(out *http.Request) { out.URL.Scheme = "https" out.URL.Host = h.authority - // keep the guest's Host when it names the CONNECT host: SigV4 signing breaks on a rewrite. + // Keep the guest's Host when it names the CONNECT host: SigV4 signing breaks on a rewrite. if inner, _, _ := hostPort(r.Host, 0); !strings.EqualFold(inner, h.host) { out.Host = h.authority } diff --git a/sandboxd/egress/proxy.go b/sandboxd/egress/proxy.go index d99fc8812..cf7f18737 100644 --- a/sandboxd/egress/proxy.go +++ b/sandboxd/egress/proxy.go @@ -170,7 +170,7 @@ func New(policy Evaluator, secrets Secrets, ca *CA, router Router, audit AuditFu holder: holder, conns: map[net.Conn]struct{}{}, } - // the stdlib default of 2 idle conns per host re-dials bursty same-host traffic. + // The stdlib default of 2 idle conns per host re-dials bursty same-host traffic. pools := &connPools{tr: &http.Transport{DialContext: direct, MaxIdleConns: maxIdleConns, MaxIdleConnsPerHost: 8, IdleConnTimeout: idleConnTimeout}, routed: map[routeKey]*http.Transport{}} if ca != nil { pools.mitm = pools.tr.Clone() @@ -314,7 +314,7 @@ func (p *Proxy) serveConnect(w http.ResponseWriter, r *http.Request) { // tunnelDecision treats an inject rule as a plain one when injects is false. func (p *Proxy) tunnelDecision(host string, port uint16, injects bool) (decision Decision, intercept bool) { - // host-gate interception: the tunnel's CONNECT verb is not the request method. + // Host-gate interception: the tunnel's CONNECT verb is not the request method. if p.ca != nil { if rule, d := p.policy.EvalHost(host, port); d == DecisionAllow && (rule.Intercept == InterceptAlways || rule.Intercept == InterceptInject && injects && p.holdsCredential(host)) { @@ -374,7 +374,7 @@ func (p *Proxy) relay(w http.ResponseWriter, r *http.Request, ev Event, rule Rul var sc *scrubber ev.Injected, sc = p.inject(rule, out, ev.Host, mitm) if sc != nil { - // the scrub needs the whole body uncompressed. + // The scrub needs the whole body uncompressed. for _, h := range []string{"Accept-Encoding", "Range", "If-Range"} { out.Header.Del(h) } diff --git a/sandboxd/engine/installca.go b/sandboxd/engine/installca.go index da0d42791..4c0da7717 100644 --- a/sandboxd/engine/installca.go +++ b/sandboxd/engine/installca.go @@ -46,7 +46,7 @@ func (e *Engine) silkdWriteFile(ctx context.Context, vsockSocket, path string, m return err } defer s.close() - // a send racing the guest's early answer+close hits EPIPE; prefer the buffered verdict. + // A send racing the guest's early answer+close hits EPIPE; prefer the buffered verdict. sendErr := func() error { if serr := s.send(wire.FsWrite{Path: path, Mode: &mode}); serr != nil { return serr @@ -85,7 +85,7 @@ func (e *Engine) silkdOutput(ctx context.Context, vsockSocket string, argv ...st defer s.close() sendErr := s.send(wire.Exec{Argv: argv, Env: map[string]string{"PATH": guestExecPATH}}) if sendErr == nil { - // a child exiting without reading stdin races this close; prefer the buffered exit frame. + // A child exiting without reading stdin races this close; prefer the buffered exit frame. sendErr = s.send(wire.StdinClose{}) } var out, stdout []byte diff --git a/sandboxd/engine/portconn.go b/sandboxd/engine/portconn.go index 053121515..45c662396 100644 --- a/sandboxd/engine/portconn.go +++ b/sandboxd/engine/portconn.go @@ -73,7 +73,7 @@ func (g *guestPortConn) Write(p []byte) (int, error) { written := 0 for len(p) > 0 { n := min(len(p), wire.PortWriteChunk) - // the hot relay path reuses one buffer instead of allocating per chunk. + // The hot relay path reuses one buffer instead of allocating per chunk. g.wbuf = wire.AppendBulkRequest(g.wbuf, "data", p[:n]) if _, err := g.Conn.Write(g.wbuf); err != nil { return written, err diff --git a/sandboxd/engine/volume.go b/sandboxd/engine/volume.go index a5e2cdbe9..e7ba47dff 100644 --- a/sandboxd/engine/volume.go +++ b/sandboxd/engine/volume.go @@ -132,7 +132,7 @@ func (e *Engine) findVolumeDevice(ctx context.Context, vsockSocket, name string, continue } device := "/dev/" + entry.Name - // the kernel publishes /sys/block before devtmpfs creates the node. + // The kernel publishes /sys/block before devtmpfs creates the node. if err := e.silkdOnce[*wire.Stat](ctx, vsockSocket, wire.FsStat{Path: device}); err != nil { if isNotFound(err) { return "", false, nil diff --git a/sandboxd/outbound/dial.go b/sandboxd/outbound/dial.go index 54e9cefed..6a42dbb83 100644 --- a/sandboxd/outbound/dial.go +++ b/sandboxd/outbound/dial.go @@ -96,7 +96,7 @@ func newDialer(verdict VerdictFunc) *net.Dialer { // destVerdict reports whether ip is an internal address allow re-admits; any other internal address, self included, is an error. func destVerdict(allow []egress.InternalAllow, self []netip.Addr, ip netip.Addr, port uint16) (bool, error) { ip = canonicalAddr(ip) - // after the NAT64 unwrap and before the block, so a named prefix wins + // After the NAT64 unwrap and before the block, so a named prefix wins if slices.ContainsFunc(allow, func(a egress.InternalAllow) bool { return a.Admits(ip, port) }) { return true, nil } diff --git a/sandboxd/outbound/outbound.go b/sandboxd/outbound/outbound.go index 7b38b05fd..112ef45b9 100644 --- a/sandboxd/outbound/outbound.go +++ b/sandboxd/outbound/outbound.go @@ -115,7 +115,7 @@ func (h *Host) ArmProxy(ctx context.Context, sb *types.Sandbox) error { d := h.prebound[sb.VMName] delete(h.prebound, sb.VMName) h.mu.Unlock() - // only an intercepting pool pays for the TLS transport and leaf cache + // Only an intercepting pool pays for the TLS transport and leaf cache ca := h.o.CA if !v.Intercepts(sb.PolicyKey()) { ca = nil diff --git a/sandboxd/pool/archive.go b/sandboxd/pool/archive.go index 603b60015..99eaf39a2 100644 --- a/sandboxd/pool/archive.go +++ b/sandboxd/pool/archive.go @@ -80,7 +80,7 @@ func (m *Manager) archiveOnce(ctx context.Context) { } func (m *Manager) archive(ctx context.Context, sb *types.Sandbox) error { - // must finish even if the sweep ctx is canceled, or the record diverges from the store. + // Must finish even if the sweep ctx is canceled, or the record diverges from the store. ctx = context.WithoutCancel(ctx) defer m.untrack(m.archiving, sb.ID) m.mu.Lock() @@ -98,18 +98,18 @@ func (m *Manager) archive(ctx context.Context, sb *types.Sandbox) error { if err = m.checkArchiveRow(ctx, sb.ID); err != nil { return fmt.Errorf("archive %s: registry: %w", sb.ID, err) } - // pin the ck before Publish makes it listable, or a delete would strand the claim + // Pin the ck before Publish makes it listable, or a delete would strand the claim ckID := store.CheckpointID(randHex(8)) m.mu.Lock() m.pendingCks[ckID] = struct{}{} m.mu.Unlock() defer m.untrack(m.pendingCks, ckID) - // a hibernated source is copied from its wake image, so no VM starts. + // A hibernated source is copied from its wake image, so no VM starts. ck, srcSnap, err := m.publishCheckpoint(ctx, sb, ckID, "archive", sb.Tenant, true) if err != nil { return err } - // the claim must still hold the exact snapshot the export captured, or the ck is stale + // The claim must still hold the exact snapshot the export captured, or the ck is stale sb.Transition.Lock() m.mu.Lock() if m.claimed[sb.ID] != sb || sb.HibernateSnap != srcSnap || sb.ArchiveCk != "" { @@ -152,7 +152,7 @@ func (m *Manager) archive(ctx context.Context, sb *types.Sandbox) error { if saveErr := m.store.commit(js); saveErr != nil { m.mu.Lock() var rb claimSnapshot - // a Release that landed meanwhile already deleted the claim; re-setting it would resurrect it + // A Release that landed meanwhile already deleted the claim; re-setting it would resurrect it if m.claimed[sb.ID] == sb { sb.ArchiveCk, sb.ArchiveEpoch, sb.ArchivePending, sb.ReplicaCk = "", 0, prevPending, replica sb.HibernateSnap, sb.VsockSocket, sb.VMName = snap, sock, vmName @@ -167,10 +167,10 @@ func (m *Manager) archive(ctx context.Context, sb *types.Sandbox) error { } m.counters.archives.Add(1) m.recordUsage(ctx, usage.Event{Event: "archive", ID: sb.ID, Reference: ck.ID, Tenant: sb.Tenant, Deadline: sb.Deadline}) - // disarm under Transition so a wake right after the release is not clobbered by a late disarm + // Disarm under Transition so a wake right after the release is not clobbered by a late disarm m.out.Disarm(sb.ID, true) sb.Transition.Unlock() - // the store ck is authoritative from here + // The store ck is authoritative from here m.destroy(ctx, vmName) m.dropSnap(ctx, snap) if replica != "" { @@ -181,7 +181,7 @@ func (m *Manager) archive(ctx context.Context, sb *types.Sandbox) error { // Caller holds Transition. func (m *Manager) wakeArchived(ctx context.Context, sb *types.Sandbox) (string, error) { - // egress never archives; a corrupt archived egress claim must fail closed. + // Egress never archives; a corrupt archived egress claim must fail closed. if sb.Key.Net == types.NetEgress { return "", fmt.Errorf("wake %s: egress lane cannot resume from archive", sb.ID) } @@ -227,7 +227,7 @@ func (m *Manager) wakeArchived(ctx context.Context, sb *types.Sandbox) (string, return "", fmt.Errorf("wake %s: persist claims", sb.ID) } logger := log.WithFunc("pool.wakeArchived") - // the pre-commit marker keeps a failed delete retryable after the journal update. + // The pre-commit marker keeps a failed delete retryable after the journal update. if delErr := m.ckpts.Delete(ctx, ck); delErr != nil { logger.Warnf(ctx, "delete consumed archive ck %s: %v", ck, delErr) } else { @@ -236,7 +236,7 @@ func (m *Manager) wakeArchived(ctx context.Context, sb *types.Sandbox) (string, } m.dropTombstone(ctx, sb.ID, consumed) } - // only the none lane reaches here, so there is no NIC to re-lock + // Only the none lane reaches here, so there is no NIC to re-lock if proxyErr := m.out.ArmProxy(ctx, sb); proxyErr != nil { logger.Errorf(ctx, proxyErr, "arm egress proxy %s", sb.ID) } diff --git a/sandboxd/pool/capture.go b/sandboxd/pool/capture.go index bc10cec68..dbf0713ce 100644 --- a/sandboxd/pool/capture.go +++ b/sandboxd/pool/capture.go @@ -55,7 +55,7 @@ func (m *Manager) exportSource(ctx context.Context, sb *types.Sandbox, exportDir } defer cleanup() vmName, guestEnv = sb.VMName, m.heldGuestEnv(sb) - // a fresh snapshot is this capture's alone, so dials need not wait out its export; a wake consumes a hibernate snapshot + // A fresh snapshot is this capture's alone, so dials need not wait out its export; a wake consumes a hibernate snapshot if snap != sb.HibernateSnap { sb.Transition.Unlock() } else { diff --git a/sandboxd/pool/checkpoint.go b/sandboxd/pool/checkpoint.go index d80cd293e..8ec390c6a 100644 --- a/sandboxd/pool/checkpoint.go +++ b/sandboxd/pool/checkpoint.go @@ -60,7 +60,7 @@ func (m *Manager) Checkpoint(ctx context.Context, id string, cred Cred, name, te // ClaimCheckpoint provisions a fresh claim cloned from a checkpoint, attributed to tenant. func (m *Manager) ClaimCheckpoint(ctx context.Context, ckptID string, o ClaimOptions) (*types.Sandbox, error) { - // a rejected id must not leave a lock-map entry, so resolve before recLock and quota + // A rejected id must not leave a lock-map entry, so resolve before recLock and quota ckpt, err := m.loadCheckpoint(ctx, ckptID) if err != nil { return nil, err @@ -76,7 +76,7 @@ func (m *Manager) ClaimCheckpointHeal(ctx context.Context, ckptID string, o Clai if m.healer == nil || !store.CheckpointIDRe.MatchString(ckptID) { return nil, ErrUnknownCheckpoint } - // resolving moves a guest memory image, so quota rejects a full node before that cost + // Resolving moves a guest memory image, so quota rejects a full node before that cost if err := m.overQuota(1, o.Tenant); err != nil { return nil, err } @@ -130,7 +130,7 @@ func (m *Manager) DeleteCheckpoint(ctx context.Context, ckptID, tenant string, s if err := m.ckpts.Delete(ctx, ckptID); err != nil { return fmt.Errorf("delete checkpoint: %w", err) } - // a shared backend has no per-node replicas to chase. + // A shared backend has no per-node replicas to chase. if scope == DeleteFleet && m.peerDelete != nil && !m.ckptsShared { m.peerDelete(context.WithoutCancel(ctx), ckptID) } @@ -157,7 +157,7 @@ func (m *Manager) FetchCheckpoint(ctx context.Context, ckptID string) (string, [ } return "", nil, nil, fmt.Errorf("fetch checkpoint: %w", err) } - // the read lock spans the transfer so a delete cannot pull the export from under it + // The read lock spans the transfer so a delete cannot pull the export from under it return dir, meta, unlock, nil } @@ -384,14 +384,14 @@ func validateHealedCheckpoint(staging, wantID string) error { return fmt.Errorf("healed record %s has an invalid key: %w", wantID, keyErr) } if !ckpt.Key.Capturable() { - // publishing a non-branchable key would poison the id and suppress a good owner + // Publishing a non-branchable key would poison the id and suppress a good owner return fmt.Errorf("healed record %s has a non-branchable (egress) key", wantID) } export, err := os.ReadDir(filepath.Join(staging, store.ExportDir)) if err != nil { return fmt.Errorf("healed record %s missing export dir: %w", wantID, err) } - // an export with no regular file clones to nothing; deeper content is cocoon's own format + // An export with no regular file clones to nothing; deeper content is cocoon's own format if !hasRegularFile(export) { return fmt.Errorf("healed record %s has no export content", wantID) } diff --git a/sandboxd/pool/claim.go b/sandboxd/pool/claim.go index 5d906351d..87432c1cb 100644 --- a/sandboxd/pool/claim.go +++ b/sandboxd/pool/claim.go @@ -53,7 +53,7 @@ func (m *Manager) ClaimWarm(ctx context.Context, key types.PoolKey, o ClaimOptio if err != nil { return nil, err } - // holds belong to this path until finalize; past it the sandbox carries them. + // Holds belong to this path until finalize; past it the sandbox carries them. reserved := applied defer func() { m.unreserveVolumes(reserved) }() m.mu.Lock() @@ -176,7 +176,7 @@ func (m *Manager) Renew(ctx context.Context, id string, cred Cred, ttl time.Dura m.mu.Unlock() return time.Time{}, ErrUnknownSandbox } - // an archived claim's Deadline is a retention window, not a lease: a TTL over it schedules a purge + // An archived claim's Deadline is a retention window, not a lease: a TTL over it schedules a purge if _, archiving := m.archiving[id]; sb.ArchiveCk != "" || archiving { m.mu.Unlock() return time.Time{}, ErrArchived @@ -188,7 +188,7 @@ func (m *Manager) Renew(ctx context.Context, id string, cred Cred, ttl time.Dura if err := m.store.commit(js); err != nil { m.mu.Lock() var rb claimSnapshot - // a concurrent renew that landed keeps its grant: roll back only what this call wrote + // A concurrent renew that landed keeps its grant: roll back only what this call wrote if m.claimed[id] == sb && sb.Deadline.Equal(deadline) { sb.Deadline, sb.LeaseSeconds, sb.OnExpire = prev, prevLease, prevExpire rb = m.store.set(sb) @@ -218,7 +218,7 @@ func (m *Manager) AgentSocket(id, token string) (string, error) { if sb.Replicated() && m.fence.Load().fenced { return "", ErrLeaseLost } - // no activity stamp: a control-plane poll must not keep an idle sandbox awake + // No activity stamp: a control-plane poll must not keep an idle sandbox awake return sb.VsockSocket, nil } @@ -326,7 +326,7 @@ func (m *Manager) releaseResolved(ctx context.Context, id string, sb *types.Sand logger.Errorf(ctx, saveErr, "persist release of %s", id) return fmt.Errorf("release %s: %w", id, saveErr) } - // cleanup must survive the caller hanging up; the claim is already dropped. + // Cleanup must survive the caller hanging up; the claim is already dropped. ctx = context.WithoutCancel(ctx) if ck != "" { m.purgeArchiveCk(ctx, id, ck, sb.Tenant) // archived: no local VM @@ -466,7 +466,7 @@ func (m *Manager) finalizeBatch(ctx context.Context, sbs []*types.Sandbox, ttl t if err != nil { m.mu.Unlock() for _, sb := range sbs { - // the rw mount dirtied the journal, so the clean umount is still owed + // The rw mount dirtied the journal, so the clean umount is still owed td := m.quiesceVolumes(ctx, sb) m.removeOrRetry(ctx, sb.VMName, "", td) } @@ -491,7 +491,7 @@ func (m *Manager) finalizeBatch(ctx context.Context, sbs []*types.Sandbox, ttl t return fmt.Errorf("arm egress %s: %w", sb.ID, armErr) } } - // usage lands only after the batch armed, so a rollback leaves no unterminated claim event + // Usage lands only after the batch armed, so a rollback leaves no unterminated claim event for _, sb := range sbs { m.recordUsage(ctx, usage.Event{ Event: "claim", @@ -543,7 +543,7 @@ func (m *Manager) reapOnce(ctx context.Context) { var dropped, purges []string var unrows []*types.Sandbox for id, sb := range m.claimed { - // a zero deadline means no expiry (an archived claim kept forever). + // A zero deadline means no expiry (an archived claim kept forever). if sb.Deadline.IsZero() || !now.After(sb.Deadline) { continue } @@ -557,7 +557,7 @@ func (m *Manager) reapOnce(ctx context.Context) { expired = append(expired, victim{action: reapPurge, id: id, ck: sb.ArchiveCk, tenant: sb.Tenant, deadline: sb.Deadline, sb: sb}) purges = append(purges, sb.ArchiveCk) case m.archivesAtDeadline(sb): - // archive instead of destroy, kept in m.claimed for archive() to move + // Archive instead of destroy, kept in m.claimed for archive() to move if _, busy := m.archiving[id]; busy { continue } @@ -642,7 +642,7 @@ func (m *Manager) reapOnce(ctx context.Context) { logger.Error(ctx, saveErr, "persist reap; rolled back") return } - // engine teardown can take minutes, so fan out bounded and never stall the ticker loop + // Engine teardown can take minutes, so fan out bounded and never stall the ticker loop m.runBounded(ctx, len(expired), func(ctx context.Context, i int) { v := expired[i] switch v.action { diff --git a/sandboxd/pool/env.go b/sandboxd/pool/env.go index a6f0f2f93..b31ba8f94 100644 --- a/sandboxd/pool/env.go +++ b/sandboxd/pool/env.go @@ -40,7 +40,7 @@ func (m *Manager) writeEnv(ctx context.Context, id, tenant, verb string, next fu if !ok || !tenantOwns(tenant, sb.Tenant) { return ErrUnknownSandbox } - // a guest write must not race a capture + // A guest write must not race a capture locked := sb.Transition.TryLock() if locked { defer sb.Transition.Unlock() diff --git a/sandboxd/pool/hibernate.go b/sandboxd/pool/hibernate.go index a01bcef90..97507a2f3 100644 --- a/sandboxd/pool/hibernate.go +++ b/sandboxd/pool/hibernate.go @@ -92,11 +92,11 @@ func (m *Manager) hibernateLocked(ctx context.Context, sb *types.Sandbox) error if err := m.diskErr(); err != nil { return fmt.Errorf("hibernate %s: %w", sb.ID, err) } - // a started transition must finish, or the record disagrees with the VM + // A started transition must finish, or the record disagrees with the VM ctx = context.WithoutCancel(ctx) // cocoon rejects sb.ID's underscore, so the snapshot name is VMName-based snap := hibernatePrefix + strings.TrimPrefix(sb.VMName, vmPrefix) + "-" + randHex(3) - // journal the intent first so Reconcile can adopt a hibernate whose commit never landed + // Journal the intent first so Reconcile can adopt a hibernate whose commit never landed intent, live := m.setIfLive(sb, func() { sb.PendingSnap = snap }) if !live { return ErrUnknownSandbox @@ -117,7 +117,7 @@ func (m *Manager) hibernateLocked(ctx context.Context, sb *types.Sandbox) error sb.ReaderSafe = readerSafe m.mu.Unlock() if hibErr := m.eng.Hibernate(ctx, sb.VMName, snap); hibErr != nil { - // the engine can report failure after the snapshot landed + // The engine can report failure after the snapshot landed adopted, resolveErr := m.settlePendingSnap(ctx, sb) if adopted { m.out.Disarm(sb.ID, true) @@ -137,7 +137,7 @@ func (m *Manager) hibernateLocked(ctx context.Context, sb *types.Sandbox) error m.dropSnap(ctx, snap) return ErrUnknownSandbox } - // the VM is hibernated either way, so the billing window closes here. + // The VM is hibernated either way, so the billing window closes here. m.recordHibernate(ctx, sb) m.out.Disarm(sb.ID, true) if err != nil { @@ -167,13 +167,13 @@ func (m *Manager) wakeOrRead(ctx context.Context, sb *types.Sandbox, readerOK bo return "", fmt.Errorf("wake %s: %w", sb.ID, err) } if sb.HibernateSnap == "" { - // no journal sync on this data-plane fast path; restart Reconcile heals the lag + // No journal sync on this data-plane fast path; restart Reconcile heals the lag if sb.StaleSnap != "" && m.store.synced() { m.dropStale(ctx, sb) } return sb.VsockSocket, nil } - // the egress lane never hibernates, so a hibernated one is corrupt state + // The egress lane never hibernates, so a hibernated one is corrupt state if sb.Key.Net == types.NetEgress { return "", fmt.Errorf("wake %s: egress lane cannot resume from hibernation", sb.ID) } @@ -192,7 +192,7 @@ func (m *Manager) wakeOrRead(ctx context.Context, sb *types.Sandbox, readerOK bo snap := sb.HibernateSnap restoredSock, err := m.eng.Restore(ctx, sb.VMName, snap) if err != nil { - // restore may have booted the VM before the engine errored + // Restore may have booted the VM before the engine errored m.stopVM(ctx, sb.VMName) return "", fmt.Errorf("wake %s: %w", sb.ID, err) } @@ -221,7 +221,7 @@ func (m *Manager) wakeOrRead(ctx context.Context, sb *types.Sandbox, readerOK bo return "", ErrUnknownSandbox } if err != nil { - // the lagging journal still references the snapshot, so park it for later reclaim + // The lagging journal still references the snapshot, so park it for later reclaim sb.StaleSnap = snap return "", fmt.Errorf("wake %s: persist claims: %w", sb.ID, err) } @@ -268,7 +268,7 @@ func (m *Manager) idleOnce(ctx context.Context) { m.idleSweep.Store(false) return } - // hibernates are seconds-long engine snapshots, so fan out off the housekeeping loop + // Hibernates are seconds-long engine snapshots, so fan out off the housekeeping loop go func() { defer m.idleSweep.Store(false) m.runBounded(ctx, len(victims), func(ctx context.Context, i int) { @@ -363,7 +363,7 @@ func (m *Manager) resolvePendingSnap(ctx context.Context, sb *types.Sandbox) (ad } if err := m.store.commit(js); err != nil { m.store.recommit(ctx, js) - // the transition is decided in memory, so report the adoption for the caller to bill + // The transition is decided in memory, so report the adoption for the caller to bill return exists, fmt.Errorf("resolve hibernate intent %s: persist: %w", sb.ID, err) } return exists, nil diff --git a/sandboxd/pool/liveness.go b/sandboxd/pool/liveness.go index 640746831..9ab5164a1 100644 --- a/sandboxd/pool/liveness.go +++ b/sandboxd/pool/liveness.go @@ -18,7 +18,7 @@ import ( const ( vmmRestartBudget = 3 vmmRestartWindow = 10 * time.Minute - // with the cocoon daemon stream live, the list only catches an event the stream dropped + // With the cocoon daemon stream live, the list only catches an event the stream dropped livenessBackstop = time.Minute vmEventsBackoff = time.Second vmEventsMaxBackoff = 30 * time.Second @@ -139,7 +139,7 @@ func (m *Manager) recoverVMM(ctx context.Context, sb *types.Sandbox) { return } logger := log.WithFunc("pool.recoverVMM") - // the sweep's list predates this lock, so a wake that finished in between reads as down there + // The sweep's list predates this lock, so a wake that finished in between reads as down there vm, found, err := m.eng.Inspect(ctx, sb.VMName) switch { case err != nil: @@ -219,7 +219,7 @@ func (m *Manager) restartLocked(ctx context.Context, sb *types.Sandbox) error { m.mu.Lock() sb.VsockSocket = sock m.mu.Unlock() - // a displaced door's close unlinks the rebound path, so the old door goes first + // A displaced door's close unlinks the rebound path, so the old door goes first m.out.Disarm(sb.ID, false) err = m.out.ArmProxy(ctx, sb) if err == nil { @@ -235,7 +235,7 @@ func (m *Manager) restartLocked(ctx context.Context, sb *types.Sandbox) error { sb.Restarts++ sb.RestartedAt = time.Now() }); !live { - // the release that dropped the claim owns the VM teardown + // The release that dropped the claim owns the VM teardown m.out.Disarm(sb.ID, true) return ErrUnknownSandbox } @@ -274,7 +274,7 @@ func coldBootBlocker(sb *types.Sandbox, found, volumes bool) string { case !found: return "vm record gone" case sb.Key.Net == types.NetEgress: - // the netdev nft chain dies with the tap, so the guest would boot with an unlocked NIC + // The netdev nft chain dies with the tap, so the guest would boot with an unlocked NIC return "vmm exited; an egress-lane sandbox cannot cold-boot" case volumes: return "vmm exited; volume mounts do not survive a cold boot" diff --git a/sandboxd/pool/reconcile.go b/sandboxd/pool/reconcile.go index b53f9bb34..ec69b2a34 100644 --- a/sandboxd/pool/reconcile.go +++ b/sandboxd/pool/reconcile.go @@ -46,25 +46,25 @@ func (m *Manager) Reconcile(ctx context.Context) error { rec, ok := live[sb.VMName] switch { case sb.ArchiveCk != "": - // archived: no local VM by design, so adopt the stub and let the first exec wake it + // Archived: no local VM by design, so adopt the stub and let the first exec wake it m.addClaimLocked(sb) continue case ok && rec.State == vmStateRunning: sb.VsockSocket = rec.VsockSocket - // running with either flag set means a crashed wake or an intent the engine never saw + // Running with either flag set means a crashed wake or an intent the engine never saw if sb.HibernateSnap != "" { resumed = append(resumed, sb) } sb.HibernateSnap, sb.PendingSnap = "", "" case ok && sb.HibernateSnap != "": - // hibernated: the VM is stopped by design and wakes on demand. + // Hibernated: the VM is stopped by design and wakes on demand. sb.PendingSnap = "" case ok && sb.PendingSnap != "" && (snapsErr != nil || slices.Contains(snaps, sb.PendingSnap)): - // the journaled intent names the wake image, so adopt it when the snapshot is there + // The journaled intent names the wake image, so adopt it when the snapshot is there sb.HibernateSnap, sb.PendingSnap, sb.ReaderSafe = sb.PendingSnap, "", false adopted = append(adopted, sb) case ok: - // the VMM died with the host or on its own; the liveness pass restarts or fails it + // The VMM died with the host or on its own; the liveness pass restarts or fails it sb.PendingSnap = "" default: dropped = append(dropped, sb) @@ -107,7 +107,7 @@ func (m *Manager) Reconcile(ctx context.Context) error { logger.Infof(ctx, "removed orphan golden %s", name) } } - // a crash mid-export leaves a fork-* staging dir nothing in this life reuses + // A crash mid-export leaves a fork-* staging dir nothing in this life reuses _ = utils.RemoveDirEntries(m.dataDir, func(name string) bool { return strings.HasPrefix(name, "fork-") }) _ = utils.RemoveDirEntries(filepath.Join(m.dataDir, readerDir), nil) @@ -117,7 +117,7 @@ func (m *Manager) Reconcile(ctx context.Context) error { m.retryArchiveDeletes(ctx) removed := m.sweepStaleVMs(ctx, live, owned) - // an unreferenced hibernate snapshot is an orphan; fork and golden snapshots never span a restart + // An unreferenced hibernate snapshot is an orphan; fork and golden snapshots never span a restart if snapsErr != nil { logger.Warnf(ctx, "snapshot sweep skipped: %v", snapsErr) } else { @@ -166,10 +166,10 @@ func (m *Manager) sweepStaleVMs(ctx context.Context, live map[string]types.VMRec func (m *Manager) removeStaleVM(ctx context.Context, name string, rec types.VMRecord) bool { logger := log.WithFunc("pool.removeStaleVM") if rec.State == vmStateCreating { - // a canceled ctx must not skip the busy check guarding the forced remove + // A canceled ctx must not skip the busy check guarding the forced remove switch outcome, err := m.eng.ReconcileStaleCreate(context.WithoutCancel(ctx), name); { case err != nil: - // verb missing (cocoon < v0.5.8) or failed: keep the old sweep. + // Verb missing (cocoon < v0.5.8) or failed: keep the old sweep. logger.Warnf(ctx, "reconcile stale create %s: %v; removing", name, err) case outcome == engine.StaleCreateCollected, outcome == engine.StaleCreateNotFound: return true @@ -178,7 +178,7 @@ func (m *Manager) removeStaleVM(ctx context.Context, name string, rec types.VMRe m.queueStaleCreate(name, rec.TapDevice()) return false } - // not-creating: the record moved on under the lock; remove normally. + // Not-creating: the record moved on under the lock; remove normally. } if m.removeVM(ctx, name) { return true @@ -217,13 +217,13 @@ func (m *Manager) resyncEgress(ctx context.Context, live map[string]types.VMReco var quarantine []*types.Sandbox for _, sb := range m.claimed { sb.TouchAt(now) - // a hibernated or archived claim has no guest to serve; its wake arms the door + // A hibernated or archived claim has no guest to serve; its wake arms the door if sb.HibernateSnap != "" || sb.ArchiveCk != "" || sb.Failed != "" { continue } if m.out.LocksNIC(sb.Key) { tap := m.readoptEgressTap(sb, live) - // a down egress-lane VM has no guest to lock or mark; the liveness pass fails it + // A down egress-lane VM has no guest to lock or mark; the liveness pass fails it if live[sb.VMName].State != vmStateRunning { continue } @@ -246,7 +246,7 @@ func (m *Manager) resyncEgress(ctx context.Context, live map[string]types.VMReco logger.Errorf(ctx, proxyErr, "arm egress proxy %s", sb.ID) } } - // quarantine before the sweep so a failed remove's still-running tap is kept. + // Quarantine before the sweep so a failed remove's still-running tap is kept. keep := make(map[string]bool, len(live)) for _, sb := range quarantine { if m.quarantineClaim(ctx, sb) { @@ -255,7 +255,7 @@ func (m *Manager) resyncEgress(ctx context.Context, live map[string]types.VMReco keep[sb.TAP] = true } } - // keep every still-running VM's tap; sweep only a confirmed-gone VM's table. + // Keep every still-running VM's tap; sweep only a confirmed-gone VM's table. for name, rec := range live { if tap := rec.TapDevice(); tap != "" && !removed[name] { keep[tap] = true diff --git a/sandboxd/pool/refill.go b/sandboxd/pool/refill.go index 2f21c3aa4..a2d08be55 100644 --- a/sandboxd/pool/refill.go +++ b/sandboxd/pool/refill.go @@ -35,7 +35,7 @@ func (m *Manager) refillOnce(ctx context.Context) { return } now := time.Now() - // spawning VMs into a full node still takes the global rtnl lock even when doomed to fail + // Spawning VMs into a full node still takes the global rtnl lock even when doomed to fail parked := m.capacityReasonLocked(now) != "" inFlight := 0 for _, p := range m.pools { @@ -121,7 +121,7 @@ func (m *Manager) refillOne(ctx context.Context, p *pool, golden string, gen uin p.noteLead(time.Since(start)) keep = true } - // a canceled context or a capacity failure says nothing about this pool's health + // A canceled context or a capacity failure says nothing about this pool's health backedOff := false if ctx.Err() == nil && capReason == "" { backedOff = p.noteRefillResult(now, err != nil) @@ -210,7 +210,7 @@ func (m *Manager) buildGolden(ctx context.Context, p *pool) { p.goldenGen++ default: p.nextBuild = time.Now().Add(buildRetryDelay) - // a cold boot hits the same bridge and disk as a refill, so it feeds the park too + // A cold boot hits the same bridge and disk as a refill, so it feeds the park too if reason := engine.CapacitySignature(err); reason != "" { m.noteCapacityLocked(time.Now(), reason) } @@ -266,7 +266,7 @@ func (m *Manager) runWarmup(ctx context.Context, warmup []string, sock string) e return m.eng.Warmup(ctx, sock, warmup) } -// a restore maps the golden memory lazily, so the warmup's pages fault in here instead of under the first claim +// A restore maps the golden memory lazily, so the warmup's pages fault in here instead of under the first claim func (m *Manager) warmClone(ctx context.Context, sb *types.Sandbox) error { if err := m.runWarmup(ctx, m.view.Load().poolWarmups[sb.Key], sb.VsockSocket); err != nil { m.destroy(ctx, sb.VMName) @@ -310,7 +310,7 @@ func (m *Manager) goldenStamp(v *configView, key types.PoolKey, imageID string) fp = m.out.CAFingerprint() } fields := []string{fp, string(m.out.Lane(key)), imageID} - // only a sized pool stamps its disk, in bytes so "40G" and "40GiB" match and unsized goldens stay adoptable + // Only a sized pool stamps its disk, in bytes so "40G" and "40GiB" match and unsized goldens stay adoptable if storage := v.poolStorage[key]; storage != "" { n, _ := config.StorageBytes(storage) fields = append(fields, "storage="+strconv.FormatInt(n, 10)) @@ -384,7 +384,7 @@ func (m *Manager) provisionCold(ctx context.Context, key types.PoolKey) (*types. if err != nil { return nil, err } - // a pre-golden cold claim must trust the root, or intercepted hosts fail TLS for its life + // A pre-golden cold claim must trust the root, or intercepted hosts fail TLS for its life if err := m.out.PrepareGuest(ctx, m.view.Load().out, key, sb.VsockSocket); err != nil { m.destroy(ctx, sb.VMName) return nil, err @@ -502,7 +502,7 @@ func (m *Manager) destroyAll(ctx context.Context, names []string) *sync.WaitGrou func (m *Manager) runBounded(ctx context.Context, n int, f func(context.Context, int)) *sync.WaitGroup { var wg sync.WaitGroup for i := range n { - // acquire inside the goroutine so a batch larger than the budget cannot block the caller + // Acquire inside the goroutine so a batch larger than the budget cannot block the caller wg.Go(func() { for _, sem := range [...]chan struct{}{m.maintSem, m.refillSem} { select { diff --git a/sandboxd/pool/remove.go b/sandboxd/pool/remove.go index 75efec26e..ebea44ca1 100644 --- a/sandboxd/pool/remove.go +++ b/sandboxd/pool/remove.go @@ -15,7 +15,7 @@ import ( func (m *Manager) removeVM(ctx context.Context, name string) bool { m.out.ClosePrebound(name) - // cancellation-immune: on a canceled ctx `cocoon vm rm` no-ops and orphans. + // Cancellation-immune: on a canceled ctx `cocoon vm rm` no-ops and orphans. ctx = context.WithoutCancel(ctx) err := m.eng.Remove(ctx, name) if err == nil { @@ -31,7 +31,7 @@ func (m *Manager) confirmGone(ctx context.Context, name string) bool { logger := log.WithFunc("pool.confirmGone") _, present, err := m.eng.Inspect(ctx, name) if err != nil { - // cannot tell: a false "gone" leaks a running VM, a retry only costs a sweep + // Cannot tell: a false "gone" leaks a running VM, a retry only costs a sweep logger.Warnf(ctx, "verify remove of %s: %v", name, err) return false } diff --git a/sandboxd/pool/setpools.go b/sandboxd/pool/setpools.go index d4d74357c..f22558d64 100644 --- a/sandboxd/pool/setpools.go +++ b/sandboxd/pool/setpools.go @@ -40,7 +40,7 @@ func (m *Manager) desiredPools(specs []config.PoolSpec) (map[types.PoolKey]confi if err := spec.ValidateLimits(); err != nil { return nil, fmt.Errorf("%w: %w", ErrBadCount, err) } - // config-owned fields; accepting one here would silently drop it + // Config-owned fields; accepting one here would silently drop it for _, f := range []struct { name string set bool @@ -74,12 +74,12 @@ func (m *Manager) applyPools(ctx context.Context, desired map[types.PoolKey]conf return nil } m.poolVersion = version - // sequenced under the mutex (apply order) so commit drops a write a later apply superseded. + // Sequenced under the mutex (apply order) so commit drops a write a later apply superseded. seq := m.poolStore.seq.Add(1) now := time.Now() for key, p := range m.pools { spec, ok := desired[key] - // a removed key gets the zero spec, so a lingering pool sheds a stale archiveAfter + // A removed key gets the zero spec, so a lingering pool sheds a stale archiveAfter p.applySpec(spec) p.removed = !ok trim = append(trim, p.trimWarm(p.effectiveTarget(now))...) @@ -100,7 +100,7 @@ func (m *Manager) applyPools(ctx context.Context, desired map[types.PoolKey]conf runCtx := context.WithoutCancel(ctx) m.destroyAll(runCtx, trim).Wait() m.refillOnce(runCtx) - // persist the applied set so a restart rebuilds from it, not the config seed. + // Persist the applied set so a restart rebuilds from it, not the config seed. return m.poolStore.commit(seq, poolset.Set{ConfigSeed: m.configSeedHash, Pools: slices.Collect(maps.Values(desired))}) } diff --git a/sandboxd/pool/stats.go b/sandboxd/pool/stats.go index 0e11db4ff..20f781a1e 100644 --- a/sandboxd/pool/stats.go +++ b/sandboxd/pool/stats.go @@ -22,7 +22,7 @@ type SandboxStats struct { // Stats reports one live claim's resource usage. func (m *Manager) Stats(ctx context.Context, id string) (SandboxStats, bool) { - // hibernate and archive rewrite HibernateSnap and VMName under m.mu; the /proc read needs none + // Hibernate and archive rewrite HibernateSnap and VMName under m.mu; the /proc read needs none m.mu.Lock() sb := m.claimed[id] if sb == nil { diff --git a/sandboxd/pool/telemetry.go b/sandboxd/pool/telemetry.go index 64b3fd264..53e83c381 100644 --- a/sandboxd/pool/telemetry.go +++ b/sandboxd/pool/telemetry.go @@ -158,7 +158,7 @@ func (m *Manager) TenantClaims() map[string]int { // Audit records one relayed request frame against a sandbox: the op and addressing fields only. func (m *Manager) Audit(ctx context.Context, id string, line []byte) { if len(line) > AuditLineCap { - // the addressing fields stay unread at this size, but a padded frame must not escape the journal + // The addressing fields stay unread at this size, but a padded frame must not escape the journal m.recordAudit(ctx, id, auditFrame{Op: "oversized"}) return } diff --git a/sandboxd/pool/template.go b/sandboxd/pool/template.go index b06d0e316..e3307e2df 100644 --- a/sandboxd/pool/template.go +++ b/sandboxd/pool/template.go @@ -56,14 +56,14 @@ func (m *Manager) Promote(ctx context.Context, id string, cred Cred, template, t } key := types.PoolKey{Template: template, Net: sb.Key.Net, Size: sb.Key.Size} if m.pooled(key) { - // a configured pool owns this key; promoting over it would change what refills produce + // A configured pool owns this key; promoting over it would change what refills produce return types.PoolKey{}, "", ErrPooledTemplate } // commitTemplate re-checks under the template lock; this only fast-fails before the export if err := m.checkTemplateOwner(ctx, store.TemplateID(key.Hash()), tenant); err != nil { return types.PoolKey{}, "", err } - // a started promote must finish uncanceled + // A started promote must finish uncanceled ctx = context.WithoutCancel(ctx) staging, err := m.tpls.Stage(store.TemplateID(key.Hash())) if err != nil { @@ -202,7 +202,7 @@ func (m *Manager) HasPromotedTemplate(ctx context.Context, key types.PoolKey, te m.tplMu.Unlock() owner := held.Tenant if !cached { - // only a shared-store template promoted elsewhere after startup. + // Only a shared-store template promoted elsewhere after startup. raw, err := m.tpls.ReadMeta(ctx, id) if err != nil { return false diff --git a/sandboxd/pool/volume.go b/sandboxd/pool/volume.go index aee84b925..8133fbf9e 100644 --- a/sandboxd/pool/volume.go +++ b/sandboxd/pool/volume.go @@ -19,7 +19,7 @@ import ( ) const ( - // sidecar, not data_dir: the marker travels with the image and survives a data_dir wipe + // Sidecar, not data_dir: the marker travels with the image and survives a data_dir wipe volumeDirtySuffix = ".dirty" volumeQuiesceMax = 10 * time.Second ) @@ -74,7 +74,7 @@ func (m *Manager) Volumes(tenant string, holders map[string]int) []types.VolumeI } infos = append(infos, info) } - // root can see peer-only names; a tenant needs local catalog metadata to apply the access list + // Root can see peer-only names; a tenant needs local catalog metadata to apply the access list if tenant == "" { for name, nodes := range holders { if _, ok := catalog[name]; !ok { @@ -164,7 +164,7 @@ func (m *Manager) resolveCatalogEntry(ctx context.Context, volume types.Volume, return resolvedVolume{}, fmt.Errorf("%w: volume %q is not writable", ErrBadVolume, volume.Name) } if _, statErr := os.Stat(entry.disk.Path); statErr != nil { - // the operator's path stays server-side; the refusal matches the unknown one + // The operator's path stays server-side; the refusal matches the unknown one log.WithFunc("pool.resolveCatalogEntry").Warnf(ctx, "stat volume %q image %s: %v", volume.Name, entry.disk.Path, statErr) return resolvedVolume{}, ErrVolumeUnavailable } @@ -201,9 +201,9 @@ func (m *Manager) applyVolumes(ctx context.Context, sb *types.Sandbox, volumes [ // applyVolume keeps one volume's steps strictly ordered; siblings overlap freely. func (m *Manager) applyVolume(ctx context.Context, sb *types.Sandbox, volume resolvedVolume, live bool) error { - // attach-only mounts nothing, so there is no umount to verify and no marker. + // Attach-only mounts nothing, so there is no umount to verify and no marker. attachOnly := volume.applied.AttachOnly - // write-ahead: the marker must be durable before any guest write can be. + // Write-ahead: the marker must be durable before any guest write can be. if volume.disk.RW && !attachOnly { if err := markVolumeDirty(volume.disk.Path); err != nil { return fmt.Errorf("mark volume %q dirty: %w", volume.applied.Name, err) @@ -237,7 +237,7 @@ func (m *Manager) quiesceVolumes(ctx context.Context, sb *types.Sandbox) volumeT } catalog := m.catalogSnapshot() logger := log.WithFunc("pool.quiesceVolumes") - // cancellation-immune like removal: a caller hanging up must not skip the flush. + // Cancellation-immune like removal: a caller hanging up must not skip the flush. ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), quiesceBudget(mounts)) defer cancel() stuck := false @@ -256,7 +256,7 @@ func (m *Manager) quiesceVolumes(ctx context.Context, sb *types.Sandbox) volumeT } } if stuck { - // the unmounts may have spent the whole budget; the fallback flush gets its own + // The unmounts may have spent the whole budget; the fallback flush gets its own syncCtx, cancelSync := context.WithTimeout(context.WithoutCancel(ctx), engine.VolumeCallTimeout) defer cancelSync() if err := m.eng.SyncGuest(syncCtx, sb.VsockSocket); err != nil { diff --git a/sandboxd/server/exec.go b/sandboxd/server/exec.go index 470100e1f..bb8609e6c 100644 --- a/sandboxd/server/exec.go +++ b/sandboxd/server/exec.go @@ -94,7 +94,7 @@ func (s *Server) handleExec(w http.ResponseWriter, r *http.Request) { return true }) if err != nil && pid != 0 { - // a dropped connection only reaches a child that writes; a silent one needs the kill + // A dropped connection only reaches a child that writes; a silent one needs the kill if killErr := s.killExec(ctx, id, token, pid); killErr != nil { log.WithFunc("server.handleExec").Errorf(ctx, killErr, "kill exec pid %d in %s", pid, id) } diff --git a/sandboxd/server/preview.go b/sandboxd/server/preview.go index 853fd8af0..457dfa822 100644 --- a/sandboxd/server/preview.go +++ b/sandboxd/server/preview.go @@ -53,7 +53,7 @@ func NewPreviewServer(secret, base, owner string, mgr PreviewManager) *PreviewSe } p := &PreviewServer{secret: []byte(secret), base: base, owner: owner, mgr: mgr} p.transport = &http.Transport{ - // a pooled guest conn skips PreviewDial, and with it wakeResolved and the Transition lock + // A pooled guest conn skips PreviewDial, and with it wakeResolved and the Transition lock DisableKeepAlives: true, DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) { id, portStr, err := net.SplitHostPort(addr) @@ -97,7 +97,7 @@ func (p *PreviewServer) serve(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid or expired preview token", http.StatusForbidden) return } - // the token names the owner by its advertise address at mint time; holding the claim is what counts + // The token names the owner by its advertise address at mint time; holding the claim is what counts if _, held := p.mgr.Sandbox(claims.ID); !held && claims.Owner != p.owner { if r.Header.Get(forwardedHeader) != "" { http.Error(w, "preview owner is not this node", http.StatusBadGateway) @@ -113,10 +113,10 @@ func (p *PreviewServer) proxyLocal(w http.ResponseWriter, r *http.Request, claim rp := &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { pr.Out.URL.Scheme = "http" - // the synthetic host carries PreviewDial's target + // The synthetic host carries PreviewDial's target pr.Out.URL.Host = fmt.Sprintf("%s:%d", claims.ID, claims.Port) pr.Out.URL.Path = "/" + strings.TrimPrefix(pr.In.URL.Path, "/p/"+r.PathValue("token")+"/") - // the raw form drops the same two segments however the client spelled them, so %2F survives + // The raw form drops the same two segments however the client spelled them, so %2F survives raw := pr.In.URL.EscapedPath() for range 2 { if i := strings.IndexByte(raw[1:], '/'); i >= 0 { @@ -126,7 +126,7 @@ func (p *PreviewServer) proxyLocal(w http.ResponseWriter, r *http.Request, claim } } pr.Out.URL.RawPath = raw - // browser credentials for the preview domain must not reach guest code + // Browser credentials for the preview domain must not reach guest code pr.Out.Header.Del("Cookie") pr.Out.Header.Del("Authorization") }, diff --git a/sandboxd/server/relay.go b/sandboxd/server/relay.go index 09f4cd869..8bd0a9275 100644 --- a/sandboxd/server/relay.go +++ b/sandboxd/server/relay.go @@ -21,7 +21,7 @@ const ( // drainGrace bounds how long a finished silkd relay waits for the client to close. drainGrace = 30 * time.Second - // the keepAlive trio fails a relay whose client vanished without a FIN in about two minutes. + // The keepAlive trio fails a relay whose client vanished without a FIN in about two minutes. keepAliveIdle = 60 * time.Second keepAliveInterval = 15 * time.Second keepAliveCount = 4 @@ -123,7 +123,7 @@ func (s *Server) splice(client net.Conn, clientR io.Reader, guest net.Conn, hell } defer release() - // the http server may have armed a header-read deadline on this conn + // The http server may have armed a header-read deadline on this conn _ = client.SetDeadline(time.Time{}) keepAlive(client) if _, err := client.Write(hello); err != nil { @@ -221,7 +221,7 @@ func copyBoth(client net.Conn, clientR io.Reader, guest net.Conn, ends relayEnds defer close(done) _, err := utils.CopyIn(guest, clientR, noSplice) if err != nil { - // the client died rather than half-closing, so nothing is left to answer it + // The client died rather than half-closing, so nothing is left to answer it _ = guest.Close() return } diff --git a/sandboxd/store/dir/dir.go b/sandboxd/store/dir/dir.go index 1930f768b..fc70fbf85 100644 --- a/sandboxd/store/dir/dir.go +++ b/sandboxd/store/dir/dir.go @@ -234,7 +234,7 @@ func (d *Store) publish(_ context.Context, staging, id, digest string) error { switch { case errors.Is(statErr, fs.ErrNotExist): stagedExport := filepath.Join(staging, store.ExportDir) - // make the generation fresh before a peer can observe it without committed meta. + // Make the generation fresh before a peer can observe it without committed meta. if err := os.Chtimes(stagedExport, now, now); err != nil { return err } @@ -252,7 +252,7 @@ func (d *Store) publish(_ context.Context, staging, id, digest string) error { if readErr != nil && !errors.Is(readErr, fs.ErrNotExist) { return readErr } - // a sweep may already have selected an expired path for removal. + // A sweep may already have selected an expired path for removal. if time.Since(genInfo.ModTime()) >= store.GenerationGrace { return fmt.Errorf("generation %s expired before commit; retry after sweep", filepath.Base(genDir)) } @@ -264,7 +264,7 @@ func (d *Store) publish(_ context.Context, staging, id, digest string) error { _ = d.sweepGenerations(id) return os.RemoveAll(staging) } - // age the previous current generation from supersession, not publication. + // Age the previous current generation from supersession, not publication. if err := touchCurrentGeneration(final, now); err != nil { return err } @@ -290,7 +290,7 @@ func (d *Store) sweepGenerations(id string) (err error) { return err default: defer func() { err = errors.Join(err, metaFile.Close()) }() - // the open file pins one inode across a concurrent meta rename. + // The open file pins one inode across a concurrent meta rename. meta, readErr := io.ReadAll(metaFile) if readErr != nil { return readErr diff --git a/sandboxd/store/peer/peer.go b/sandboxd/store/peer/peer.go index da9ea9c5f..8ac240855 100644 --- a/sandboxd/store/peer/peer.go +++ b/sandboxd/store/peer/peer.go @@ -38,7 +38,7 @@ func (h *Healer) Pull(ctx context.Context, id, staging string, validate Validate if len(addrs) == 0 { return store.ErrNotFound } - // a client hanging up must not abandon a started pull; the budget bounds it. + // A client hanging up must not abandon a started pull; the budget bounds it. ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), healBudget) defer cancel() return h.pullFrom(ctx, id, staging, addrs, validate) @@ -48,7 +48,7 @@ func (h *Healer) pullFrom(ctx context.Context, id, staging string, addrs []strin perOwner := healBudget / time.Duration(len(addrs)) var errs []error for _, addr := range addrs { - // one peer's rejected or partial transfer must not linger into the next's. + // One peer's rejected or partial transfer must not linger into the next's. if err := utils.RemoveDirEntries(staging, nil); err != nil { return fmt.Errorf("reset staging: %w", err) } diff --git a/sandboxd/store/peer/probe.go b/sandboxd/store/peer/probe.go index eba4d9365..1b0362275 100644 --- a/sandboxd/store/peer/probe.go +++ b/sandboxd/store/peer/probe.go @@ -74,7 +74,7 @@ func (p *HTTPProber) Owners(ctx context.Context, id string) []string { // HealOwners is Owners' wide twin: a heal wants the largest source list, uncached. func (p *HTTPProber) HealOwners(ctx context.Context, id string) []string { v, _, _ := p.healFlight.Do(id, func() (any, error) { - // no grace: a heal must not stop early on a fast owner and hide a slower valid source. + // No grace: a heal must not stop early on a fast owner and hide a slower valid source. return p.fanOut(ctx, id, maxHealOwners, 0), nil }) return v.([]string) @@ -108,7 +108,7 @@ func (p *HTTPProber) fanOut(ctx context.Context, id string, maxOwners int, grace } go func() { wg.Wait(); close(wins) }() - // grace opens only after the first win: a genuine miss must hear from every peer. + // Grace opens only after the first win: a genuine miss must hear from every peer. var owners []string var graceCh <-chan time.Time for { diff --git a/sandboxd/store/peer/transport.go b/sandboxd/store/peer/transport.go index 262dc9291..e5511fda4 100644 --- a/sandboxd/store/peer/transport.go +++ b/sandboxd/store/peer/transport.go @@ -24,7 +24,7 @@ import ( ) const ( - // generous for a guest memory image, but a wedged peer must fail so the next owner is tried. + // Generous for a guest memory image, but a wedged peer must fail so the next owner is tried. pullTimeout = 30 * time.Minute maxRecordBytes = 1 << 40 // 1 TiB @@ -49,7 +49,7 @@ type Puller interface { // HTTPPuller pulls records over sandboxd's control-plane HTTP port. type HTTPPuller struct { - // a nil Client uses a default with no overall timeout; the deadline comes from the context. + // A nil Client uses a default with no overall timeout; the deadline comes from the context. Client *http.Client Token string } diff --git a/sandboxd/store/s3/s3.go b/sandboxd/store/s3/s3.go index 1ff9b7d9b..58b7e0fc6 100644 --- a/sandboxd/store/s3/s3.go +++ b/sandboxd/store/s3/s3.go @@ -96,7 +96,7 @@ func New(ctx context.Context, cfg store.S3Config, stagingRoot string, idRe *rege if cfg.Bucket == "" { return nil, fmt.Errorf("s3 checkpoint store needs a bucket") } - // a prefix without its trailing slash hides every record from the delimiter listing. + // A prefix without its trailing slash hides every record from the delimiter listing. if cfg.Prefix != "" && !strings.HasSuffix(cfg.Prefix, "/") { cfg.Prefix += "/" } @@ -386,7 +386,7 @@ func (s *Store) publish(ctx context.Context, staging, id, lineage string, digest if err = s.putObject(ctx, s.key(id, store.MetaFile), metaRaw, metadata); err != nil { return "", err } - // keep old generations: another node may have selected the previous meta. + // Keep old generations: another node may have selected the previous meta. if err := os.RemoveAll(staging); err != nil { return "", err } @@ -494,7 +494,7 @@ func (s *Store) chunkKey(lineage, sha string) string { } func (s *Store) recordIDs(ctx context.Context) ([]string, error) { - // delimiter listing yields one CommonPrefix per record instead of every export object. + // Delimiter listing yields one CommonPrefix per record instead of every export object. var ids []string p := awss3.NewListObjectsV2Paginator(s.client, &awss3.ListObjectsV2Input{ Bucket: &s.bucket, Prefix: &s.prefix, Delimiter: new("/"), @@ -600,7 +600,7 @@ func (s *Store) deleteKeys(ctx context.Context, keys []string) error { return fmt.Errorf("delete %d objects: %w", len(chunk), err) } for _, e := range out.Errors { - // strict backends error on deleting an absent key where AWS succeeds silently. + // Strict backends error on deleting an absent key where AWS succeeds silently. if code := aws.ToString(e.Code); code == "NoSuchKey" || code == "NoSuchVersion" { continue } diff --git a/sdk/go/port.go b/sdk/go/port.go index ab07c6ae7..c8fdedc00 100644 --- a/sdk/go/port.go +++ b/sdk/go/port.go @@ -144,7 +144,7 @@ func (s *Sandbox) openStream(ctx context.Context, req wire.Request) (*PortConn, func (s *Sandbox) proxyConn(ctx context.Context, local net.Conn, port uint16) { defer func() { _ = local.Close() }() - // the copy can sit in local.Read forever; only closing the conn unblocks it, so ctx teardown reaches local too + // The copy can sit in local.Read forever; only closing the conn unblocks it, so ctx teardown reaches local too unarm := context.AfterFunc(ctx, func() { _ = local.Close() }) defer unarm() guest, err := s.DialPort(ctx, port) diff --git a/sdk/go/proc.go b/sdk/go/proc.go index e2aaa180e..7bbca2d6a 100644 --- a/sdk/go/proc.go +++ b/sdk/go/proc.go @@ -69,7 +69,7 @@ func (s *Sandbox) drainProc(ctx context.Context, req wire.Request, stdout, stder } defer l.close() _, code, exited, err := pumpStdio(ctx, conn, stdout, stderr) - // logs closes with done after the exit frame + // Logs closes with done after the exit frame if _, replay := req.(*wire.Logs); replay && exited && err == nil { err = terminalErr(ctx, conn) } diff --git a/sdk/go/sandbox.go b/sdk/go/sandbox.go index 0a3ceb34b..cf28fd302 100644 --- a/sdk/go/sandbox.go +++ b/sdk/go/sandbox.go @@ -119,7 +119,7 @@ func (s *Sandbox) Run(ctx context.Context, cmd Cmd) (int, error) { stdinDone := make(chan struct{}) if cmd.Stdin == nil { - // a guest that already answered and closed fails this send; the frames it sent still come back below + // A guest that already answered and closed fails this send; the frames it sent still come back below _ = conn.Send(wire.StdinClose{}) close(stdinDone) } else { @@ -130,7 +130,7 @@ func (s *Sandbox) Run(ctx context.Context, cmd Cmd) (int, error) { } pid, code, exited, err := pumpStdio(ctx, conn, cmd.Stdout, cmd.Stderr) - // a pump still parked in Read would write into the next RPC, so its connection is not kept + // A pump still parked in Read would write into the next RPC, so its connection is not kept select { case <-stdinDone: err = l.done(err) diff --git a/sdk/go/upgrade.go b/sdk/go/upgrade.go index e6aea1d0b..117a69e93 100644 --- a/sdk/go/upgrade.go +++ b/sdk/go/upgrade.go @@ -89,7 +89,7 @@ func (c *Client) dialAgent(ctx context.Context, addr, id, token string) (*upgrad if scheme != httpsScheme { return u, nil } - // a TLS edge may be a proxy that drops bytes sent ahead of the 101 + // A TLS edge may be a proxy that drops bytes sent ahead of the 101 if _, err = u.Write(nil); err != nil { _ = raw.Close() return nil, fmt.Errorf("write upgrade request: %w", err)