package nas import ( "context" "fmt" "io" "log" "os" "sync" ) // NASService writes to a NAS destination without caring how this host reaches // it. Parsing the destination and attaching it are delegated to a Location and // a Connector; everything below operates on the resolved base path, which is // always an ordinary path this host's filesystem understands. type NASService struct { Config NASConfig location Location connector Connector mu sync.RWMutex attached Attachment connected bool } // New parses the configured destination and selects a connection strategy for // the running host. It performs no I/O and does not touch the network, so it is // safe to call before deciding whether a transfer will actually happen; call // Connect to attach the destination. func New(config NASConfig) (*NASService, error) { loc, err := ParseLocation(config.Path) if err != nil { return nil, err } return &NASService{ Config: config, location: loc, connector: defaultConnector(loc), }, nil } // Connect attaches the destination, ensures the target directory exists, and // proves it is writable. The write probe matters: on both platforms a share can // be reachable and still reject writes, and finding that out at startup beats // discovering it mid-recording. func (nt *NASService) Connect(ctx context.Context) error { att, err := nt.connector.Attach(ctx, nt.location, nt.Config) if err != nil { return err } nt.mu.Lock() nt.attached = att nt.mu.Unlock() // From here on the attachment exists, so any failure has to undo it — // otherwise a mount this process created would outlive the failed startup // and be left behind on the host. if err := nt.EnsureDirectoryExists(att.BasePath); err != nil { nt.abandon(ctx, att) return fmt.Errorf("%s is reachable but %s is unusable: %w", nt.location, att.BasePath, err) } if err := nt.writeProbe(att.BasePath); err != nil { nt.abandon(ctx, att) return err } nt.mu.Lock() nt.connected = true nt.mu.Unlock() log.Printf("Connected to NAS at %s", att.BasePath) return nil } // abandon releases a half-finished attachment after Connect fails. The // original error is the one worth reporting, so a teardown failure is only // logged. func (nt *NASService) abandon(ctx context.Context, att Attachment) { // Keep the notes: they explain how far the host got, which is exactly what // the caller needs to report. Everything else is cleared so the service // cannot be mistaken for usable and Detach cannot run twice. nt.mu.Lock() nt.attached = Attachment{Notes: att.Notes} nt.connected = false nt.mu.Unlock() if err := nt.connector.Detach(ctx, att); err != nil { log.Printf("Warning: failed to release NAS attachment after a failed connect: %v", err) } } // writeProbe creates and removes a file to confirm the destination accepts // writes. func (nt *NASService) writeProbe(basePath string) error { testFile := joinBase(basePath, ".connection_test") f, err := os.Create(testFile) if err != nil { return fmt.Errorf("%s is not writable: %w", basePath, err) } f.Close() if err := os.Remove(testFile); err != nil { log.Printf("Warning: failed to remove connection test file %s: %v", testFile, err) } return nil } // Disconnect releases only what Connect established. A share that was already // mounted or already connected when the recorder started is left exactly as it // was found. func (nt *NASService) Disconnect(ctx context.Context) error { nt.mu.Lock() att := nt.attached nt.attached = Attachment{} nt.connected = false nt.mu.Unlock() if err := nt.connector.Detach(ctx, att); err != nil { return err } if att.Owned { log.Printf("Released NAS connection to %s", nt.location) } return nil } // LocalPath is the resolved base directory on this host, valid after Connect. func (nt *NASService) LocalPath() string { nt.mu.RLock() defer nt.mu.RUnlock() return nt.attached.BasePath } // Join resolves elements against the NAS base path using whatever separator // this host's base path requires. func (nt *NASService) Join(elem ...string) string { return joinBase(nt.LocalPath(), elem...) } // Location returns the parsed destination. func (nt *NASService) Location() Location { return nt.location } // ConnectionInfo describes how this host reaches the destination, for check // output and startup logs. Safe to call before Connect, when it reports only // what is known from configuration. func (nt *NASService) ConnectionInfo() []string { nt.mu.RLock() defer nt.mu.RUnlock() info := []string{ "configured: " + nt.location.String(), "strategy: " + nt.connector.Name(), } info = append(info, nt.attached.Notes...) if nt.attached.BasePath != "" && nt.attached.BasePath != nt.location.Raw { info = append(info, "resolved path: "+nt.attached.BasePath) } return info } func (nt *NASService) IsConnected() bool { nt.mu.RLock() defer nt.mu.RUnlock() return nt.connected } func (nt *NASService) CopyFile(ctx context.Context, srcPath, destPath string) error { src, err := os.Open(srcPath) if err != nil { return fmt.Errorf("Failed to open source file: %w", err) } defer src.Close() dest, err := os.Create(destPath) if err != nil { return fmt.Errorf("Failed to create destination file: %w", err) } defer dest.Close() done := make(chan error, 1) go func() { _, err := io.Copy(dest, src) done <- err }() select { case <-ctx.Done(): return ctx.Err() case err := <-done: if err != nil { return err } return dest.Sync() } } func (nt *NASService) VerifyTransfer(srcPath, destPath string) error { srcInfo, err := os.Stat(srcPath) if err != nil { return fmt.Errorf("Failed to stat source file: %w", err) } destInfo, err := os.Stat(destPath) if err != nil { return fmt.Errorf("Failed to stat destination file: %w", err) } if srcInfo.Size() != destInfo.Size() { return fmt.Errorf("size mismatch: source=%d, dest=%d", srcInfo.Size(), destInfo.Size()) } return nil } func (nt *NASService) EnsureDirectoryExists(path string) error { if err := os.MkdirAll(path, 0755); err != nil { return fmt.Errorf("Failed to create directory: %w", err) } return nil } // FileExists checks whether a file already exists on the NAS, optionally // verifying its size. destinationPath is relative to the NAS base path. func (nt *NASService) FileExists(destinationPath string, expectedSize int64) (bool, error) { fullDestPath := nt.Join(destinationPath) destInfo, err := os.Stat(fullDestPath) if err != nil { if os.IsNotExist(err) { return false, nil // File doesn't exist, no error } return false, fmt.Errorf("failed to stat NAS file: %w", err) } // File exists, check size if expected size is provided if expectedSize > 0 && destInfo.Size() != expectedSize { log.Printf("NAS file size mismatch for %s: expected=%d, actual=%d", fullDestPath, expectedSize, destInfo.Size()) return false, nil // File exists but wrong size, treat as not existing } return true, nil } // GetFileSize returns the size of a file on the NAS, relative to the base path. func (nt *NASService) GetFileSize(destinationPath string) (int64, error) { fullDestPath := nt.Join(destinationPath) destInfo, err := os.Stat(fullDestPath) if err != nil { return 0, fmt.Errorf("failed to stat NAS file: %w", err) } return destInfo.Size(), nil }