Add nasctl: Go NAS control plane with React frontend

This commit is contained in:
2026-07-05 17:37:19 -04:00
parent 359fd5a160
commit 4f0754ecc5
56 changed files with 6725 additions and 1 deletions
+14
View File
@@ -0,0 +1,14 @@
package modules
import (
"context"
"github.com/darroyo/nasctl/internal/db"
)
// Module represents a configurable subsystem managed by nasctl.
type Module interface {
Name() string
IsDirty(ctx context.Context, database *db.DB) (bool, error)
Apply(ctx context.Context, database *db.DB) error
}
+4
View File
@@ -0,0 +1,4 @@
# Generated by nasctl. Do not edit manually.
{{range .Exports}}
{{.Path}} {{.ClientSpec}}
{{- end}}
+168
View File
@@ -0,0 +1,168 @@
package nfs
import (
"bytes"
"context"
"embed"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/darroyo/nasctl/internal/db"
"github.com/darroyo/nasctl/internal/system"
)
const ModuleName = "nfs"
//go:embed exports.tmpl
var exportsTemplate embed.FS
type Config struct {
ExportsPath string
Reload bool
}
type Module struct {
cfg Config
}
type templateExport struct {
Path string
ClientSpec string
}
type templateData struct {
Exports []templateExport
}
func New(cfg Config) *Module {
if cfg.ExportsPath == "" {
cfg.ExportsPath = "/etc/exports"
}
return &Module{cfg: cfg}
}
func (m *Module) Name() string {
return ModuleName
}
func (m *Module) IsDirty(ctx context.Context, database *db.DB) (bool, error) {
return database.IsDirty(ModuleName)
}
func (m *Module) Apply(ctx context.Context, database *db.DB) error {
exports, err := database.ListNFSExports()
if err != nil {
return err
}
content, err := m.renderConfig(exports)
if err != nil {
return err
}
if err := writeAtomic(m.cfg.ExportsPath, content); err != nil {
return err
}
if m.cfg.Reload {
stdout, stderr, err := system.Run(ctx, "exportfs", "-ra")
if err != nil {
return fmt.Errorf("exportfs -ra: %w (stdout=%q stderr=%q)", err, stdout, stderr)
}
}
message := fmt.Sprintf("applied %d nfs export(s) to %s", len(exports), m.cfg.ExportsPath)
if err := database.AppendApplyLog(ModuleName, message, true); err != nil {
return err
}
return database.ClearDirty(ModuleName)
}
// clientSpec builds the "client(opts) client(opts)" segment of an exports line.
// If no clients are configured, it defaults to "*(opts)".
func clientSpec(clients []string, options string) string {
opts := strings.TrimSpace(options)
if opts == "" {
opts = "ro"
}
if len(clients) == 0 {
return fmt.Sprintf("*(%s)", opts)
}
specs := make([]string, 0, len(clients))
for _, client := range clients {
client = strings.TrimSpace(client)
if client == "" {
continue
}
specs = append(specs, fmt.Sprintf("%s(%s)", client, opts))
}
if len(specs) == 0 {
return fmt.Sprintf("*(%s)", opts)
}
return strings.Join(specs, " ")
}
func (m *Module) renderConfig(exports []db.NFSExport) ([]byte, error) {
tmplContent, err := exportsTemplate.ReadFile("exports.tmpl")
if err != nil {
return nil, fmt.Errorf("read exports template: %w", err)
}
tmpl, err := template.New("exports").Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parse exports template: %w", err)
}
data := templateData{Exports: make([]templateExport, 0, len(exports))}
for _, export := range exports {
data.Exports = append(data.Exports, templateExport{
Path: export.Path,
ClientSpec: clientSpec(export.Clients, export.Options),
})
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("execute exports template: %w", err)
}
return buf.Bytes(), nil
}
func writeAtomic(path string, content []byte) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create config dir: %w", err)
}
tmp, err := os.CreateTemp(dir, ".exports.*")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmp.Name()
cleanup := func() {
_ = tmp.Close()
_ = os.Remove(tmpPath)
}
if _, err := tmp.Write(content); err != nil {
cleanup()
return fmt.Errorf("write temp config: %w", err)
}
if err := tmp.Chmod(0o644); err != nil {
cleanup()
return fmt.Errorf("chmod temp config: %w", err)
}
if err := tmp.Close(); err != nil {
cleanup()
return fmt.Errorf("close temp config: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
cleanup()
return fmt.Errorf("rename temp config: %w", err)
}
return nil
}
+158
View File
@@ -0,0 +1,158 @@
package samba
import (
"bytes"
"context"
"embed"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/darroyo/nasctl/internal/db"
"github.com/darroyo/nasctl/internal/system"
)
const ModuleName = "samba"
//go:embed smb.conf.tmpl
var smbConfTemplate embed.FS
type Config struct {
SMBConfPath string
Reload bool
}
type Module struct {
cfg Config
}
type templateShare struct {
Name string
Path string
Comment string
ReadOnly bool
GuestOK bool
ValidUsers []string
ValidGroups []string
}
type templateData struct {
Shares []templateShare
}
func New(cfg Config) *Module {
if cfg.SMBConfPath == "" {
cfg.SMBConfPath = "/etc/samba/smb.conf"
}
return &Module{cfg: cfg}
}
func (m *Module) Name() string {
return ModuleName
}
func (m *Module) IsDirty(ctx context.Context, database *db.DB) (bool, error) {
return database.IsDirty(ModuleName)
}
func (m *Module) Apply(ctx context.Context, database *db.DB) error {
shares, err := database.ListSambaShares()
if err != nil {
return err
}
content, err := m.renderConfig(shares)
if err != nil {
return err
}
if err := writeAtomic(m.cfg.SMBConfPath, content); err != nil {
return err
}
if m.cfg.Reload {
stdout, stderr, err := system.Run(ctx, "systemctl", "reload", "smbd")
if err != nil {
return fmt.Errorf("reload smbd: %w (stdout=%q stderr=%q)", err, stdout, stderr)
}
}
message := fmt.Sprintf("applied %d samba share(s) to %s", len(shares), m.cfg.SMBConfPath)
if err := database.AppendApplyLog(ModuleName, message, true); err != nil {
return err
}
return database.ClearDirty(ModuleName)
}
func (m *Module) renderConfig(shares []db.SambaShare) ([]byte, error) {
tmplContent, err := smbConfTemplate.ReadFile("smb.conf.tmpl")
if err != nil {
return nil, fmt.Errorf("read smb.conf template: %w", err)
}
funcMap := template.FuncMap{
"join": strings.Join,
}
tmpl, err := template.New("smb.conf").Funcs(funcMap).Parse(string(tmplContent))
if err != nil {
return nil, fmt.Errorf("parse smb.conf template: %w", err)
}
data := templateData{Shares: make([]templateShare, 0, len(shares))}
for _, share := range shares {
data.Shares = append(data.Shares, templateShare{
Name: share.Name,
Path: share.Path,
Comment: share.Comment,
ReadOnly: share.ReadOnly,
GuestOK: share.GuestOK,
ValidUsers: share.ValidUsers,
ValidGroups: share.ValidGroups,
})
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("execute smb.conf template: %w", err)
}
return buf.Bytes(), nil
}
func writeAtomic(path string, content []byte) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create config dir: %w", err)
}
tmp, err := os.CreateTemp(dir, ".smb.conf.*")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmp.Name()
cleanup := func() {
_ = tmp.Close()
_ = os.Remove(tmpPath)
}
if _, err := tmp.Write(content); err != nil {
cleanup()
return fmt.Errorf("write temp config: %w", err)
}
if err := tmp.Chmod(0o644); err != nil {
cleanup()
return fmt.Errorf("chmod temp config: %w", err)
}
if err := tmp.Close(); err != nil {
cleanup()
return fmt.Errorf("close temp config: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
cleanup()
return fmt.Errorf("rename temp config: %w", err)
}
return nil
}
+24
View File
@@ -0,0 +1,24 @@
# Generated by nasctl. Do not edit manually.
[global]
workgroup = WORKGROUP
server string = nasctl
security = user
map to guest = Bad User
dns proxy = no
{{range .Shares}}
[{{.Name}}]
path = {{.Path}}
comment = {{.Comment}}
browseable = yes
read only = {{if .ReadOnly}}yes{{else}}no{{end}}
guest ok = {{if .GuestOK}}yes{{else}}no{{end}}
{{- if .ValidUsers}}
valid users = {{join .ValidUsers ","}}
{{- end}}
{{- if .ValidGroups}}
valid groups = {{join .ValidGroups ","}}
{{- end}}
{{end}}
+185
View File
@@ -0,0 +1,185 @@
package users
import (
"context"
"fmt"
"strings"
"github.com/darroyo/nasctl/internal/db"
"github.com/darroyo/nasctl/internal/system"
)
const ModuleName = "users"
type Config struct {
// Execute controls whether system commands actually run. Disabled in dev.
Execute bool
// DefaultShell used when creating users.
DefaultShell string
// CreateHome creates a home directory for new users.
CreateHome bool
}
type Module struct {
cfg Config
}
func New(cfg Config) *Module {
if cfg.DefaultShell == "" {
cfg.DefaultShell = "/usr/sbin/nologin"
}
return &Module{cfg: cfg}
}
func (m *Module) Name() string {
return ModuleName
}
func (m *Module) IsDirty(ctx context.Context, database *db.DB) (bool, error) {
return database.IsDirty(ModuleName)
}
func (m *Module) Apply(ctx context.Context, database *db.DB) error {
deleted, err := database.ListDeletedUsers()
if err != nil {
return err
}
for _, username := range deleted {
if err := m.deleteUser(ctx, username); err != nil {
return err
}
if err := database.ClearDeletedUser(username); err != nil {
return err
}
}
usersList, err := database.ListUsers()
if err != nil {
return err
}
for _, user := range usersList {
if err := m.reconcileUser(ctx, database, user); err != nil {
return err
}
}
message := fmt.Sprintf("reconciled %d user(s), %d deletion(s)", len(usersList), len(deleted))
if err := database.AppendApplyLog(ModuleName, message, true); err != nil {
return err
}
return database.ClearDirty(ModuleName)
}
func (m *Module) reconcileUser(ctx context.Context, database *db.DB, user db.User) error {
if err := system.ValidateUsername(user.Username); err != nil {
return err
}
exists := m.cfg.Execute && system.UserExists(ctx, user.Username)
if !m.cfg.Execute {
// In dev mode we do not touch the system; just clear pending secrets
// so they are not retained indefinitely.
if user.PendingPassword != "" {
return database.ClearUserPendingPassword(user.ID)
}
return nil
}
groups := sanitizeGroups(user.Groups)
if !exists {
args := []string{"-s", m.cfg.DefaultShell}
if m.cfg.CreateHome {
args = append(args, "-m")
} else {
args = append(args, "-M")
}
if len(groups) > 0 {
args = append(args, "-G", strings.Join(groups, ","))
}
args = append(args, user.Username)
if err := m.run(ctx, "useradd", args...); err != nil {
return err
}
} else {
args := []string{"-G", strings.Join(groups, ",")}
args = append(args, user.Username)
if err := m.run(ctx, "usermod", args...); err != nil {
return err
}
}
if user.Disabled {
if err := m.run(ctx, "usermod", "-L", user.Username); err != nil {
return err
}
} else {
// Unlock; ignore error when there is nothing to unlock.
_ = m.run(ctx, "usermod", "-U", user.Username)
}
if err := m.applySMB(ctx, database, user); err != nil {
return err
}
return nil
}
func (m *Module) applySMB(ctx context.Context, database *db.DB, user db.User) error {
if user.SMBEnabled {
if user.PendingPassword != "" {
// smbpasswd -a -s reads the new password twice from stdin.
input := user.PendingPassword + "\n" + user.PendingPassword + "\n"
stdout, stderr, err := system.RunWithInput(ctx, input, "smbpasswd", "-a", "-s", user.Username)
if err != nil {
return fmt.Errorf("smbpasswd -a for %s: %w (stdout=%q stderr=%q)", user.Username, err, stdout, stderr)
}
if err := database.ClearUserPendingPassword(user.ID); err != nil {
return err
}
}
// Ensure the smb account is enabled.
_ = m.run(ctx, "smbpasswd", "-e", user.Username)
} else {
// Disable SMB access; ignore error when the account is not present.
_ = m.run(ctx, "smbpasswd", "-x", user.Username)
}
return nil
}
func (m *Module) deleteUser(ctx context.Context, username string) error {
if err := system.ValidateUsername(username); err != nil {
return err
}
if !m.cfg.Execute {
return nil
}
// Remove SMB entry first (ignore if absent), then the system user.
_ = m.run(ctx, "smbpasswd", "-x", username)
if system.UserExists(ctx, username) {
if err := m.run(ctx, "userdel", username); err != nil {
return err
}
}
return nil
}
func (m *Module) run(ctx context.Context, name string, args ...string) error {
stdout, stderr, err := system.Run(ctx, name, args...)
if err != nil {
return fmt.Errorf("%s %s: %w (stdout=%q stderr=%q)", name, strings.Join(args, " "), err, stdout, stderr)
}
return nil
}
func sanitizeGroups(groups []string) []string {
out := make([]string, 0, len(groups))
for _, g := range groups {
g = strings.TrimSpace(g)
if g != "" {
out = append(out, g)
}
}
return out
}