示例#1
0
func (s *ProxySuite) SetUpTest(c *C) {
	s.conf = config.DefaultConfig()
	s.conf.TraceKey = "my_trace_key"
	s.conf.EndpointTimeout = 500 * time.Millisecond

	mbus := fakeyagnats.New()

	s.r = registry.NewCFRegistry(s.conf, mbus)
	fmt.Printf("Config: %#v", s.conf)

	s.accessLogFile = new(test_util.FakeFile)
	accessLog := access_log.NewFileAndLoggregatorAccessLogger(s.accessLogFile, "localhost:9843", "secret", 42)
	go accessLog.Run()

	s.p = NewProxy(ProxyArgs{
		EndpointTimeout: s.conf.EndpointTimeout,
		Ip:              s.conf.Ip,
		TraceKey:        s.conf.TraceKey,
		Registry:        s.r,
		Reporter:        nullVarz{},
		Logger:          accessLog,
	})

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}

	server := server.Server{Handler: s.p}
	go server.Serve(ln)

	s.proxyServer = ln
}
func (s *CreateRunningAccessLoggerSuite) TestPanicsIfInvalidAccessLogLocation(c *C) {
	config := config.DefaultConfig()
	config.AccessLog = "/this\\should/panic"
	c.Assert(func() {
		CreateRunningAccessLogger(config)
	}, PanicMatches, "open /this\\\\should/panic: no such file or directory")
}
示例#3
0
func (s *ProxySuite) TestProxyPanicsIfInvalidAccessLogLocation(c *C) {
	x := config.DefaultConfig()
	x.AccessLog = "/this\\should/panic"
	c.Assert(func() {
		NewProxy(x, nil, nil)
	}, PanicMatches, "open /this\\\\should/panic: no such file or directory")
}
示例#4
0
func (s *ProxySuite) TestProxyHasAccessLoggerIfBothAccesLogAndLoggregatorUrl(c *C) {
	x := config.DefaultConfig()
	x.LoggregatorConfig.Url = "10.10.3.13:4325"
	x.AccessLog = "/dev/null"
	proxy := NewProxy(x, nil, nil)
	c.Assert(proxy.AccessLogger, NotNil)
}
示例#5
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),
			},
		)
	}
}
示例#6
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)
	}

	logger.Info("Setting up NATs connection")
	natsClient := connectToNatsServer(c, logger)

	registry := rregistry.NewRouteRegistry(c, natsClient)

	logger.Info("Setting up routing_api route fetcher")
	setupRouteFetcher(c, registry)

	varz := rvarz.NewVarz(registry)

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

	proxy := buildProxy(c, registry, accessLogger, varz)

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

	errChan := router.Run()

	logger.Info("gorouter.started")

	waitOnErrOrSignal(c, logger, errChan, router)

	os.Exit(0)
}
func (s *ProxySuite) TestProxyCreatesAnAccessLogger(c *C) {
	x := config.DefaultConfig()
	x.LoggregatorConfig.Url = "10.10.3.13:4325"
	x.AccessLog = ""

	proxy := NewProxy(x, nil, nil)
	var accessLoggerInterface access_log.AccessLogger
	c.Assert(proxy.AccessLogger, Implements, &accessLoggerInterface)
}
示例#8
0
func (s *LoggerSuite) TestSetupLoggerFromConfig(c *C) {
	cfg := config.DefaultConfig()
	cfg.Logging.File = "/tmp/gorouter.log"

	SetupLoggerFromConfig(cfg)

	count := Counter.GetCount("info")
	logger := steno.NewLogger("test")
	logger.Info("Hello")
	c.Assert(Counter.GetCount("info"), Equals, count+1)
}
示例#9
0
func main() {
	c := config.DefaultConfig()
	if configFile != "" {
		c = config.InitConfigFromFile(configFile)
	}

	log.SetupLoggerFromConfig(c)

	router.NewRouter(c).Run()

	select {}
}
示例#10
0
func generateConfig(statusPort, proxyPort uint16, natsPorts ...uint16) *config.Config {
	c := config.DefaultConfig()

	c.Port = proxyPort
	c.Index = 2
	c.TraceKey = "my_trace_key"

	// Hardcode the IP to localhost to avoid leaving the machine while running tests
	c.Ip = "127.0.0.1"

	c.StartResponseDelayInterval = 10 * time.Millisecond
	c.PublishStartMessageIntervalInSeconds = 10
	c.PruneStaleDropletsInterval = 0
	c.DropletStaleThreshold = 0
	c.PublishActiveAppsInterval = 0
	c.Zone = "z1"

	c.EndpointTimeout = 500 * time.Millisecond

	c.Status = config.StatusConfig{
		Port: statusPort,
		User: "******",
		Pass: "******",
	}

	c.Nats = []config.NatsConfig{}
	for _, natsPort := range natsPorts {
		c.Nats = append(c.Nats, config.NatsConfig{
			Host: "localhost",
			Port: natsPort,
			User: "******",
			Pass: "******",
		})
	}

	c.Logging = config.LoggingConfig{
		File:          "/dev/stdout",
		Level:         "debug",
		MetronAddress: "localhost:3457",
		JobName:       "router_test_z1_0",
	}

	c.OAuth = config.OAuthConfig{
		TokenEndpoint: "uaa.cf.service.internal",
		Port:          8443,
		SkipOAuthTLSVerification: true,
	}

	c.RouteServiceSecret = "kCvXxNMB0JO2vinxoru9Hg=="

	return c
}
示例#11
0
func generateConfig(natsPort, statusPort, proxyPort uint16) *config.Config {
	logger := lagertest.NewTestLogger("test")
	c := config.DefaultConfig(logger)

	c.Port = proxyPort
	c.Index = 2
	c.TraceKey = "my_trace_key"

	// Hardcode the IP to localhost to avoid leaving the machine while running tests
	c.Ip = "127.0.0.1"

	c.StartResponseDelayInterval = 10 * time.Millisecond
	c.PublishStartMessageIntervalInSeconds = 10
	c.PruneStaleDropletsInterval = 0
	c.DropletStaleThreshold = 0
	c.PublishActiveAppsInterval = 0
	c.Zone = "z1"

	c.EndpointTimeout = 500 * time.Millisecond

	c.Status = config.StatusConfig{
		Port: statusPort,
		User: "******",
		Pass: "******",
	}

	c.Nats = []config.NatsConfig{
		{
			Host: "localhost",
			Port: natsPort,
			User: "******",
			Pass: "******",
		},
	}

	c.Logging = config.LoggingConfig{
		File:          "/dev/stdout",
		Level:         "info",
		MetronAddress: "localhost:3457",
		JobName:       "router_test_z1_0",
	}

	c.OAuth = token_fetcher.OAuthConfig{
		TokenEndpoint: "http://localhost",
		Port:          8080,
	}

	c.RouteServiceSecret = "kCvXxNMB0JO2vinxoru9Hg=="

	return c
}
示例#12
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),
			},
		)
	}
}
func (s *ProxySuite) SetUpTest(c *C) {
	config := config.DefaultConfig()
	config.TraceKey = "my_trace_key"
	config.EndpointTimeout = 500 * time.Millisecond

	mbus := fakeyagnats.New()
	s.r = registry.NewRegistry(config, mbus)
	s.p = NewProxy(config, s.r, nullVarz{})

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}

	server := server.Server{Handler: s.p}
	go server.Serve(ln)

	s.proxyServer = ln
}
示例#14
0
func (s *RegistrySuite) SetUpTest(c *C) {
	var configObj *config.Config

	configObj = config.DefaultConfig()
	configObj.DropletStaleThreshold = 10 * time.Millisecond

	s.messageBus = fakeyagnats.New()
	s.Registry = NewRegistry(configObj, s.messageBus)

	fooEndpoint = &route.Endpoint{
		Host: "192.168.1.1",
		Port: 1234,

		ApplicationId: "12345",
		Tags: map[string]string{
			"runtime":   "ruby18",
			"framework": "sinatra",
		},
	}

	barEndpoint = &route.Endpoint{
		Host: "192.168.1.2",
		Port: 4321,

		ApplicationId: "54321",
		Tags: map[string]string{
			"runtime":   "javascript",
			"framework": "node",
		},
	}

	bar2Endpoint = &route.Endpoint{
		Host: "192.168.1.3",
		Port: 1234,

		ApplicationId: "54321",
		Tags: map[string]string{
			"runtime":   "javascript",
			"framework": "node",
		},
	}
}
示例#15
0
func SpecConfig(natsPort, statusPort, proxyPort uint16) *config.Config {
	c := config.DefaultConfig()

	c.Port = proxyPort
	c.Index = 2
	c.TraceKey = "my_trace_key"

	// Hardcode the IP to localhost to avoid leaving the machine while running tests
	c.Ip = "127.0.0.1"

	c.StartResponseDelayInterval = 10 * time.Millisecond
	c.PublishStartMessageIntervalInSeconds = 10
	c.PruneStaleDropletsInterval = 0
	c.DropletStaleThreshold = 0
	c.PublishActiveAppsInterval = 0

	c.EndpointTimeout = 500 * time.Millisecond

	c.Status = config.StatusConfig{
		Port: statusPort,
		User: "******",
		Pass: "******",
	}

	c.Nats = []config.NatsConfig{
		{
			Host: "localhost",
			Port: natsPort,
			User: "******",
			Pass: "******",
		},
	}

	c.Logging = config.LoggingConfig{
		File:  "/dev/stdout",
		Level: "info",
	}

	return c
}
package access_log_test

