StreamRecorder/pkg/nas/connector_mount.go
Aaron e2566fdefa
Some checks failed
Build Go Binaries / build (push) Has been cancelled
Claude bugfixes
2026-08-07 03:49:37 +00:00

179 lines
5.8 KiB
Go

package nas
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
)
// linuxConnector reaches a share the way Linux does: through a mount point in
// the single filesystem tree. There is no per-path authentication, so the
// question is not "can we connect" but "where is this share mounted".
//
// The default and by far the safest answer is that the host already mounted it
// (fstab, autofs, systemd, or `docker run -v`), so the connector looks the
// share up in the mount table. Mounting it here is opt-in because it requires
// root and changes system state that outlives a failed run.
type linuxConnector struct {
run commandRunner
mountsPath string
// geteuid is indirected for tests; production uses os.Geteuid.
geteuid func() int
}
func (c *linuxConnector) Name() string { return "mount" }
func (c *linuxConnector) Attach(ctx context.Context, loc Location, cfg NASConfig) (Attachment, error) {
entries, err := readMountTable(c.mountsPath)
if err != nil {
return Attachment{}, err
}
if point, rest, ok := findMount(entries, loc); ok {
return Attachment{
BasePath: filepath.Join(append([]string{point}, rest...)...),
Notes: []string{
"share: " + loc.SMBSource(),
fmt.Sprintf("resolved via existing mount at %s", point),
},
}, nil
}
if !cfg.AutoMount {
return Attachment{}, fmt.Errorf("%s", notMountedMessage(loc, cfg))
}
return c.mount(ctx, loc, cfg)
}
func (c *linuxConnector) Detach(ctx context.Context, att Attachment) error {
// Never unmount a share the host had already mounted; other software may
// be using it, and we did not put it there.
if !att.Owned || att.mountPoint == "" {
return nil
}
if out, err := c.run(ctx, "umount", att.mountPoint); err != nil {
return fmt.Errorf("failed to unmount %s: %v", att.mountPoint, summarize(err, out))
}
return nil
}
// mount performs an opt-in mount.cifs of the share.
func (c *linuxConnector) mount(ctx context.Context, loc Location, cfg NASConfig) (Attachment, error) {
geteuid := c.geteuid
if geteuid == nil {
geteuid = os.Geteuid
}
if geteuid() != 0 {
return Attachment{}, fmt.Errorf(
"NAS_AUTO_MOUNT is set but mounting %s requires root; run as root, or mount the share beforehand and %s",
loc.SMBSource(), suggestMountPointConfig(loc))
}
point := autoMountPoint(loc, cfg)
if err := os.MkdirAll(point, 0755); err != nil {
return Attachment{}, fmt.Errorf("failed to create mount point %s: %w", point, err)
}
credentialsPath, cleanup, err := writeCredentialsFile(cfg)
if err != nil {
return Attachment{}, err
}
defer cleanup()
if cfg.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cfg.Timeout)
defer cancel()
}
if out, err := c.run(ctx, "mount", mountArgs(loc, point, credentialsPath)...); err != nil {
return Attachment{}, fmt.Errorf("failed to mount %s at %s: %v", loc.SMBSource(), point, summarize(err, out))
}
return Attachment{
BasePath: filepath.Join(append([]string{point}, loc.Sub...)...),
Owned: true,
mountPoint: point,
Notes: []string{
"share: " + loc.SMBSource(),
"user: " + usernameNote(cfg.Username),
fmt.Sprintf("mounted at %s by this process (will unmount on shutdown)", point),
},
}, nil
}
// mountArgs builds the mount.cifs invocation. Kept pure so it can be asserted
// without mounting anything.
func mountArgs(loc Location, mountPoint, credentialsPath string) []string {
options := "rw"
if credentialsPath != "" {
options += ",credentials=" + credentialsPath
} else {
options += ",guest"
}
return []string{"-t", "cifs", loc.SMBSource(), mountPoint, "-o", options}
}
// writeCredentialsFile stages the NAS credentials in a 0600 file. mount.cifs
// also accepts user=/pass= options, but those land in the process table where
// any local user can read the password; a credentials file does not.
func writeCredentialsFile(cfg NASConfig) (path string, cleanup func(), err error) {
if cfg.Username == "" || cfg.Password == "" {
return "", func() {}, nil
}
dir, err := os.MkdirTemp("", "streamrecorder-cifs-")
if err != nil {
return "", func() {}, fmt.Errorf("failed to stage NAS credentials: %w", err)
}
cleanup = func() { os.RemoveAll(dir) }
path = filepath.Join(dir, "credentials")
content := fmt.Sprintf("username=%s\npassword=%s\n", cfg.Username, cfg.Password)
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
cleanup()
return "", func() {}, fmt.Errorf("failed to write NAS credentials file: %w", err)
}
return path, cleanup, nil
}
// autoMountPoint chooses where to mount the share when the operator has not
// named a location. Everything lands under one predictable directory so a
// leftover mount is easy to find and clean up.
func autoMountPoint(loc Location, cfg NASConfig) string {
if cfg.MountPoint != "" {
return cfg.MountPoint
}
return filepath.Join("/mnt", "streamrecorder", strings.ToLower(loc.Server), strings.ToLower(loc.Share))
}
// notMountedMessage explains the failure in terms of what the operator should
// actually type. A bare "no such mount" would leave them guessing.
func notMountedMessage(loc Location, cfg NASConfig) string {
source := loc.SMBSource()
example := filepath.Join("/mnt", strings.ToLower(loc.Share))
credentials := ""
if cfg.Username != "" {
credentials = fmt.Sprintf(",username=%s,password=***", cfg.Username)
}
return fmt.Sprintf(
"%s is not mounted on this host. Either mount it and %s, for example:\n"+
" sudo mkdir -p %s && sudo mount -t cifs %s %s -o rw%s\n"+
"or set NAS_AUTO_MOUNT=true to have the recorder mount it (requires root)",
source, suggestMountPointConfig(loc), example, source, example, credentials)
}
func suggestMountPointConfig(loc Location) string {
if len(loc.Sub) == 0 {
return "set NAS_OUTPUT_PATH to the mount point"
}
return fmt.Sprintf("set NAS_OUTPUT_PATH to the mount point plus %s", loc.SubPath())
}