func loop(receiverChannel chan *client.Response, env src.Env) {
	for response := range receiverChannel {
		key := env.NakedKey(response.Node.Key, *env.EtcdDir)
		parts := strings.Split(key, "/")
		env.UpdateData(parts, response.Node.Value, response.Action, env.Data)

		log.Printf("[CHANGE]: %s %s %s", response.Action, key, response.Node.Value)

		env.Cycle()
	}
}
func main() {
	var err error
	env := src.Env{Etcd: etcdFlag, EtcdDir: etcdDirFlag, Data: make(map[string]interface{})}

	src.RegisterRendererFlags()
	src.RegisterReloaderFlags()

	flag.Usage = printHelp
	flag.Parse()

	// renderer
	env.Renderer, err = src.OpenRenderer(*rendererFlag)
	if err != nil {
		panic(err)
	}

	// reloader
	env.Reloader, err = src.OpenReloader(*reloaderFlag)
	if err != nil {
		panic(err)
	}

	// main app context
	ctx, cancel := context.WithCancel(context.Background())

	// etcd
	etcdClientConfig := client.Config{Endpoints: []string{*env.Etcd}}
	etcdClient, err := client.New(etcdClientConfig)
	if err != nil {
		log.Fatal("Cannot connect to etcd machines, pleace check --etcd")
	}
	etcdKeyClient := client.NewKeysAPI(etcdClient)

	etcdGetOptions := &client.GetOptions{Recursive: true, Sort: false}
	etcdResponse, err := etcdKeyClient.Get(ctx, *env.EtcdDir, etcdGetOptions)
	if err != nil {
		panic(err)
	}
	if !etcdResponse.Node.Dir {
		panic("etc-dir should be a directory")
	}
	env.BuildData(*etcdResponse.Node, *env.EtcdDir, env.Data)
	env.Cycle()

	// watcher
	log.Printf("[MAIN] Waiting for changes from etcd @ %s", *env.EtcdDir)
	etcdWatcherOptions := &client.WatcherOptions{AfterIndex: 0, Recursive: true}
	etcdWatcher := etcdKeyClient.Watcher(*env.EtcdDir, etcdWatcherOptions)

	watcher := src.Watcher{EtcdWatcher: etcdWatcher}
	receiverChannel := watcher.Loop(ctx)

	// signals
	osSignal := make(chan os.Signal)
	signal.Notify(osSignal, os.Interrupt)
	go func() {
		for _ = range osSignal {
			log.Print("Interrupt received, finishing")
			cancel()
		}
	}()

	loop(receiverChannel, env)
}
Example #3
0
func main() {
	env := src.Env{}
	env.Data = make(map[string]interface{})

	env.Etcd = flag.String("etcd", "http://*****:*****@ %s", *env.EtcdDir)
	go etcdClient.Watch(*env.EtcdDir, 0, true, receiverChannel, stopChannel)

	// signals
	osSignal := make(chan os.Signal)
	signal.Notify(osSignal, os.Interrupt)
	go func() {
		for _ = range osSignal {
			log.Print("Interrupt received, finishing")
			stopChannel <- true
		}
	}()

	loop(receiverChannel, env)
}