Files
CephfsMig/internal/migration/process.go
T
Sebastian UnterschützandClaude Opus 5.5 7705ed3eaf chore: import CephMig prototype
Initial import of the existing CephFS subvolume migration prototype,
including the native libcephfs transport, rsync backend, local Ceph
lab environment and integration tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 18:05:53 +01:00

93 lines
2.1 KiB
Go

package migration
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"syscall"
"time"
)
type Executor interface {
Exec(context.Context, io.Writer, string, ...string) error
}
type Process struct{ Stderr io.Writer }
type ProcessError struct {
Name string
Err error
Diagnostic string
}
func (e *ProcessError) Error() string { return fmt.Sprintf("%s failed: %v", e.Name, e.Err) }
func (e *ProcessError) Unwrap() error { return e.Err }
type tailBuffer struct{ data []byte }
func (b *tailBuffer) Write(p []byte) (int, error) {
const limit = 4096
n := len(p)
if n >= limit {
b.data = append(b.data[:0], p[n-limit:]...)
return n, nil
}
if len(b.data)+n > limit {
b.data = append(b.data[:0], b.data[len(b.data)+n-limit:]...)
}
b.data = append(b.data, p...)
return n, nil
}
func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdout = out
var diagnostic tailBuffer
cmd.Stderr = &diagnostic
if p.Stderr != nil {
cmd.Stderr = io.MultiWriter(p.Stderr, &diagnostic)
}
cmd.Env = append(os.Environ(), "LC_ALL=C")
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
cmd.WaitDelay = 5 * time.Second
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
// Do not print arguments: Ceph metadata values may be confidential.
return &ProcessError{Name: name, Err: err, Diagnostic: strings.TrimSpace(string(diagnostic.data))}
}
return nil
}
type limitedBuffer struct {
bytes.Buffer
limit int
}
func (b *limitedBuffer) Write(p []byte) (int, error) {
if len(p) > b.limit-b.Len() {
return 0, errors.New("command output exceeds configured limit")
}
return b.Buffer.Write(p)
}
func output(ctx context.Context, x Executor, name string, args ...string) ([]byte, error) {
b := &limitedBuffer{limit: 16 << 20}
if err := x.Exec(ctx, b, name, args...); err != nil {
return nil, err
}
return b.Bytes(), nil
}