当前位置: 首页>>代码示例>>Golang>>正文


Golang KeysAPI.Watcher方法代码示例

本文整理汇总了Golang中github.com/coreos/etcd/client.KeysAPI.Watcher方法的典型用法代码示例。如果您正苦于以下问题:Golang KeysAPI.Watcher方法的具体用法?Golang KeysAPI.Watcher怎么用?Golang KeysAPI.Watcher使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/coreos/etcd/client.KeysAPI的用法示例。


在下文中一共展示了KeysAPI.Watcher方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: doServerWatch

func doServerWatch(kapi client.KeysAPI) {

	watcher := kapi.Watcher(runningbase, &client.WatcherOptions{Recursive: true})

	for true {
		resp, err := watcher.Next(context.TODO())

		if err != nil {
			if _, ok := err.(*client.ClusterError); ok {
				continue
			}
			log.Fatal(err)
		}

		fmt.Println(resp.Node.Key + " " + resp.Node.Value)

		_, server := path.Split(resp.Node.Key)
		switch resp.Action {
		case "create":
			fmt.Println(server + " has started heart beat")
		case "compareAndSwap":
			fmt.Println(server + " heart beat")
		case "compareAndDelete":
			fmt.Println(server + " has shut down correctly")
		case "expire":
			fmt.Println("*** " + server + " has missed heartbeat")
		default:
			fmt.Println("Didn't handle " + resp.Action)
		}
	}

}
开发者ID:compose-ex,项目名称:examplco2,代码行数:32,代码来源:examplco2.go

示例2: watch

func watch(kAPI etcd.KeysAPI, key string, stop chan struct{}) (res *etcd.Response) {
	for res == nil {
		select {
		case <-stop:
			log.Debugf("Gracefully closing etcd watch loop: key=%s", key)
			return
		default:
			opts := &etcd.WatcherOptions{
				AfterIndex: 0,
				Recursive:  true,
			}
			watcher := kAPI.Watcher(key, opts)
			log.Debugf("Creating etcd watcher: %s", key)

			var err error
			res, err = watcher.Next(context.Background())
			if err != nil {
				log.Errorf("etcd watcher %v returned error: %v", key, err)
			}
		}

		// Let's not slam the etcd server in the event that we know
		// an unexpected error occurred.
		time.Sleep(time.Second)
	}

	return
}
开发者ID:MohamedFAhmed,项目名称:heapster,代码行数:28,代码来源:event.go

示例3: watchKey

func watchKey(key string, blockControlChan chan blocker.ControlMsg, kapi client.KeysAPI) {
	watcher := kapi.Watcher(key, &client.WatcherOptions{Recursive: true})

	for {
		response, _ := watcher.Next(context.Background())
		switch response.Action {
		case "create":
			// counter: sync.set
			handleKey(*response.Node, blockControlChan, true)
			log.Println("[sync]\tetcd: create: " + response.Node.Key)
		case "set":
			// counter: sync.set
			handleKey(*response.Node, blockControlChan, true)
			log.Println("[sync]\tetcd: create: " + response.Node.Key)
		case "delete":
			// counter: sync.delete
			handleKey(*response.Node, blockControlChan, false)
			log.Println("[sync]\tetcd: delete: " + response.Node.Key)
		case "expire":
			// counter: sync.expire
			handleKey(*response.Node, blockControlChan, false)
			log.Println("[sync]\tetcd: expired: " + response.Node.Key)
		}
	}
}
开发者ID:timbuchwaldt,项目名称:dblock,代码行数:25,代码来源:sync.go

示例4: etcdWatch

