Lower the complexity of newCluster()

Move the computation of clusterKey and bindAddress
to separate functions.
This commit is contained in:
kaiyou 2020-05-06 18:56:27 +02:00 committed by Leo Antunes
parent 7c398181a7
commit f2e53dd869
1 changed files with 44 additions and 31 deletions

View File

@ -43,40 +43,16 @@ func newCluster(config *config, wg *wgState) (*cluster, error) {
if !config.Init {
loadState(state)
}
if len(clusterKey) == 0 {
clusterKey = state.ClusterKey
clusterKey, err := computeClusterKey(state, clusterKey)
if err != nil {
return nil, err
}
if len(clusterKey) == 0 {
clusterKey = make([]byte, clusterKeyLen)
_, err := rand.Read(clusterKey)
bindAddr, err := computeBindAddr(config.BindAddr, config.BindIface)
if err != nil {
return nil, err
}
// TODO: refactor this into subcommand ("showkey"?)
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Printf("new cluster key generated: %s\n", base64.StdEncoding.EncodeToString(clusterKey))
}
}
state.ClusterKey = clusterKey
// we check for mutual exclusion in config.go
bindAddr := config.BindAddr
if config.BindIface != "" {
iface, err := net.InterfaceByName(config.BindIface)
if err != nil {
return nil, err
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
if len(addrs) > 0 {
if addr, ok := addrs[0].(*net.IPNet); ok {
bindAddr = addr.IP.String()
}
}
}
mlConfig := memberlist.DefaultWANConfig()
mlConfig.LogOutput = logrus.StandardLogger().WriterLevel(logrus.DebugLevel)
@ -231,6 +207,43 @@ func (n *node) String() string {
return n.Addr.String()
}
func computeClusterKey(state *ClusterState, clusterKey []byte) ([]byte, error) {
if len(clusterKey) == 0 {
clusterKey = state.ClusterKey
}
if len(clusterKey) == 0 {
clusterKey = make([]byte, clusterKeyLen)
_, err := rand.Read(clusterKey)
if err != nil {
return nil, err
}
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Printf("new cluster key generated: %s\n", base64.StdEncoding.EncodeToString(clusterKey))
}
}
state.ClusterKey = clusterKey
return clusterKey, nil
}
func computeBindAddr(bindAddr string, bindIface string) (string, error) {
if bindIface != "" {
iface, err := net.InterfaceByName(bindIface)
if err != nil {
return "", err
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
if len(addrs) > 0 {
if addr, ok := addrs[0].(*net.IPNet); ok {
bindAddr = addr.IP.String()
}
}
}
return bindAddr, nil
}
func (c *cluster) saveState() error {
if err := os.MkdirAll(path.Dir(statePath), 0700); err != nil {
return err