Пример #1
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	statsdHost := flag.String("statsd", "", "Statsd host to record load test metrics")
	flag.Parse()

	stats, err := statsd.NewClient(*statsdHost, "hystrix.loadtest.service")
	if err != nil {
		log.Fatalf("could not initialize statsd client: %v", err)
	}

	c, err := plugins.InitializeStatsdCollector(&plugins.StatsdCollectorConfig{
		StatsdAddr: *statsdHost,
		Prefix:     "hystrix.loadtest.circuits",
	})
	if err != nil {
		log.Fatalf("could not initialize statsd client: %v", err)
	}
	metricCollector.Registry.Register(c.NewStatsdCollector)

	hystrix.ConfigureCommand("test", hystrix.CommandConfig{
		Timeout: 50,
	})

	go rotateDelay()

	http.HandleFunc("/", timedHandler(handle, stats))
	log.Print("starting server")
	log.Fatal(http.ListenAndServe(":8888", nil))
}
Пример #2
0
func main() {

	for {

		client, err := statsd.NewClient("104.130.20.4:8125", hostname())
		if err != nil {
			fmt.Println(err.Error())
		}

		memoryUtil()

		defer client.Close()

		value, _ := memoryUtil()

		fmt.Println(value)

		client.Gauge("Apache2", value, 0.4)

		fmt.Println(hostname())

		time.Sleep(1 * time.Second)

	}
}
Пример #3
0
func main() {
	configPath := flag.String("config", "config.yml", "Path to configuration file")
	flag.Parse()

	configBytes, err := ioutil.ReadFile(*configPath)
	cmd.FailOnError(err, fmt.Sprintf("Failed to read configuration file from '%s'", *configPath))
	var c config
	err = yaml.Unmarshal(configBytes, &c)
	cmd.FailOnError(err, fmt.Sprintf("Failed to parse configuration file from '%s'", *configPath))

	go cmd.DebugServer(c.DebugAddr)

	stats, err := statsd.NewClient(c.StatsdServer, c.StatsdPrefix)
	cmd.FailOnError(err, "Failed to create StatsD client")
	scope := metrics.NewStatsdScope(stats, "caa-service")

	resolver := bdns.NewDNSResolverImpl(
		c.DNSTimeout.Duration,
		[]string{c.DNSResolver},
		scope,
		clock.Default(),
		5,
	)

	s, l, err := bgrpc.NewServer(&c.GRPC, scope)
	cmd.FailOnError(err, "Failed to setup gRPC server")
	ccs := &caaCheckerServer{resolver, scope}
	pb.RegisterCAACheckerServer(s, ccs)
	err = s.Serve(l)
	cmd.FailOnError(err, "gRPC service failed")
}
Пример #4
0
// NewStatsd returns a new Statsd implementation that sends stats to addr.
func NewStatsd(addr, prefix string) (*Statsd, error) {
	c, err := statsd.NewClient(addr, prefix)
	if err != nil {
		return nil, err
	}
	return &Statsd{
		client: c,
	}, nil
}
Пример #5
0
func sendStats(statsdHost string, prefix string, gauges map[string]int64, counters map[string]int64) {
	client, err := statsd.NewClient(statsdHost, prefix)
	if err != nil {
		color.Red("ERROR: can't connect to statsd")
	}
	defer client.Close()
	sendGauges(client, gauges)
	sendCounters(client, counters)
}
Пример #6
0
// InitializeStatsdCollector creates the connection to the Statsd server
// and should be called before any metrics are recorded.
//
// Users should ensure to call Close() on the client.
func InitializeStatsdCollector(config *StatsdCollectorConfig) (*StatsdCollectorClient, error) {
	c, err := statsd.NewClient(config.StatsdAddr, config.Prefix)
	if err != nil {
		log.Printf("Could not initiale buffered client: %s. Falling back to a Noop Statsd client", err)
		c, _ = statsd.NewNoopClient()
	}
	return &StatsdCollectorClient{
		client: c,
	}, err
}
func main() {
	perLogBufferSize := flag.Int("perLogBufferSize", 25000, "")
	perLogDBWorkers := flag.Int("perLogDBWorkers", 5, "")
	dbMaxIdleConns := flag.Int("dbMaxIdleConns", 300, "")
	flag.Parse()

	configFilename := "config.json"

	var config cross.Config
	contents, err := ioutil.ReadFile(configFilename)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = json.Unmarshal(contents, &config)
	if err != nil {
		fmt.Println(err)
		return
	}

	stats, err := statsd.NewClient(config.StatsdURI, "pollinator")
	if err != nil {
		fmt.Println(err)
		return
	}
	db, err := cross.NewDatabase(config.DatabaseURI, stats, *dbMaxIdleConns)
	if err != nil {
		fmt.Println(err)
		return
	}
	logs := make([]*cross.Log, len(config.Logs))
	for i, kl := range config.Logs {
		log, err := cross.NewLog(db, stats, kl, *perLogBufferSize, *perLogDBWorkers)
		if err != nil {
			fmt.Println(err)
			return
		}
		logs[i] = log
	}

	p := pollinator{
		db:        db,
		dbWorkers: 250,
		stats:     stats,
		logs:      logs,
	}
	// p.getUpdates()
	for _, l := range p.logs {
		missing, err := l.CountMissingChains()
		fmt.Printf("%s: %d (%s)\n", l.Description, missing, err)
	}
}
Пример #8
0
func main() {
	appname := path.Base(os.Args[0])
	logrus.SetFormatter(&logrus.JSONFormatter{})
	logger = logrus.WithFields(logrus.Fields{
		"applicationname": appname,
	})
	var k8shost, k8sport, k8sproto, prefix string
	var statsdhost, statsdport string

	if k8shost = os.Getenv("KUBERNETES_SERVICE_HOST"); k8shost == "" {
		logger.Panic("Must Supply KUBERNETES_SERVICE_HOST")
	}
	if k8sport = os.Getenv("KUBERNETES_SERVICE_PORT"); k8sport == "" {
		logger.Panic("Must Supply KUBERNETES_SERVICE_PORT")
	}
	if k8sproto = os.Getenv("KUBERNETES_SERVICE_PROTO"); k8sproto == "" {
		logger.Panic("Must Supply KUBERNETES_SERVICE_PROTO (http/https)")
	}
	if statsdhost = os.Getenv("STATSD_SERVICE_HOST"); statsdhost == "" {
		logger.Panic("Must Supply STATSD_SERVICE_HOST")
	}
	if statsdport = os.Getenv("STATSD_SERVICE_PORT"); statsdport == "" {
		logger.Panic("Must Supply STATSD_SERVICE_PORT")
	}
	if prefix = os.Getenv("STATSD_PREFIX"); prefix == "" {
		prefix = "k8smon"
	}

	k8s := fmt.Sprintf("%s://%s:%s", k8sproto, k8shost, k8sport)
	logger.Infof("Connecting to Kubernetes Master: %s", k8s)
	config := unversioned.Config{
		Host:    k8s,
		Version: "v1",
	}
	var err error

	k8sclient, err = unversioned.New(&config)
	if err != nil {
		logger.Panic("Unable to connect to Kubernetes Master", err)
	}

	sd := fmt.Sprintf("%s:%s", statsdhost, statsdport)
	logger.Infof("Connecting to statsd: %s", sd)
	statsdclient, err = statsd.NewClient(sd, prefix)
	if err != nil {
		logger.Panic("Unable to connect to statsd", err)
	}
	for {
		CountInstances()
		time.Sleep(time.Second * 5)
	}
}
Пример #9
0
// SendStats will send all stats collected by TubesStats() to statsd
//
// Return error if fail to connect to statsd
func SendStats(stats map[string]map[string]int) error {
	client, err := statsd.NewClient(config.StatsdAddr, config.StatsdPrefix)
	if err != nil {
		return fmt.Errorf("Failed to connect to statsd: %s", err)
	}
	for tube, sts := range stats {
		verbose1("sending stats of tube %s", tube)
		for stat, value := range sts {
			name := fmt.Sprintf("%s.%s", tube, stat)
			client.Gauge(name, int64(value), 1.0)
			verbose2("%s.%s: %d", config.StatsdPrefix, name, value)
		}
	}
	return nil
}
Пример #10
0
func main() {
	var prefix string

	mysqlDSN := "root:root@tcp(127.0.0.1:3306)/mysql"
	statsdURL := "127.0.0.1:8125"

	flag.StringVar(&prefix, "prefix", "", "prefix to send to statsd, usually server hostname")
	flag.Parse()

	if flag.NArg() < 2 {
		fmt.Println("Usage: mysql-query-metric-statsd QUERY METRIC_NAME")
		fmt.Println("\nOptions:")
		flag.PrintDefaults()
		os.Exit(0)
	}

	if os.Getenv("MYSQL_DSN") != "" {
		mysqlDSN = os.Getenv("MYSQL_DSN")
	}

	if os.Getenv("STATSD_URL") != "" {
		statsdURL = os.Getenv("STATSD_URL")
	}

	query := flag.Arg(0)
	metricName := flag.Arg(1)

	db, err := sql.Open("mysql", mysqlDSN)
	if err != nil {
		log.Fatal("Error connecting to mysql:", err)
	}

	log.Println("Executing mysql query:", query)
	var value int64
	if err := db.QueryRow(query).Scan(&value); err != nil {
		log.Fatal("Error executing mysql query:", err)
	}

	sc, err := statsd.NewClient(statsdURL, prefix)
	if err != nil {
		log.Fatal("Error creating statsd client:", err)
	}
	defer sc.Close()

	sc.Gauge(metricName, value, 1.0)

	log.Printf("Sent metric prefix=%v name=%v value=%v", prefix, metricName, value)
}
Пример #11
0
func main() {
	port := "8125"
	if len(os.Args) > 1 {
		port = os.Args[1]
	}

	client, err := statsd.NewClient(fmt.Sprintf("127.0.0.1:%s", port), "testNamespace")
	if err != nil {
		fmt.Printf("Error connecting to statsd server: %v\n", err.Error())
		return
	}
	defer client.Close()

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		inputs := strings.Split(line, " ")
		if len(inputs) < 3 {
			fmt.Printf("Wrong number of inputs, 3 needed at least\n")
			continue
		}
		statsdType := inputs[0]
		name := inputs[1]

		value, _ := strconv.ParseInt(inputs[2], 10, 0)
		var sampleRate float32 = 1.0
		if len(inputs) == 4 {
			rate, _ := strconv.ParseFloat(inputs[3], 32)
			sampleRate = float32(rate)
		}

		switch statsdType {
		case "count":
			client.Inc(name, value, sampleRate)
		case "gauge":
			client.Gauge(name, value, sampleRate)
		case "gaugedelta":
			client.GaugeDelta(name, value, sampleRate)
		case "timing":
			client.Timing(name, value, sampleRate)
		default:
			fmt.Printf("Unsupported operation: %s\n", statsdType)
		}
	}
}
Пример #12
0
/*
  Connects statsd server and sends the metric
*/
func statsdSender(config *configuration, msg string) {
	client, err := statsd.NewClient(statsdURIBuilder(config), "")
	if err != nil {
		logger.Error(err.Error())
	}
	defer client.Close()
	arr := strings.Split(msg, ":")
	key := arr[0]
	value, err := strconv.ParseInt(arr[1], 10, 64)
	if err != nil {
		logger.Error(err.Error())
	}
	//	logger.Info("Statsd data flushed: %s", msg)
	err = client.Inc(key, value, 1.0)
	if err != nil {
		logger.Error(err.Error())
	}
}
Пример #13
0
func SendStatsD(gs string, gt string, gv int64) {

	// connect to statsd
	var sd string = "127.0.0.1:8125"
	var gk string = "nginx"

	client, err := statsd.NewClient(sd, gk)
	if err != nil {
		log.Println(err)
	}
	defer client.Close()

	// send metrics to statsd
	var fi float32 = 10.0
	var mt string = "status.demo_nginx_com"

	client.Inc(mt+"."+gs+"."+gt, gv, fi)
}
Пример #14
0
// NewStatsdStatsRecorder accepts an address and a namespace as strings and returns a pointer
// to an initialized Stat instance.
func NewStatsdStatsRecorder(address, namespace string) *StatsdStatsRecorder {
	client, err := statsd.NewClient(address, namespace)

	if err != nil {
		return nil
	}

	stats := &StatsdStatsRecorder{
		address: address,
		// arbitrary buffer size just to support as much
		// non blocking as possible
		counter: make(chan *StatsdStat, 100),
		timer:   make(chan *StatsdStat, 100),
		gauge:   make(chan *StatsdStat, 100),
		client:  client,
	}

	go stats.Start()
	return stats
}
Пример #15
0
// Open allocates resources for the stats writer.
func (s *StatsWriter) Open(host string, port string, prefix string) error {

	var err error

	if s.isOpen {
		return errors.New("Stats Writer is already open")
	}
	s.isOpen = true

	// If necessary, use the no-op client so we don't need to test everywhere.
	if host == "" {
		s.Client, _ = statsd.NewNoopClient()
		err = errors.New("Stats Writer not configured")
	} else {
		addr := net.JoinHostPort(host, port)
		s.Client, err = statsd.NewClient(addr, prefix)
		if err != nil {
			s.Client, _ = statsd.NewNoopClient()
		}
	}

	// Report memory usage stats every second.
	s.quit = make(chan struct{})
	if err == nil {
		// Don't bother starting the ticker when using the no-op client.
		// (We still make the channel, to simplify the close.)
		statsTicker := time.NewTicker(time.Second * 1)
		go func() {
			for _ = range statsTicker.C {
				select {
				case <-s.quit:
					return
				default:
					s.sendMemoryStats()
				}
			}
		}()
	}

	return err
}
Пример #16
0
func SendStatsD(gs string, gt string, gv int64) {

	// assign variables for statsd server and metric name prefix
	var statsdServer string = "127.0.0.1:8125"
	var gk string = "nginx"

	// connect to statsd
	client, err := statsd.NewClient(statsdServer, gk)
	if err != nil {
		log.Println(err)
	}
	defer client.Close()

	// assign variables for metric name and interval
	var fi float32 = 10.0
	var st string = "status"
	var sn string = "demo_nginx_com"

	// send metrics to statsd
	client.Inc(st+"."+sn+"."+gs+"."+gt, gv, fi)
}
Пример #17
0
func pushStats(statsd_config Statsd, status ServerStatus) error {
	prefix := fmt.Sprintf("statsd.mongodb.%s.%s.%s", statsd_config.Env, statsd_config.Cluster, status.Host)
	host_port := fmt.Sprintf("%s:%d", statsd_config.Host, statsd_config.Port)
	client, err := statsd.NewClient(host_port, prefix)
	if err != nil {
		return err
	}
	defer client.Close()

	err = pushConnections(client, status.Connections)
	if err != nil {
		return err
	}

	err = pushOpcounters(client, status.Opcounters)
	if err != nil {
		return err
	}

	err = pushMem(client, status.Mem)
	if err != nil {
		return err
	}

	err = pushGlobalLocks(client, status.GlobalLocks)
	if err != nil {
		return err
	}

	err = pushExtraInfo(client, status.ExtraInfo)
	if err != nil {
		return err
	}

	return nil
}
Пример #18
0
func main() {

	// command line flags
	var opts struct {
		HostPort  string        `long:"host" default:"127.0.0.1:8125" description:"host:port of statsd server"`
		Prefix    string        `long:"prefix" default:"test-client" description:"Statsd prefix"`
		StatType  string        `long:"type" default:"count" description:"stat type to send. Can be timing, count, guage"`
		StatValue int64         `long:"value" default:"1" description:"Value to send"`
		Name      string        `short:"n" long:"name" default:"counter" description:"stat name"`
		Rate      float32       `short:"r" long:"rate" default:"1.0" description:"sample rate"`
		Volume    int           `short:"c" long:"count" default:"1000" description:"Number of stats to send. Volume."`
		Nil       bool          `long:"nil" default:"false" description:"Use nil client"`
		Buffered  bool          `long:"buffered" default:"false" description:"Use a buffered client"`
		Duration  time.Duration `short:"d" long:"duration" default:"10s" description:"How long to spread the volume across. Each second of duration volume/seconds events will be sent."`
	}

	// parse said flags
	_, err := flags.Parse(&opts)
	if err != nil {
		if e, ok := err.(*flags.Error); ok {
			if e.Type == flags.ErrHelp {
				os.Exit(0)
			}
		}
		fmt.Printf("Error: %+v\n", err)
		os.Exit(1)
	}

	if opts.Nil && opts.Buffered {
		fmt.Printf("Specifying both nil and buffered together is invalid.")
		os.Exit(1)
	}

	var client statsd.Statter
	if !opts.Nil {
		if !opts.Buffered {
			client, err = statsd.NewClient(opts.HostPort, opts.Prefix)
		} else {
			client, err = statsd.NewBufferedClient(opts.HostPort, opts.Prefix, opts.Duration/time.Duration(4), 0)
		}
		if err != nil {
			log.Fatal(err)
		}
		defer client.Close()
	}

	var stat func(stat string, value int64, rate float32) error
	switch opts.StatType {
	case "count":
		stat = func(stat string, value int64, rate float32) error {
			return client.Inc(stat, value, rate)
		}
	case "gauge":
		stat = func(stat string, value int64, rate float32) error {
			return client.Gauge(stat, value, rate)
		}
	case "timing":
		stat = func(stat string, value int64, rate float32) error {
			return client.Timing(stat, value, rate)
		}
	default:
		log.Fatal("Unsupported state type")
	}

	pertick := opts.Volume / int(opts.Duration.Seconds()) / 10
	// add some extra tiem, because the first tick takes a while
	ender := time.After(opts.Duration + 100*time.Millisecond)
	c := time.Tick(time.Second / 10)
	count := 0
	for {
		select {
		case <-c:
			for x := 0; x < pertick; x++ {
				err := stat(opts.Name, opts.StatValue, opts.Rate)
				if err != nil {
					log.Printf("Got Error: %+v", err)
					break
				}
				count += 1
			}
		case <-ender:
			log.Printf("%d events called", count)
			os.Exit(0)
			return
		}
	}
}
Пример #19
0
func main() {
	configFilename := "config.yml"
	content, err := ioutil.ReadFile(configFilename)
	if err != nil {
		fmt.Println(err)
		return
	}
	var c config
	err = yaml.Unmarshal(content, &c)
	whoisTimeout, err := time.ParseDuration(c.WHOIS.Timeout)
	if err != nil {
		fmt.Println(err)
		return
	}
	whoisKeepAlive, err := time.ParseDuration(c.WHOIS.KeepAlive)
	if err != nil {
		fmt.Println(err)
		return
	}
	asnFinder := asnFinder.New(
		c.WHOIS.Host,
		c.WHOIS.Port,
		whoisTimeout,
		whoisKeepAlive,
	)
	stats, err := statsd.NewClient(net.JoinHostPort(c.StatsD.Host, c.StatsD.Port), "gobservatory")
	if err != nil {
		fmt.Println(err)
		return
	}
	database, err := db.New(stats)
	if err != nil {
		fmt.Println(err)
		return
	}

	nssPool, err := core.PoolFromPEM(c.NSSPool)
	if err != nil {
		fmt.Println(err)
		return
	}
	msPool, err := core.PoolFromPEM(c.MSPool)
	if err != nil {
		fmt.Println(err)
		return
	}
	transPool, err := core.PoolFromPEM(c.TransPool)
	if err != nil {
		fmt.Println(err)
		return
	}
	go core.ProfileCmd(stats)
	obs := submission.New(
		nssPool,
		msPool,
		transPool,
		c.SubmissionAPI.Host,
		c.SubmissionAPI.Port,
		asnFinder,
		database,
		stats,
	)

	wg := new(sync.WaitGroup)
	for i := 0; i < c.Workers; i++ {
		wg.Add(1)
		go obs.ParseSubmissions(wg)
	}

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, os.Interrupt)
	go func() {
		for _ = range sigChan {
			fmt.Println("\nInterrupt! Shutting down API server and waiting for remaining submissions to be processed")
			err = obs.Shutdown()
			if err != nil {
				fmt.Printf("Problem shutting down API server: %s\n", err)
				return
			}
		}
	}()

	err = obs.Serve("", "")
	if err != nil {
		fmt.Println(err)
		return
	}
	wg.Wait()
}
Пример #20
0
func main() {

	for {

		client, err := statsd.NewClient("127.0.0.1:8125", "nginx")
		// handle any errors
		if err != nil {
			log.Fatal(err)
		}

		var status_json string = "http://demo.nginx.com/status"

		// request status json from NGINX Plus
		x, err := http.Get(status_json)
		if err != nil {
			log.Fatalf("ERROR: %s", err)
		}

		x_dec := json.NewDecoder(x.Body)

		// sleep x seconds
		time.Sleep(time.Millisecond * 1000)

		// re-request json from NGINX Plus
		y, err := http.Get(status_json)
		if err != nil {
			log.Fatalf("ERROR: %s", err)
		}

		y_dec := json.NewDecoder(y.Body)

		// loop through both to get diff

		var x_data StatusJSON
		if err := x_dec.Decode(&x_data); err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		var y_data StatusJSON
		if err := y_dec.Decode(&y_data); err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		// processes
		ngx_proc := (y_data.Processes.Respawned)
		fmt.Println("status.demo.processes.respawned", ngx_proc)
		client.Inc("status.demo.processes.respawned", ngx_proc, 1.0)

		// connections
		ngx_ca := (y_data.Connections.Accepted - x_data.Connections.Accepted)
		fmt.Println("status.demo.connections.accepted", ngx_ca)
		client.Inc("status.demo.connections.accepted", ngx_ca, 1.0)

		ngx_cd := (y_data.Connections.Dropped - x_data.Connections.Dropped)
		fmt.Println("status.demo.connections.dropped", ngx_cd)
		client.Inc("status.demo.connections.dropped", ngx_cd, 1.0)

		ngx_can := (y_data.Connections.Active)
		fmt.Println("status.demo.connections.active", ngx_can)
		client.Inc("status.demo.connections.active", ngx_can, 1.0)

		ngx_cai := (y_data.Connections.Idle)
		fmt.Println("status.demo.connections.idle", ngx_cai)
		client.Inc("status.demo.connections.idle", ngx_cai, 1.0)

		// requests
		ngx_req := (y_data.Requests.Current)
		fmt.Println("status.demo.requests.current", ngx_req)
		client.Inc("status.demo.requests.current", ngx_req, 1.0)

		ngx_reqt := (y_data.Requests.Total - x_data.Requests.Total)
		fmt.Println("status.demo.requests.total", ngx_reqt)
		client.Inc("status.demo.requests.total", ngx_reqt, 1.0)

		// server zones
		ngx_sz_oproc := (y_data.ServerZones.One.Processing)
		fmt.Println("status.demo.serverzones.one.processing", ngx_sz_oproc)
		client.Inc("status.demo.serverzones.one.processing", ngx_sz_oproc, 1.0)

		ngx_sz_orec := (y_data.ServerZones.One.Received - x_data.ServerZones.One.Received)
		fmt.Println("status.demo.serverzones.one.received", ngx_sz_orec)
		client.Inc("status.demo.serverzones.one.received", ngx_sz_orec, 1.0)

		ngx_sz_osent := (y_data.ServerZones.One.Sent - x_data.ServerZones.One.Sent)
		fmt.Println("status.demo.serverzones.one.sent", ngx_sz_osent)
		client.Inc("status.demo.serverzones.one.sent", ngx_sz_osent, 1.0)

		ngx_sz_oreq := (y_data.ServerZones.One.Requests - x_data.ServerZones.One.Requests)
		fmt.Println("status.demo.serverzones.one.requests", ngx_sz_oreq)
		client.Inc("status.demo.serverzones.one.requests", ngx_sz_oreq, 1.0)

		ngx_sz_oresp_t := (y_data.ServerZones.One.Responses.Total - x_data.ServerZones.One.Responses.Total)
		fmt.Println("status.demo.serverzones.one.responses.total", ngx_sz_oresp_t)
		client.Inc("status.demo.serverzones.one.responses.total", ngx_sz_oresp_t, 1.0)

		ngx_sz_oresp_1xx := (y_data.ServerZones.One.Responses.OneXx - x_data.ServerZones.One.Responses.OneXx)
		fmt.Println("status.demo.serverzones.one.responses.1xx", ngx_sz_oresp_1xx)
		client.Inc("status.demo.serverzones.one.responses.1xx", ngx_sz_oresp_1xx, 1.0)

		ngx_sz_oresp_2xx := (y_data.ServerZones.One.Responses.TwoXx - x_data.ServerZones.One.Responses.TwoXx)
		fmt.Println("status.demo.serverzones.one.responses.2xx", ngx_sz_oresp_2xx)
		client.Inc("status.demo.serverzones.one.responses.2xx", ngx_sz_oresp_2xx, 1.0)

		ngx_sz_oresp_3xx := (y_data.ServerZones.One.Responses.ThreeXx - x_data.ServerZones.One.Responses.ThreeXx)
		fmt.Println("status.demo.serverzones.one.responses.3xx", ngx_sz_oresp_3xx)
		client.Inc("status.demo.serverzones.one.responses.3xx", ngx_sz_oresp_3xx, 1.0)

		ngx_sz_oresp_4xx := (y_data.ServerZones.One.Responses.FourXx - x_data.ServerZones.One.Responses.FourXx)
		fmt.Println("status.demo.serverzones.one.responses.4xx", ngx_sz_oresp_4xx)
		client.Inc("status.demo.serverzones.one.responses.4xx", ngx_sz_oresp_4xx, 1.0)

		ngx_sz_oresp_5xx := (y_data.ServerZones.One.Responses.FiveXx - x_data.ServerZones.One.Responses.FiveXx)
		fmt.Println("status.demo.serverzones.one.responses.5xx", ngx_sz_oresp_5xx)
		client.Inc("status.demo.serverzones.one.responses.5xx", ngx_sz_oresp_5xx, 1.0)

		ngx_sz_oresp_err_perc := (ngx_sz_oresp_4xx + ngx_sz_oresp_5xx/ngx_sz_oresp_t)
		fmt.Println("status.demo.serverzones.one.responses.error_percentage", ngx_sz_oresp_err_perc)
		client.Inc("status.demo.serverzones.one.responses.error_percentage", ngx_sz_oresp_err_perc, 1.0)

		// close any open connections before loop restarts
		// close any open connections before loop restarts
		client.Close()
		x.Body.Close()
		y.Body.Close()

	}

}
Пример #21
0
func main() {
	app := cli.NewApp()
	app.Name = "stxy"
	app.Version = "0.0.4"
	app.Usage = "haproxy stats to statsd"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "haproxy-url",
			Value: "localhost:22002/;csv",
			Usage: "host:port of haproxy server",
		},
		cli.StringFlag{
			Name:  "statsd-url, s",
			Value: "localhost:8125",
			Usage: "host:port of statsd server",
		},
		cli.StringFlag{
			Name:  "prefix,p",
			Usage: "statsd namespace",
			Value: "haproxy",
		},
		cli.StringFlag{
			Name:  "interval,i",
			Usage: "time in milliseconds",
			Value: "10000",
		},
	}
	app.Action = func(c *cli.Context) {
		interval, _ := strconv.ParseInt(c.String("interval"), 10, 64)
		for {
			client, err := statsd.NewClient(c.String("s"), c.String("p"))
			// handle any errors
			if err != nil {
				log.Fatal(err)
			}
			// make sure to clean up
			defer client.Close()
			initial_stats := get_stats(c.String("haproxy-url"))
			previous := map[string]int64{}
			for _, v := range initial_stats {
				if v[1] == "BACKEND" {
					previous[fmt.Sprint("1xx_", v[0])] = get_value(v, "hrsp_1xx", 39)
					previous[fmt.Sprint("2xx_", v[0])] = get_value(v, "hrsp_2xx", 40)
					previous[fmt.Sprint("3xx_", v[0])] = get_value(v, "hrsp_3xx", 41)
					previous[fmt.Sprint("4xx_", v[0])] = get_value(v, "hrsp_4xx", 42)
					previous[fmt.Sprint("5xx_", v[0])] = get_value(v, "hrsp_5xx", 43)
				}
			}
			time.Sleep(time.Duration(interval) * time.Millisecond)
			records := get_stats(c.String("haproxy-url"))
			for _, record := range records {
				if record[1] == "BACKEND" {
					go send_gauge(client, record, "scur", 4)
					go send_gauge(client, record, "smax", 5)
					go send_gauge(client, record, "ereq", 12)
					go send_gauge(client, record, "econ", 13)
					go send_gauge(client, record, "rate", 33)
					go send_gauge(client, record, "bin", 8)
					go send_gauge(client, record, "bout", 9)
					go send_counter(previous[fmt.Sprint("1xx_", record[0])], client, record, "hrsp_1xx", 39)
					go send_counter(previous[fmt.Sprint("2xx_", record[0])], client, record, "hrsp_2xx", 40)
					go send_counter(previous[fmt.Sprint("3xx_", record[0])], client, record, "hrsp_3xx", 41)
					go send_counter(previous[fmt.Sprint("4xx_", record[0])], client, record, "hrsp_4xx", 42)
					go send_counter(previous[fmt.Sprint("5xx_", record[0])], client, record, "hrsp_5xx", 43)
					go send_gauge(client, record, "qtime", 58)
					go send_gauge(client, record, "ctime", 59)
					go send_gauge(client, record, "rtime", 60)
					go send_gauge(client, record, "ttime", 61)
				}
			}
			color.White("-------------------")
		}
	}
	app.Run(os.Args)
}