// etcdWatch calls etcd's Watch function, and handles any errors. Meant to be called
// as a goroutine.
func (w *etcdWatcher) etcdWatch(ctx context.Context, client etcd.KeysAPI, key string, resourceVersion uint64) {
	defer util.HandleCrash()
	defer close(w.etcdError)
	defer close(w.etcdIncoming)
	if resourceVersion == 0 {
		latest, err := etcdGetInitialWatchState(ctx, client, key, w.list, w.etcdIncoming)
		if err != nil {
			w.etcdError <- err
			return
		}
		resourceVersion = latest
	}

	opts := etcd.WatcherOptions{
		Recursive:  w.list,
		AfterIndex: resourceVersion,
	}
	watcher := client.Watcher(key, &opts)
	w.stopLock.Lock()
	w.ctx, w.cancel = context.WithCancel(ctx)
	w.stopLock.Unlock()

	for {
		resp, err := watcher.Next(w.ctx)
		if err != nil {
			w.etcdError <- err
			return
		}
		w.etcdIncoming <- resp
	}
}
开发者ID:ruizeng,项目名称:kubernetes,代码行数:33,代码来源:etcd_watcher.go

示例5: mustWatchServiceDefs

// non-blocking
func mustWatchServiceDefs(ctx context.Context, client etcd.KeysAPI, basepath *string, changed chan<- bool) {
	wOpts := &etcd.WatcherOptions{Recursive: true}
	watcher := client.Watcher(*basepath, wOpts)

	watchOperation := func() error {
		resp, err := watcher.Next(ctx)
		if err != nil {
			switch v := err.(type) {
			case etcd.Error:
				if v.Code == etcd.ErrorCodeEventIndexCleared {
					watcher = client.Watcher(*basepath, wOpts)

					log.WithFields(log.Fields{
						"basepath": *basepath,
						"code":     v.Code,
						"cause":    v.Cause,
						"index":    v.Index,
						"message":  v.Message,
					}).Warn("refreshed watcher")

					return nil
				}
			default:
				if err.Error() == "unexpected end of JSON input" {
					log.WithField("error", err).Warn("probably a connection timeout. are we in etcd 0.4.x?")
					return nil
				} else {
					return err
				}
			}
		}

		if resp.Action != "get" {
			changed <- true
		}

		return nil
	}

	notify := func(err error, dur time.Duration) {
		log.WithFields(log.Fields{
			"dur":          dur,
			"error":        err,
			"service_path": *basepath,
		}).Error("service definition watch failed. backing off.")
	}

	go func() {
		for {
			err := backoff.RetryNotify(watchOperation, backoff.NewExponentialBackOff(), notify)
			if err != nil {
				log.WithFields(log.Fields{
					"error":        err,
					"service_path": *basepath,
				}).Fatal("unable to recover communication with etcd, watch abandoned")
			}
		}
	}()
}
开发者ID:christian-blades-cb,项目名称:desoto,代码行数:60,代码来源:main.go

示例6: etcdWatch

// etcdWatch calls etcd's Watch function, and handles any errors. Meant to be called
// as a goroutine.
func (w *etcdWatcher) etcdWatch(ctx context.Context, client etcd.KeysAPI, key string, resourceVersion uint64) {
	defer utilruntime.HandleCrash()
	defer close(w.etcdError)
	defer close(w.etcdIncoming)

	// All calls to etcd are coming from this function - once it is finished
	// no other call to etcd should be generated by this watcher.
	done := func() {}

	// We need to be prepared, that Stop() can be called at any time.
	// It can potentially also be called, even before this function is called.
	// If that is the case, we simply skip all the code here.
	// See #18928 for more details.
	var watcher etcd.Watcher
	returned := func() bool {
		w.stopLock.Lock()
		defer w.stopLock.Unlock()
		if w.stopped {
			// Watcher has already been stopped - don't event initiate it here.
			return true
		}
		w.wg.Add(1)
		done = w.wg.Done
		// Perform initialization of watcher under lock - we want to avoid situation when
		// Stop() is called in the meantime (which in tests can cause etcd termination and
		// strange behavior here).
		if resourceVersion == 0 {
			latest, err := etcdGetInitialWatchState(ctx, client, key, w.list, w.quorum, w.etcdIncoming)
			if err != nil {
				w.etcdError <- err
				return true
			}
			resourceVersion = latest
		}

		opts := etcd.WatcherOptions{
			Recursive:  w.list,
			AfterIndex: resourceVersion,
		}
		watcher = client.Watcher(key, &opts)
		w.ctx, w.cancel = context.WithCancel(ctx)
		return false
	}()
	defer done()
	if returned {
		return
	}

	for {
		resp, err := watcher.Next(w.ctx)
		if err != nil {
			w.etcdError <- err
			return
		}
		w.etcdIncoming <- resp
	}
}
开发者ID:nhr,项目名称:origin,代码行数:59,代码来源:etcd_watcher.go

