feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-18 10:41:36 +01:00
1 parent 8d4915543e
commit e5bde9c61f
32 files changed
+2083 -64

No files matched your search

+131 -28
View File
@@ -17,6 +17,7 @@ import (
tea "charm.land/bubbletea/v2"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
@@ -30,6 +31,7 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{
"doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"configure": true,
"notes": true,
"search": true,
@@ -75,6 +77,10 @@ func main() {
if managedSubcommands[args[0]] {
if err := rootCmd().Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
os.Exit(1)
}
return
@@ -208,25 +214,43 @@ func prependArgs(extra, args []string, dests []int) []string {
// resolvedHost is a NetBox host with the address to connect to.
type resolvedHost struct {
Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
Origin string
Resolver string
CachedAt time.Time
Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
}
// resolveTarget finds host in the cache (also by shortcut) or NetBox and
// resolves its address. It exits on failure.
func resolveTarget(cfg *config.Config, host string) resolvedHost {
result, err := resolveTargetE(cfg, host, true)
if err != nil {
fatalf("%v", err)
}
return result
}
func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) {
c := newCache(cfg)
_ = c.Load()
maybeBackgroundRefresh(cfg, c)
if record {
maybeBackgroundRefresh(cfg, c)
}
source, _ := netbox.SplitTarget(host)
useCache := len(cfg.NetBoxes) == 0 || source != ""
used := func(entry cache.Entry) resolvedHost {
c.MarkUsed(entry.Name)
_ = c.Save()
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags}
if record {
c.MarkUsed(entry.Name)
_ = c.Save()
}
origin := "cache"
if entry.Static {
origin = "static"
}
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt}
}
// Static hosts from the config win and need no NetBox.
@@ -237,16 +261,16 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
}
entry, found, err := c.GetStatic(host, normalize)
if err != nil {
fatalf("%v", err)
return resolvedHost{}, err
}
if found {
return used(entry)
return used(entry), nil
}
}
// Cache hit with a fresh TTL — connect directly without querying NetBox.
if entry, fresh := c.Get(host); fresh && useCache {
return used(entry)
return used(entry), nil
}
// Shortcut cache lookup: scan entries whose normalized name matches the input.
@@ -257,11 +281,11 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
normalize := normalizeTarget(cfg.Shortcuts, source != "")
entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize)
if err != nil {
fatalf("%v", err)
return resolvedHost{}, err
}
if found {
if fresh {
return used(entry)
return used(entry), nil
}
// Stale shortcut match — use canonical name for NetBox re-fetch.
lookupHost = entry.Name
@@ -269,7 +293,7 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
}
if !cfg.HasNetBox() {
fatalf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host)
return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host)
}
nbClient := newNetBoxClient(cfg)
@@ -280,33 +304,35 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled {
entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false))
if cacheErr != nil {
fatalf("%v", cacheErr)
return resolvedHost{}, cacheErr
}
if found {
target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains)
}
}
if err != nil {
fatalf("NetBox: %v", err)
return resolvedHost{}, fmt.Errorf("NetBox: %w", err)
}
if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind {
return used(cached)
return used(cached), nil
}
chain, err := resolver.New(cfg.Resolver)
if err != nil {
fatalf("resolver: %v", err)
return resolvedHost{}, err
}
ip, err := chain.Resolve(ctx, &target, nbClient)
ip, strategy, err := chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil {
fatalf("IP resolution for %q: %v", host, err)
return resolvedHost{}, fmt.Errorf("IP resolution for %q: %w", host, err)
}
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster}
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy}
c.Upsert(entry)
return used(entry)
result := used(entry)
result.Origin = "live"
return result, nil
}
// findSSHHost uses the paginated, ambiguity-checking lookup for connection
@@ -353,7 +379,24 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
fatalf("%v", err)
}
_, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
result := client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags)
post := config.HookCommand(opts.PostDisconnect)
if flags.DryRun {
if post != "" {
fmt.Fprintf(os.Stderr, "# post_disconnect (skipped in --dry-run): %s\n", post)
}
}
if !flags.DryRun && (post != "" || cfg.Activity.Enabled) {
if result.Notice != "" {
fmt.Fprintln(os.Stderr, result.Notice)
}
code := supervise(cfg, host, client.Name, append([]string{client.Name}, result.Args...), post, 0, false, os.Stdin, os.Stdout, os.Stderr)
if code != 0 {
os.Exit(code)
}
return
}
execClient(client, result, flags)
}
// hostOptions merges the global, instance, and rule SSH options for host.
@@ -391,6 +434,49 @@ func runTUI() {
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
m.SetHostLabel(cfg.HostLabel)
m.SetHistoryLimit(cfg.TUI.HistoryLimit)
state, stateErr := activity.Read()
if stateErr != nil {
fmt.Fprintf(os.Stderr, "favorites: %v\n", stateErr)
}
m.SetPreferences(state.Favorites, state.Pinned, func(favorites, pinned map[string]bool) error {
err := activity.Update(func(s *activity.State) {
merge := func(dst, previous, next map[string]bool) {
for name, value := range next {
if previous[name] != value {
if value {
dst[name] = true
} else {
delete(dst, name)
}
}
}
for name, value := range previous {
if value && !next[name] {
delete(dst, name)
}
}
}
merge(s.Favorites, state.Favorites, favorites)
merge(s.Pinned, state.Pinned, pinned)
})
if err == nil {
state.Favorites = favorites
state.Pinned = pinned
}
return err
})
m.SetCommands(func(name, kind string, tags []string) []string {
var names []string
h := commandHost(resolvedHost{Name: name, Kind: kind, Tags: tags})
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
}
}
sort.Strings(names)
return names
})
if cfg.Shortcuts.Show {
aliases := shortcutAliases(c.All(), *cfg)
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] })
@@ -413,6 +499,22 @@ func runTUI() {
if host == nil {
return
}
if host.Command != "" {
args := []string{"run", host.Command, "--", host.Name}
if len(host.Targets) > 0 {
args = append([]string{"batch", host.Command}, host.Targets...)
}
root := rootCmd()
root.SetArgs(args)
if err := root.Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
fatalf("%v", err)
}
return
}
if host.Action == tui.ActionMulti {
if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil {
fatalf("%v", err)
@@ -439,11 +541,12 @@ func runTUI() {
if err != nil {
fatalf("resolver: %v", err)
}
host.IP, err = chain.Resolve(ctx, &target, nbClient)
var strategy string
host.IP, strategy, err = chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil {
fatalf("IP resolution: %v", err)
}
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster})
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy})
tags = target.Tags
}
fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP)
@@ -529,7 +632,7 @@ func rootCmd() *cobra.Command {
},
}
root.AddCommand(runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd())
root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd())
// cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd()
@@ -792,7 +895,7 @@ func cacheRefreshCmd() *cobra.Command {
continue
}
ip, err := chain.Resolve(ctx, e, nbClient)
ip, strategy, err := chain.ResolveWithStrategy(ctx, e, nbClient)
if err != nil {
// Do not turn a failed configured strategy into a fresh
// primary-IP cache hit that bypasses the resolver.
@@ -803,7 +906,7 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue
}
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster})
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Resolver: strategy})
written++
}