navid/veinsforge / bfca04557da72007d094c4fe1628fdd6aaf975ac929859b3a57f65b88a4b9f56 / internal/vn/runner.go

runner.go

← internal/vn · 7944 bytes · raw · download

package vn

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"time"
)

// Runner wraps the vn binary. Every command is executed without a shell, with
// a private HOME, a timeout, and a bounded output buffer.
type Runner struct {
	Bin        string
	Home       string
	RepoRoot   string
	CacheDir   string
	KeyName    string
	KeyPublic  string
	KeyFinger  string
	Logger     *log.Logger
	CommandTTL time.Duration

	mu         sync.Mutex
	repoLocks  map[string]*sync.Mutex
	fetchAt    map[int64]time.Time
	fetchHead  map[int64]string
	currentRev map[int64]string
}

type CommandError struct {
	Args   []string
	Stderr string
	Err    error
}

func (e *CommandError) Error() string {
	msg := strings.TrimSpace(e.Stderr)
	if msg == "" {
		msg = e.Err.Error()
	}
	return msg
}

func (e *CommandError) Unwrap() error { return e.Err }

func NewRunner(bin, home, repoRoot, cacheDir string, logger *log.Logger) *Runner {
	return &Runner{
		Bin:        bin,
		Home:       home,
		RepoRoot:   repoRoot,
		CacheDir:   cacheDir,
		KeyName:    "veinsforge",
		Logger:     logger,
		CommandTTL: 30 * time.Second,
		repoLocks:  make(map[string]*sync.Mutex),
		fetchAt:    make(map[int64]time.Time),
		fetchHead:  make(map[int64]string),
		currentRev: make(map[int64]string),
	}
}

// EnsureKey creates and loads the service key used for local clone/merge work.
func (r *Runner) EnsureKey(ctx context.Context) error {
	keyPath := filepath.Join(r.Home, ".config", "veins", "keys", r.KeyName+".key")
	if _, err := os.Stat(keyPath); err != nil {
		if !errors.Is(err, os.ErrNotExist) {
			return err
		}
		if _, _, err := r.run(ctx, r.Home, nil, "key", "generate", r.KeyName); err != nil {
			return fmt.Errorf("generate service key: %w", err)
		}
	}
	if err := os.Chmod(keyPath, 0o600); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}
	out, _, err := r.run(ctx, r.Home, nil, "key", "show", r.KeyName)
	if err != nil {
		return fmt.Errorf("read service key: %w", err)
	}
	for _, line := range strings.Split(string(out), "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "public key:") {
			r.KeyPublic = strings.TrimSpace(strings.TrimPrefix(line, "public key:"))
		}
		if strings.HasPrefix(line, "fingerprint:") {
			r.KeyFinger = strings.TrimSpace(strings.TrimPrefix(line, "fingerprint:"))
		}
	}
	if r.KeyPublic == "" {
		return errors.New("service key has no public key")
	}
	return nil
}

func (r *Runner) repoLock(key string) *sync.Mutex {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.repoLocks[key] == nil {
		r.repoLocks[key] = &sync.Mutex{}
	}
	return r.repoLocks[key]
}

func (r *Runner) run(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, []byte, error) {
	timeout := r.CommandTTL
	if timeout <= 0 {
		timeout = 30 * time.Second
	}
	return r.runWithTimeout(ctx, dir, extraEnv, timeout, args...)
}

func (r *Runner) runWithTimeout(ctx context.Context, dir string, extraEnv []string, timeout time.Duration, args ...string) ([]byte, []byte, error) {
	if r.Bin == "" {
		return nil, nil, errors.New("vn binary is not configured")
	}
	if timeout <= 0 {
		timeout = 30 * time.Second
	}
	cctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	cmd := exec.CommandContext(cctx, r.Bin, args...)
	cmd.Dir = dir
	env := append([]string{}, os.Environ()...)
	env = append(env,
		"HOME="+r.Home,
		"XDG_CONFIG_HOME="+filepath.Join(r.Home, ".config"),
		"GIT_AUTHOR_NAME=veinsforge",
		"GIT_AUTHOR_EMAIL=veinsforge@localhost",
		"GIT_TERMINAL_PROMPT=0",
	)
	env = append(env, extraEnv...)
	cmd.Env = env
	var stdout, stderr limitedBuffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	out := stdout.Bytes()
	errOut := stderr.Bytes()
	if err != nil {
		if cctx.Err() == context.DeadlineExceeded {
			err = fmt.Errorf("command timed out")
		}
		if r.Logger != nil {
			r.Logger.Printf("vn %s failed: %v: %s", strings.Join(args, " "), err, truncate(string(errOut), 1024))
		}
		return out, errOut, &CommandError{Args: args, Stderr: string(errOut), Err: err}
	}
	return out, errOut, nil
}

