func addLockDirChild(client *etcd.Client, key string) (*etcd.Response, error) { hostname, err := os.Hostname() if err != nil { return nil, errgo.Notef(err, "fail to get hostname") } client.SyncCluster() return client.AddChild(key, hostname, 0) }
// newEtcdBackend constructs a etcd backend using a given machine address. func newEtcdBackend(conf map[string]string) (Backend, error) { // Get the etcd path form the configuration. path, ok := conf["path"] if !ok { path = "/vault" } // Ensure path is prefixed. if !strings.HasPrefix(path, "/") { path = "/" + path } // Set a default machines list and check for an overriding address value. machines := "http://128.0.0.1:2379" if address, ok := conf["address"]; ok { machines = address } machinesParsed := strings.Split(machines, EtcdMachineDelimiter) // Create a new client from the supplied address and attempt to sync with the // cluster. var client *etcd.Client cert, has_cert := conf["tls_cert_file"] key, has_key := conf["tls_key_file"] ca, has_ca := conf["tls_ca_file"] if has_cert || has_key || has_ca { var err error client, err = etcd.NewTLSClient(machinesParsed, cert, key, ca) if err != nil { return nil, err } } else { client = etcd.NewClient(machinesParsed) } if !client.SyncCluster() { return nil, EtcdSyncClusterError } // Setup the backend. return &EtcdBackend{ path: path, client: client, }, nil }
func newEtcdClient(etcdServer string) (*etcd.Client, error) { var ( client *etcd.Client err error ) for attempt := 1; attempt <= maxConnectAttempts; attempt++ { if _, err = etcdutil.GetEtcdVersion(etcdServer); err == nil { break } if attempt == maxConnectAttempts { break } glog.Infof("[Attempt: %d] Attempting access to etcd after 5 second sleep", attempt) time.Sleep(5 * time.Second) } if err != nil { return nil, fmt.Errorf("failed to connect to etcd server: %v, error: %v", etcdServer, err) } glog.Infof("Etcd server found: %v", etcdServer) // loop until we have > 0 machines && machines[0] != "" poll, timeout := 1*time.Second, 10*time.Second if err := wait.Poll(poll, timeout, func() (bool, error) { if client = etcd.NewClient([]string{etcdServer}); client == nil { return false, fmt.Errorf("etcd.NewClient returned nil") } client.SyncCluster() machines := client.GetCluster() if len(machines) == 0 || len(machines[0]) == 0 { return false, nil } return true, nil }); err != nil { return nil, fmt.Errorf("Timed out after %s waiting for at least 1 synchronized etcd server in the cluster. Error: %v", timeout, err) } return client, nil }
func main() { _, err := flags.ParseArgs(&Options, os.Args[1:]) if err != nil { os.Exit(1) } if Options.Debug { log_debug = true debugMsg("Debug mode enabled") } // Create an ETCD client var e *etcd.Client if Options.Cert != "" && Options.Key != "" { debugMsg("Connecting using TLS: ", Options.EtcdHosts, Options.Cert, Options.Key, Options.CaCert) e, err = etcd.NewTLSClient(Options.EtcdHosts, Options.Cert, Options.Key, Options.CaCert) if err != nil { logger.Fatalf("Failed to connect to Etcd server using TLS: ", err) } } else { e = etcd.NewClient(Options.EtcdHosts) } if !e.SyncCluster() { logger.Printf("[WARNING] Failed to connect to etcd cluster at launch time") } // Register the metrics writer if len(Options.GraphiteServer) > 0 { addr, err := net.ResolveTCPAddr("tcp", Options.GraphiteServer) if err != nil { logger.Fatalf("Failed to parse graphite server: ", err) } prefix := "discodns" hostname, err := os.Hostname() if err != nil { logger.Fatalf("Unable to get hostname: ", err) } prefix = prefix + "." + strings.Replace(hostname, ".", "_", -1) go metrics.Graphite(metrics.DefaultRegistry, time.Duration(Options.GraphiteDuration)*time.Second, prefix, addr) } else if Options.MetricsDuration > 0 { go metrics.Log(metrics.DefaultRegistry, time.Duration(Options.MetricsDuration)*time.Second, logger) // Register a bunch of debug metrics metrics.RegisterDebugGCStats(metrics.DefaultRegistry) metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) go metrics.CaptureDebugGCStats(metrics.DefaultRegistry, time.Duration(Options.MetricsDuration)) go metrics.CaptureRuntimeMemStats(metrics.DefaultRegistry, time.Duration(Options.MetricsDuration)) } else { logger.Printf("Metric logging disabled") } // Start up the DNS resolver server server := &Server{ addr: Options.ListenAddress, port: Options.ListenPort, etcd: e, prefix: Options.Prefix, rTimeout: time.Duration(5) * time.Second, wTimeout: time.Duration(5) * time.Second, defaultTtl: Options.DefaultTtl, queryFilterer: &QueryFilterer{acceptFilters: parseFilters(Options.Accept), rejectFilters: parseFilters(Options.Reject)}} server.Run() logger.Printf("Listening on %s:%d\n", Options.ListenAddress, Options.ListenPort) sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) forever: for { select { case <-sig: logger.Printf("Bye bye :(\n") break forever } } }
func main() { var ( nodes string taskList string tasks []string confPath string confData *lib.RunConfig cliVars string cliData map[string]interface{} verbose bool taskDir string tmplDir string etcdClient *etcd.Client base *cobra.Command err error ) base = &cobra.Command{ Use: "atom", Short: "atom", Long: "atom", Run: func(cmd *cobra.Command, args []string) { confData, err = lib.ParseAtomConfig(confPath) if err != nil { log.Printf("Config read error: %s", err) if (taskDir == "") || (tmplDir == "") { return } else { confData = &lib.RunConfig{ TaskDir: taskDir, TmplDir: tmplDir, Verbose: verbose, } } } if err := yaml.Unmarshal([]byte(cliVars), &cliData); err != nil { log.Printf("Error: %s", err) } if nodes == "" { etcdClient = nil } else { etcdClient = etcd.NewClient([]string{nodes}) etcdClient.SetDialTimeout(time.Duration(3) * time.Second) if !etcdClient.SyncCluster() { log.Fatal("Couldn't sync with etcd cluster.") } etcdClient.SetConsistency(etcd.STRONG_CONSISTENCY) } for _, name := range strings.Split(taskList, ",") { if name == "" { continue } tasks = append(tasks, name) } if len(tasks) <= 0 { tasks = nil } atom := lib.NewAtom(confData, &cliData, etcdClient) atom.Run(tasks...) }, } base.Flags().StringVarP(&taskList, "run", "r", "", "tasks to run") base.PersistentFlags().StringVarP(&cliVars, "data", "d", "", "cli data (string, yaml)") base.PersistentFlags().StringVarP(&confPath, "conf", "c", "/etc/atom/atom.yml", "atom.yml") base.PersistentFlags().StringVarP(&nodes, "nodes", "n", "", "etcd nodes") base.PersistentFlags().StringVarP(&taskDir, "task", "t", "", "task directory") base.PersistentFlags().StringVarP(&tmplDir, "template", "m", "", "template directory") base.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose") base.Execute() }