Beispiel #1
10
func main() {
	var ns *nats.Conn
	var err error
	const maxWait = 30

	i := 0
	for ; i < maxWait; i++ {
		ns, err = nats.Connect(os.Getenv("NATS_URI"))
		if err == nil {
			break
		}
		time.Sleep(1 * time.Second)
	}
	if err != nil {
		log.Fatalln("nats.Connect:", err)
	}

	defer ns.Close()

	subReader, err := ns.SubscribeSync("nats-cast")
	if err != nil {
		log.Fatalln("nats.SubscribeSync:", err)
	}

	fmt.Println("waiting for messages from cast-server...")
	for {
		msg, err := subReader.NextMsg(5 * time.Minute)
		if err == nats.ErrConnectionClosed {
			return
		} else if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(msg.Data))
	}
}
Beispiel #2
4
func TestNilConnection(t *testing.T) {
	var nc *nats.Conn
	data := []byte("ok")

	// Publish
	if err := nc.Publish("foo", data); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if err := nc.PublishMsg(nil); err == nil || err != nats.ErrInvalidMsg {
		t.Fatalf("Expected ErrInvalidMsg error, got %v\n", err)
	}
	if err := nc.PublishMsg(&nats.Msg{}); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if err := nc.PublishRequest("foo", "reply", data); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}

	// Subscribe
	if _, err := nc.Subscribe("foo", nil); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if _, err := nc.SubscribeSync("foo"); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if _, err := nc.QueueSubscribe("foo", "bar", nil); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	ch := make(chan *nats.Msg)
	if _, err := nc.ChanSubscribe("foo", ch); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if _, err := nc.ChanQueueSubscribe("foo", "bar", ch); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if _, err := nc.QueueSubscribeSyncWithChan("foo", "bar", ch); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}

	// Flush
	if err := nc.Flush(); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}
	if err := nc.FlushTimeout(time.Millisecond); err == nil || err != nats.ErrInvalidConnection {
		t.Fatalf("Expected ErrInvalidConnection error, got %v\n", err)
	}

	// Nil Subscribers
	var sub *nats.Subscription
	if sub.Type() != nats.NilSubscription {
		t.Fatalf("Got wrong type for nil subscription, %v\n", sub.Type())
	}
	if sub.IsValid() {
		t.Fatalf("Expected IsValid() to return false")
	}
	if err := sub.Unsubscribe(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected Unsubscribe to return proper error, got %v\n", err)
	}
	if err := sub.AutoUnsubscribe(1); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, err := sub.NextMsg(time.Millisecond); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, err := sub.QueuedMsgs(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, _, err := sub.Pending(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, _, err := sub.MaxPending(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if err := sub.ClearMaxPending(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, _, err := sub.PendingLimits(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if err := sub.SetPendingLimits(1, 1); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, err := sub.Delivered(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
	if _, err := sub.Dropped(); err == nil || err != nats.ErrBadSubscription {
		t.Fatalf("Expected ErrBadSubscription error, got %v\n", err)
	}
}
Beispiel #3
0
func connectToNatsServer(logger lager.Logger, c *config.Config, startMsg chan<- struct{}) *nats.Conn {
	var natsClient *nats.Conn
	var natsHost atomic.Value
	var err error

	options := natsOptions(logger, c, &natsHost, startMsg)
	attempts := 3
	for attempts > 0 {
		natsClient, err = options.Connect()
		if err == nil {
			break
		} else {
			attempts--
			time.Sleep(100 * time.Millisecond)
		}
	}

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

	var natsHostStr string
	natsUrl, err := url.Parse(natsClient.ConnectedUrl())
	if err == nil {
		natsHostStr = natsUrl.Host
	}

	logger.Info("Successfully-connected-to-nats", lager.Data{"host": natsHostStr})

	natsHost.Store(natsHostStr)
	return natsClient
}
Beispiel #4
0
// NewNATSAgent subscribes for subject in queue and returns agent
func NewNATSAgent(subj, queue string, conn *nats.Conn, client HTTPClient) (NATSAgent, error) {
	h := NATSAgent{}
	h.httpClient = client
	h.conn = conn
	_, err := conn.QueueSubscribe(subj, queue, h.handler)
	return h, err
}
Beispiel #5
0
func testConnection(conn *nats.Conn) error {
	if conn == nil {
		return fmt.Errorf("natsproxy: Connection cannot be nil")
	}
	if conn.Status() != nats.CONNECTED {
		return ErrNatsClientNotConnected
	}
	return nil
}
Beispiel #6
0
func NewElectronConn(opt *nats.Options) (ec *ElectronConn, err error) {
	var nc *nats.Conn
	if opt == nil {
		nc, err = nats.Connect(nats.DefaultURL)
	} else {
		nc, err = opt.Connect()
	}
	if err != nil {
		return nil, err
	}

	ec = &ElectronConn{conn: nc}
	f := func(m *nats.Msg) {
		ID := atomic.AddUint32(&ec.genID, 1)
		if err := nc.Publish(m.Reply, []byte(fmt.Sprintf("%d", ID))); err != nil {
			logrus.Error(err)
			return
		}
		ec.Lock()
		ec.clients = append(ec.clients, ID)
		ec.Unlock()
	}
	if _, err = nc.Subscribe("register", f); err != nil {
		nc.Close()
		return nil, fmt.Errorf("nats: %v", err)
	}

	if ec.jsonConn, err = nats.NewEncodedConn(nc, "json"); err != nil {
		nc.Close()
		return nil, fmt.Errorf("nats: %v", err)
	}
	return
}
Beispiel #7
0
func (s *Subscriber) setup(nc *nats.Conn, m *nats.Msg) {
	body := m.Data
	input := messages.Setup{}
	err := json.Unmarshal(body, &input)
	if err != nil {
		nc, _ := nats.Connect(nats.DefaultURL)
		nc.Publish(m.Reply, []byte(`{"error":"error setting up github labels"}`))
		return
	}
	g := getAdapter(input.Config)
	g.Labels = input.States
	g.Setup(input.States, input.Org, input.Repo)
	nc.Publish(m.Reply, []byte(`success`))
}
func connect(conn *nats.Conn, subj string, timeout time.Duration) (*nats.Msg, string, error) {
	inbox := nats.NewInbox()
	s, err := conn.Subscribe(inbox, nil)
	if err != nil {
		return nil, "", err
	}
	s.AutoUnsubscribe(1)
	err = conn.PublishRequest(subj, inbox, nil)
	if err != nil {
		return nil, "", err
	}
	msg, err := s.NextMsg(timeout)
	if err != nil {
		return nil, "", err
	}
	return msg, inbox, nil
}
Beispiel #9
0
func natsHandler(nc *nats.Conn) http.Handler {
	result := func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		subject := vars["subject"]
		msg, err := ioutil.ReadAll(r.Body)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		err = nc.Publish(subject, msg)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	}
	return http.Handler(http.HandlerFunc(result))
}
Beispiel #10
0
func (c *VcapComponent) Register(mbusClient *nats.Conn) error {
	mbusClient.Subscribe("vcap.component.discover", func(msg *nats.Msg) {
		if msg.Reply == "" {
			log.Info(fmt.Sprintf("Received message with empty reply on subject %s", msg.Subject))
			return
		}

		c.Varz.Uptime = c.Varz.StartTime.Elapsed()
		b, e := json.Marshal(c.Varz)
		if e != nil {
			log.Error("error-json-marshaling", e)
			return
		}

		mbusClient.Publish(msg.Reply, b)
	})

	b, e := json.Marshal(c.Varz)
	if e != nil {
		log.Error("error-json-marshaling", e)
		return e
	}

	mbusClient.Publish("vcap.component.announce", b)

	log.Info(fmt.Sprintf("Component %s registered successfully", c.Varz.Type))
	return nil
}
Beispiel #11
0
// Subscribe to workflow.move in order to move an issue to its
// new status and execute proper hooks
func (w *WFMove) Subscribe(nc *nats.Conn) {
	e := ErrorMessage{}
	nc.Subscribe("workflow.move", func(m *nats.Msg) {
		input, err := w.mapInput(string(m.Data))
		if err != nil {
			e.Error = err.Error()
			nc.Publish(m.Reply, e.toJSON())
			return
		}

		i, err := w.executeTransition(input)
		if err != nil {
			e.Error = err.Error()
			nc.Publish(m.Reply, e.toJSON())
			return
		}

		nc.Publish(m.Reply, ToJSON(i))
	})
}
// Subscribe to workflow.states.available in order to return
// all available status for the current status of the issue
func (w *WFStatesAvailable) Subscribe(nc *nats.Conn) {
	e := ErrorMessage{}
	nc.Subscribe("workflow.states.available", func(m *nats.Msg) {
		i, err := w.mapInput(m.Data)
		if err != nil {
			e.Error = err.Error()
			nc.Publish(m.Reply, e.toJSON())
			return
		}

		s := i.Issue.AvailableExitStates()
		json, err := json.Marshal(s)
		if err != nil {
			e.Error = err.Error()
			nc.Publish(m.Reply, e.toJSON())
			return
		}

		nc.Publish(m.Reply, json)
	})
}
Beispiel #13
0
// Subscribe to workflow.states.all and return all valid states
// for the given issue
func (w *WFStatesAll) Subscribe(nc *nats.Conn) {
	e := ErrorMessage{}
	nc.Subscribe("workflow.states.all", func(m *nats.Msg) {
		i := Issue{}
		s := i.AllStates()
		json, err := json.Marshal(s)
		if err != nil {
			e.Error = err.Error()
			nc.Publish(m.Reply, e.toJSON())
			return
		}

		nc.Publish(m.Reply, json)
	})
}
	"code.cloudfoundry.org/lager/lagertest"

	"github.com/nats-io/nats"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Subscriber", func() {
	var (
		sub     *mbus.Subscriber
		subOpts *mbus.SubscriberOpts
		process ifrit.Process

		registry *fakes.FakeRegistryInterface

		natsRunner   *test_util.NATSRunner
		natsPort     uint16
		natsClient   *nats.Conn
		startMsgChan chan struct{}

		logger lager.Logger
	)

	BeforeEach(func() {
		natsPort = test_util.NextAvailPort()

		natsRunner = test_util.NewNATSRunner(int(natsPort))
		natsRunner.Start()
		natsClient = natsRunner.MessageBus

		registry = new(fakes.FakeRegistryInterface)
Beispiel #15
0
	testcommon "github.com/cloudfoundry/gorouter/test/common"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"
)

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

	const uuid_regex = `^[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}$`

	var (
		natsRunner *test_util.NATSRunner
		natsPort   uint16
		config     *cfg.Config

		mbusClient   *nats.Conn
		registry     *rregistry.RouteRegistry
		varz         vvarz.Varz
		router       *Router
		signals      chan os.Signal
		closeChannel chan struct{}
		readyChan    chan struct{}
		logger       lager.Logger
	)

	BeforeEach(func() {
		natsPort = test_util.NextAvailPort()
		natsRunner = test_util.NewNATSRunner(int(natsPort))
		natsRunner.Start()

		fakeEmitter := fake.NewFakeEventEmitter("fake")
		dropsonde.InitializeWithEmitter(fakeEmitter)
Beispiel #16
0
	"code.cloudfoundry.org/gorouter/metrics/reporter/fakes"
	testcommon "code.cloudfoundry.org/gorouter/test/common"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
)

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

	const uuid_regex = `^[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}$`

	var (
		natsRunner *test_util.NATSRunner
		natsPort   uint16
		config     *cfg.Config

		mbusClient *nats.Conn
		registry   *rregistry.RouteRegistry
		varz       vvarz.Varz
		router     *Router
		logger     lager.Logger
		statusPort uint16
	)

	BeforeEach(func() {
		natsPort = test_util.NextAvailPort()
		proxyPort := test_util.NextAvailPort()
		statusPort = test_util.NextAvailPort()
		cert, err := tls.LoadX509KeyPair("../test/assets/certs/server.pem", "../test/assets/certs/server.key")
		Expect(err).ToNot(HaveOccurred())

		config = test_util.SpecConfig(statusPort, proxyPort, natsPort)
		config.EnableSSL = true
Beispiel #17
0
func NatsPub(subject string, nc *nats.Conn, data []byte) {
	nc.Publish(subject, data)
}
func reconnectedHandler(nc *nats.Conn) {
	log.Fatalf("connection %q reconnected to NATS Server at %q",
		nc.Opts.Name, nc.ConnectedUrl())
}
func disconnectedHandler(nc *nats.Conn) {
	if nc.LastError() != nil {
		log.Fatalf("connection %q has been disconnected: %v",
			nc.Opts.Name, nc.LastError())
	}
}
Beispiel #20
0
		duration := stringMap["uptime"].(string)
		Expect(duration).NotTo(Equal(`"uptime":"0d:0h:0m:0s"`))
	})

	It("returns 404 for non existent paths", func() {
		serveComponent(component)

		req := buildGetRequest(component, "/non-existent-path")
		req.SetBasicAuth("username", "password")

		code, _, _ := doGetRequest(req)
		Expect(code).To(Equal(404))
	})

	Describe("Register", func() {
		var mbusClient *nats.Conn
		var natsRunner *test_util.NATSRunner
		var logger lager.Logger

		BeforeEach(func() {
			natsPort := test_util.NextAvailPort()
			natsRunner = test_util.NewNATSRunner(int(natsPort))
			natsRunner.Start()
			mbusClient = natsRunner.MessageBus

			logger = lagertest.NewTestLogger("test")
		})

		AfterEach(func() {
			natsRunner.Stop()
		})
var testBinaryPath string

var _ = BeforeSuite(func() {
	var err error
	testBinaryPath, err = gexec.Build("github.com/logsearch/nats-to-syslog")
	handleError(err)
})

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

var _ = Describe("NatsToSyslog", func() {
	var (
		gnatsd       *gexec.Session
		natsClient   *nats.Conn
		syslogServer *net.TCPListener
	)

	BeforeEach(func() {
		gnatsd = startGNATSd()

		var err error
		natsClient, err = nats.Connect("nats://*****:*****@127.0.0.1:4567")
		handleError(err)

		syslogServer = startSyslogServer()
	})

	It("forwards NATS messages to syslog", func() {
		testBinary := exec.Command(testBinaryPath, "-nats-uri", "nats://*****:*****@127.0.0.1:4567", "-syslog-endpoint", "localhost:6789", "-nats-subject", "testSubject", "-debug", "true")