import (
	. "github.com/cloudfoundry/gorouter/access_log"

	"github.com/cloudfoundry/gorouter/config"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("AccessLog", func() {

	It("creates null access loger if no access log and loggregator is disabled", func() {
		config := config.DefaultConfig()

		Expect(CreateRunningAccessLogger(config)).To(BeAssignableToTypeOf(&NullAccessLogger{}))
	})

	It("creates an access log when loggegrator is enabled", func() {
		config := config.DefaultConfig()
		config.Logging.LoggregatorEnabled = true
		config.AccessLog = ""

		accessLogger, _ := CreateRunningAccessLogger(config)
		Expect(accessLogger.(*FileAndLoggregatorAccessLogger).FileWriter()).To(BeNil())
		Expect(accessLogger.(*FileAndLoggregatorAccessLogger).DropsondeSourceInstance()).To(Equal("0"))

	})

	It("creates an access log if an access log is specified", func() {
		config := config.DefaultConfig()
示例#17
0
	"github.com/cloudfoundry/gorouter/config"
	"github.com/cloudfoundry/gorouter/proxy"
	"github.com/cloudfoundry/gorouter/registry"
	"github.com/cloudfoundry/gorouter/route"
	"github.com/cloudfoundry/gorouter/varz"
	"github.com/cloudfoundry/yagnats/fakeyagnats"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"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,
		})
示例#18
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)
}
示例#19
0
	"encoding/json"
	"time"
)

