func (s *RCSuite) TestRouterClientGreeting(c *C) {
	mbus := fakeyagnats.New()

	routerClient := NewCFRouterClient("1.2.3.4", mbus)

	routerClient.Register(123, "abc")

	err := routerClient.Greet()
	c.Assert(err, IsNil)

	greetMsg := mbus.PublishedMessages("router.greet")[0]

	greetCallback := mbus.Subscriptions(greetMsg.ReplyTo)[0]
	greetCallback.Callback(&yagnats.Message{
		Payload: []byte(`{"minimumRegisterIntervalInSeconds":1}`),
	})

	c.Assert(len(mbus.PublishedMessages("router.register")), Equals, 1)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages("router.register")), Equals, 1)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages("router.register")), Equals, 2)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages("router.register")), Equals, 2)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages("router.register")), Equals, 3)
}
func (s *RCSuite) TestRouterClientRouterStartHandling(c *C) {
	mbus := fakeyagnats.New()

	routerClient := NewCFRouterClient("1.2.3.4", mbus)

	err := routerClient.Greet()
	c.Assert(err, IsNil)

	startCallback := mbus.Subscriptions["router.start"][0]
	startCallback.Callback(&yagnats.Message{
		Payload: []byte(`{"minimumRegisterIntervalInSeconds":1}`),
	})

	routerClient.Register(123, "abc")

	c.Assert(len(mbus.PublishedMessages["router.register"]), Equals, 1)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages["router.register"]), Equals, 1)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages["router.register"]), Equals, 2)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages["router.register"]), Equals, 2)

	time.Sleep(600 * time.Millisecond)

	c.Assert(len(mbus.PublishedMessages["router.register"]), Equals, 3)
}
Exemple #3
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
}
Exemple #4
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),
			},
		)
	}
}
Exemple #5
0
func createNatsClientAndHandler() (client *fakeyagnats.FakeYagnats, handler natsHandler) {
	settings := boshsettings.Settings{
		AgentId: "my-agent-id",
		Mbus:    "nats://*****:*****@127.0.0.1:1234",
	}

	client = fakeyagnats.New()
	handler = newNatsHandler(client, settings)
	return
}
func (s *RCSuite) TestRouterClientUnregistering(c *C) {
	mbus := fakeyagnats.New()

	routerClient := NewCFRouterClient("1.2.3.4", mbus)

	routerClient.Unregister(123, "abc")

	unregistrations := mbus.PublishedMessages["router.unregister"]

	c.Assert(len(unregistrations), Not(Equals), 0)
	c.Assert(string(unregistrations[0].Payload), Equals, `{"uris":["abc"],"host":"1.2.3.4","port":123}`)
}
func (s *RCSuite) TestRouterClientRegistering(c *C) {
	mbus := fakeyagnats.New()

	routerClient := NewCFRouterClient("1.2.3.4", mbus)

	routerClient.Register(123, "abc")

	registrations := mbus.PublishedMessages("router.register")

	c.Assert(len(registrations), Not(Equals), 0)
	c.Assert(string(registrations[0].Payload), Equals,
		`{"uris":["abc"],"host":"1.2.3.4","port":123,"private_instance_id":"`+routerClient.PrivateInstanceId+`"}`)
}
Exemple #8
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
}
Exemple #10
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",
		},
	}
}
Exemple #11
0
func buildNatsClientAndHandler(settings boshsettings.Service) (client *fakeyagnats.FakeYagnats, handler natsHandler) {
	logger := boshlog.NewLogger(boshlog.LEVEL_NONE)
	client = fakeyagnats.New()
	handler = newNatsHandler(settings, logger, client)
	return
}
	"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",
			})

		bar2Endpoint = route.NewEndpoint("54321", "192.168.1.3", 1234,
			"id3", map[string]string{
Exemple #13
0
func main() {
	seed := time.Now().UnixNano()
	rand.Seed(seed)

	flag.Parse()

	if *version {
		fmt.Printf("version: %s\ngitSha: %s\nsourceUrl: https://github.com/cloudfoundry/loggregator/tree/%s\n\n",
			versionNumber, gitSha, gitSha)
		return
	}

	runtime.GOMAXPROCS(runtime.NumCPU())

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			panic(err)
		}
		pprof.StartCPUProfile(f)
		defer func() {
			pprof.StopCPUProfile()
			f.Close()
		}()
	}

	if *memprofile != "" {
		f, err := os.Create(*memprofile)
		if err != nil {
			panic(err)
		}
		go func() {
			defer f.Close()
			ticker := time.NewTicker(time.Second * 1)
			defer ticker.Stop()
			for {
				<-ticker.C
				pprof.WriteHeapProfile(f)
			}
		}()
	}

	config, logger := parseConfig(logLevel, configFile, logFilePath)

	if len(config.NatsHosts) == 0 {
		logger.Warn("Startup: Did not receive a NATS host - not going to regsiter component")
		cfcomponent.DefaultYagnatsClientProvider = func(logger *gosteno.Logger, c *cfcomponent.Config) (yagnats.NATSClient, error) {
			return fakeyagnats.New(), nil
		}
	}

	err := config.Validate(logger)
	if err != nil {
		panic(err)
	}

	l := New("0.0.0.0", config, logger)

	cfc, err := cfcomponent.NewComponent(
		logger,
		"LoggregatorServer",
		config.Index,
		&LoggregatorServerHealthMonitor{},
		config.VarzPort,
		[]string{config.VarzUser, config.VarzPass},
		l.Emitters(),
	)

	if err != nil {
		panic(err)
	}

	cr := collectorregistrar.NewCollectorRegistrar(config.MbusClient, logger)
	err = cr.RegisterWithCollector(cfc)
	if err != nil {
		logger.Warnf("Unable to register with collector. Err: %v.", err)
	}

	go func() {
		err := cfc.StartMonitoringEndpoints()
		if err != nil {
			panic(err)
		}
	}()

	l.Start()
	logger.Info("Startup: loggregator server started.")

	killChan := make(chan os.Signal)
	signal.Notify(killChan, os.Kill, os.Interrupt)

	for {
		select {
		case <-cfcomponent.RegisterGoRoutineDumpSignalChannel():
			cfcomponent.DumpGoRoutine()
		case <-killChan:
			logger.Info("Shutting down")
			l.Stop()
			return
		}
	}
}
func init() {
	Describe("natsHandler", func() {
		var (
			settingsService *fakesettings.FakeSettingsService
			client          *fakeyagnats.FakeYagnats
			logger          boshlog.Logger
			handler         boshhandler.Handler
		)

		BeforeEach(func() {
			settingsService = &fakesettings.FakeSettingsService{
				Settings: boshsettings.Settings{
					AgentID: "my-agent-id",
					Mbus:    "nats://*****:*****@127.0.0.1:1234",
				},
			}
			logger = boshlog.NewLogger(boshlog.LevelNone)
			client = fakeyagnats.New()
			handler = NewNatsHandler(settingsService, client, logger)
		})

		Describe("Start", func() {
			It("starts", func() {
				var receivedRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					receivedRequest = req
					return boshhandler.NewValueResponse("expected value")
				})
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider()).ToNot(BeNil())

				Expect(client.SubscriptionCount()).To(Equal(1))
				subscriptions := client.Subscriptions("agent.my-agent-id")
				Expect(len(subscriptions)).To(Equal(1))

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`)
				subscription := subscriptions[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				Expect(receivedRequest).To(Equal(boshhandler.Request{
					ReplyTo: "reply to me!",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("reply to me!")
				Expect(len(messages)).To(Equal(1))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"expected value"}`)))
			})

			It("does not respond if the response is nil", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					return nil
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`),
				})

				Expect(client.PublishedMessageCount()).To(Equal(0))
			})

			It("responds with an error if the response is bigger than 1MB", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					// gets inflated by json.Marshal when enveloping
					size := 0

					switch req.Method {
					case "small":
						size = 1024*1024 - 12
					case "big":
						size = 1024 * 1024
					default:
						panic("unknown request size")
					}

					chars := make([]byte, size)
					for i := range chars {
						chars[i] = 'A'
					}
					return boshhandler.NewValueResponse(string(chars))
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"small","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"big","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("fake-reply-to")
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(MatchRegexp("value"))
				Expect(messages[1].Payload).To(Equal([]byte(
					`{"exception":{"message":"Response exceeded maximum allowed length"}}`)))
			})

			It("can add additional handler funcs to receive requests", func() {
				var firstHandlerReq, secondHandlerRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					firstHandlerReq = req
					return boshhandler.NewValueResponse("first-handler-resp")
				})
				defer handler.Stop()

				handler.RegisterAdditionalFunc(func(req boshhandler.Request) (resp boshhandler.Response) {
					secondHandlerRequest = req
					return boshhandler.NewValueResponse("second-handler-resp")
				})

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "fake-reply-to"}`)

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				// Expected requests received by both handlers
				Expect(firstHandlerReq).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(secondHandlerRequest).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				// Bosh handler responses were sent
				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("fake-reply-to")
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"first-handler-resp"}`)))
				Expect(messages[1].Payload).To(Equal([]byte(`{"value":"second-handler-resp"}`)))
			})

			It("has the correct connection info", func() {
				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider()).To(Equal(&yagnats.ConnectionInfo{
					Addr:     "127.0.0.1:1234",
					Username: "******",
					Password: "******",
				}))
			})

			It("does not err when no username and password", func() {
				settingsService.Settings.Mbus = "nats://127.0.0.1:1234"
				handler = NewNatsHandler(settingsService, client, logger)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()
			})

			It("errs when has username without password", func() {
				settingsService.Settings.Mbus = "nats://[email protected]:1234"
				handler = NewNatsHandler(settingsService, client, logger)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).To(HaveOccurred())
				defer handler.Stop()
			})
		})

		Describe("Send", func() {
			It("sends the message over nats to a subject that includes the target and topic", func() {
				errCh := make(chan error, 1)

				payload := map[string]string{"key1": "value1", "keyA": "valueA"}

				go func() {
					errCh <- handler.Send(boshhandler.HealthMonitor, boshhandler.Heartbeat, payload)
				}()

				var err error
				select {
				case err = <-errCh:
				}
				Expect(err).ToNot(HaveOccurred())

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("hm.agent.heartbeat.my-agent-id")
				Expect(messages).To(HaveLen(1))
				Expect(messages[0].Payload).To(Equal(
					[]byte("{\"key1\":\"value1\",\"keyA\":\"valueA\"}"),
				))
			})
		})
	})
}
Exemple #15
0
func init() {
	Describe("natsHandler", func() {
		var (
			client  *fakeyagnats.FakeYagnats
			logger  boshlog.Logger
			handler boshhandler.Handler
		)

		BeforeEach(func() {
			settings := &fakesettings.FakeSettingsService{
				AgentID: "my-agent-id",
				MbusURL: "nats://*****:*****@127.0.0.1:1234",
			}
			logger = boshlog.NewLogger(boshlog.LevelNone)
			client = fakeyagnats.New()
			handler = NewNatsHandler(settings, logger, client)
		})

		Describe("Start", func() {
			It("starts", func() {
				var receivedRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					receivedRequest = req
					return boshhandler.NewValueResponse("expected value")
				})
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider).ToNot(BeNil())

				Expect(len(client.Subscriptions)).To(Equal(1))
				subscriptions := client.Subscriptions["agent.my-agent-id"]
				Expect(len(subscriptions)).To(Equal(1))

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`)
				subscription := client.Subscriptions["agent.my-agent-id"][0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				Expect(receivedRequest).To(Equal(boshhandler.Request{
					ReplyTo: "reply to me!",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(len(client.PublishedMessages)).To(Equal(1))
				messages := client.PublishedMessages["reply to me!"]
				Expect(len(messages)).To(Equal(1))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"expected value"}`)))
			})

			It("does not respond if the response is nil", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					return nil
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions["agent.my-agent-id"][0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`),
				})

				Expect(len(client.PublishedMessages)).To(Equal(0))
			})

			It("responds with an error if the response is bigger than 1MB", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					// gets inflated by json.Marshal when enveloping
					size := 0

					switch req.Method {
					case "small":
						size = 1024*1024 - 12
					case "big":
						size = 1024 * 1024
					default:
						panic("unknown request size")
					}

					chars := make([]byte, size)
					for i := range chars {
						chars[i] = 'A'
					}
					return boshhandler.NewValueResponse(string(chars))
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions["agent.my-agent-id"][0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"small","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"big","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				Expect(len(client.PublishedMessages)).To(Equal(1))
				messages := client.PublishedMessages["fake-reply-to"]
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(MatchRegexp("value"))
				Expect(messages[1].Payload).To(Equal([]byte(
					`{"exception":{"message":"Response exceeded maximum size allowed to be sent over NATS"}}`)))
			})

			It("can add additional handler funcs to receive requests", func() {
				var firstHandlerReq, secondHandlerRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					firstHandlerReq = req
					return boshhandler.NewValueResponse("first-handler-resp")
				})
				defer handler.Stop()

				handler.RegisterAdditionalHandlerFunc(func(req boshhandler.Request) (resp boshhandler.Response) {
					secondHandlerRequest = req
					return boshhandler.NewValueResponse("second-handler-resp")
				})

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "fake-reply-to"}`)

				subscription := client.Subscriptions["agent.my-agent-id"][0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				// Expected requests received by both handlers
				Expect(firstHandlerReq).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(secondHandlerRequest).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				// Bosh handler responses were sent
				Expect(len(client.PublishedMessages)).To(Equal(1))
				messages := client.PublishedMessages["fake-reply-to"]
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"first-handler-resp"}`)))
				Expect(messages[1].Payload).To(Equal([]byte(`{"value":"second-handler-resp"}`)))
			})

			It("has the correct connection info", func() {
				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider).To(Equal(&yagnats.ConnectionInfo{
					Addr:     "127.0.0.1:1234",
					Username: "******",
					Password: "******",
				}))
			})

			It("does not err when no username and password", func() {
				settings := &fakesettings.FakeSettingsService{MbusURL: "nats://127.0.0.1:1234"}
				handler = NewNatsHandler(settings, logger, client)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()
			})

			It("errs when has username without password", func() {
				settings := &fakesettings.FakeSettingsService{MbusURL: "nats://[email protected]:1234"}
				handler = NewNatsHandler(settings, logger, client)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).To(HaveOccurred())
				defer handler.Stop()
			})
		})

		Describe("SendToHealthManager", func() {
			It("sends periodic heartbeats", func() {
				errCh := make(chan error, 1)

				jobName := "foo"
				jobIndex := 0
				expectedHeartbeat := Heartbeat{Job: &jobName, Index: &jobIndex}

				go func() {
					errCh <- handler.SendToHealthManager("heartbeat", expectedHeartbeat)
				}()

				var err error
				select {
				case err = <-errCh:
				}
				Expect(err).ToNot(HaveOccurred())

				Expect(len(client.PublishedMessages)).To(Equal(1))
				messages := client.PublishedMessages["hm.agent.heartbeat.my-agent-id"]

				Expect(len(messages)).To(Equal(1))
				message := messages[0]

				expectedJSON, _ := json.Marshal(expectedHeartbeat)
				Expect(string(expectedJSON)).To(Equal(string(message.Payload)))
			})
		})
	})
}
}

