Don't open a raft snapshot file until we have a successful snapshot response. (#9894)
* Don't open the snapshot file until we have a successful response * Check the success of Close if nothing else errors
This commit is contained in:
parent
4062c8a5c3
commit
ed131225a2
|
@ -2,6 +2,7 @@ package command
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
|
@ -71,24 +72,54 @@ func (c *OperatorRaftSnapshotSaveCommand) Run(args []string) int {
|
|||
return 1
|
||||
}
|
||||
|
||||
snapFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
c.UI.Error(fmt.Sprintf("Error opening output file: %s", err))
|
||||
return 2
|
||||
w := &lazyOpenWriter{
|
||||
openFunc: func() (io.WriteCloser, error) {
|
||||
return os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
},
|
||||
}
|
||||
defer snapFile.Close()
|
||||
|
||||
client, err := c.Client()
|
||||
if err != nil {
|
||||
w.Close()
|
||||
c.UI.Error(err.Error())
|
||||
return 2
|
||||
}
|
||||
|
||||
err = client.Sys().RaftSnapshot(snapFile)
|
||||
err = client.Sys().RaftSnapshot(w)
|
||||
if err != nil {
|
||||
w.Close()
|
||||
c.UI.Error(fmt.Sprintf("Error taking the snapshot: %s", err))
|
||||
return 2
|
||||
}
|
||||
|
||||
err = w.Close()
|
||||
if err != nil {
|
||||
c.UI.Error(fmt.Sprintf("Error taking the snapshot: %s", err))
|
||||
return 2
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
type lazyOpenWriter struct {
|
||||
openFunc func() (io.WriteCloser, error)
|
||||
writer io.WriteCloser
|
||||
}
|
||||
|
||||
|
||||
func (l *lazyOpenWriter) Write(p []byte) (n int, err error) {
|
||||
if l.writer == nil {
|
||||
var err error
|
||||
l.writer, err = l.openFunc()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return l.writer.Write(p)
|
||||
}
|
||||
|
||||
func (l *lazyOpenWriter) Close() error {
|
||||
if l.writer != nil {
|
||||
return l.writer.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
Loading…
Reference in New Issue