var _ = Describe("RouteRegistry", func() {
	var r *RouteRegistry
	var messageBus *fakeyagnats.FakeNATSConn
	var reporter *fakes.FakeRouteReporter

	var fooEndpoint, barEndpoint, bar2Endpoint *route.Endpoint
	var configObj *config.Config

	BeforeEach(func() {

		logger := lagertest.NewTestLogger("test")
		configObj = config.DefaultConfig(logger)
		configObj.PruneStaleDropletsInterval = 50 * time.Millisecond
		configObj.DropletStaleThreshold = 10 * time.Millisecond

		messageBus = fakeyagnats.Connect()
		reporter = new(fakes.FakeRouteReporter)

		r = NewRouteRegistry(configObj, messageBus, reporter)
		fooEndpoint = route.NewEndpoint("12345", "192.168.1.1", 1234,
			"id1", map[string]string{
				"runtime":   "ruby18",
				"framework": "sinatra",
			}, -1, "")

		barEndpoint = route.NewEndpoint("54321", "192.168.1.2", 4321,
			"id2", map[string]string{
示例#20
0
func (s *VarzSuite) SetUpTest(c *C) {
	r := registry.NewCFRegistry(config.DefaultConfig(), fakeyagnats.New())
	s.Registry = r
	s.Varz = NewVarz(r)
}
示例#21
0
	"github.com/cloudfoundry/yagnats/fakeyagnats"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

var _ = Describe("Varz", func() {
	var Varz Varz
	var Registry *registry.RouteRegistry

	BeforeEach(func() {
		Registry = registry.NewRouteRegistry(config.DefaultConfig(), fakeyagnats.Connect())
		Varz = NewVarz(Registry)
	})

	It("contains the following items", func() {
		v := Varz

		members := []string{
			"responses_2xx",
			"responses_3xx",
			"responses_4xx",
			"responses_5xx",
			"responses_xxx",
			"latency",
			"rate",
			"tags",
func (s *CreateRunningAccessLoggerSuite) TestCreatesRealAccessLoggerIfBothAccesLogAndLoggregatorUrl(c *C) {
	config := config.DefaultConfig()
	config.LoggregatorConfig.Url = "10.10.3.13:4325"
	config.AccessLog = "/dev/null"
	c.Assert(CreateRunningAccessLogger(config), FitsTypeOf, &FileAndLoggregatorAccessLogger{})
}
		logger       lager.Logger
		client       *fake_routing_api.FakeClient

		token *token_fetcher.Token

		response     []db.Route
		process      ifrit.Process
		eventChannel chan routing_api.Event
		errorChannel chan error

		clock *fakeclock.FakeClock
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		cfg = config.DefaultConfig(logger)
		cfg.PruneStaleDropletsInterval = 2 * time.Second

		retryInterval := 0
		tokenFetcher = &testTokenFetcher.FakeTokenFetcher{}
		registry = &testRegistry.FakeRegistryInterface{}

		token = &token_fetcher.Token{
			AccessToken: "access_token",
			ExpireTime:  5,
		}
		client = &fake_routing_api.FakeClient{}

		eventChannel = make(chan routing_api.Event)
		errorChannel = make(chan error)
		eventSource := fake_routing_api.FakeEventSource{}
	"github.com/cloudfoundry/gorouter/route"
	"github.com/cloudfoundry/yagnats/fakeyagnats"

	"encoding/json"
	"time"
)

var _ = Describe("RouteRegistry", func() {
	var r *RouteRegistry
	var messageBus *fakeyagnats.FakeYagnats

	var fooEndpoint, barEndpoint, bar2Endpoint *route.Endpoint
	var configObj *config.Config

	BeforeEach(func() {
		configObj = config.DefaultConfig()
		configObj.PruneStaleDropletsInterval = 50 * time.Millisecond
		configObj.DropletStaleThreshold = 10 * time.Millisecond

		messageBus = fakeyagnats.New()
		r = NewRouteRegistry(configObj, messageBus)
		fooEndpoint = route.NewEndpoint("12345", "192.168.1.1", 1234,
			"id1", map[string]string{
				"runtime":   "ruby18",
				"framework": "sinatra",
			})

		barEndpoint = route.NewEndpoint("54321", "192.168.1.2", 4321,
			"id2", map[string]string{
				"runtime":   "javascript",
				"framework": "node",
示例#25
0
func main() {
	flag.StringVar(&configFile, "c", "", "Configuration File")
	cf_lager.AddFlags(flag.CommandLine)
	flag.Parse()

	c := config.DefaultConfig()
	logCounter := schema.NewLogCounter()

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

	prefix := "gorouter.stdout"
	if c.Logging.Syslog != "" {
		prefix = c.Logging.Syslog
	}
	logger, reconfigurableSink := cf_lager.New(prefix)
	InitLoggerFromConfig(logger, c, logCounter)

	logger.Info("starting")

	err := dropsonde.Initialize(c.Logging.MetronAddress, c.Logging.JobName)
	if err != nil {
		logger.Fatal("dropsonde-initialize-error", err)
	}

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

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

	logger.Info("setting-up-nats-connection")
	natsClient := connectToNatsServer(logger.Session("nats"), c)
	logger.Info("Successfully-connected-to-nats")

	metricsReporter := metrics.NewMetricsReporter()
	registry := rregistry.NewRouteRegistry(logger.Session("registry"), c, metricsReporter)

	varz := rvarz.NewVarz(registry)
	compositeReporter := metrics.NewCompositeReporter(varz, metricsReporter)

	accessLogger, err := access_log.CreateRunningAccessLogger(logger.Session("access-log"), c)
	if err != nil {
		logger.Fatal("error-creating-access-logger", err)
	}

	var crypto secure.Crypto
	var cryptoPrev secure.Crypto
	if c.RouteServiceEnabled {
		crypto = createCrypto(logger, c.RouteServiceSecret)
		if c.RouteServiceSecretPrev != "" {
			cryptoPrev = createCrypto(logger, c.RouteServiceSecretPrev)
		}
	}

	proxy := buildProxy(logger.Session("proxy"), c, registry, accessLogger, compositeReporter, crypto, cryptoPrev)

	router, err := router.NewRouter(logger.Session("router"), c, proxy, natsClient, registry, varz, logCounter, nil)
	if err != nil {
		logger.Fatal("initialize-router-error", err)
	}

	members := grouper.Members{
		{"router", router},
	}
	if c.RoutingApiEnabled() {
		logger.Info("setting-up-routing-api")
		routeFetcher := setupRouteFetcher(logger.Session("route-fetcher"), c, registry)

		// check connectivity to routing api
		err := routeFetcher.FetchRoutes()
		if err != nil {
			logger.Fatal("routing-api-connection-failed", err)
		}
		members = append(members, grouper.Member{"router-fetcher", routeFetcher})
	}

	group := grouper.NewOrdered(os.Interrupt, members)

	monitor := ifrit.Invoke(sigmon.New(group, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1))

	err = <-monitor.Wait()
	if err != nil {
		logger.Error("gorouter.exited-with-failure", err)
		os.Exit(1)
	}

	os.Exit(0)
}
示例#26
0
文件: main.go 项目: idouba/gorouter
func main() {
	flag.StringVar(&configFile, "c", "", "Configuration File")
	cf_lager.AddFlags(flag.CommandLine)
	flag.Parse()

	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)
	}

	logger.Info("Setting up NATs connection")
	natsClient := connectToNatsServer(logger, c)

	metricsReporter := metrics.NewMetricsReporter()
	registry := rregistry.NewRouteRegistry(c, natsClient, metricsReporter)

	varz := rvarz.NewVarz(registry)
	compositeReporter := metrics.NewCompositeReporter(varz, metricsReporter)

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

	var crypto secure.Crypto
	var cryptoPrev secure.Crypto
	if c.RouteServiceEnabled {
		crypto = createCrypto(logger, c.RouteServiceSecret)
		if c.RouteServiceSecretPrev != "" {
			cryptoPrev = createCrypto(logger, c.RouteServiceSecretPrev)
		}
	}

	proxy := buildProxy(c, registry, accessLogger, compositeReporter, crypto, cryptoPrev)

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

	members := grouper.Members{
		{"router", router},
	}
	if c.RoutingApiEnabled() {
		logger.Info("Setting up route fetcher")
		routeFetcher := setupRouteFetcher(logger, c, registry)
		members = append(members, grouper.Member{"router-fetcher", routeFetcher})
	}

	group := grouper.NewOrdered(os.Interrupt, members)

	monitor := ifrit.Invoke(sigmon.New(group, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1))

	err = <-monitor.Wait()
	if err != nil {
		logger.Error("gorouter.exited-with-failure")
		os.Exit(1)
	}

	os.Exit(0)
}
示例#27
0
		logger    lager.Logger
		client    *fake_routing_api.FakeClient

		token *schema.Token

		response     []db.Route
		process      ifrit.Process
		eventChannel chan routing_api.Event
		errorChannel chan error

		clock *fakeclock.FakeClock
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		cfg = config.DefaultConfig()
		cfg.PruneStaleDropletsInterval = 2 * time.Second

		retryInterval := 0
		uaaClient = &testUaaClient.FakeClient{}
		registry = &testRegistry.FakeRegistryInterface{}

		token = &schema.Token{
			AccessToken: "access_token",
			ExpiresIn:   5,
		}
		client = &fake_routing_api.FakeClient{}

		eventChannel = make(chan routing_api.Event)
		errorChannel = make(chan error)
		eventSource := fake_routing_api.FakeEventSource{}
func (s *CreateRunningAccessLoggerSuite) TestCreateNullAccessLoggerIfNoAccesLogAndNoLoggregatorUrl(c *C) {
	config := config.DefaultConfig()
	c.Assert(CreateRunningAccessLogger(config), FitsTypeOf, &NullAccessLogger{})
}
示例#29
0
	"github.com/pivotal-golang/lager/lagertest"

	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

var _ = Describe("Varz", func() {
	var Varz Varz
	var Registry *registry.RouteRegistry
	var logger lager.Logger

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")
		Registry = registry.NewRouteRegistry(logger, config.DefaultConfig(), fakeyagnats.Connect(), new(fakes.FakeRouteRegistryReporter))
		Varz = NewVarz(Registry)
	})

	It("contains the following items", func() {
		v := Varz

		members := []string{
			"responses_2xx",
			"responses_3xx",
			"responses_4xx",
			"responses_5xx",
			"responses_xxx",
			"latency",
			"rate",
			"tags",
func (s *CreateRunningAccessLoggerSuite) TestCreatesRealAccessLoggerIfAccesLogButNoLoggregatorUrl(c *C) {
	config := config.DefaultConfig()
	config.AccessLog = "/dev/null"
	c.Assert(CreateRunningAccessLogger(config), FitsTypeOf, &FileAndLoggregatorAccessLogger{})
}