feat: add host actions, lifecycle hooks and operational tools
This commit is contained in:
1 parent
8d4915543e
commit
e5bde9c61f
32 files changed
+2083
-64
No files matched your search
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
type batchRetry struct {
|
||||
Command string
|
||||
Hosts []string
|
||||
Extra []string
|
||||
}
|
||||
type batchResult struct {
|
||||
Host string
|
||||
Code int
|
||||
}
|
||||
|
||||
var batchExecutable = os.Executable
|
||||
|
||||
func batchPath() string {
|
||||
return filepath.Join(filepath.Dir(config.Path()), "netssh", "last-failed.json")
|
||||
}
|
||||
func batchCmd() *cobra.Command {
|
||||
var parallel int
|
||||
var retry, yes, dry bool
|
||||
cmd := &cobra.Command{Use: "batch COMMAND HOST... [-- EXTRA_ARGS...]", Short: "Run a configured command on hosts with bounded parallelism", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if parallel < 1 || parallel > 64 {
|
||||
return fmt.Errorf("parallel must be between 1 and 64")
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
work := batchRetry{}
|
||||
if retry {
|
||||
if len(args) > 0 {
|
||||
return fmt.Errorf("--retry-failed takes no positional arguments")
|
||||
}
|
||||
data, err := os.ReadFile(batchPath())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = json.Unmarshal(data, &work); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
split := cmd.ArgsLenAtDash()
|
||||
if split >= 0 {
|
||||
work.Extra = args[split:]
|
||||
args = args[:split]
|
||||
}
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("specify COMMAND and at least one HOST")
|
||||
}
|
||||
work.Command, work.Hosts = args[0], args[1:]
|
||||
}
|
||||
command, ok := cfg.Commands[work.Command]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown command %q", work.Command)
|
||||
}
|
||||
if len(work.Hosts) == 0 {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "No failed hosts to retry.")
|
||||
return nil
|
||||
}
|
||||
// Resolve and validate the entire list before launching any action.
|
||||
var targets []string
|
||||
seen := map[string]bool{}
|
||||
for _, target := range work.Hosts {
|
||||
h, err := resolveTargetE(cfg, target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !command.Allowed(commandHost(h)) {
|
||||
return fmt.Errorf("%s is not allowed on %s", work.Command, h.Name)
|
||||
}
|
||||
if !seen[h.Name] {
|
||||
targets = append(targets, h.Name)
|
||||
seen[h.Name] = true
|
||||
}
|
||||
}
|
||||
if command.Confirm && !dry {
|
||||
if err := confirmAction(fmt.Sprintf("Run %s on %d hosts", work.Command, len(targets)), yes); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
executable, err := batchExecutable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Temporary output files bound memory even for very verbose commands.
|
||||
dir, err := os.MkdirTemp("", "netssh-batch-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
jobs := make(chan int)
|
||||
results := make(chan batchResult, len(targets))
|
||||
var wg sync.WaitGroup
|
||||
var output sync.Mutex
|
||||
for n := 0; n < parallel; n++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range jobs {
|
||||
host := targets[i]
|
||||
if ctx.Err() != nil {
|
||||
results <- batchResult{host, 130}
|
||||
continue
|
||||
}
|
||||
output.Lock()
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "[%s] starting\n", host)
|
||||
output.Unlock()
|
||||
f, err := os.CreateTemp(dir, "output-")
|
||||
if err != nil {
|
||||
results <- batchResult{host, 1}
|
||||
continue
|
||||
}
|
||||
argv := []string{executable, "run", "--yes"}
|
||||
if dry {
|
||||
argv = append(argv, "--dry-run")
|
||||
}
|
||||
argv = append(argv, work.Command, "--", host)
|
||||
argv = append(argv, work.Extra...)
|
||||
r := runner.Run(ctx, argv, runner.Options{Stdout: f, Stderr: f})
|
||||
f.Close()
|
||||
output.Lock()
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "[%s] exit=%d duration=%s\n", host, r.Code, r.Duration.Round(time.Millisecond))
|
||||
read, err := os.Open(f.Name())
|
||||
if err == nil {
|
||||
_, _ = io.Copy(cmd.OutOrStdout(), read)
|
||||
read.Close()
|
||||
}
|
||||
output.Unlock()
|
||||
results <- batchResult{host, r.Code}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := range targets {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
failed := map[string]bool{}
|
||||
for r := range results {
|
||||
if r.Code != 0 {
|
||||
failed[r.Host] = true
|
||||
}
|
||||
}
|
||||
work.Hosts = nil
|
||||
for _, host := range targets {
|
||||
if failed[host] {
|
||||
work.Hosts = append(work.Hosts, host)
|
||||
}
|
||||
}
|
||||
if !dry {
|
||||
data, _ := json.Marshal(work)
|
||||
if err := os.MkdirAll(filepath.Dir(batchPath()), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := storage.WriteFile(batchPath(), data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%d succeeded, %d failed\n", len(targets)-len(failed), len(failed))
|
||||
if len(failed) > 0 {
|
||||
return fmt.Errorf("batch failed; retry with netssh batch --retry-failed")
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
cmd.Flags().IntVar(¶llel, "parallel", 4, "Maximum simultaneous hosts (1-64)")
|
||||
cmd.Flags().BoolVar(&retry, "retry-failed", false, "Repeat failed targets from the last batch")
|
||||
cmd.Flags().BoolVar(&yes, "yes", false, "Confirm the batch action")
|
||||
cmd.Flags().BoolVar(&dry, "dry-run", false, "Resolve and print commands without running")
|
||||
return cmd
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string
|
||||
}
|
||||
plain := strings.NewReplacer(".", "_", "/", "_")
|
||||
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
|
||||
if alias.Host == "" {
|
||||
if alias.Host == "" || alias.Command != "" {
|
||||
continue // the command alias for netssh itself
|
||||
}
|
||||
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
|
||||
|
||||
+131
-28
@@ -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++
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func doctorCmd() *cobra.Command {
|
||||
var online bool
|
||||
cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
failed := false
|
||||
report := func(label string, err error) {
|
||||
if err != nil {
|
||||
failed = true
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err)
|
||||
} else {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label)
|
||||
}
|
||||
}
|
||||
report("configuration", nil)
|
||||
_, err = resolver.New(cfg.Resolver)
|
||||
report("resolver", err)
|
||||
programs := map[string]bool{"ssh": true, "sftp": true, "scp": true}
|
||||
for name, c := range cfg.Commands {
|
||||
programs[c.Args[0]] = true
|
||||
if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") {
|
||||
switch c.Args[0] {
|
||||
case "bash", "sh", "python", "python3":
|
||||
f, err := os.Open(c.Args[1])
|
||||
if err == nil {
|
||||
f.Close()
|
||||
}
|
||||
report("script "+name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
var names []string
|
||||
for p := range programs {
|
||||
names = append(names, p)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, p := range names {
|
||||
_, err := exec.LookPath(p)
|
||||
report("program "+p, err)
|
||||
}
|
||||
report("cache", newCache(cfg).Load())
|
||||
if online {
|
||||
sources := cfg.NetBoxes
|
||||
if len(sources) == 0 && cfg.NetBox.URL != "" {
|
||||
sources = []config.NetBoxConfig{cfg.NetBox}
|
||||
}
|
||||
for _, s := range sources {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
_, err := netbox.NewClient(s.URL, s.Token, s.TokenVersion).Search(ctx, "", netbox.SearchOptions{})
|
||||
cancel()
|
||||
report("NetBox "+s.Name, err)
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
return fmt.Errorf("doctor found problems")
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance")
|
||||
return cmd
|
||||
}
|
||||
func explainCmd() *cobra.Command {
|
||||
return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := resolveTargetE(cfg, args[0], false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
selectors := commandHost(h)
|
||||
user, port := hostDefaults(cfg, h)
|
||||
opts := hostOptions(cfg, h)
|
||||
var rules []int
|
||||
for i, r := range cfg.SSH.Rules {
|
||||
if r.Match.Matches(selectors) {
|
||||
rules = append(rules, i+1)
|
||||
}
|
||||
}
|
||||
strategy := h.Resolver
|
||||
if strategy == "" {
|
||||
if h.Origin == "static" {
|
||||
strategy = "static address"
|
||||
} else {
|
||||
strategy = "not recorded in this cache entry"
|
||||
}
|
||||
}
|
||||
return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
|
||||
"target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt,
|
||||
"resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts,
|
||||
})
|
||||
}}
|
||||
}
|
||||
func favoritesCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
s, err := activity.Read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var names []string
|
||||
for n := range s.Favorites {
|
||||
if s.Favorites[n] {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, n := range names {
|
||||
marker := "favorite"
|
||||
if s.Pinned[n] {
|
||||
marker = "pinned"
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker)
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
for _, action := range []string{"add", "remove", "pin", "unpin"} {
|
||||
cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
target := args[0]
|
||||
if action == "add" || action == "pin" {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := resolveTargetE(cfg, target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target = h.Name
|
||||
}
|
||||
return activity.Update(func(s *activity.State) {
|
||||
switch action {
|
||||
case "add":
|
||||
s.Favorites[target] = true
|
||||
case "pin":
|
||||
s.Favorites[target] = true
|
||||
s.Pinned[target] = true
|
||||
case "unpin":
|
||||
delete(s.Pinned, target)
|
||||
case "remove":
|
||||
delete(s.Favorites, target)
|
||||
delete(s.Pinned, target)
|
||||
}
|
||||
})
|
||||
}})
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
func historyCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := activity.Read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := len(s.Records) - 1; i >= 0; i-- {
|
||||
r := s.Records[i]
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond))
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error {
|
||||
return activity.Update(func(s *activity.State) { s.Records = nil })
|
||||
}})
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
func writeOperationsConfig(t *testing.T, extra string) {
|
||||
t.Helper()
|
||||
prepareTransferTest(t)
|
||||
data := `hosts:
|
||||
- name: router
|
||||
address: 192.0.2.1
|
||||
tags: [router]
|
||||
- name: fail
|
||||
address: 192.0.2.2
|
||||
- name: okay
|
||||
address: 192.0.2.3
|
||||
resolver:
|
||||
strategies: [primary_ip]
|
||||
` + extra
|
||||
if err := os.WriteFile(config.Path(), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestPostHooksFiltersAndConfirmation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
marker := filepath.Join(dir, "post")
|
||||
writeOperationsConfig(t, fmt.Sprintf(`
|
||||
commands:
|
||||
success:
|
||||
args: [sh, -c, "exit 0", "{host}"]
|
||||
post_run: 'printf "%%s:%%s" "$NETSSH_HOST" "$NETSSH_EXIT_CODE" > %s'
|
||||
failure:
|
||||
args: [sh, -c, "exit 7", "{host}"]
|
||||
post_run: 'printf "%%s" "$NETSSH_EXIT_CODE" > %s; exit 9'
|
||||
postfail:
|
||||
args: [sh, -c, "exit 0", "{host}"]
|
||||
post_run: exit 9
|
||||
protected:
|
||||
args: [sh, -c, "exit 0", "{host}"]
|
||||
confirm: true
|
||||
match: {tag: router, kind: static, name: "rou*"}
|
||||
timeout:
|
||||
args: [sh, -c, "sleep 20", "{host}"]
|
||||
timeout: 50ms
|
||||
activity:
|
||||
enabled: true
|
||||
retention_days: 30
|
||||
max_entries: 50
|
||||
`, marker, marker))
|
||||
if out, err := runNetssh(t, "run", "--dry-run", "success", "router"); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatal("dry-run executed post hook")
|
||||
}
|
||||
if out, err := runNetssh(t, "run", "success", "router"); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
data, _ := os.ReadFile(marker)
|
||||
if string(data) != "router:0" {
|
||||
t.Fatal(string(data))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
code int
|
||||
}{{"failure", 7}, {"postfail", 9}, {"timeout", 124}} {
|
||||
_, err := runNetssh(t, "run", tc.name, "router")
|
||||
exit, ok := err.(*exec.ExitError)
|
||||
if !ok || exit.ExitCode() != tc.code {
|
||||
t.Fatalf("%s: %v", tc.name, err)
|
||||
}
|
||||
}
|
||||
data, _ = os.ReadFile(marker)
|
||||
if string(data) != "7" {
|
||||
t.Fatal(string(data))
|
||||
}
|
||||
if out, err := runNetssh(t, "run", "protected", "router"); err == nil || !strings.Contains(out, "--yes") {
|
||||
t.Fatalf("%q %v", out, err)
|
||||
}
|
||||
if out, err := runNetssh(t, "run", "--yes", "protected", "router"); err != nil {
|
||||
t.Fatalf("%q %v", out, err)
|
||||
}
|
||||
if out, err := runNetssh(t, "run", "--yes", "protected", "okay"); err == nil || !strings.Contains(out, "not allowed") {
|
||||
t.Fatalf("%q %v", out, err)
|
||||
}
|
||||
state, err := activity.Read()
|
||||
if err != nil || len(state.Records) != 5 {
|
||||
t.Fatalf("%+v %v", state, err)
|
||||
}
|
||||
}
|
||||
func TestSSHPostDisconnect(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
marker := filepath.Join(dir, "after")
|
||||
writeOperationsConfig(t, fmt.Sprintf("ssh:\n post_disconnect: 'printf \"%%s\" \"$NETSSH_EXIT_CODE\" > %s'\n", marker))
|
||||
if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nexit 6\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
_, err := runNetssh(t, "router")
|
||||
exit, ok := err.(*exec.ExitError)
|
||||
if !ok || exit.ExitCode() != 6 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(marker)
|
||||
if string(data) != "6" {
|
||||
t.Fatalf("post: %s", data)
|
||||
}
|
||||
}
|
||||
func TestExplainAndFavorites(t *testing.T) {
|
||||
writeOperationsConfig(t, "tui:\n history_limit: 25\nssh:\n rules:\n - match: {tag: router}\n post_disconnect: echo done\n")
|
||||
out, err := runNetssh(t, "explain", "router")
|
||||
if err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result["source"] != "static" || result["address"] != "192.0.2.1" {
|
||||
t.Fatal(result)
|
||||
}
|
||||
for _, args := range [][]string{{"favorites", "pin", "router"}, {"favorites", "add", "okay"}} {
|
||||
if out, err := runNetssh(t, args...); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
}
|
||||
state, err := activity.Read()
|
||||
if err != nil || !state.Pinned["router"] || !state.Favorites["okay"] {
|
||||
t.Fatalf("%+v %v", state, err)
|
||||
}
|
||||
if out, err := runNetssh(t, "favorites", "remove", "router"); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
state, _ = activity.Read()
|
||||
if state.Pinned["router"] || state.Favorites["router"] {
|
||||
t.Fatal(state)
|
||||
}
|
||||
}
|
||||
func TestPortableConfigOmitsAllExecutableSecrets(t *testing.T) {
|
||||
c := config.Config{
|
||||
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://user:URLSECRET@netbox.example", Token: "TOKEN", SSH: config.SSHOptions{PreConnect: "HOOKSECRET"}}},
|
||||
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{Options: map[string]string{"ProxyCommand": "OPTIONSECRET"}, PostDisconnect: "POSTSECRET"}},
|
||||
Commands: map[string]config.HostCommand{"check": {Args: []string{"echo", "COMMANDSECRET", "{host}"}}},
|
||||
Hosts: []config.StaticHost{{Name: "router", Address: "192.0.2.1", SSH: config.SSHOptions{PreConnect: "STATICSECRET"}}},
|
||||
TUI: config.TUIConfig{HistoryLimit: 25},
|
||||
}
|
||||
data, err := json.Marshal(portableConfig(c))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"URLSECRET", "TOKEN", "HOOKSECRET", "OPTIONSECRET", "POSTSECRET", "COMMANDSECRET", "STATICSECRET"} {
|
||||
if bytes.Contains(data, []byte(secret)) {
|
||||
t.Fatalf("export leaked %s", secret)
|
||||
}
|
||||
}
|
||||
parsed, err := decodePortable(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.TUI.HistoryLimit != 25 || len(parsed.NetBoxes) != 1 || parsed.NetBoxes[0].URL != "https://netbox.example" {
|
||||
t.Fatalf("%+v", parsed)
|
||||
}
|
||||
hostile := []byte("netbox:\n url: https://netbox.example\n token: bad\nssh:\n pre_connect: touch /tmp/never\ncommands:\n check:\n args: [sh, -c, evil]\n")
|
||||
parsed, err = decodePortable(hostile)
|
||||
if err != nil || parsed.NetBox.Token != "" || parsed.SSH.PreConnect != "" || len(parsed.Commands) != 0 {
|
||||
t.Fatalf("%+v %v", parsed, err)
|
||||
}
|
||||
}
|
||||
func TestBatchRetryFailedOnly(t *testing.T) {
|
||||
bin := filepath.Join(t.TempDir(), "netssh")
|
||||
build := exec.Command("go", "build", "-o", bin, ".")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build: %s %v", out, err)
|
||||
}
|
||||
old := batchExecutable
|
||||
batchExecutable = func() (string, error) { return bin, nil }
|
||||
t.Cleanup(func() { batchExecutable = old })
|
||||
dir := t.TempDir()
|
||||
script := filepath.Join(dir, "check.sh")
|
||||
ready := filepath.Join(dir, "ready")
|
||||
if err := os.WriteFile(script, []byte(fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = fail ] && [ ! -f %q ]; then exit 3; fi\nprintf 'ran %%s\\n' \"$1\"\n", ready)), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeOperationsConfig(t, fmt.Sprintf("commands:\n check:\n args: [%q, \"{host}\"]\n", script))
|
||||
run := func(args ...string) (string, error) {
|
||||
cmd := batchCmd()
|
||||
cmd.SetArgs(args)
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&out)
|
||||
err := cmd.Execute()
|
||||
return out.String(), err
|
||||
}
|
||||
out, err := run("--parallel", "2", "check", "router", "fail", "okay")
|
||||
if err == nil || !strings.Contains(out, "2 succeeded, 1 failed") {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
data, _ := os.ReadFile(batchPath())
|
||||
var retry batchRetry
|
||||
if err := json.Unmarshal(data, &retry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(retry.Hosts, []string{"fail"}) {
|
||||
t.Fatalf("%+v", retry)
|
||||
}
|
||||
if err := os.WriteFile(ready, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err = run("--retry-failed")
|
||||
if err != nil || !strings.Contains(out, "1 succeeded, 0 failed") || strings.Contains(out, "ran router") {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportPreservesOnlyMatchingCredentials(t *testing.T) {
|
||||
writeOperationsConfig(t, "")
|
||||
original := []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: LOCALPROD\n - name: lab\n url: https://lab.example\n token: LOCALLAB\ncommands:\n local:\n args: [echo, \"{host}\"]\n")
|
||||
if err := os.WriteFile(config.Path(), original, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shared := filepath.Join(t.TempDir(), "shared.yaml")
|
||||
if err := os.WriteFile(shared, []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: UNTRUSTED\n - name: lab\n url: https://other.example\ntui:\n history_limit: 25\nssh:\n pre_connect: evil\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := runNetssh(t, "config", "import", shared, "--dry-run"); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
after, _ := os.ReadFile(config.Path())
|
||||
if !bytes.Equal(original, after) {
|
||||
t.Fatal("preview changed config")
|
||||
}
|
||||
if out, err := runNetssh(t, "config", "import", shared, "--yes"); err != nil {
|
||||
t.Fatalf("%s %v", out, err)
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.NetBoxes[0].Token != "LOCALPROD" || cfg.NetBoxes[1].Token != "" || cfg.SSH.PreConnect != "" || len(cfg.Commands) != 1 || cfg.TUI.HistoryLimit != 25 {
|
||||
t.Fatalf("incorrect imported settings: names=%d tui=%d", len(cfg.NetBoxes), cfg.TUI.HistoryLimit)
|
||||
}
|
||||
backup, _ := os.ReadFile(config.Path() + ".before-import")
|
||||
if !bytes.Equal(backup, original) {
|
||||
t.Fatal("backup differs")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
|
||||
// secrets may be embedded there, and cannot reliably be detected by key name.
|
||||
func portableConfig(c config.Config) map[string]any {
|
||||
cleanURL := func(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
u.User = nil
|
||||
u.RawQuery = ""
|
||||
u.Fragment = ""
|
||||
return u.String()
|
||||
}
|
||||
sources := []map[string]any{}
|
||||
for _, s := range c.NetBoxes {
|
||||
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
|
||||
}
|
||||
hosts := []map[string]any{}
|
||||
for _, h := range c.Hosts {
|
||||
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
|
||||
}
|
||||
rewrites := []map[string]string{}
|
||||
for _, r := range c.Shortcuts.Rewrites {
|
||||
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
|
||||
}
|
||||
out := map[string]any{
|
||||
"hosts": hosts, "groups": c.Groups,
|
||||
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
|
||||
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
|
||||
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
|
||||
"completion": map[string]any{"max_results": c.Completion.MaxResults},
|
||||
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
|
||||
}
|
||||
if len(sources) > 0 {
|
||||
out["netboxes"] = sources
|
||||
} else if c.NetBox.URL != "" {
|
||||
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func decodePortable(data []byte) (config.Config, error) {
|
||||
v := viper.New()
|
||||
v.SetConfigType("yaml")
|
||||
v.SetDefault("tui.history_limit", 10)
|
||||
var c config.Config
|
||||
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err := v.Unmarshal(&c); err != nil {
|
||||
return c, err
|
||||
}
|
||||
// Strip executable settings and credentials even from externally edited files.
|
||||
safe, _ := json.Marshal(portableConfig(c))
|
||||
v = viper.New()
|
||||
v.SetConfigType("json")
|
||||
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
|
||||
return c, err
|
||||
}
|
||||
c = config.Config{}
|
||||
err := v.Unmarshal(&c)
|
||||
return c, err
|
||||
}
|
||||
func configCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
|
||||
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), string(data))
|
||||
return nil
|
||||
}
|
||||
return storage.WriteFile(args[0], append(data, '\n'), 0600)
|
||||
}}
|
||||
var yes, dry bool
|
||||
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
data, err := os.ReadFile(args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
incoming, err := decodePortable(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
|
||||
for i := range incoming.NetBoxes {
|
||||
for _, old := range current.NetBoxes {
|
||||
s := &incoming.NetBoxes[i]
|
||||
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
|
||||
s.Token = old.Token
|
||||
s.TokenVersion = old.TokenVersion
|
||||
s.SSH = old.SSH
|
||||
}
|
||||
}
|
||||
}
|
||||
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
|
||||
incoming.NetBox.Token = current.NetBox.Token
|
||||
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
|
||||
incoming.NetBox.SSH = current.NetBox.SSH
|
||||
}
|
||||
incoming.Commands = current.Commands
|
||||
incoming.Activity = current.Activity
|
||||
incoming.Cache = current.Cache
|
||||
incoming.Multi = current.Multi
|
||||
incoming.Shell = current.Shell
|
||||
incoming.SSH.SSHOptions = current.SSH.SSHOptions
|
||||
incoming.SSH.Rules = current.SSH.Rules
|
||||
for i := range incoming.Hosts {
|
||||
for _, old := range current.Hosts {
|
||||
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
|
||||
incoming.Hosts[i].SSH = old.SSH
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
|
||||
if err := validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
|
||||
if dry {
|
||||
return nil
|
||||
}
|
||||
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
|
||||
return err
|
||||
}
|
||||
if existing, err := os.ReadFile(config.Path()); err == nil {
|
||||
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return setup.Save(incoming)
|
||||
}}
|
||||
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
|
||||
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
|
||||
cmd.AddCommand(export, imp)
|
||||
return cmd
|
||||
}
|
||||
+31
-8
@@ -3,13 +3,13 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"github.com/charmbracelet/x/term"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ func expandHostCommand(command config.HostCommand, host resolvedHost, extra []st
|
||||
}
|
||||
|
||||
func runCmd() *cobra.Command {
|
||||
var dryRun bool
|
||||
var dryRun, yes, status bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
|
||||
Short: "Run a configured local command for a NetBox or static host",
|
||||
@@ -39,9 +39,18 @@ func runCmd() *cobra.Command {
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown configured command %q", args[0])
|
||||
}
|
||||
host := resolveTarget(cfg, args[1])
|
||||
host, err := resolveTargetE(cfg, args[1], !dryRun)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !command.Allowed(commandHost(host)) {
|
||||
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
|
||||
}
|
||||
argv := expandHostCommand(command, host, args[2:])
|
||||
if dryRun {
|
||||
if post := config.HookCommand(command.PostRun); post != "" {
|
||||
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
|
||||
}
|
||||
for i, arg := range argv {
|
||||
if i > 0 {
|
||||
fmt.Fprint(cmd.OutOrStdout(), " ")
|
||||
@@ -51,11 +60,19 @@ func runCmd() *cobra.Command {
|
||||
fmt.Fprintln(cmd.OutOrStdout())
|
||||
return nil
|
||||
}
|
||||
path, err := exec.LookPath(argv[0])
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s not found in PATH: %w", argv[0], err)
|
||||
if command.Confirm {
|
||||
if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return syscall.Exec(path, argv, os.Environ())
|
||||
timeout, _ := time.ParseDuration(command.Timeout)
|
||||
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
|
||||
if code != 0 {
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
return &commandExit{code}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) == 0 {
|
||||
@@ -78,6 +95,12 @@ func runCmd() *cobra.Command {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
|
||||
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
|
||||
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
|
||||
return cmd
|
||||
}
|
||||
|
||||
type commandExit struct{ code int }
|
||||
|
||||
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
|
||||
"github.com/charmbracelet/x/term"
|
||||
)
|
||||
|
||||
func commandHost(h resolvedHost) config.SSHHost {
|
||||
instance, name := netbox.SplitTarget(h.Name)
|
||||
return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags}
|
||||
}
|
||||
func confirmAction(message string, yes bool) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
if !term.IsTerminal(os.Stdin.Fd()) {
|
||||
return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "%s? [y/N] ", message)
|
||||
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("cancelled")
|
||||
}
|
||||
func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
start := time.Now()
|
||||
env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name)
|
||||
result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name})
|
||||
code := result.Code
|
||||
if result.Started && config.HookCommand(post) != "" {
|
||||
hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second})
|
||||
if hook.Code != 0 {
|
||||
fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code)
|
||||
if code == 0 {
|
||||
code = hook.Code
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil {
|
||||
fmt.Fprintf(stderr, "activity: %v\n", err)
|
||||
}
|
||||
return code
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Integration helpers run this test binary as netssh. An automatic refresh
|
||||
// would otherwise launch the test binary again with "cache refresh", rerunning
|
||||
// the entire suite. Explicit cache-refresh tests still exercise the real command.
|
||||
func TestMain(m *testing.M) {
|
||||
_ = os.Setenv("NETSSH_NO_REFRESH", "1")
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
@@ -204,10 +204,10 @@ func uninstallCmd() *cobra.Command {
|
||||
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
|
||||
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
|
||||
- the cache directory with hosts, aliases, and per-instance caches
|
||||
- the config file (a private backup is kept) and local server notes
|
||||
- the config file (a private backup is kept) and local notes, favorites, action history and batch retry state
|
||||
- the netssh binary
|
||||
|
||||
Use --keep-config to keep the config file and notes for a reinstall.`,
|
||||
Use --keep-config to keep the config file and local state for a reinstall.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load()
|
||||
@@ -244,7 +244,7 @@ Use --keep-config to keep the config file and notes for a reinstall.`,
|
||||
return err
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes")
|
||||
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local state")
|
||||
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
|
||||
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
|
||||
return cmd
|
||||
|
||||
Reference in new issue
Block a user