Example #1
0
func TestPrintDistribution(t *testing.T) {
	var (
		quantiles = []int{50, 90, 95, 99}
		h         = expvar.NewHistogram("test_print_distribution", 0, 100, 3, quantiles...)
		seed      = int64(555)
		mean      = int64(5)
		stdev     = int64(1)
	)
	teststat.PopulateNormalHistogram(t, h, seed, mean, stdev)

	var buf bytes.Buffer
	metrics.PrintDistribution(&buf, h)
	t.Logf("\n%s\n", buf.String())

	// Count the number of bar chart characters.
	// We should have ca. 100 in any distribution with a small-enough stdev.

	var n int
	for _, r := range buf.String() {
		if r == '#' {
			n++
		}
	}
	if want, have, tol := 100, n, 5; int(math.Abs(float64(want-have))) > tol {
		t.Errorf("want %d, have %d (tolerance %d)", want, have, tol)
	}
}
Example #2
0
func TestHistogramQuantiles(t *testing.T) {
	metricName := "test_histogram"
	quantiles := []int{50, 90, 95, 99}
	h := expvar.NewHistogram(metricName, 0, 100, 3, quantiles...)

	const seed, mean, stdev int64 = 424242, 50, 10
	teststat.PopulateNormalHistogram(t, h, seed, mean, stdev)
	teststat.AssertExpvarNormalHistogram(t, metricName, mean, stdev, quantiles)
}
Example #3
0
func TestHistogramQuantiles(t *testing.T) {
	var (
		name      = "test_histogram"
		quantiles = []int{50, 90, 95, 99}
		h         = expvar.NewHistogram(name, 0, 100, 3, quantiles...).With(metrics.Field{Key: "ignored", Value: "field"})
	)
	const seed, mean, stdev int64 = 424242, 50, 10
	teststat.PopulateNormalHistogram(t, h, seed, mean, stdev)
	teststat.AssertExpvarNormalHistogram(t, name, mean, stdev, quantiles)
}
Example #4
0
func TestInvalidQuantile(t *testing.T) {
	defer func() {
		if err := recover(); err == nil {
			t.Errorf("expected panic, got none")
		} else {
			t.Logf("got expected panic: %v", err)
		}
	}()
	expvar.NewHistogram("foo", 0.0, 100.0, 3, 50, 90, 95, 99, 101)
}
Example #5
0
// NewMetricsExpvar initializes and returns a Metrics exposed over the expvar system.
func NewMetricsExpvar() Metrics {
	return Metrics{
		RequestCount: expvar.NewCounter("request_count"),
		ResponseTime: metrics.NewTimeHistogram(
			time.Microsecond,
			expvar.NewHistogram("response_time", 0, int64(time.Second), sigfigs, quantiles...),
		),
		Uploads:      expvar.NewCounter("uploads"),
		UploadErrors: expvar.NewCounter("upload_errors"),
	}
}
Example #6
0
func NewHist(name string) metrics.Histogram {
	var h metrics.Histogram
	if name != "" && archaius.Conf.Collect {
		h = expvar.NewHistogram(name, 1000, maxHistObservable, 1, []int{50, 99}...)
		if sampleMap == nil {
			sampleMap = make(map[metrics.Histogram][]int64)
		}
		sampleMap[h] = make([]int64, 0, sampleCount)
		return h
	}
	return nil
}
Example #7
0
func TestScaledHistogram(t *testing.T) {
	quantiles := []int{50, 90, 99}
	scale := int64(10)
	metricName := "test_scaled_histogram"

	var h metrics.Histogram
	h = expvar.NewHistogram(metricName, 0, 1000, 3, quantiles...)
	h = metrics.NewScaledHistogram(h, scale)

	const seed, mean, stdev = 333, 500, 100          // input values
	populateNormalHistogram(t, h, seed, mean, stdev) // will be scaled down
	assertExpvarNormalHistogram(t, metricName, mean/scale, stdev/scale, quantiles)
}
Example #8
0
func TestTimeHistogram(t *testing.T) {
	const metricName string = "test_time_histogram"
	quantiles := []int{50, 90, 99}
	h0 := expvar.NewHistogram(metricName, 0, 200, 3, quantiles...)
	h := metrics.NewTimeHistogram(time.Millisecond, h0)
	const seed, mean, stdev int64 = 321, 100, 20

	for i := 0; i < 4321; i++ {
		sample := time.Duration(rand.NormFloat64()*float64(stdev)+float64(mean)) * time.Millisecond
		h.Observe(sample)
	}

	assertExpvarNormalHistogram(t, metricName, mean, stdev, quantiles)
}
Example #9
0
func TestScaledHistogram(t *testing.T) {
	var (
		quantiles  = []int{50, 90, 99}
		scale      = int64(10)
		metricName = "test_scaled_histogram"
	)

	var h metrics.Histogram
	h = expvar.NewHistogram(metricName, 0, 1000, 3, quantiles...)
	h = metrics.NewScaledHistogram(h, scale)
	h = h.With(metrics.Field{Key: "a", Value: "b"})

	const seed, mean, stdev = 333, 500, 100                   // input values
	teststat.PopulateNormalHistogram(t, h, seed, mean, stdev) // will be scaled down
	assertExpvarNormalHistogram(t, metricName, mean/scale, stdev/scale, quantiles)
}
Example #10
0
func TestMultiHistogram(t *testing.T) {
	quantiles := []int{50, 90, 99}
	h := metrics.NewMultiHistogram(
		expvar.NewHistogram("omicron", 0, 100, 3, quantiles...),
		prometheus.NewSummary(stdprometheus.SummaryOpts{
			Namespace: "test",
			Subsystem: "multi_histogram",
			Name:      "nu",
			Help:      "Nu histogram.",
		}, []string{}),
	)

	const seed, mean, stdev int64 = 123, 50, 10
	populateNormalHistogram(t, h, seed, mean, stdev)
	assertExpvarNormalHistogram(t, "omicron", mean, stdev, quantiles)
	assertPrometheusNormalHistogram(t, `test_multi_histogram_nu`, mean, stdev)
}
Example #11
0
func TestTimeHistogram(t *testing.T) {
	var (
		metricName = "test_time_histogram"
		minValue   = int64(0)
		maxValue   = int64(200)
		sigfigs    = 3
		quantiles  = []int{50, 90, 99}
		h          = expvar.NewHistogram(metricName, minValue, maxValue, sigfigs, quantiles...)
		th         = metrics.NewTimeHistogram(time.Millisecond, h).With(metrics.Field{Key: "a", Value: "b"})
	)

	const seed, mean, stdev int64 = 321, 100, 20

	for i := 0; i < 4321; i++ {
		sample := time.Duration(rand.NormFloat64()*float64(stdev)+float64(mean)) * time.Millisecond
		th.Observe(sample)
	}

	assertExpvarNormalHistogram(t, metricName, mean, stdev, quantiles)
}
Example #12
0
func makeInstrumentation(namespace, name, helpCounter, helpDuration string) (metrics.Counter, metrics.TimeHistogram) {
	counter := metrics.NewMultiCounter(
		expvar.NewCounter(fmt.Sprintf("requests_%s", name)),
		statsd.NewCounter(ioutil.Discard, fmt.Sprintf("requests_%s_total", name), time.Second),
		prometheus.NewCounter(stdprometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: name,
			Name:      "requests_total",
			Help:      helpCounter,
		}, []string{}),
	)
	duration := metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
		expvar.NewHistogram(fmt.Sprintf("duration_%s_nanoseconds_total", name), 0, 1e9, 3, 50, 95, 99),
		statsd.NewHistogram(ioutil.Discard, fmt.Sprintf("duration_%s_nanoseconds_total", name), time.Second),
		prometheus.NewSummary(stdprometheus.SummaryOpts{
			Namespace: namespace,
			Subsystem: name,
			Name:      "duration_nanoseconds_total",
			Help:      helpDuration,
		}, []string{}),
	))

	return counter, duration
}
Example #13
0
File: main.go Project: sasha-s/kit
func main() {
	// Flag domain. Note that gRPC transitively registers flags via its import
	// of glog. So, we define a new flag set, to keep those domains distinct.
	fs := flag.NewFlagSet("", flag.ExitOnError)
	var (
		debugAddr     = fs.String("debug.addr", ":8000", "Address for HTTP debug/instrumentation server")
		httpAddr      = fs.String("http.addr", ":8001", "Address for HTTP (JSON) server")
		netrpcAddr    = fs.String("netrpc.addr", ":8003", "Address for net/rpc server")
		proxyHTTPAddr = fs.String("proxy.http.url", "", "if set, proxy requests over HTTP to this addsvc")

		zipkinServiceName            = fs.String("zipkin.service.name", "addsvc", "Zipkin service name")
		zipkinCollectorAddr          = fs.String("zipkin.collector.addr", "", "Zipkin Scribe collector address (empty will log spans)")
		zipkinCollectorTimeout       = fs.Duration("zipkin.collector.timeout", time.Second, "Zipkin collector timeout")
		zipkinCollectorBatchSize     = fs.Int("zipkin.collector.batch.size", 100, "Zipkin collector batch size")
		zipkinCollectorBatchInterval = fs.Duration("zipkin.collector.batch.interval", time.Second, "Zipkin collector batch interval")
	)
	flag.Usage = fs.Usage // only show our flags
	fs.Parse(os.Args[1:])

	// `package log` domain
	var logger kitlog.Logger
	logger = kitlog.NewLogfmtLogger(os.Stderr)
	logger = kitlog.NewContext(logger).With("ts", kitlog.DefaultTimestampUTC)
	stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) // redirect stdlib logging to us
	stdlog.SetFlags(0)                                // flags are handled in our logger

	// `package metrics` domain
	requests := metrics.NewMultiCounter(
		expvar.NewCounter("requests"),
		statsd.NewCounter(ioutil.Discard, "requests_total", time.Second),
		prometheus.NewCounter(stdprometheus.CounterOpts{
			Namespace: "addsvc",
			Subsystem: "add",
			Name:      "requests_total",
			Help:      "Total number of received requests.",
		}, []string{}),
	)
	duration := metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
		expvar.NewHistogram("duration_nanoseconds_total", 0, 1e9, 3, 50, 95, 99),
		statsd.NewHistogram(ioutil.Discard, "duration_nanoseconds_total", time.Second),
		prometheus.NewSummary(stdprometheus.SummaryOpts{
			Namespace: "addsvc",
			Subsystem: "add",
			Name:      "duration_nanoseconds_total",
			Help:      "Total nanoseconds spend serving requests.",
		}, []string{}),
	))

	_, _ = requests, duration

	// `package tracing` domain
	zipkinHostPort := "localhost:1234" // TODO Zipkin makes overly simple assumptions about services
	var zipkinCollector zipkin.Collector = loggingCollector{logger}
	if *zipkinCollectorAddr != "" {
		var err error
		if zipkinCollector, err = zipkin.NewScribeCollector(
			*zipkinCollectorAddr,
			*zipkinCollectorTimeout,
			zipkin.ScribeBatchSize(*zipkinCollectorBatchSize),
			zipkin.ScribeBatchInterval(*zipkinCollectorBatchInterval),
			zipkin.ScribeLogger(logger),
		); err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
	}
	zipkinMethodName := "add"
	zipkinSpanFunc := zipkin.MakeNewSpanFunc(zipkinHostPort, *zipkinServiceName, zipkinMethodName)

	// Our business and operational domain
	var a add.Adder = pureAdd{}
	if *proxyHTTPAddr != "" {
		var e endpoint.Endpoint
		e = add.NewAdderAddHTTPClient("GET", *proxyHTTPAddr, zipkin.ToRequest(zipkinSpanFunc))
		e = zipkin.AnnotateClient(zipkinSpanFunc, zipkinCollector)(e)
		a = add.MakeAdderClient(func(method string) endpoint.Endpoint {
			if method != "Add" {
				panic(fmt.Errorf("unknown method %s", method))
			}
			return e
		})
	}
	// This could happen at endpoint level.
	// a = logging(logger)(a)
	// a = instrument(requests, duration)(a)

	// Server domain
	var e endpoint.Endpoint
	e = add.MakeAdderEndpoints(a).Add
	e = zipkin.AnnotateServer(zipkinSpanFunc, zipkinCollector)(e)

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Transport: HTTP (debug/instrumentation)
	go func() {
		logger.Log("addr", *debugAddr, "transport", "debug")
		errc <- http.ListenAndServe(*debugAddr, nil)
	}()

	// Transport: HTTP (JSON)
	go func() {
		ctx, cancel := context.WithCancel(root)
		defer cancel()
		before := []httptransport.RequestFunc{zipkin.ToContext(zipkinSpanFunc, logger)}
		after := []httptransport.ResponseFunc{}
		handler := add.MakeAdderAddHTTPBinding(ctx, e, before, after)
		logger.Log("addr", *httpAddr, "transport", "HTTP/JSON")
		errc <- http.ListenAndServe(*httpAddr, handler)
	}()

	// Transport: net/rpc
	go func() {
		ctx, cancel := context.WithCancel(root)
		defer cancel()
		s := rpc.NewServer()
		s.RegisterName("Add", add.AdderAddNetrpcBinding{ctx, e})
		s.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
		logger.Log("addr", *netrpcAddr, "transport", "net/rpc")
		errc <- http.ListenAndServe(*netrpcAddr, s)
	}()

	logger.Log("fatal", <-errc)
}
Example #14
0
File: main.go Project: EthanK28/kit
func main() {
	// Flag domain. Note that gRPC transitively registers flags via its import
	// of glog. So, we define a new flag set, to keep those domains distinct.
	fs := flag.NewFlagSet("", flag.ExitOnError)
	var (
		debugAddr        = fs.String("debug.addr", ":8000", "Address for HTTP debug/instrumentation server")
		httpAddr         = fs.String("http.addr", ":8001", "Address for HTTP (JSON) server")
		grpcAddr         = fs.String("grpc.addr", ":8002", "Address for gRPC server")
		netrpcAddr       = fs.String("netrpc.addr", ":8003", "Address for net/rpc server")
		thriftAddr       = fs.String("thrift.addr", ":8004", "Address for Thrift server")
		thriftProtocol   = fs.String("thrift.protocol", "binary", "binary, compact, json, simplejson")
		thriftBufferSize = fs.Int("thrift.buffer.size", 0, "0 for unbuffered")
		thriftFramed     = fs.Bool("thrift.framed", false, "true to enable framing")

		proxyHTTPAddr = fs.String("proxy.http.url", "", "if set, proxy requests over HTTP to this addsvc")

		zipkinServiceName            = fs.String("zipkin.service.name", "addsvc", "Zipkin service name")
		zipkinCollectorAddr          = fs.String("zipkin.collector.addr", "", "Zipkin Scribe collector address (empty will log spans)")
		zipkinCollectorTimeout       = fs.Duration("zipkin.collector.timeout", time.Second, "Zipkin collector timeout")
		zipkinCollectorBatchSize     = fs.Int("zipkin.collector.batch.size", 100, "Zipkin collector batch size")
		zipkinCollectorBatchInterval = fs.Duration("zipkin.collector.batch.interval", time.Second, "Zipkin collector batch interval")
	)
	flag.Usage = fs.Usage // only show our flags
	fs.Parse(os.Args[1:])

	// `package log` domain
	var logger kitlog.Logger
	logger = kitlog.NewLogfmtLogger(os.Stderr)
	logger = kitlog.With(logger, "ts", kitlog.DefaultTimestampUTC)
	stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) // redirect stdlib logging to us
	stdlog.SetFlags(0)                                // flags are handled in our logger

	// `package metrics` domain
	requests := metrics.NewMultiCounter(
		expvar.NewCounter("requests"),
		statsd.NewCounter(ioutil.Discard, "requests_total", time.Second),
		prometheus.NewCounter(stdprometheus.CounterOpts{
			Namespace: "addsvc",
			Subsystem: "add",
			Name:      "requests_total",
			Help:      "Total number of received requests.",
		}, []string{}),
	)
	duration := metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
		expvar.NewHistogram("duration_nanoseconds_total", 0, 1e9, 3, 50, 95, 99),
		statsd.NewHistogram(ioutil.Discard, "duration_nanoseconds_total", time.Second),
		prometheus.NewSummary(stdprometheus.SummaryOpts{
			Namespace: "addsvc",
			Subsystem: "add",
			Name:      "duration_nanoseconds_total",
			Help:      "Total nanoseconds spend serving requests.",
		}, []string{}),
	))

	// `package tracing` domain
	zipkinHostPort := "localhost:1234" // TODO Zipkin makes overly simple assumptions about services
	var zipkinCollector zipkin.Collector = loggingCollector{logger}
	if *zipkinCollectorAddr != "" {
		var err error
		if zipkinCollector, err = zipkin.NewScribeCollector(
			*zipkinCollectorAddr,
			*zipkinCollectorTimeout,
			*zipkinCollectorBatchSize,
			*zipkinCollectorBatchInterval,
		); err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
	}
	zipkinMethodName := "add"
	zipkinSpanFunc := zipkin.MakeNewSpanFunc(zipkinHostPort, *zipkinServiceName, zipkinMethodName)
	zipkin.Log.Swap(logger) // log diagnostic/error details

	// Our business and operational domain
	var a Add = pureAdd
	if *proxyHTTPAddr != "" {
		var e endpoint.Endpoint
		e = httpclient.NewClient("GET", *proxyHTTPAddr, zipkin.ToRequest(zipkinSpanFunc))
		e = zipkin.AnnotateClient(zipkinSpanFunc, zipkinCollector)(e)
		a = proxyAdd(e, logger)
	}
	a = logging(logger)(a)
	a = instrument(requests, duration)(a)

	// Server domain
	var e endpoint.Endpoint
	e = makeEndpoint(a)
	e = zipkin.AnnotateServer(zipkinSpanFunc, zipkinCollector)(e)

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Transport: HTTP (debug/instrumentation)
	go func() {
		logger.Log("addr", *debugAddr, "transport", "debug")
		errc <- http.ListenAndServe(*debugAddr, nil)
	}()

	// Transport: HTTP (JSON)
	go func() {
		ctx, cancel := context.WithCancel(root)
		defer cancel()
		before := []httptransport.BeforeFunc{zipkin.ToContext(zipkinSpanFunc)}
		after := []httptransport.AfterFunc{}
		handler := makeHTTPBinding(ctx, e, before, after)
		logger.Log("addr", *httpAddr, "transport", "HTTP/JSON")
		errc <- http.ListenAndServe(*httpAddr, handler)
	}()

	// Transport: gRPC
	go func() {
		ln, err := net.Listen("tcp", *grpcAddr)
		if err != nil {
			errc <- err
			return
		}
		s := grpc.NewServer() // uses its own context?
		pb.RegisterAddServer(s, grpcBinding{e})
		logger.Log("addr", *grpcAddr, "transport", "gRPC")
		errc <- s.Serve(ln)
	}()

	// Transport: net/rpc
	go func() {
		ctx, cancel := context.WithCancel(root)
		defer cancel()
		s := rpc.NewServer()
		s.RegisterName("addsvc", NetrpcBinding{ctx, e})
		s.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
		logger.Log("addr", *netrpcAddr, "transport", "net/rpc")
		errc <- http.ListenAndServe(*netrpcAddr, s)
	}()

	// Transport: Thrift
	go func() {
		ctx, cancel := context.WithCancel(root)
		defer cancel()

		var protocolFactory thrift.TProtocolFactory
		switch *thriftProtocol {
		case "binary":
			protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
		case "compact":
			protocolFactory = thrift.NewTCompactProtocolFactory()
		case "json":
			protocolFactory = thrift.NewTJSONProtocolFactory()
		case "simplejson":
			protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
		default:
			errc <- fmt.Errorf("invalid Thrift protocol %q", *thriftProtocol)
			return
		}

		var transportFactory thrift.TTransportFactory
		if *thriftBufferSize > 0 {
			transportFactory = thrift.NewTBufferedTransportFactory(*thriftBufferSize)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}

		if *thriftFramed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}

		transport, err := thrift.NewTServerSocket(*thriftAddr)
		if err != nil {
			errc <- err
			return
		}

		logger.Log("addr", *thriftAddr, "transport", "Thrift")
		errc <- thrift.NewTSimpleServer4(
			thriftadd.NewAddServiceProcessor(thriftBinding{ctx, e}),
			transport,
			transportFactory,
			protocolFactory,
		).Serve()
	}()

	logger.Log("fatal", <-errc)
}
Example #15
0
// NewHistogram implements Provider.
func (p expvarProvider) NewHistogram(name string, buckets int) metrics.Histogram {
	return expvar.NewHistogram(name, buckets)
}
Example #16
0
File: main.go Project: zyanho/kit
func main() {
	// Flag domain. Note that gRPC transitively registers flags via its import
	// of glog. So, we define a new flag set, to keep those domains distinct.
	fs := flag.NewFlagSet("", flag.ExitOnError)
	var (
		debugAddr        = fs.String("debug.addr", ":8000", "Address for HTTP debug/instrumentation server")
		httpAddr         = fs.String("http.addr", ":8001", "Address for HTTP (JSON) server")
		grpcAddr         = fs.String("grpc.addr", ":8002", "Address for gRPC server")
		netrpcAddr       = fs.String("netrpc.addr", ":8003", "Address for net/rpc server")
		thriftAddr       = fs.String("thrift.addr", ":8004", "Address for Thrift server")
		thriftProtocol   = fs.String("thrift.protocol", "binary", "binary, compact, json, simplejson")
		thriftBufferSize = fs.Int("thrift.buffer.size", 0, "0 for unbuffered")
		thriftFramed     = fs.Bool("thrift.framed", false, "true to enable framing")

		// Supported OpenTracing backends
		zipkinAddr           = fs.String("zipkin.kafka.addr", "", "Enable Zipkin tracing via a Kafka server host:port")
		appdashAddr          = fs.String("appdash.addr", "", "Enable Appdash tracing via an Appdash server host:port")
		lightstepAccessToken = fs.String("lightstep.token", "", "Enable LightStep tracing via a LightStep access token")
	)
	flag.Usage = fs.Usage // only show our flags
	if err := fs.Parse(os.Args[1:]); err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}

	// package log
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC).With("caller", log.DefaultCaller)
		stdlog.SetFlags(0)                             // flags are handled by Go kit's logger
		stdlog.SetOutput(log.NewStdlibAdapter(logger)) // redirect anything using stdlib log to us
	}

	// package metrics
	var requestDuration metrics.TimeHistogram
	{
		requestDuration = metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
			"request_duration_ns",
			expvar.NewHistogram("request_duration_ns", 0, 5e9, 1, 50, 95, 99),
			prometheus.NewSummary(stdprometheus.SummaryOpts{
				Namespace: "myorg",
				Subsystem: "addsvc",
				Name:      "duration_ns",
				Help:      "Request duration in nanoseconds.",
			}, []string{"method"}),
		))
	}

	// Set up OpenTracing
	var tracer opentracing.Tracer
	{
		switch {
		case *appdashAddr != "" && *lightstepAccessToken == "" && *zipkinAddr == "":
			tracer = appdashot.NewTracer(appdash.NewRemoteCollector(*appdashAddr))
		case *appdashAddr == "" && *lightstepAccessToken != "" && *zipkinAddr == "":
			tracer = lightstep.NewTracer(lightstep.Options{
				AccessToken: *lightstepAccessToken,
			})
			defer lightstep.FlushLightStepTracer(tracer)
		case *appdashAddr == "" && *lightstepAccessToken == "" && *zipkinAddr != "":
			collector, err := zipkin.NewKafkaCollector(
				strings.Split(*zipkinAddr, ","),
				zipkin.KafkaLogger(logger),
			)
			if err != nil {
				logger.Log("err", "unable to create collector", "fatal", err)
				os.Exit(1)
			}
			tracer, err = zipkin.NewTracer(
				zipkin.NewRecorder(collector, false, "localhost:80", "addsvc"),
			)
			if err != nil {
				logger.Log("err", "unable to create zipkin tracer", "fatal", err)
				os.Exit(1)
			}
		case *appdashAddr == "" && *lightstepAccessToken == "" && *zipkinAddr == "":
			tracer = opentracing.GlobalTracer() // no-op
		default:
			logger.Log("fatal", "specify a single -appdash.addr, -lightstep.access.token or -zipkin.kafka.addr")
			os.Exit(1)
		}
	}

	// Business domain
	var svc server.AddService
	{
		svc = pureAddService{}
		svc = loggingMiddleware{svc, logger}
		svc = instrumentingMiddleware{svc, requestDuration}
	}

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Debug/instrumentation
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "debug")
		transportLogger.Log("addr", *debugAddr)
		errc <- http.ListenAndServe(*debugAddr, nil) // DefaultServeMux
	}()

	// Transport: HTTP/JSON
	go func() {
		var (
			transportLogger = log.NewContext(logger).With("transport", "HTTP/JSON")
			tracingLogger   = log.NewContext(transportLogger).With("component", "tracing")
			mux             = http.NewServeMux()
			sum, concat     endpoint.Endpoint
		)

		sum = makeSumEndpoint(svc)
		sum = kitot.TraceServer(tracer, "sum")(sum)
		mux.Handle("/sum", httptransport.NewServer(
			root,
			sum,
			server.DecodeSumRequest,
			server.EncodeSumResponse,
			httptransport.ServerErrorLogger(transportLogger),
			httptransport.ServerBefore(kitot.FromHTTPRequest(tracer, "sum", tracingLogger)),
		))

		concat = makeConcatEndpoint(svc)
		concat = kitot.TraceServer(tracer, "concat")(concat)
		mux.Handle("/concat", httptransport.NewServer(
			root,
			concat,
			server.DecodeConcatRequest,
			server.EncodeConcatResponse,
			httptransport.ServerErrorLogger(transportLogger),
			httptransport.ServerBefore(kitot.FromHTTPRequest(tracer, "concat", tracingLogger)),
		))

		transportLogger.Log("addr", *httpAddr)
		errc <- http.ListenAndServe(*httpAddr, mux)
	}()

	// Transport: gRPC
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "gRPC")
		tracingLogger := log.NewContext(transportLogger).With("component", "tracing")
		ln, err := net.Listen("tcp", *grpcAddr)
		if err != nil {
			errc <- err
			return
		}
		s := grpc.NewServer() // uses its own, internal context
		pb.RegisterAddServer(s, newGRPCBinding(root, tracer, svc, tracingLogger))
		transportLogger.Log("addr", *grpcAddr)
		errc <- s.Serve(ln)
	}()

	// Transport: net/rpc
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "net/rpc")
		s := rpc.NewServer()
		if err := s.RegisterName("addsvc", netrpcBinding{svc}); err != nil {
			errc <- err
			return
		}
		s.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
		transportLogger.Log("addr", *netrpcAddr)
		errc <- http.ListenAndServe(*netrpcAddr, s)
	}()

	// Transport: Thrift
	go func() {
		var protocolFactory thrift.TProtocolFactory
		switch *thriftProtocol {
		case "binary":
			protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
		case "compact":
			protocolFactory = thrift.NewTCompactProtocolFactory()
		case "json":
			protocolFactory = thrift.NewTJSONProtocolFactory()
		case "simplejson":
			protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
		default:
			errc <- fmt.Errorf("invalid Thrift protocol %q", *thriftProtocol)
			return
		}
		var transportFactory thrift.TTransportFactory
		if *thriftBufferSize > 0 {
			transportFactory = thrift.NewTBufferedTransportFactory(*thriftBufferSize)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}
		if *thriftFramed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		transport, err := thrift.NewTServerSocket(*thriftAddr)
		if err != nil {
			errc <- err
			return
		}
		transportLogger := log.NewContext(logger).With("transport", "thrift")
		transportLogger.Log("addr", *thriftAddr)
		errc <- thrift.NewTSimpleServer4(
			thriftadd.NewAddServiceProcessor(thriftBinding{svc}),
			transport,
			transportFactory,
			protocolFactory,
		).Serve()
	}()

	logger.Log("fatal", <-errc)
}
Example #17
0
func main() {
	// Flag domain. Note that gRPC transitively registers flags via its import
	// of glog. So, we define a new flag set, to keep those domains distinct.
	fs := flag.NewFlagSet("", flag.ExitOnError)
	var (
		debugAddr                    = fs.String("debug.addr", ":8000", "Address for HTTP debug/instrumentation server")
		httpAddr                     = fs.String("http.addr", ":8001", "Address for HTTP (JSON) server")
		grpcAddr                     = fs.String("grpc.addr", ":8002", "Address for gRPC server")
		netrpcAddr                   = fs.String("netrpc.addr", ":8003", "Address for net/rpc server")
		thriftAddr                   = fs.String("thrift.addr", ":8004", "Address for Thrift server")
		thriftProtocol               = fs.String("thrift.protocol", "binary", "binary, compact, json, simplejson")
		thriftBufferSize             = fs.Int("thrift.buffer.size", 0, "0 for unbuffered")
		thriftFramed                 = fs.Bool("thrift.framed", false, "true to enable framing")
		zipkinHostPort               = fs.String("zipkin.host.port", "my.service.domain:12345", "Zipkin host:port")
		zipkinServiceName            = fs.String("zipkin.service.name", "addsvc", "Zipkin service name")
		zipkinCollectorAddr          = fs.String("zipkin.collector.addr", "", "Zipkin Scribe collector address (empty will log spans)")
		zipkinCollectorTimeout       = fs.Duration("zipkin.collector.timeout", time.Second, "Zipkin collector timeout")
		zipkinCollectorBatchSize     = fs.Int("zipkin.collector.batch.size", 100, "Zipkin collector batch size")
		zipkinCollectorBatchInterval = fs.Duration("zipkin.collector.batch.interval", time.Second, "Zipkin collector batch interval")
	)
	flag.Usage = fs.Usage // only show our flags
	if err := fs.Parse(os.Args[1:]); err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}

	// package log
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC).With("caller", log.DefaultCaller)
		stdlog.SetFlags(0)                             // flags are handled by Go kit's logger
		stdlog.SetOutput(log.NewStdlibAdapter(logger)) // redirect anything using stdlib log to us
	}

	// package metrics
	var requestDuration metrics.TimeHistogram
	{
		requestDuration = metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
			expvar.NewHistogram("request_duration_ns", 0, 5e9, 1, 50, 95, 99),
			prometheus.NewSummary(stdprometheus.SummaryOpts{
				Namespace: "myorg",
				Subsystem: "addsvc",
				Name:      "duration_ns",
				Help:      "Request duration in nanoseconds.",
			}, []string{"method"}),
		))
	}

	// package tracing
	var collector zipkin.Collector
	{
		zipkinLogger := log.NewContext(logger).With("component", "zipkin")
		collector = loggingCollector{zipkinLogger} // TODO(pb)
		if *zipkinCollectorAddr != "" {
			var err error
			if collector, err = zipkin.NewScribeCollector(
				*zipkinCollectorAddr,
				*zipkinCollectorTimeout,
				zipkin.ScribeBatchSize(*zipkinCollectorBatchSize),
				zipkin.ScribeBatchInterval(*zipkinCollectorBatchInterval),
				zipkin.ScribeLogger(zipkinLogger),
			); err != nil {
				zipkinLogger.Log("err", err)
				os.Exit(1)
			}
		}
	}

	// Business domain
	var svc server.AddService
	{
		svc = pureAddService{}
		svc = loggingMiddleware{svc, logger}
		svc = instrumentingMiddleware{svc, requestDuration}
	}

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Debug/instrumentation
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "debug")
		transportLogger.Log("addr", *debugAddr)
		errc <- http.ListenAndServe(*debugAddr, nil) // DefaultServeMux
	}()

	// Transport: HTTP/JSON
	go func() {
		var (
			transportLogger = log.NewContext(logger).With("transport", "HTTP/JSON")
			tracingLogger   = log.NewContext(transportLogger).With("component", "tracing")
			newSumSpan      = zipkin.MakeNewSpanFunc(*zipkinHostPort, *zipkinServiceName, "sum")
			newConcatSpan   = zipkin.MakeNewSpanFunc(*zipkinHostPort, *zipkinServiceName, "concat")
			traceSum        = zipkin.ToContext(newSumSpan, tracingLogger)
			traceConcat     = zipkin.ToContext(newConcatSpan, tracingLogger)
			mux             = http.NewServeMux()
			sum, concat     endpoint.Endpoint
		)

		sum = makeSumEndpoint(svc)
		sum = zipkin.AnnotateServer(newSumSpan, collector)(sum)
		mux.Handle("/sum", httptransport.NewServer(
			root,
			sum,
			server.DecodeSumRequest,
			server.EncodeSumResponse,
			httptransport.ServerBefore(traceSum),
			httptransport.ServerErrorLogger(transportLogger),
		))

		concat = makeConcatEndpoint(svc)
		concat = zipkin.AnnotateServer(newConcatSpan, collector)(concat)
		mux.Handle("/concat", httptransport.NewServer(
			root,
			concat,
			server.DecodeConcatRequest,
			server.EncodeConcatResponse,
			httptransport.ServerBefore(traceConcat),
			httptransport.ServerErrorLogger(transportLogger),
		))

		transportLogger.Log("addr", *httpAddr)
		errc <- http.ListenAndServe(*httpAddr, mux)
	}()

	// Transport: gRPC
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "gRPC")
		ln, err := net.Listen("tcp", *grpcAddr)
		if err != nil {
			errc <- err
			return
		}
		s := grpc.NewServer() // uses its own, internal context
		pb.RegisterAddServer(s, grpcBinding{svc})
		transportLogger.Log("addr", *grpcAddr)
		errc <- s.Serve(ln)
	}()

	// Transport: net/rpc
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "net/rpc")
		s := rpc.NewServer()
		if err := s.RegisterName("addsvc", netrpcBinding{svc}); err != nil {
			errc <- err
			return
		}
		s.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
		transportLogger.Log("addr", *netrpcAddr)
		errc <- http.ListenAndServe(*netrpcAddr, s)
	}()

	// Transport: Thrift
	go func() {
		var protocolFactory thrift.TProtocolFactory
		switch *thriftProtocol {
		case "binary":
			protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
		case "compact":
			protocolFactory = thrift.NewTCompactProtocolFactory()
		case "json":
			protocolFactory = thrift.NewTJSONProtocolFactory()
		case "simplejson":
			protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
		default:
			errc <- fmt.Errorf("invalid Thrift protocol %q", *thriftProtocol)
			return
		}
		var transportFactory thrift.TTransportFactory
		if *thriftBufferSize > 0 {
			transportFactory = thrift.NewTBufferedTransportFactory(*thriftBufferSize)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}
		if *thriftFramed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		transport, err := thrift.NewTServerSocket(*thriftAddr)
		if err != nil {
			errc <- err
			return
		}
		transportLogger := log.NewContext(logger).With("transport", "net/rpc")
		transportLogger.Log("addr", *thriftAddr)
		errc <- thrift.NewTSimpleServer4(
			thriftadd.NewAddServiceProcessor(thriftBinding{svc}),
			transport,
			transportFactory,
			protocolFactory,
		).Serve()
	}()

	logger.Log("fatal", <-errc)
}
Example #18
0
func main() {
	fs := flag.NewFlagSet("", flag.ExitOnError)
	var (
		debugAddr = fs.String("debug.addr", ":8000", "Address for HTTP debug/instrumentation server")
		httpAddr  = fs.String("http.addr", ":8001", "Address for HTTP (JSON) server")
	)

	flag.Usage = fs.Usage // only show our flags
	if err := fs.Parse(os.Args[1:]); err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}

	// package log
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC).With("caller", log.DefaultCaller)
		stdlog.SetFlags(0)                             // flags are handled by Go kit's logger
		stdlog.SetOutput(log.NewStdlibAdapter(logger)) // redirect anything using stdlib log to us
	}

	// package metrics
	var requestDuration metrics.TimeHistogram
	{
		requestDuration = metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
			expvar.NewHistogram("request_duration_ns", 0, 5e9, 1, 50, 95, 99),
			prometheus.NewSummary(stdprometheus.SummaryOpts{
				Namespace: "myorg",
				Subsystem: "addsvc",
				Name:      "duration_ns",
				Help:      "Request duration in nanoseconds.",
			}, []string{"method"}),
		))
	}

	// Business domain
	var svc server.InfoService
	{
		svc = pureInfoService{}
		svc = loggingMiddleware{svc, logger}
		svc = instrumentingMiddleware{svc, requestDuration}
	}

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Debug/instrumentation
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "debug")
		_ = transportLogger.Log("addr", *debugAddr)
		errc <- http.ListenAndServe(*debugAddr, nil) // DefaultServeMux
	}()

	// Transport: HTTP/JSON
	go func() {
		var (
			transportLogger = log.NewContext(logger).With("transport", "HTTP/JSON")
			mux             = http.NewServeMux()
			hello, host     endpoint.Endpoint
		)

		hello = makeHelloEndpoint(svc)
		mux.Handle("/hello", httptransport.NewServer(
			root,
			hello,
			server.DecodeHelloRequest,
			server.EncodeHelloResponse,
			httptransport.ServerErrorLogger(transportLogger),
		))

		host = makeHostEndpoint(svc)
		mux.Handle("/host", httptransport.NewServer(
			root,
			host,
			server.DecodeHostRequest,
			server.EncodeHostResponse,
			httptransport.ServerErrorLogger(transportLogger),
		))

		_ = transportLogger.Log("addr", *httpAddr)
		errc <- http.ListenAndServe(*httpAddr, mux)
	}()

	_ = logger.Log("fatal", <-errc)
}
Example #19
0
File: main.go Project: gmuch/gmuch
func main() {
	flag.Parse()

	// package log
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC).With("caller", log.DefaultCaller)
		stdlog.SetFlags(0)                             // flags are handled by Go kit's logger
		stdlog.SetOutput(log.NewStdlibAdapter(logger)) // redirect anything using stdlib log to us
	}

	// package metrics
	var (
		requestCount   metrics.Counter
		requestLatency metrics.TimeHistogram
	)
	{
		fieldKeys := []string{"method", "error"}
		requestCount = kitprometheus.NewCounter(stdprometheus.CounterOpts{
			Namespace: "gmuch",
			Subsystem: "api",
			Name:      "request_count",
			Help:      "Number of requests received.",
		}, fieldKeys)
		requestLatency = metrics.NewTimeHistogram(time.Nanosecond, metrics.NewMultiHistogram(
			expvar.NewHistogram("request_duration_ns", 0, 5e9, 1, 50, 95, 99),
			kitprometheus.NewSummary(stdprometheus.SummaryOpts{
				Namespace: "gmuch",
				Subsystem: "api",
				Name:      "duration_ns",
				Help:      "Request duration in nanoseconds.",
			}, fieldKeys),
		))
	}

	// Business domain
	var g server.GmuchService
	{
		g = gmuch.New(*dbPath, logger)
		g = server.LoggingMiddleware(logger)(g)
		g = server.InstrumentingMiddleware(requestCount, requestLatency)(g)
	}

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Debug/instrumentation
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "debug")
		_ = transportLogger.Log("addr", *debugAddr)
		errc <- http.ListenAndServe(*debugAddr, nil) // DefaultServeMux
	}()

	// Transport: HTTP/JSON
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "HTTP/JSON")
		mux := http.NewServeMux()

		mux.Handle("/query", httptransport.NewServer(
			root,
			shttp.EndpointenizeQuery(g),
			shttp.DecodeQueryRequest,
			shttp.EncodeQueryResponse,
			httptransport.ServerErrorLogger(transportLogger),
		))
		mux.Handle("/thread", httptransport.NewServer(
			root,
			shttp.EndpointenizeThread(g),
			shttp.DecodeThreadRequest,
			shttp.EncodeThreadResponse,
			httptransport.ServerErrorLogger(transportLogger),
		))

		_ = transportLogger.Log("addr", *httpAddr)
		errc <- http.ListenAndServe(*httpAddr, mux)
	}()

	// Transport: gRPC
	go func() {
		transportLogger := log.NewContext(logger).With("transport", "gRPC")
		ln, err := net.Listen("tcp", *grpcAddr)
		if err != nil {
			errc <- err
			return
		}
		s := grpc.NewServer() // uses its own, internal context
		sgrpc.RegisterGmuchServer(s, sgrpc.Binding{g})
		_ = transportLogger.Log("addr", *grpcAddr)
		errc <- s.Serve(ln)
	}()

	_ = logger.Log("fatal", <-errc)
}