Skip to content

Instantly share code, notes, and snippets.

@xh4n3
Last active June 7, 2016 14:33
Show Gist options
  • Save xh4n3/c5207ff5dd63886a4e5f2b4a8b00a404 to your computer and use it in GitHub Desktop.
Save xh4n3/c5207ff5dd63886a4e5f2b4a8b00a404 to your computer and use it in GitHub Desktop.
Client Set returns ErrClusterUnavailable but succeed
package main
import (
"github.com/coreos/etcd/client"
"golang.org/x/net/context"
"log"
"time"
)
var (
kapi client.KeysAPI
endpoints = []string{"http://127.0.0.1:2379"}
retryDelay = time.Second * time.Duration(5)
key = "/test"
)
func connect() bool {
// init connection
cfg := client.Config{
Endpoints: endpoints,
Transport: client.DefaultTransport,
// set timeout per request to fail fast when the target endpoint is unavailable
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
if err != nil {
log.Fatal(err)
}
kapi = client.NewKeysAPI(c)
// TODO: use /health to check node's health as well
// checks if available
_, err = kapi.Get(context.Background(), "/", nil)
if err != nil {
log.Print(err.Error())
return false
} else {
return true
}
}
func reconnect() {
for !connect() {
log.Print(endpoints)
log.Print("Reconnect..")
time.Sleep(retryDelay)
}
}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
connect()
testEtcd()
}
func testEtcd() {
_, err := kapi.Get(context.Background(), key, nil)
if err != nil {
log.Println(err)
if client.IsKeyNotFound(err) {
_, err := kapi.Set(context.Background(), key, "", &client.SetOptions{Dir: true})
if err != nil {
log.Println(err)
}
}
} else {
log.Fatal(err)
}
//time.Sleep(retryDelay)
_, err = kapi.Get(context.Background(), key, nil)
if err != nil {
log.Println(err)
if client.IsKeyNotFound(err) {
_, err := kapi.Set(context.Background(), key, "", &client.SetOptions{Dir: true})
if err != nil {
log.Println(err)
}
}
} else {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment