github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/operator_snapshot_state.go (about) 1 package command 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "strings" 8 9 flaghelper "github.com/hashicorp/nomad/helper/flags" 10 "github.com/hashicorp/nomad/helper/raftutil" 11 "github.com/hashicorp/nomad/nomad" 12 "github.com/posener/complete" 13 ) 14 15 type OperatorSnapshotStateCommand struct { 16 Meta 17 } 18 19 func (c *OperatorSnapshotStateCommand) Help() string { 20 helpText := ` 21 Usage: nomad operator snapshot state [options] <file> 22 23 Displays a JSON representation of state in the snapshot. 24 25 To inspect the file "backup.snap": 26 27 $ nomad operator snapshot state backup.snap 28 29 Snapshot State Options: 30 31 -filter 32 Specifies an expression used to filter query results. 33 34 ` 35 return strings.TrimSpace(helpText) 36 } 37 38 func (c *OperatorSnapshotStateCommand) AutocompleteFlags() complete.Flags { 39 return complete.Flags{} 40 } 41 42 func (c *OperatorSnapshotStateCommand) AutocompleteArgs() complete.Predictor { 43 return complete.PredictNothing 44 } 45 46 func (c *OperatorSnapshotStateCommand) Synopsis() string { 47 return "Displays information about a Nomad snapshot file" 48 } 49 50 func (c *OperatorSnapshotStateCommand) Name() string { return "operator snapshot state" } 51 52 func (c *OperatorSnapshotStateCommand) Run(args []string) int { 53 var filterExpr flaghelper.StringFlag 54 55 flags := c.Meta.FlagSet(c.Name(), FlagSetClient) 56 flags.Usage = func() { c.Ui.Output(c.Help()) } 57 58 flags.Var(&filterExpr, "filter", "") 59 if err := flags.Parse(args); err != nil { 60 c.Ui.Error(fmt.Sprintf("Failed to parse args: %v", err)) 61 return 1 62 } 63 64 filter, err := nomad.NewFSMFilter(filterExpr.String()) 65 if err != nil { 66 c.Ui.Error(fmt.Sprintf("Invalid filter expression %q: %s", filterExpr, err)) 67 return 1 68 } 69 70 // Check that we either got no filename or exactly one. 71 if len(flags.Args()) != 1 { 72 c.Ui.Error("This command takes one argument: <file>") 73 c.Ui.Error(commandErrorText(c)) 74 return 1 75 } 76 77 path := flags.Args()[0] 78 f, err := os.Open(path) 79 if err != nil { 80 c.Ui.Error(fmt.Sprintf("Error opening snapshot file: %s", err)) 81 return 1 82 } 83 defer f.Close() 84 85 state, meta, err := raftutil.RestoreFromArchive(f, filter) 86 if err != nil { 87 c.Ui.Error(fmt.Sprintf("Failed to read archive file: %s", err)) 88 return 1 89 } 90 91 sm := raftutil.StateAsMap(state) 92 sm["SnapshotMeta"] = []interface{}{meta} 93 94 enc := json.NewEncoder(os.Stdout) 95 enc.SetIndent("", " ") 96 if err := enc.Encode(sm); err != nil { 97 c.Ui.Error(fmt.Sprintf("Failed to encode output: %v", err)) 98 return 1 99 } 100 101 return 0 102 }