Example #1
0
func BenchmarkRegister(b *testing.B) {
	c := config.DefaultConfig()
	mbus := fakeyagnats.New()
	r := registry.NewCFRegistry(c, mbus)

	proxy.NewProxy(proxy.ProxyArgs{
		EndpointTimeout: c.EndpointTimeout,
		Ip:              c.Ip,
		TraceKey:        c.TraceKey,
		Registry:        r,
		Reporter:        varz.NewVarz(r),
		Logger:          access_log.CreateRunningAccessLogger(c),
	})

	for i := 0; i < b.N; i++ {
		str := strconv.Itoa(i)

		r.Register(
			route.Uri("bench.vcap.me."+str),
			&route.Endpoint{
				Host: "localhost",
				Port: uint16(i),
			},
		)
	}
}
Example #2
0
func NewRouter(c *config.Config) *Router {
	router := &Router{
		config: c,
	}

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

	router.mbusClient = yagnats.NewClient()

	router.registry = registry.NewCFRegistry(router.config, router.mbusClient)
	router.registry.StartPruningCycle()

	router.varz = varz.NewVarz(router.registry)
	args := proxy.ProxyArgs{
		EndpointTimeout: router.config.EndpointTimeout,
		Ip:              router.config.Ip,
		TraceKey:        router.config.TraceKey,
		Registry:        router.registry,
		Reporter:        router.varz,
		Logger:          access_log.CreateRunningAccessLogger(router.config),
	}
	router.proxy = proxy.NewProxy(args)

	var host string
	if router.config.Status.Port != 0 {
		host = fmt.Sprintf("%s:%d", router.config.Ip, router.config.Status.Port)
	}

	varz := &vcap.Varz{
		UniqueVarz: router.varz,
	}
	varz.LogCounts = log.Counter

	healthz := &vcap.Healthz{
		LockableObject: router.registry,
	}

	router.component = &vcap.VcapComponent{
		Type:        "Router",
		Index:       router.config.Index,
		Host:        host,
		Credentials: []string{router.config.Status.User, router.config.Status.Pass},
		Config:      router.config,
		Varz:        varz,
		Healthz:     healthz,
		InfoRoutes: map[string]json.Marshaler{
			"/routes": router.registry,
		},
	}

	vcap.StartComponent(router.component)

	return router
}
Example #3
0
func buildProxy(c *config.Config, registry rregistry.RegistryInterface, accessLogger access_log.AccessLogger, varz rvarz.Varz) proxy.Proxy {
	args := proxy.ProxyArgs{
		EndpointTimeout: c.EndpointTimeout,
		Ip:              c.Ip,
		TraceKey:        c.TraceKey,
		Registry:        registry,
		Reporter:        varz,
		AccessLogger:    accessLogger,
		SecureCookies:   c.SecureCookies,
		TLSConfig: &tls.Config{
			CipherSuites:       c.CipherSuites,
			InsecureSkipVerify: c.SSLSkipValidation,
		},
	}
	return proxy.NewProxy(args)
}
Example #4
0
func BenchmarkRegister(b *testing.B) {
	c := config.DefaultConfig()
	mbus := fakeyagnats.New()
	r := registry.NewRegistry(c, mbus)
	p := proxy.NewProxy(c, r, varz.NewVarz(r))

	for i := 0; i < b.N; i++ {
		str := strconv.Itoa(i)

		p.Register(
			route.Uri("bench.vcap.me."+str),
			&route.Endpoint{
				Host: "localhost",
				Port: uint16(i),
			},
		)
	}
}
Example #5
0
func buildProxy(c *config.Config, registry rregistry.RegistryInterface, accessLogger access_log.AccessLogger, reporter metrics.ProxyReporter, crypto secure.Crypto, cryptoPrev secure.Crypto) proxy.Proxy {
	args := proxy.ProxyArgs{
		EndpointTimeout: c.EndpointTimeout,
		Ip:              c.Ip,
		TraceKey:        c.TraceKey,
		Registry:        registry,
		Reporter:        reporter,
		AccessLogger:    accessLogger,
		SecureCookies:   c.SecureCookies,
		TLSConfig: &tls.Config{
			CipherSuites:       c.CipherSuites,
			InsecureSkipVerify: c.SSLSkipValidation,
		},
		RouteServiceEnabled: c.RouteServiceEnabled,
		RouteServiceTimeout: c.RouteServiceTimeout,
		Crypto:              crypto,
		CryptoPrev:          cryptoPrev,
		ExtraHeadersToLog:   c.ExtraHeadersToLog,
	}
	return proxy.NewProxy(args)
}
		natsRunner.Start()

		proxyPort := test_util.NextAvailPort()
		statusPort := test_util.NextAvailPort()

		config = test_util.SpecConfig(natsPort, statusPort, proxyPort)
		config.EndpointTimeout = 5 * time.Second

		mbusClient = natsRunner.MessageBus.(*yagnats.Client)
		registry = rregistry.NewRouteRegistry(config, mbusClient)
		varz = vvarz.NewVarz(registry)
		logcounter := vcap.NewLogCounter()
		proxy := proxy.NewProxy(proxy.ProxyArgs{
			EndpointTimeout: config.EndpointTimeout,
			Ip:              config.Ip,
			TraceKey:        config.TraceKey,
			Registry:        registry,
			Reporter:        varz,
			AccessLogger:    &access_log.NullAccessLogger{},
		})
		r, err := NewRouter(config, proxy, mbusClient, registry, varz, logcounter)
		Ω(err).ShouldNot(HaveOccurred())
		router = r
		r.Run()
	})

	AfterEach(func() {
		if natsRunner != nil {
			natsRunner.Stop()
		}

		if router != nil {
Example #7
0
				CipherSuites:       conf.CipherSuites,
				InsecureSkipVerify: conf.SSLSkipValidation,
			}

			fakeAccessLogger = &fakelogger.FakeAccessLogger{}

			mbus := fakeyagnats.Connect()
			r = registry.NewRouteRegistry(conf, mbus, new(fakes.FakeRouteReporter))

			proxyObj = proxy.NewProxy(proxy.ProxyArgs{
				EndpointTimeout:     conf.EndpointTimeout,
				Ip:                  conf.Ip,
				TraceKey:            conf.TraceKey,
				Registry:            r,
				Reporter:            nullVarz{},
				AccessLogger:        fakeAccessLogger,
				SecureCookies:       conf.SecureCookies,
				TLSConfig:           tlsConfig,
				RouteServiceEnabled: conf.RouteServiceEnabled,
				RouteServiceTimeout: conf.RouteServiceTimeout,
				Crypto:              crypto,
				CryptoPrev:          cryptoPrev,
			})

			r.Register(route.Uri("some-app"), &route.Endpoint{})
		})

		Context("Log response time", func() {
			It("logs response time for HTTP connections", func() {
				body := []byte("some body")
				req := test_util.NewRequest("GET", "some-app", "/", bytes.NewReader(body))
				resp := httptest.NewRecorder()
Example #8
0
	"strconv"
)

var _ = Describe("AccessLogRecord", func() {
	Measure("Register", func(b Benchmarker) {
		c := config.DefaultConfig()
		mbus := fakeyagnats.NewApceraClientWrapper()
		r := registry.NewRouteRegistry(c, mbus)

		accesslog, err := access_log.CreateRunningAccessLogger(c)
		Ω(err).ToNot(HaveOccurred())

		proxy.NewProxy(proxy.ProxyArgs{
			EndpointTimeout: c.EndpointTimeout,
			Ip:              c.Ip,
			TraceKey:        c.TraceKey,
			Registry:        r,
			Reporter:        varz.NewVarz(r),
			AccessLogger:    accesslog,
		})

		b.Time("RegisterTime", func() {
			for i := 0; i < 1000; i++ {
				str := strconv.Itoa(i)
				r.Register(
					route.Uri("bench.vcap.me."+str),
					route.NewEndpoint("", "localhost", uint16(i), "", nil),
				)
			}
		})
	}, 10)
Example #9
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)
}
Example #10
0
	conf.EnableSSL = true
	conf.CipherSuites = []uint16{tls.TLS_RSA_WITH_AES_256_CBC_SHA}

	tlsConfig := &tls.Config{
		CipherSuites:       conf.CipherSuites,
		InsecureSkipVerify: conf.SkipSSLValidation,
	}

	p = proxy.NewProxy(proxy.ProxyArgs{
		EndpointTimeout:            conf.EndpointTimeout,
		Ip:                         conf.Ip,
		TraceKey:                   conf.TraceKey,
		Logger:                     logger,
		Registry:                   r,
		Reporter:                   test_helpers.NullVarz{},
		AccessLogger:               accessLog,
		SecureCookies:              conf.SecureCookies,
		TLSConfig:                  tlsConfig,
		RouteServiceEnabled:        conf.RouteServiceEnabled,
		RouteServiceTimeout:        conf.RouteServiceTimeout,
		Crypto:                     crypto,
		CryptoPrev:                 cryptoPrev,
		RouteServiceRecommendHttps: recommendHttps,
	})

	proxyServer, err = net.Listen("tcp", "127.0.0.1:0")
	Expect(err).NotTo(HaveOccurred())

	server := http.Server{Handler: p}
	go server.Serve(proxyServer)
})
Example #11
0
func main() {
	c := config.DefaultConfig()
	logCounter := vcap.NewLogCounter()
	InitLoggerFromConfig(c, logCounter)

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

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

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

	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 := yagnats.NewApceraClientWrapper(natsMembers)

	err := natsClient.Connect()

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

	registry := rregistry.NewRouteRegistry(c, natsClient)

	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,
	}
	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)
}
	go accessLog.Run()

	conf.EnableSSL = true
	conf.CipherSuites = []uint16{tls.TLS_RSA_WITH_AES_256_CBC_SHA}

	tlsConfig := &tls.Config{
		CipherSuites:       conf.CipherSuites,
		InsecureSkipVerify: conf.SSLSkipValidation,
	}

	p = proxy.NewProxy(proxy.ProxyArgs{
		EndpointTimeout:     conf.EndpointTimeout,
		Ip:                  conf.Ip,
		TraceKey:            conf.TraceKey,
		Registry:            r,
		Reporter:            nullVarz{},
		AccessLogger:        accessLog,
		SecureCookies:       conf.SecureCookies,
		TLSConfig:           tlsConfig,
		RouteServiceTimeout: conf.RouteServiceTimeout,
	})

	proxyServer, err = net.Listen("tcp", "127.0.0.1:0")
	Ω(err).NotTo(HaveOccurred())

	server := http.Server{Handler: p}
	go server.Serve(proxyServer)
})

var _ = AfterEach(func() {
	proxyServer.Close()