Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

etcd_watch #168

Merged
merged 1 commit into from Oct 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 57 additions & 0 deletions examples/complex-etcd/main.go
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"fmt"
"log"
"os/exec"
"strings"
"time"

Expand Down Expand Up @@ -227,5 +228,61 @@ func main() {
}

fmt.Printf("Third (combined) request test passed.\n")

kCheck.Delete("")

// Watch test

sKey = "child"
providerCfg = etcd.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: time.Second * 5,
Prefix: true,
Key: "child",
}

provider = etcd.Provider(providerCfg)

if err := kCheck.Load(provider, nil); err != nil {
log.Fatalf("error loading config: %v", err)
}

changedC := make(chan string, 1)

provider.Watch(func(event interface{}, err error) {
if err != nil {
fmt.Printf("Unexpected error: %v", err)
return
}

kCheck.Load(provider, nil)
changedC <- kCheck.String(string(event.(*clientv3.Event).Kv.Key))
})

var newVal string = "Brian"
cmd := exec.Command("etcdctl", "put", "child1", newVal)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}

if strings.Compare(newVal, <-changedC) != 0 {
fmt.Printf("Watch failed: new value comparison FAILED\n")
return
}

newVal = "Kate"
cmd = exec.Command("etcdctl", "put", "child2", newVal)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}

if strings.Compare(newVal, <-changedC) != 0 {
fmt.Printf("Watch failed: new value comparison FAILED\n")
return
}
fmt.Printf("Watch test passed.\n")

fmt.Printf("ALL TESTS PASSED\n")
}
20 changes: 20 additions & 0 deletions providers/etcd/etcd.go
Expand Up @@ -90,3 +90,23 @@ func (e *Etcd) Read() (map[string]interface{}, error) {

return mp, nil
}

func (e *Etcd) Watch(cb func(event interface{}, err error)) error {
var w clientv3.WatchChan

go func() {
if e.cfg.Prefix {
w = e.client.Watch(context.Background(), e.cfg.Key, clientv3.WithPrefix())
} else {
w = e.client.Watch(context.Background(), e.cfg.Key)
}

for wresp := range w {
for _, ev := range wresp.Events {
cb(ev, nil)
}
}
}()

return nil
}