-
-
Save MilosSimic/11825862e38cdd7e0cfa5ddd153e3153 to your computer and use it in GitHub Desktop.
Use hashicorp/serf with golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os" | |
"os/signal" | |
"strconv" | |
"syscall" | |
"github.com/hashicorp/serf/serf" | |
"github.com/pkg/errors" | |
) | |
// go buidl && BIND_ADDR=127.0.0.1 BIND_PORT=6666 ADVERTISE_ADDR=127.0.0.1 ADVERTISE_PORT=6666 CLUSTER_ADDR=127.0.0.1 CLUSTER_PORT=6666 NAME=a1 ./go-serf-example | |
// BIND_ADDR=127.0.0.1 BIND_PORT=6667 ADVERTISE_ADDR=127.0.0.1 ADVERTISE_PORT=6667 CLUSTER_ADDR=127.0.0.1 CLUSTER_PORT=6666 NAME=a2 ./go-serf-example | |
func main() { | |
cluster, err := setupCluster( | |
os.Getenv("BIND_ADDR"), | |
os.Getenv("BIND_PORT"), // BIND defines where the agent listen for incomming connection | |
os.Getenv("ADVERTISE_ADDR"), | |
os.Getenv("ADVERTISE_PORT"), // ADVERTISE defines where the agent is reachable, often it the same as BIND | |
os.Getenv("CLUSTER_ADDR"), | |
os.Getenv("CLUSTER_PORT"), // CLUSTER is the address of a first agent | |
os.Getenv("NAME")) // NAME must be unique in a cluster | |
if err != nil { | |
log.Fatal(err) | |
} | |
c := make(chan os.Signal, 2) | |
signal.Notify(c, os.Interrupt, syscall.SIGTERM) | |
<-c | |
cluster.Leave() | |
os.Exit(1) | |
} | |
func setupCluster(bindAddr, bindPort, advertiseAddr, advertisePort, clusterAddr, clusterPort, name string) (*serf.Serf, error) { | |
conf := serf.DefaultConfig() | |
conf.Init() | |
conf.MemberlistConfig.AdvertiseAddr = advertiseAddr | |
conf.MemberlistConfig.AdvertisePort, _ = strconv.Atoi(advertisePort) | |
conf.MemberlistConfig.BindAddr = bindAddr | |
conf.MemberlistConfig.BindPort, _ = strconv.Atoi(bindPort) | |
conf.MemberlistConfig.ProtocolVersion = 3 // Version 3 enable the ability to bind different port for each agent | |
conf.NodeName = name | |
cluster, err := serf.Create(conf) | |
if err != nil { | |
return nil, errors.Wrap(err, "Couldn't create cluster") | |
} | |
_, err = cluster.Join([]string{clusterAddr + ":" + clusterPort}, true) | |
if err != nil { | |
log.Printf("Couldn't join cluster, starting own: %v\n", err) | |
} | |
return cluster, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment