etcdctl: watch use etcd/client

This commit is contained in:
Xiang Li 2015-06-05 16:22:37 -07:00 committed by Yicheng Qin
parent b20c06348d
commit 5b01b3877f

View File

@ -20,7 +20,8 @@ import (
"os/signal" "os/signal"
"github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli" "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
"github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd" "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
"github.com/coreos/etcd/client"
) )
// NewWatchCommand returns the CLI command for "watch". // NewWatchCommand returns the CLI command for "watch".
@ -34,66 +35,47 @@ func NewWatchCommand() cli.Command {
cli.BoolFlag{Name: "recursive", Usage: "returns all values for key and child keys"}, cli.BoolFlag{Name: "recursive", Usage: "returns all values for key and child keys"},
}, },
Action: func(c *cli.Context) { Action: func(c *cli.Context) {
handleKey(c, watchCommandFunc) watchCommandFunc(c, mustNewKeyAPI(c))
}, },
} }
} }
// watchCommandFunc executes the "watch" command. // watchCommandFunc executes the "watch" command.
func watchCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) { func watchCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 { if len(c.Args()) == 0 {
return nil, errors.New("Key required") handleError(ExitBadArgs, errors.New("key required"))
} }
key := c.Args()[0] key := c.Args()[0]
recursive := c.Bool("recursive") recursive := c.Bool("recursive")
forever := c.Bool("forever") forever := c.Bool("forever")
index := 0 index := 0
if c.Int("after-index") != 0 { if c.Int("after-index") != 0 {
index = c.Int("after-index") + 1 index = c.Int("after-index") + 1
} }
if forever { stop := false
sigch := make(chan os.Signal, 1) w := ki.Watcher(key, &client.WatcherOptions{AfterIndex: uint64(index), Recursive: recursive})
signal.Notify(sigch, os.Interrupt)
stop := make(chan bool)
go func() { sigch := make(chan os.Signal, 1)
<-sigch signal.Notify(sigch, os.Interrupt)
os.Exit(0)
}()
receiver := make(chan *etcd.Response) go func() {
errCh := make(chan error, 1) <-sigch
os.Exit(0)
go func() { }()
_, err := client.Watch(key, uint64(index), recursive, receiver, stop)
errCh <- err
}()
for {
select {
case resp := <-receiver:
printAll(resp, c.GlobalString("output"))
case err := <-errCh:
handleError(-1, err)
}
}
} else {
var resp *etcd.Response
var err error
resp, err = client.Watch(key, uint64(index), recursive, nil, nil)
for !stop {
resp, err := w.Next(context.TODO())
if err != nil { if err != nil {
handleError(ExitServerError, err) handleError(ExitServerError, err)
} }
if resp.Node.Dir {
if err != nil { continue
return nil, err
} }
printAll(resp, c.GlobalString("output")) printResponseKey(resp, c.GlobalString("output"))
}
return nil, nil if !forever {
stop = true
}
}
} }