Example #1
0
func main() {

	var server, query string
	flag.StringVar(&server, "s", "riemann:5555", "riemann server")
	flag.StringVar(&query, "q", "true", "query string")
	flag.Parse()

	conn, err := raidman.Dial("tcp", server)

	if err != nil {
		log.Fatal(err)
	}

	events, err := conn.Query(query)
	if err != nil {
		log.Fatal(err)
	}

	output, err := json.Marshal(events)
	if err != nil {
		log.Fatal("json encoding issue:", err)
	}
	os.Stdout.Write(output)

	conn.Close()
}
Example #2
0
func processGlobalFlags(c *cli.Context) time.Duration {
	var network string
	if c.GlobalBool("tcp") {
		network = "tcp"
	} else {
		network = "udp"
	}
	client, err := raidman.Dial(network, fmt.Sprintf("%s:%d", c.GlobalString("host"), c.GlobalInt("port")))
	if c.GlobalString("event-host") == "nil" {
		log.Panic("Failed to automatically get the hostname. Please specify it with --host")
	}
	if err != nil {
		log.Panicf("Failed to connect to the riemann host because %s", err)
	}
	attribute, err := processAttributes(c.GlobalStringSlice("attribute"))
	if err != nil {
		log.Panic(err)
	}
	eventTemplate := raidman.Event{
		Ttl:        float32(c.GlobalDuration("ttl").Seconds()),
		Tags:       c.GlobalStringSlice("tags"),
		Host:       c.GlobalString("event-host"),
		Attributes: attribute,
	}
	riemannSend = func(url, method string, duration float64) {
		event := eventTemplate
		event.Service = fmt.Sprintf("%s %s", url, method)
		event.Time = time.Now().Unix()
		event.Metric = duration
		client.Send(&event)
	}

	return c.GlobalDuration("interval")
}
// integration test
func TestRiemannPublish(t *testing.T) {
	// This integration test requires a Riemann Server
	broker := os.Getenv("SNAP_TEST_RIEMANN")
	if broker == "" {
		fmt.Println("Skipping integration tests")
		return
	}

	var buf bytes.Buffer
	buf.Reset()
	r := NewRiemannPublisher()
	config := make(map[string]ctypes.ConfigValue)
	config["broker"] = ctypes.ConfigValueStr{Value: broker}
	cp, _ := r.GetConfigPolicy()
	cfg, _ := cp.Get([]string{""}).Process(config)
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"intel", "cpu", "temp"}, time.Now(), "bacon-powered", nil, nil, 100),
	}
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)
	err := r.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
	Convey("Publish metric to Riemann", t, func() {
		Convey("So err should not be returned", func() {
			So(err, ShouldBeNil)
		})
		Convey("So metric retrieved equals metric published", func() {
			c, _ := raidman.Dial("tcp", broker)
			events, _ := c.Query("host = \"bacon-powered\"")
			So(len(events), ShouldBeGreaterThan, 0)
		})
	})
}
// publish sends events to riemann
func (r *riemannPublisher) publish(event *raidman.Event, broker string) error {
	c, err := raidman.Dial("tcp", broker)
	if err != nil {
		return err
	}
	defer c.Close()
	return c.Send(event)
}
Example #5
0
func connectToRiemannOrExit() *raidman.Client {
	socket := fmt.Sprintf("%s:%d", riemannHost, riemannPort)
	client, err := raidman.Dial(riemannProto, socket)
	if err != nil {
		log.Printf("Could not connect to riemann at %s.", socket)
		log.Fatal(err)
	}
	return client
}
Example #6
0
func (r *Riemann) Connect() error {
	c, err := raidman.Dial(r.Transport, r.URL)

	if err != nil {
		return err
	}

	r.client = c
	return nil
}
Example #7
0
func (r *Riemann) Connect() error {
	log.Printf(deprecationMsg)
	c, err := raidman.Dial(r.Transport, r.URL)

	if err != nil {
		r.client = nil
		return err
	}

	r.client = c
	return nil
}
func Alert(event *raidman.Event) {
	c, err := raidman.Dial("tcp", *host+":"+*port)
	if err != nil {
		panic(err)
	}
	err = c.Send(event)

	if err != nil {
		panic(err)
	}
	c.Close()
}
func NewRiemannPoster(address string, chanGroup *ChanGroup) *RiemannPoster {
	riemann, err := raidman.Dial("tcp", address)

	if err != nil {
		panic(err)
	}

	return &RiemannPoster{
		chanGroup:      chanGroup,
		riemann:        riemann,
		riemannAddress: address,
	}
}
func main() {

	var riemannHost string
	var riemannPort string
	var eventState string
	var eventMessage string
	var eventHost string
	var eventService string
	var eventMetric float64

	hostname, _ := os.Hostname()

	flag.StringVar(&riemannHost, "riemannHost", "localhost", "Riemann hostname")
	flag.StringVar(&riemannPort, "riemannPort", "5555", "Riemann listen port")
	flag.StringVar(&eventState, "eventState", "ok", "event state: ok or critical")
	flag.StringVar(&eventMessage, "eventMessage", "ping", "event description to send to Riemann")
	flag.StringVar(&eventHost, "eventHost", hostname, "hostname of the server that send the event")
	flag.StringVar(&eventService, "eventService", "cf-operational-tools", "name of the service")
	flag.Float64Var(&eventMetric, "eventMetric", 1.0, "metric for the event")
	flag.Parse()

	c, err := raidman.Dial("tcp", riemannHost+":"+riemannPort)
	if err != nil {
		panic(err)
	}

	var event = &raidman.Event{
		State:       eventState,
		Service:     eventService,
		Metric:      eventMetric,
		Description: eventMessage,
		Host:        eventHost,
		Time:        time.Now().Unix(),
	}

	err = c.Send(event)
	if err != nil {
		panic(err)
	}

	events, err := c.Query("service = \"" + eventService + "\"")
	if err != nil {
		panic(err)
	}

	if len(events) < 1 {
		panic("Submitted event not found")
	}

	c.Close()
}
Example #11
0
func main() {
	var gearman, riemann, tagswithdelim string
	var interval int
	flag.StringVar(&gearman, "gearman", "tcp://localhost:4730",
		"Use the specified host:port to connect to gearman.")
	flag.StringVar(&riemann, "riemann", "tcp://localhost:5555",
		"Write events to Riemann running at this port. Can also specify 'stdout' to debug.")
	flag.StringVar(&tagswithdelim, "tags", "",
		"Tags to add to the Riemann event.")
	flag.IntVar(&interval, "interval", 60000, "Interval in ms to output data.")
	flag.Parse()
	tags := strings.Split(tagswithdelim, ",")

	// Set up gearadmin
	gearmanURL, err := url.Parse(gearman)
	if err != nil {
		log.Fatal("error parsing gearman url: %s", err)
	}
	gearmanConn, err := net.Dial(gearmanURL.Scheme, gearmanURL.Host)
	if err != nil {
		log.Fatal("error connecting to gearman: %s", err)
	}
	defer gearmanConn.Close()
	gearadmin := gearadmin.NewGearmanAdmin(gearmanConn)

	// Set up where we'll write riemann events
	var riemannClient riemanner.RaidmanClient
	if riemann == "stdout" {
		riemannClient = NewDebugRaidmanClient(os.Stdout)
	} else {
		riemannURL, err := url.Parse(riemann)
		if err != nil {
			log.Fatal("error parsing riemann url: %s", err)
		}
		raidmanClient, err := raidman.Dial(riemannURL.Scheme, riemannURL.Host)
		if err != nil {
			log.Fatal("error connecting to riemann:", err)
		}
		defer raidmanClient.Close()
		riemannClient = raidmanClient
	}

	// Send the stats when we first start, and then at the specified interval
	sendMetrics(gearadmin, riemannClient, tags)
	for _ = range time.Tick(time.Duration(interval) * time.Millisecond) {
		sendMetrics(gearadmin, riemannClient, tags)
	}
}
Example #12
0
func Notify(event *raidman.Event) error {
	conn, err := raidman.Dial("tcp", *HOST+":"+*PORT)

	if err != nil {
		return err
	} else {

		send_err := conn.Send(event)

		if send_err != nil {
			return send_err
		} else {
			conn.Close()
			return nil
		}

	}
}
Example #13
0
func main() {
	c, err := raidman.Dial("tcp", "localhost:5555")
	if err != nil {
		panic(err)
	}

	fmt.Printf("connected to localhost\n")

	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	var event = &raidman.Event{
		State:   "ok",
		Host:    hostname,
		Service: "raidman-sample",
		Metric:  100,
		Ttl:     10,
	}

	err = c.Send(event)
	if err != nil {
		panic(err)
	}

	fmt.Printf("event sent\n")

	events, err := c.Query(fmt.Sprintf("host = \"%s\"", hostname))
	if err != nil {
		panic(err)
	}

	if len(events) < 1 {
		panic("Submitted event not found")
	}

	fmt.Printf("query: %q\n", events)

	c.Close()
}
Example #14
0
func establishRiemannClient(host string) chan *raidman.Client {
	connChannel := make(chan *raidman.Client)

	go func() {
		connect := func() error {
			c, err := raidman.Dial("tcp", host)
			if err != nil {
				log.Println("Error connecting to Riemann, will retry.", err)
				return err
			} else {
				log.Println("connected to riemann server", host)
				connChannel <- c
				return nil
			}
		}

		policy := &backoff.ConstantBackOff{time.Second * 5}
		backoff.Retry(connect, policy)
	}()

	return connChannel
}
func (p *RiemannPoster) deliver(event *raidman.Event) {
	ctx := slog.Context{}
	defer func() { LogWithContext(ctx) }()

	start := time.Now()

	log.Printf("sending %#v\n", *event)

	err := p.riemann.Send(event)

	if err != nil {
		log.Println(ctx, "delivery error, trying to reconnect:", err)
		new_riemann, err := raidman.Dial("tcp", p.riemannAddress)
		if err == nil {
			log.Println("reconnected!")
			p.riemann = new_riemann
		} else {
			log.Println("reconnection failed:", err)
		}
	}

	ctx.MeasureSince("riemann_poster.time", start)
}
Example #16
0
func main() {
	var opts Options

	// create parsers
	parser := flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash)
	iniParser := flags.NewIniParser(parser)

	// parse command-line arguments
	_, err := parser.ParseArgs(os.Args)
	checkError("parsing arguments", err)

	if _, err := os.Stat(opts.IniFile); err == nil {
		err = iniParser.ParseFile(opts.IniFile)
		checkError("parsing ini file", err)
	}

	if opts.RiemannHost == "" {
		parser.WriteHelp(os.Stdout)
		log.Fatal("riemann host not provided")
	}

	if opts.Event.Service == "" {
		parser.WriteHelp(os.Stdout)
		log.Fatal("event service name not provided")
	}

	if opts.Debug {
		// Only log the warning severity or above.
		log.SetLevel(log.DebugLevel)
	}

	if opts.Event.Description == "" {
		bytes, err := ioutil.ReadAll(os.Stdin)
		checkError("error reading from stdin", err)
		opts.Event.Description = string(bytes)
	}

	addr := fmt.Sprintf("%s:%d", opts.RiemannHost, opts.RiemannPort)
	log.Debugf("connecting to %s with %s", addr, opts.Proto)

	riemann, err := raidman.Dial(opts.Proto, addr)
	checkError("connecting to Riemann", err)

	defer riemann.Close()

	log.Debug("creating sender")
	sender := riemannSender.NewSender(riemann)

	err = sender.Send(&raidman.Event{
		Ttl:         opts.Event.Ttl,
		Time:        opts.Event.Time,
		Tags:        opts.Event.Tags,
		Host:        opts.Event.Host,
		State:       opts.Event.State,
		Service:     opts.Event.Service,
		Metric:      opts.Event.Metric,
		Description: opts.Event.Description,
		Attributes:  opts.Event.Attributes,
	})
	checkError("sending event", err)

	log.Debug("done")
}