2020-05-07 12:26:55 +02:00
|
|
|
package cluster
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2020-05-15 10:17:11 +02:00
|
|
|
"fmt"
|
2020-05-07 12:26:55 +02:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/costela/wesher/common"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
// State keeps track of information needed to rejoin the cluster
|
2020-05-10 16:48:20 +02:00
|
|
|
type state struct {
|
2020-05-07 12:26:55 +02:00
|
|
|
ClusterKey []byte
|
|
|
|
Nodes []common.Node
|
|
|
|
}
|
|
|
|
|
2020-05-15 10:17:11 +02:00
|
|
|
var defaultStatePath = "/var/lib/wesher/%s.json"
|
2020-05-07 12:26:55 +02:00
|
|
|
|
2020-05-15 10:17:11 +02:00
|
|
|
func (s *state) save(clusterName string) error {
|
|
|
|
statePath := fmt.Sprintf(defaultStatePath, clusterName)
|
2020-05-07 12:26:55 +02:00
|
|
|
if err := os.MkdirAll(path.Dir(statePath), 0700); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-05-10 16:59:51 +02:00
|
|
|
stateOut, err := json.MarshalIndent(s, "", " ")
|
2020-05-07 12:26:55 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ioutil.WriteFile(statePath, stateOut, 0600)
|
|
|
|
}
|
|
|
|
|
2020-05-15 10:17:11 +02:00
|
|
|
func loadState(cs *state, clusterName string) {
|
|
|
|
statePath := fmt.Sprintf(defaultStatePath, clusterName)
|
2020-05-07 12:26:55 +02:00
|
|
|
content, err := ioutil.ReadFile(statePath)
|
|
|
|
if err != nil {
|
|
|
|
if !os.IsNotExist(err) {
|
|
|
|
logrus.Warnf("could not open state in %s: %s", statePath, err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// avoid partially unmarshalled content by using a temp var
|
2020-05-10 16:48:20 +02:00
|
|
|
csTmp := &state{}
|
2020-05-07 12:26:55 +02:00
|
|
|
if err := json.Unmarshal(content, csTmp); err != nil {
|
|
|
|
logrus.Warnf("could not decode state: %s", err)
|
|
|
|
} else {
|
|
|
|
*cs = *csTmp
|
|
|
|
}
|
|
|
|
}
|