Allow backup to stdout

This commit is contained in:
Ben Johnson 2021-05-19 15:04:36 -06:00
parent eb79c35cbd
commit a4f282c8e8
2 changed files with 18 additions and 10 deletions

View file

@ -28,7 +28,7 @@ func newBackupCommand(stdin io.Reader, stdout io.Writer, stderr io.Writer) *cobr
Use: "backup",
Short: "Back up pilosa server",
Long: `
Backs up a pilosa server to a local snapshot file.
Backs up a pilosa server to a local, tar-formatted snapshot file.
`,
RunE: func(c *cobra.Command, args []string) error {
return cmd.Run(context.Background())
@ -36,7 +36,7 @@ Backs up a pilosa server to a local snapshot file.
}
flags := ccmd.Flags()
flags.StringVarP(&cmd.OutputPath, "output", "o", "", "output path to write to")
flags.StringVarP(&cmd.OutputPath, "output", "o", "", "output path to write to; specify '-' to send to stdout")
flags.StringVar(&cmd.Host, "host", "localhost:10101", "host:port of Pilosa.")
ctl.SetTLSConfig(flags, "", &cmd.TLS.CertificatePath, &cmd.TLS.CertificateKeyPath, &cmd.TLS.CACertPath, &cmd.TLS.SkipVerify, &cmd.TLS.EnableClientVerification)
return ccmd

View file

@ -73,6 +73,7 @@ func (cmd *BackupCommand) Run(ctx context.Context) (err error) {
if cmd.OutputPath == "" {
return fmt.Errorf("-o flag required")
}
useStdout := cmd.OutputPath == "-"
// Parse TLS configuration for node-specific clients.
tls := cmd.TLSConfiguration()
@ -94,12 +95,17 @@ func (cmd *BackupCommand) Run(ctx context.Context) (err error) {
}
schema := &pilosa.Schema{Indexes: indexes}
// Create output file in temporary location.
w, err := os.Create(cmd.OutputPath + ".tmp")
if err != nil {
return err
// Create output file in temporary location, or send to stdout if a dash is specified.
var w io.Writer
if useStdout {
w = os.Stdout
} else {
f, err := os.Create(cmd.OutputPath + ".tmp")
if err != nil {
return err
}
defer f.Close()
}
defer w.Close()
// Open a tar writer to the temporary file.
tw := tar.NewWriter(w)
@ -125,9 +131,11 @@ func (cmd *BackupCommand) Run(ctx context.Context) (err error) {
}
// Move data file to final location.
logger.Printf("writing backup: %s", cmd.OutputPath)
if err := os.Rename(cmd.OutputPath+".tmp", cmd.OutputPath); err != nil {
return err
if !useStdout {
logger.Printf("writing backup: %s", cmd.OutputPath)
if err := os.Rename(cmd.OutputPath+".tmp", cmd.OutputPath); err != nil {
return err
}
}
return nil