Exemplo n.º 1
0
func connectToNatsServer(c *config.Config, logger *steno.Logger) yagnats.NATSConn {
	var natsClient yagnats.NATSConn
	var err error

	natsServers := c.NatsServers()
	attempts := 3
	for attempts > 0 {
		natsClient, err = yagnats.Connect(natsServers)
		if err == nil {
			break
		} else {
			attempts--
			time.Sleep(100 * time.Millisecond)
		}
	}

	if err != nil {
		logger.Errorf("Error connecting to NATS: %s\n", err)
		os.Exit(1)
	}

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		logger.Errorf("Close on NATS client. nats.Conn: %+v", *conn)
		os.Exit(1)
	})

	return natsClient
}
Exemplo n.º 2
0
func connectToMessageBus(l logger.Logger, conf *config.Config) yagnats.NATSConn {
	members := make([]string, len(conf.NATS))

	for _, natsConf := range conf.NATS {
		uri := url.URL{
			Scheme: "nats",
			User:   url.UserPassword(natsConf.User, natsConf.Password),
			Host:   fmt.Sprintf("%s:%d", natsConf.Host, natsConf.Port),
		}
		members = append(members, uri.String())
	}

	natsClient, err := yagnats.Connect(members)
	if err != nil {
		l.Error("Failed to connect to the message bus", err)
		os.Exit(1)
	}

	natsClient.AddReconnectedCB(func(conn *nats.Conn) {
		l.Info(fmt.Sprintf("NATS Client Reconnected. Server URL: %s", conn.Opts.Url))
	})

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		err := errors.New(fmt.Sprintf("NATS Client Closed. nats.Conn: %+v", conn))
		l.Error("NATS Closed", err)
		os.Exit(1)
	})

	return natsClient
}
Exemplo n.º 3
0
func connectToNatsServer(logger lager.Logger, c *config.Config) yagnats.NATSConn {
	var natsClient yagnats.NATSConn
	var err error

	natsServers := c.NatsServers()
	attempts := 3
	for attempts > 0 {
		natsClient, err = yagnats.Connect(natsServers)
		if err == nil {
			break
		} else {
			attempts--
			time.Sleep(100 * time.Millisecond)
		}
	}

	if err != nil {
		logger.Fatal("nats-connection-error", err)
	}

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		logger.Fatal("nats-connection-closed", errors.New("unexpected close"), lager.Data{"connection": *conn})
	})

	return natsClient
}
Exemplo n.º 4
0
func (runner *NATSRunner) Start() {
	if runner.natsSession != nil {
		panic("starting an already started NATS runner!!!")
	}

	_, err := exec.LookPath("gnatsd")
	if err != nil {
		fmt.Println("You need gnatsd installed!")
		os.Exit(1)
	}

	cmd := exec.Command("gnatsd", "-p", strconv.Itoa(runner.port))
	sess, err := gexec.Start(
		cmd,
		gexec.NewPrefixedWriter("\x1b[32m[o]\x1b[34m[gnatsd]\x1b[0m ", ginkgo.GinkgoWriter),
		gexec.NewPrefixedWriter("\x1b[91m[e]\x1b[34m[gnatsd]\x1b[0m ", ginkgo.GinkgoWriter),
	)
	Expect(err).NotTo(HaveOccurred(), "Make sure to have gnatsd on your path")

	runner.natsSession = sess

	Expect(err).NotTo(HaveOccurred())

	var messageBus yagnats.NATSConn
	Eventually(func() error {
		messageBus, err = yagnats.Connect([]string{fmt.Sprintf("nats://127.0.0.1:%d", runner.port)})
		return err
	}, 5, 0.1).ShouldNot(HaveOccurred())

	runner.MessageBus = messageBus
}
Exemplo n.º 5
0
func newMessageBus(c *config.Config) (yagnats.NATSConn, error) {
	natsMembers := make([]string, len(c.Nats))
	for _, info := range c.Nats {
		uri := url.URL{
			Scheme: "nats",
			User:   url.UserPassword(info.User, info.Pass),
			Host:   fmt.Sprintf("%s:%d", info.Host, info.Port),
		}
		natsMembers = append(natsMembers, uri.String())
	}

	return yagnats.Connect(natsMembers)
}
Exemplo n.º 6
0
func (runner *NATSRunner) Start() {
	_, err := exec.LookPath("gnatsd")
	if err != nil {
		fmt.Println("You need gnatsd installed!")
		os.Exit(1)
	}

	runner.natsCommand = exec.Command("gnatsd", "-p", strconv.Itoa(runner.port))
	err = runner.natsCommand.Start()
	Ω(err).ShouldNot(HaveOccurred(), "Make sure to have gnatsd on your path")
	var messageBus yagnats.NATSConn
	Eventually(func() error {
		messageBus, err = yagnats.Connect([]string{fmt.Sprintf("nats://127.0.0.1:%d", runner.port)})
		return err
	}, 5, 0.1).ShouldNot(HaveOccurred())

	runner.MessageBus = messageBus
}
func StartFakeRouter() {

	var startMessage = func() []byte {
		d := RouterStart{
			MinimumRegisterIntervalInSeconds: 20,
		}

		value, _ := json.Marshal(d)
		return value
	}

	natsMembers := make([]string, 1)
	uri := url.URL{
		Scheme: "nats",
		User:   url.UserPassword("", ""),
		Host:   "127.0.0.1:4222",
	}
	natsMembers = append(natsMembers, uri.String())

	var natsClient yagnats.NATSConn
	var err error
	for i := 0; i < 10; i++ {
		natsClient, err = yagnats.Connect(natsMembers)
		if err == nil {
			break
		}
		time.Sleep(time.Second)
	}
	Expect(err).ToNot(HaveOccurred())

	natsClient.Subscribe("router.register", func(msg *nats.Msg) {
	})
	natsClient.Subscribe("router.greet", func(msg *nats.Msg) {
		natsClient.Publish(msg.Reply, startMessage())
	})

	natsClient.Publish("router.start", startMessage())
}
Exemplo n.º 8
0
func main() {
	c := config.DefaultConfig()
	logCounter := vcap.NewLogCounter()

	if configFile != "" {
		c = config.InitConfigFromFile(configFile)
	}

	InitLoggerFromConfig(c, logCounter)
	logger := steno.NewLogger("router.main")

	err := dropsonde.Initialize(c.Logging.MetronAddress, c.Logging.JobName)
	if err != nil {
		logger.Errorf("Dropsonde failed to initialize: %s", err.Error())
		os.Exit(1)
	}

	// setup number of procs
	if c.GoMaxProcs != 0 {
		runtime.GOMAXPROCS(c.GoMaxProcs)
	}

	if c.DebugAddr != "" {
		cf_debug_server.Run(c.DebugAddr)
	}

	natsServers := c.NatsServers()
	var natsClient yagnats.NATSConn
	attempts := 3
	for attempts > 0 {
		natsClient, err = yagnats.Connect(natsServers)
		if err == nil {
			break
		} else {
			attempts--
			time.Sleep(100 * time.Millisecond)
		}
	}

	if err != nil {
		logger.Errorf("Error connecting to NATS: %s\n", err)
		os.Exit(1)
	}

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		logger.Errorf("Close on NATS client. nats.Conn: %+v", *conn)
		os.Exit(1)
	})

	registry := rregistry.NewRouteRegistry(c, natsClient)

	if c.RoutingApiEnabled() {
		logger.Info("Setting up routing_api route fetcher")
		tokenFetcher := token_fetcher.NewTokenFetcher(&c.OAuth)
		routingApiUri := fmt.Sprintf("%s:%d", c.RoutingApi.Uri, c.RoutingApi.Port)
		routingApiClient := routing_api.NewClient(routingApiUri)
		routeFetcher := route_fetcher.NewRouteFetcher(steno.NewLogger("router.route_fetcher"), tokenFetcher, registry, c, routingApiClient, 1)
		routeFetcher.StartFetchCycle()
		routeFetcher.StartEventCycle()
	}

	varz := rvarz.NewVarz(registry)

	accessLogger, err := access_log.CreateRunningAccessLogger(c)
	if err != nil {
		logger.Fatalf("Error creating access logger: %s\n", err)
	}

	args := proxy.ProxyArgs{
		EndpointTimeout: c.EndpointTimeout,
		Ip:              c.Ip,
		TraceKey:        c.TraceKey,
		Registry:        registry,
		Reporter:        varz,
		AccessLogger:    accessLogger,
		SecureCookies:   c.SecureCookies,
	}
	p := proxy.NewProxy(args)

	router, err := router.NewRouter(c, p, natsClient, registry, varz, logCounter)
	if err != nil {
		logger.Errorf("An error occurred: %s", err.Error())
		os.Exit(1)
	}

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)

	errChan := router.Run()

	logger.Info("gorouter.started")

	select {
	case err := <-errChan:
		if err != nil {
			logger.Errorf("Error occurred: %s", err.Error())
			os.Exit(1)
		}
	case sig := <-signals:
		go func() {
			for sig := range signals {
				logger.Infod(
					map[string]interface{}{
						"signal": sig.String(),
					},
					"gorouter.signal.ignored",
				)
			}
		}()

		if sig == syscall.SIGUSR1 {
			logger.Infod(
				map[string]interface{}{
					"timeout": (c.DrainTimeout).String(),
				},
				"gorouter.draining",
			)

			router.Drain(c.DrainTimeout)
		}

		stoppingAt := time.Now()

		logger.Info("gorouter.stopping")

		router.Stop()

		logger.Infod(
			map[string]interface{}{
				"took": time.Since(stoppingAt).String(),
			},
			"gorouter.stopped",
		)
	}

	os.Exit(0)
}
Exemplo n.º 9
0
Arquivo: main.go Projeto: mgazz/ila
func main() {

	c := config.DefaultConfig()

	logCounter := vcap.NewLogCounter()

	if configFile != "" {
		c = config.InitConfigFromFile(configFile)
	}

	//config := configuration.Bootstrap()
	InitLoggerFromConfig(c, logCounter)
	logger := steno.NewLogger("ila.main")
	logger.Info("started")

	natsMembers := make([]string, len(c.Nats))

	for _, info := range c.Nats {
		uri := url.URL{
			Scheme: "nats",
			User:   url.UserPassword(info.User, info.Pass),
			Host:   fmt.Sprintf("%s:%d", info.Host, info.Port),
		}
		natsMembers = append(natsMembers, uri.String())
	}

	natsClient, err := yagnats.Connect(natsMembers)

	if err != nil {
		logger.Fatalf("Error connecting to NATS: %s\n", err)
	}

	nman := manager.NewNatsManager(natsClient, c)

	//nman.StartAppScalingControl()
	nman.StartInstancesExamination()
	nman.StartDeaExamination()
	signals := make(chan os.Signal, 1)

	signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)

	//errChan := router.Run()
	logger.Info("ila.started")

	select {
	//case err := <-errChan:
	//if err != nil {
	//logger.Errorf("Error occurred: %s", err.Error())
	//os.Exit(1)
	//}
	case sig := <-signals:

		go func() {
			for sig := range signals {
				logger.Infod(
					map[string]interface{}{
						"signal": sig.String(),
					},
					"ila.signal.ignored",
				)
			}
		}()

		if sig == syscall.SIGUSR1 {
			logger.Infod(
				map[string]interface{}{
					"timeout": time.Now().String(),
				},
				"ila.timeout",
			)

		}

		stoppingAt := time.Now()

		logger.Infod(
			map[string]interface{}{
				"took": time.Since(stoppingAt).String(),
			},
			"ila.stopped",
		)
	}

	os.Exit(0)

}