var _ = Describe("Proxy", func() {
	var r *registry.RouteRegistry
	var p Proxy
	var conf *config.Config
	var proxyServer net.Listener
	var accessLog access_log.AccessLogger
	var accessLogFile *test_util.FakeFile

	BeforeEach(func() {
		conf = config.DefaultConfig()
		conf.TraceKey = "my_trace_key"
		conf.EndpointTimeout = 500 * time.Millisecond

		mbus := fakeyagnats.New()

		r = registry.NewRouteRegistry(conf, mbus)

		accessLogFile = new(test_util.FakeFile)
		accessLog = access_log.NewFileAndLoggregatorAccessLogger(accessLogFile, nil)
		go accessLog.Run()

		p = NewProxy(ProxyArgs{
			EndpointTimeout: conf.EndpointTimeout,
			Ip:              conf.Ip,
			TraceKey:        conf.TraceKey,
			Registry:        r,
			Reporter:        nullVarz{},
			AccessLogger:    accessLog,
		})
Exemple #17
0
func buildNatsClientAndHandler(settings boshsettings.Service) (client *fakeyagnats.FakeYagnats, handler boshhandler.Handler) {
	logger := boshlog.NewLogger(boshlog.LevelNone)
	client = fakeyagnats.New()
	handler = NewNatsHandler(settings, logger, client)
	return
}
Exemple #18
0
func (s *VarzSuite) SetUpTest(c *C) {
	r := registry.NewCFRegistry(config.DefaultConfig(), fakeyagnats.New())
	s.Registry = r
	s.Varz = NewVarz(r)
}
	"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.New())
		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",