示例#1
0
func statsPageHandler(w http.ResponseWriter, r *http.Request, bctx *BasePageContext) {
	ctx := &struct {
		*BasePageContext
		Stats []*stat
	}{
		BasePageContext: bctx,
		Stats:           []*stat{},
	}

	var stats *expvar.Map
	stats = expvar.Get("counters").(*expvar.Map)
	servStat := expvar.Get("states").(*expvar.Map)
	errors := expvar.Get("errors").(*expvar.Map)

	for _, ep := range bctx.Globals.GetEndpoints() {
		epname := ep.Name
		all := stats.Get(epname)
		success := stats.Get(epname + "|pass")
		unauth := stats.Get(epname + "|401")
		fail := stats.Get(epname + "|403")
		status := servStat.Get(epname)
		statusSSL := servStat.Get(epname + "|ssl")
		err := errors.Get(epname)
		errSSL := errors.Get(epname + "|ssl")
		ctx.Stats = append(ctx.Stats, &stat{epname, fail, success, unauth, all, status, statusSSL,
			err, errSSL})
	}

	RenderTemplateStd(w, ctx, "stats.tmpl")
}
示例#2
0
文件: status.go 项目: yonglehou/hooky
func GetStatus(w rest.ResponseWriter, r *rest.Request) {
	// b := GetBase(r)
	status := make(map[string]string)
	status["status"] = "ok"
	status["attemptsError"] = expvar.Get("attemptsError").String()
	status["attemptsSuccess"] = expvar.Get("attemptsSuccess").String()
	w.WriteJson(status)
}
示例#3
0
func TestNew(t *testing.T) {
	// Publishes prefix in expvar, panics the second time
	assert.Nil(t, expvar.Get("name"))
	New("name")
	assert.NotNil(t, expvar.Get("name"))
	assert.IsType(t, expvar.Get("name"), &expvar.Map{})
	assert.Panics(t, func() {
		New("name")
	})
}
示例#4
0
func TestPublished(t *testing.T) {
	l, err := Listen("")
	if err != nil {
		t.Fatal(err)
	}
	opened := make(chan struct{})
	closed := make(chan struct{})
	go func() {
		for {
			conn, err := l.Accept()
			opened <- struct{}{}
			if err != nil {
				t.Fatal(err)
			}
			go func() {
				b := make([]byte, 100)
				for {
					_, err := conn.Read(b)
					if err != nil {
						conn.Close()
						closed <- struct{}{}
						return
					}
				}
			}()
		}
	}()

	addr := l.Addr().String()
	for i := 1; i <= 3; i++ {
		conn1, err := net.Dial("tcp", addr)
		if err != nil {
			t.Fatal(err)
		}
		<-opened
		if v := expvar.Get("ConnCount").String(); v != "1" {
			t.Errorf("ConnCount: %v, want 1", v)
		}
		conn1.Close()
		<-closed
		if v := expvar.Get("ConnCount").String(); v != "0" {
			t.Errorf("ConnCount: %v, want 1", v)
		}
		if v := expvar.Get("ConnAccepted").String(); v != fmt.Sprintf("%d", i) {
			t.Errorf("ConnAccepted: %v, want %d", v, i)
		}
	}
}
示例#5
0
文件: server.go 项目: millken/kaman
func wsServer(ws *websocket.Conn) {
	var buf string
	defer func() {
		if err := ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		} else {
			log.Println("Websocket closed")
		}
	}()
	//q := ws.Request().URL.Query()
	//name := q.Get("name")
	stopped := false
	ticker := time.Tick(time.Duration(1) * time.Second)
	for !stopped {
		select {
		case <-ticker:
			val := expvar.Get(metricsVar)
			if val == nil {
				buf = ""
			} else {
				buf = val.String()
			}
			_, err := ws.Write([]byte(buf))
			if err != nil {
				log.Printf("Websocket error: %s\n", err.Error())
				stopped = true
			}

		}
	}
}
示例#6
0
func TestDerive(t *testing.T) {
	d := NewDerive(api.Identifier{
		Host:   "example.com",
		Plugin: "golang",
		Type:   "derive",
	})

	for i := 0; i < 10; i++ {
		d.Add(i)
	}

	want := api.ValueList{
		Identifier: api.Identifier{
			Host:   "example.com",
			Plugin: "golang",
			Type:   "derive",
		},
		Values: []api.Value{api.Derive(45)},
	}
	got := d.ValueList()

	if !reflect.DeepEqual(got, want) {
		t.Errorf("got %#v, want %#v", got, want)
	}

	s := expvar.Get("example.com/golang/derive").String()
	if s != "45" {
		t.Errorf("got %q, want %q", s, "45")
	}
}
func init() {
	registry := expvar.Get("registry")
	if registry == nil {
		registry = expvar.NewMap("registry")
	}

	cache := registry.(*expvar.Map).Get("cache")
	if cache == nil {
		cache = &expvar.Map{}
		cache.(*expvar.Map).Init()
		registry.(*expvar.Map).Set("cache", cache)
	}

	storage := cache.(*expvar.Map).Get("storage")
	if storage == nil {
		storage = &expvar.Map{}
		storage.(*expvar.Map).Init()
		cache.(*expvar.Map).Set("storage", storage)
	}

	storage.(*expvar.Map).Set("blobdescriptor", expvar.Func(func() interface{} {
		// no need for synchronous access: the increments are atomic and
		// during reading, we don't care if the data is up to date. The
		// numbers will always *eventually* be reported correctly.
		return blobStatterCacheMetrics
	}))
}
示例#8
0
// Gets an exported var and returns its unquoted string contents
func GetStringVar(name string) string {
	s, err := strconv.Unquote(expvar.Get(name).String())
	if err != nil {
		panic(err)
	}
	return s
}
示例#9
0
// NewStatistics returns an expvar-based map with the given key. Within that map
// is another map. Within there "name" is the Measurement name, "tags" are the tags,
// and values are placed at the key "values".
func NewStatistics(key, name string, tags map[string]string) *expvar.Map {
	expvarMu.Lock()
	defer expvarMu.Unlock()

	// Add expvar for this service.
	var v expvar.Var
	if v = expvar.Get(key); v == nil {
		v = expvar.NewMap(key)
	}
	m := v.(*expvar.Map)

	// Set the name
	nameVar := &expvar.String{}
	nameVar.Set(name)
	m.Set("name", nameVar)

	// Set the tags
	tagsVar := &expvar.Map{}
	tagsVar.Init()
	for k, v := range tags {
		value := &expvar.String{}
		value.Set(v)
		tagsVar.Set(k, value)
	}
	m.Set("tags", tagsVar)

	// Create and set the values entry used for actual stats.
	statMap := &expvar.Map{}
	statMap.Init()
	m.Set("values", statMap)

	return statMap
}
示例#10
0
// Gets an exported var and returns its float value
func GetFloatVar(name string) float64 {
	f, err := strconv.ParseFloat(expvar.Get(name).String(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
示例#11
0
// Gets an exported var and returns its int value
func GetIntVar(name string) int64 {
	i, err := strconv.ParseInt(expvar.Get(name).String(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}
示例#12
0
func TestGauge(t *testing.T) {
	g := NewGauge(api.Identifier{
		Host:   "example.com",
		Plugin: "golang",
		Type:   "gauge",
	})

	g.Set(42.0)

	want := api.ValueList{
		Identifier: api.Identifier{
			Host:   "example.com",
			Plugin: "golang",
			Type:   "gauge",
		},
		Values: []api.Value{api.Gauge(42)},
	}
	got := g.ValueList()

	if !reflect.DeepEqual(got, want) {
		t.Errorf("got %#v, want %#v", got, want)
	}

	s := expvar.Get("example.com/golang/gauge").String()
	if s != "42" {
		t.Errorf("got %q, want %q", s, "42")
	}
}
示例#13
0
func TestGauge(t *testing.T) {
	s := New("gauge")
	v := expvar.Get("gauge").(*expvar.Map)
	s.Gauge("test", 1)
	assert.Equal(t, "1", v.Get("test").String())
	s.Gauge("test", -1)
	assert.Equal(t, "-1", v.Get("test").String())
}
示例#14
0
func TestCount(t *testing.T) {
	s := New("count")
	v := expvar.Get("count").(*expvar.Map)
	s.Count("test", 1)
	assert.Equal(t, "1", v.Get("test").String())
	s.Count("test", -1)
	assert.Equal(t, "0", v.Get("test").String())
}
示例#15
0
func TestCallbackGauge(t *testing.T) {
	value := 42.43
	metricName := "foo"
	expvar.PublishCallbackGauge(metricName, func() float64 { return value })
	if want, have := fmt.Sprint(value), stdexpvar.Get(metricName).String(); want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
示例#16
0
func checkMemcacheExpvar(t *testing.T, name string, expectedVal string) {
	val := expvar.Get(name)
	if val == nil {
		t.Fatalf("cannot find exported variable: %s", name)
	}
	if val.String() != expectedVal {
		t.Fatalf("name: %s, expect to get %s, but got: %s", name, expectedVal, val.String())
	}
}
示例#17
0
func TestWatcherErrors(t *testing.T) {
	orig, err := strconv.ParseInt(expvar.Get("log_watcher_error_count").String(), 10, 64)
	if err != nil {
		t.Fatalf("couldn't convert expvar %q", expvar.Get("log_watcher_error_count").String())
	}
	w, err := NewLogWatcher()
	if err != nil {
		t.Fatalf("couldn't create a watcher")
	}
	w.Errors <- errors.New("just a test, not really an error")
	if err := w.Close(); err != nil {
		t.Fatalf("watcher close failed: %q", err)
	}
	diff := pretty.Compare(strconv.FormatInt(orig+1, 10), expvar.Get("log_watcher_error_count").String())
	if len(diff) > 0 {
		t.Errorf("log watcher error count doens't match:\n%s", diff)
	}
}
示例#18
0
func TestCounter(t *testing.T) {
	var (
		name  = "m"
		value = 123
	)
	expvar.NewCounter(name).With(metrics.Field{Key: "ignored", Value: "field"}).Add(uint64(value))
	if want, have := fmt.Sprint(value), stdexpvar.Get(name).String(); want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
示例#19
0
func GetStatement(key string) (stmt mysql.Stmt, err error) {
	stmt, ok := Statements[key]
	if !ok {
		qry := expvar.Get(key)
		if qry == nil {
			err = errors.New("Invalid query reference")
		}
	}
	return

}
示例#20
0
func TestWatcherErrors(t *testing.T) {
	w, err := NewLogWatcher()
	if err != nil {
		t.Fatalf("couldn't create a watcher")
	}
	w.Errors <- errors.New("test error")
	w.Close()
	diff := pretty.Compare(expvar.Get("log_watcher_error_count").String(), "1")
	if len(diff) > 0 {
		t.Errorf("log watcher error count doens't match:\n%s", diff)
	}
}
示例#21
0
func TestGauge(t *testing.T) {
	var (
		name  = "xyz"
		value = 54321
		delta = 12345
		g     = expvar.NewGauge(name).With(metrics.Field{Key: "ignored", Value: "field"})
	)
	g.Set(float64(value))
	g.Add(float64(delta))
	if want, have := fmt.Sprint(value+delta), stdexpvar.Get(name).String(); want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
示例#22
0
文件: multi_test.go 项目: qband/down
func TestMultiGauge(t *testing.T) {
	g := metrics.NewMultiGauge(
		"multidelta",
		expvar.NewGauge("delta"),
		prometheus.NewGauge(stdprometheus.GaugeOpts{
			Namespace: "test",
			Subsystem: "multi_gauge",
			Name:      "kappa",
			Help:      "Kappa gauge.",
		}, []string{"a"}),
	)

	f := metrics.Field{Key: "a", Value: "aaa"}
	g.With(f).Set(34)

	if want, have := "34", stdexpvar.Get("delta").String(); want != have {
		t.Errorf("expvar: want %q, have %q", want, have)
	}
	if want, have := strings.Join([]string{
		`# HELP test_multi_gauge_kappa Kappa gauge.`,
		`# TYPE test_multi_gauge_kappa gauge`,
		`test_multi_gauge_kappa{a="aaa"} 34`,
	}, "\n"), scrapePrometheus(t); !strings.Contains(have, want) {
		t.Errorf("Prometheus metric stanza not found or incorrect\n%s", have)
	}

	g.With(f).Add(-40)

	if want, have := "-6", stdexpvar.Get("delta").String(); want != have {
		t.Errorf("expvar: want %q, have %q", want, have)
	}
	if want, have := strings.Join([]string{
		`# HELP test_multi_gauge_kappa Kappa gauge.`,
		`# TYPE test_multi_gauge_kappa gauge`,
		`test_multi_gauge_kappa{a="aaa"} -6`,
	}, "\n"), scrapePrometheus(t); !strings.Contains(have, want) {
		t.Errorf("Prometheus metric stanza not found or incorrect\n%s", have)
	}
}
示例#23
0
// setExpvar configures the expvar based collection for this service. It must be done within a
// lock so previous registrations for this key can be checked. Re-registering a key will result
// in a panic.
func (s *Service) setExpvar() {
	expvarMu.Lock()
	defer expvarMu.Unlock()

	key := strings.Join([]string{"graphite", s.protocol, s.bindAddress}, ":")

	// Add expvar for this service.
	var m expvar.Var
	if m = expvar.Get(key); m == nil {
		m = expvar.NewMap(key)
	}
	s.statMap = m.(*expvar.Map)
}
示例#24
0
文件: exp.go 项目: YaSuenag/hsbeat
func (exp *exp) getFloat(name string) *expvar.Float {
	var v *expvar.Float
	exp.expvarLock.Lock()
	p := expvar.Get(name)
	if p != nil {
		v = p.(*expvar.Float)
	} else {
		v = new(expvar.Float)
		expvar.Publish(name, v)
	}
	exp.expvarLock.Unlock()
	return v
}
示例#25
0
文件: stats.go 项目: millken/kaman
func (mh *metricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate,no-cache,no-store")

	//	_, _ = metrics.Snapshot()
	val := expvar.Get(metricsVar)
	if val == nil {
		w.WriteHeader(http.StatusNotImplemented)
		w.Write([]byte("No metrics."))
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(val.String()))
}
示例#26
0
func GetStatement(key string) (stmt *autorc.Stmt, err error) {
	stmt, ok := Statements[key]
	if !ok {
		qry := expvar.Get(key)
		if qry == nil {
			err = errors.New("Invalid query reference")
		} else {
			stmt, err = Db.Prepare(qry.String())
		}
	}
	return

}
示例#27
0
func assertExpvarNormalHistogram(t *testing.T, metricName string, mean, stdev int64, quantiles []int) {
	const tolerance int = 2
	for _, quantile := range quantiles {
		want := normalValueAtQuantile(mean, stdev, quantile)
		s := stdexpvar.Get(fmt.Sprintf("%s_p%02d", metricName, quantile)).String()
		have, err := strconv.Atoi(s)
		if err != nil {
			t.Fatal(err)
		}
		if int(math.Abs(float64(want)-float64(have))) > tolerance {
			t.Errorf("quantile %d: want %d, have %d", quantile, want, have)
		}
	}
}
示例#28
0
func TestGets(t *testing.T) {
	var p pool.Pool
	p = pool.RoundRobin([]string{"≠"})
	p = pool.Instrument(p)
	p = pool.Report(ioutil.Discard, p)

	n := 123
	for i := 0; i < n; i++ {
		p.Get()
	}

	want := strconv.FormatInt(int64(n), 10)
	have := expvar.Get(pool.ExpvarKeyGets).String()
	if want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
示例#29
0
文件: expvar.go 项目: 40a/bootkube
// Collect implements Collector.
func (e *ExpvarCollector) Collect(ch chan<- Metric) {
	for name, desc := range e.exports {
		var m Metric
		expVar := expvar.Get(name)
		if expVar == nil {
			continue
		}
		var v interface{}
		labels := make([]string, len(desc.variableLabels))
		if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
			ch <- NewInvalidMetric(desc, err)
			continue
		}
		var processValue func(v interface{}, i int)
		processValue = func(v interface{}, i int) {
			if i >= len(labels) {
				copiedLabels := append(make([]string, 0, len(labels)), labels...)
				switch v := v.(type) {
				case float64:
					m = MustNewConstMetric(desc, UntypedValue, v, copiedLabels...)
				case bool:
					if v {
						m = MustNewConstMetric(desc, UntypedValue, 1, copiedLabels...)
					} else {
						m = MustNewConstMetric(desc, UntypedValue, 0, copiedLabels...)
					}
				default:
					return
				}
				ch <- m
				return
			}
			vm, ok := v.(map[string]interface{})
			if !ok {
				return
			}
			for lv, val := range vm {
				labels[i] = lv
				processValue(val, i+1)
			}
		}
		processValue(v, 0)
	}
}
示例#30
0
func (ab *AmqpBeat) exposeMetrics() {
	go func() {
		http.ListenAndServe(*ab.RbConfig.AmqpInput.StatsAddress, nil)
	}()

	go func(metrics chan *metric) {
		mmap := make(map[string]*expvar.Int)
		for m := range metrics {
			if _, ok := mmap[m.name]; !ok {
				v := expvar.Get(m.name)
				if v == nil {
					v = expvar.NewInt(m.name)
				}
				mmap[m.name] = v.(*expvar.Int)
			}
			mmap[m.name].Set(m.value)
		}
	}(ab.metrics)
}