示例7: generateConfigWatcher

func generateConfigWatcher(kapi client.KeysAPI, resp *client.Response) (*client.Response, error) {

	watcher := kapi.Watcher(*etcdPrefix, &client.WatcherOptions{Recursive: true, AfterIndex: resp.Index})
	ctx := context.Background()

	resp, err := watcher.Next(ctx)
	if err != nil {
		return resp, err
	}
	return generateConfig(kapi)

}
开发者ID:themecloud,项目名称:etcd2envfile,代码行数:12,代码来源:etcd2envfile.go

示例8: watch

func watch(kapi client.KeysAPI, key string, fn callback) {
	watcher := kapi.Watcher(key, nil)

	for {
		resp, err := watcher.Next(context.TODO())
		if err != nil {
			log.Printf("!! ERR: %v\n", err)
			break
		}
		if err := fn(resp.Node); err != nil {
			// we got an outdated node. we should trigger a get
			// to ensure we get the latest value.
			get(kapi, key, fn)
		}
	}

}
开发者ID:cyx,项目名称:hackday,代码行数:17,代码来源:main.go

示例9: watchService

func watchService(ctx *done.Context, api client.KeysAPI, space *Namespace) {
	dir := watchDir(space.name)
	opts := &client.WatcherOptions{Recursive: true}
	watcher := api.Watcher(dir, opts)

	log.Infof("watch %s start", dir)
	for {
		update(watcher, space)
		select {
		case <-ctx.Done():
			log.Infof("watch %s done", dir)
			ctx.OK()
			return
		default:
			continue
		}
	}
}
开发者ID:ironzhang,项目名称:golang,代码行数:18,代码来源:etcd_discover.go

示例10: waitForEtcd

func waitForEtcd(api client.KeysAPI, c *cli.Context) error {
	_, err := api.Get(context.Background(), c.String("key-watch"), nil)
	if err != nil {
		// key is not present have to watch it
		if m, _ := regexp.MatchString("100", err.Error()); m {
			w := api.Watcher(c.String("key-watch"), &client.WatcherOptions{AfterIndex: 0, Recursive: false})
			_, err := w.Next(context.Background())
			if err != nil {
				return err
			}
			return nil
		} else {
			return err
		}
	}
	// key is already present
	return nil
}
开发者ID:dictybase-docker,项目名称:chado-sqitch,代码行数:18,代码来源:runner.go

示例11: doServer

func doServer(kapi client.KeysAPI) {
	var key = configbase + *servername

	var settings map[string]string
	settings = make(map[string]string)

	resp, err := kapi.Get(context.TODO(), key, &client.GetOptions{Recursive: true})
	if err != nil {
		log.Fatal(err)
	}

	for _, node := range resp.Node.Nodes {
		_, setting := path.Split(node.Key)
		settings[setting] = node.Value
	}

	fmt.Println(settings)

	watcher := kapi.Watcher(key, &client.WatcherOptions{Recursive: true})

	for true {
		resp, err := watcher.Next(context.TODO())

		if err != nil {
			if _, ok := err.(*client.ClusterError); ok {
				continue
			}
			log.Fatal(err)
		}

		switch resp.Action {
		case "set":
			_, setting := path.Split(resp.Node.Key)
			settings[setting] = resp.Node.Value
		case "delete", "expire":
			_, setting := path.Split(resp.Node.Key)
			delete(settings, setting)
		}

		fmt.Println(settings)
	}

}
开发者ID:compose-ex,项目名称:examplco,代码行数:43,代码来源:examplco.go

示例12: watchCommandFunc

