From 0165b7a504007a09f0b85173898331be6e2ea7a7 Mon Sep 17 00:00:00 2001 From: Leo Antunes Date: Wed, 27 Mar 2019 22:25:14 +0100 Subject: [PATCH] add --init option for explicit cluster reset --- README.md | 1 + cluster.go | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 35021ac..0cf71e6 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ All options can be passed either as command-line flags or environment variables: |---|---|---|---| | `--cluster-key KEY` | WESHER_CLUSTER_KEY | shared key for cluster membership; must be 32 bytes base64 encoded; will be generated if not provided | autogenerated/loaded | | `--join HOST,...` | WESHER_JOIN | comma separated list of hostnames or IP addresses to existing cluster members; if not provided, will attempt resuming any known state or otherwise wait for further members | | +| `--init` | WESHER_INIT | whether to explicitly (re)initialize the cluster; any known state from previous runs will be forgotten | `false` | | `--bind-addr ADDR` | WESHER_BIND_ADDR | IP address to bind to for cluster membership | autodetected | | `--cluster-port PORT` | WESHER_CLUSTER_PORT | port used for membership gossip traffic (both TCP and UDP); must be the same across cluster | `7946` | | `--wireguard-port PORT` | WESHER_WIREGUARD_PORT | port used for wireguard traffic (UDP); must be the same across cluster | `51820` | diff --git a/cluster.go b/cluster.go index a0599cb..22b1aa9 100644 --- a/cluster.go +++ b/cluster.go @@ -43,7 +43,10 @@ const statePath = "/var/lib/wesher/state.json" func newCluster(config *config, wg *wgState) (*cluster, error) { clusterKey := config.ClusterKey - state := loadState() + state := &ClusterState{} + if !config.Init { + loadState(state) + } if len(clusterKey) == 0 { clusterKey = state.ClusterKey } @@ -223,19 +226,21 @@ func (c *cluster) saveState() error { return ioutil.WriteFile(statePath, stateOut, 0700) } -func loadState() *ClusterState { +func loadState(cs *ClusterState) { content, err := ioutil.ReadFile(statePath) if err != nil { if !os.IsNotExist(err) { logrus.Warnf("could not open state in %s: %s", statePath, err) } - return &ClusterState{} + return } - s := &ClusterState{} - if err := json.Unmarshal(content, s); err != nil { + // avoid partially unmarshalled content by using a temp var + csTmp := &ClusterState{} + if err := json.Unmarshal(content, csTmp); err != nil { logrus.Warnf("could not decode state: %s", err) - return &ClusterState{} // avoid partially unmarshalled content + } else { + *cs = *csTmp } - return s + return }