func (r *Runner) runLong(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, []byte, error) {
	return r.runWithTimeout(ctx, dir, extraEnv, 5*time.Minute, args...)
}

// runOK is run with a fallback that includes stdout in the error text.
func (r *Runner) runOK(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, error) {
	out, errOut, err := r.run(ctx, dir, extraEnv, args...)
	if err != nil {
		if len(bytes.TrimSpace(errOut)) == 0 && len(bytes.TrimSpace(out)) > 0 {
			return nil, &CommandError{Args: args, Stderr: string(out), Err: err}
		}
		return nil, err
	}
	return out, nil
}

func (r *Runner) RepoPath(owner, name string) string {
	return filepath.Join(r.RepoRoot, owner, name)
}

func (r *Runner) BrowsePath(repoID int64) string {
	return filepath.Join(r.CacheDir, "browse", fmt.Sprintf("%d", repoID))
}

func (r *Runner) CreateRepo(ctx context.Context, owner, name string) (string, error) {
	path := r.RepoPath(owner, name)
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return "", err
	}
	if _, err := r.runOK(ctx, filepath.Dir(path), nil, "init", path); err != nil {
		return "", err
	}
	_ = os.Chmod(path, 0o700)
	return path, nil
}

func (r *Runner) RepoExists(path string) bool {
	_, err := os.Stat(filepath.Join(path, ".veins", "format"))
	return err == nil
}

// RenameRepo moves a served repository to a new name under the same owner. The
// caller is responsible for updating the database record and access policy.
func (r *Runner) RenameRepo(ctx context.Context, owner, oldName, newName string, repoID int64) error {
	if oldName == newName {
		return nil
	}
	oldPath := r.RepoPath(owner, oldName)
	newPath := r.RepoPath(owner, newName)
	if !pathWithin(r.RepoRoot, oldPath) || !pathWithin(r.RepoRoot, newPath) {
		return errors.New("refusing to rename a path outside the repository root")
	}
	lock := r.repoLock(oldPath)
	lock.Lock()
	defer lock.Unlock()
	if _, err := os.Lstat(newPath); err == nil {
		return fmt.Errorf("destination %q already exists", newPath)
	} else if !errors.Is(err, os.ErrNotExist) {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(newPath), 0o700); err != nil {
		return err
	}
	if err := os.Rename(oldPath, newPath); err != nil {
		return err
	}
	r.mu.Lock()
	delete(r.fetchAt, repoID)
	delete(r.fetchHead, repoID)
	delete(r.currentRev, repoID)
	r.mu.Unlock()
	return nil
}

func (r *Runner) RemoveRepo(ctx context.Context, owner, name string, repoID int64) error {
	path := r.RepoPath(owner, name)
	if !pathWithin(r.RepoRoot, path) {
		return errors.New("refusing to remove path outside repository root")
	}
	if err := os.RemoveAll(path); err != nil {
		return err
	}
	browse := r.BrowsePath(repoID)
	if pathWithin(filepath.Join(r.CacheDir, "browse"), browse) {
		_ = os.RemoveAll(browse)
	}
	r.mu.Lock()
	delete(r.fetchAt, repoID)
	delete(r.fetchHead, repoID)
	delete(r.currentRev, repoID)
	r.mu.Unlock()
	return nil
}

func pathWithin(root, child string) bool {
	rel, err := filepath.Rel(root, child)
	return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}

type limitedBuffer struct {
	buf bytes.Buffer
	max int
}

func (b *limitedBuffer) Write(p []byte) (int, error) {
	if b.max == 0 {
		b.max = 16 << 20
	}
	remaining := b.max - b.buf.Len()
	if remaining <= 0 {
		return len(p), nil
	}
	if len(p) > remaining {
		b.buf.Write(p[:remaining])
	} else {
		b.buf.Write(p)
	}
	return len(p), nil
}

func (b *limitedBuffer) Bytes() []byte { return b.buf.Bytes() }

func truncate(s string, n int) string {
	if len(s) <= n {
		return s
	}
	return s[:n] + "..."
}

func sortedKeys[V any](m map[string]V) []string {
	out := make([]string, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	sort.Strings(out)
	return out
}

var _ io.Writer = (*limitedBuffer)(nil)