// watchCommandFunc executes the "watch" command.
func watchCommandFunc(c *cli.Context, ki client.KeysAPI) {
	if len(c.Args()) == 0 {
		handleError(ExitBadArgs, errors.New("key required"))
	}
	key := c.Args()[0]
	recursive := c.Bool("recursive")
	forever := c.Bool("forever")
	index := 0
	if c.Int("after-index") != 0 {
		index = c.Int("after-index") + 1
	}

	stop := false
	w := ki.Watcher(key, &client.WatcherOptions{AfterIndex: uint64(index), Recursive: recursive})

	sigch := make(chan os.Signal, 1)
	signal.Notify(sigch, os.Interrupt)

	go func() {
		<-sigch
		os.Exit(0)
	}()

	for !stop {
		resp, err := w.Next(context.TODO())
		if err != nil {
			handleError(ExitServerError, err)
		}
		if resp.Node.Dir {
			continue
		}
		if recursive {
			fmt.Printf("[%s] %s\n", resp.Action, resp.Node.Key)
		}

		printResponseKey(resp, c.GlobalString("output"))

		if !forever {
			stop = true
		}
	}
}
开发者ID:polarbird,项目名称:etcd,代码行数:43,代码来源:watch_command.go

示例13: OnUpdateIFace

func OnUpdateIFace(etcdCli etcd.Client, key string, fn func(val interface{})) {
	var kapi etcd.KeysAPI
	var ctx context.Context

	kapi = etcd.NewKeysAPI(etcdCli)
	ctx = context.Background()

	go func(w etcd.Watcher) {
		var err error
		var resp *etcd.Response

		for {
			resp, err = w.Next(ctx)
			if err == nil {
				Goose.Updater.Logf(3, "Updating config variable %s = %s", key, resp.Node.Value)
				fn(resp.Node.Value)
			} else {
				Goose.Updater.Logf(1, "Error updating config variable %s (%s)", key, err)
			}
		}
	}(kapi.Watcher("/"+key, nil))
}
开发者ID:luisfurquim,项目名称:etcdconfig,代码行数:22,代码来源:etcdconfig.go

示例14: newNotifier

func newNotifier(kapi client.KeysAPI, path string) notifier {
	w := notifier{make(chan struct{}, 1)}

	go func() {

		for {
			watcher := kapi.Watcher(path, &client.WatcherOptions{Recursive: true})

			var err error
			var response *client.Response
			for err == nil {
				response, err = watcher.Next(context.Background())
				logResponse(response)
				select {
				case w.ch <- struct{}{}:
					log.Println("received event from watcher, sent change message on notifier channel.")
				default:
					log.Println("received event from watcher, not sending message on notifier channel, buffer full and no-one listening.")
				}
			}

			if err == context.Canceled {
				log.Println("context cancelled error")
			} else if err == context.DeadlineExceeded {
				log.Println("deadline exceeded error")
			} else if cerr, ok := err.(*client.ClusterError); ok {
				log.Printf("cluster error. Details: %v\n", cerr.Detail())
			} else {
				// bad cluster endpoints, which are not etcd servers
				log.Println(err.Error())
			}

			log.Println("sleeping for 15s before rebuilding config due to error")
			time.Sleep(15 * time.Second)
		}
	}()

	return w
}
开发者ID:Financial-Times,项目名称:vulcan-config-builder,代码行数:39,代码来源:main.go

示例15: OnUpdateTree

func OnUpdateTree(etcdCli etcd.Client, key string, fn func(key string, val interface{}, action string)) {
	var kapi etcd.KeysAPI
	var ctx context.Context

	kapi = etcd.NewKeysAPI(etcdCli)
	ctx = context.Background()

	go func(w etcd.Watcher) {
		var err error
		var resp *etcd.Response

		for {
			resp, err = w.Next(ctx)
			if err == nil {
				Goose.Updater.Logf(3, "Updating (%s) config variable %s = %s", resp.Action, key, resp.Node.Value)
				fn(resp.Node.Key, resp.Node.Value, resp.Action)
			} else {
				Goose.Updater.Logf(1, "Error updating config variable %s (%s)", key, err)
			}
		}
	}(kapi.Watcher("/"+key, &etcd.WatcherOptions{Recursive: true}))
}
开发者ID:luisfurquim,项目名称:etcdconfig,代码行数:22,代码来源:etcdconfig.go


注:本文中的github.com/coreos/etcd/client.KeysAPI.Watcher方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。