summaryrefslogtreecommitdiff
path: root/libgo/go/expvar
diff options
context:
space:
mode:
Diffstat (limited to 'libgo/go/expvar')
-rw-r--r--libgo/go/expvar/expvar.go299
-rw-r--r--libgo/go/expvar/expvar_test.go154
2 files changed, 453 insertions, 0 deletions
diff --git a/libgo/go/expvar/expvar.go b/libgo/go/expvar/expvar.go
new file mode 100644
index 000000000..b1f0f6c1b
--- /dev/null
+++ b/libgo/go/expvar/expvar.go
@@ -0,0 +1,299 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// The expvar package provides a standardized interface to public variables,
+// such as operation counters in servers. It exposes these variables via
+// HTTP at /debug/vars in JSON format.
+//
+// Operations to set or modify these public variables are atomic.
+//
+// In addition to adding the HTTP handler, this package registers the
+// following variables:
+//
+// cmdline os.Args
+// memstats runtime.Memstats
+//
+// The package is sometimes only imported for the side effect of
+// registering its HTTP handler and the above variables. To use it
+// this way, simply link this package into your program:
+// import _ "expvar"
+//
+package expvar
+
+import (
+ "bytes"
+ "fmt"
+ "http"
+ "json"
+ "log"
+ "os"
+ "runtime"
+ "strconv"
+ "sync"
+)
+
+// Var is an abstract type for all exported variables.
+type Var interface {
+ String() string
+}
+
+// Int is a 64-bit integer variable that satisfies the Var interface.
+type Int struct {
+ i int64
+ mu sync.Mutex
+}
+
+func (v *Int) String() string { return strconv.Itoa64(v.i) }
+
+func (v *Int) Add(delta int64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.i += delta
+}
+
+func (v *Int) Set(value int64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.i = value
+}
+
+// Float is a 64-bit float variable that satisfies the Var interface.
+type Float struct {
+ f float64
+ mu sync.Mutex
+}
+
+func (v *Float) String() string { return strconv.Ftoa64(v.f, 'g', -1) }
+
+// Add adds delta to v.
+func (v *Float) Add(delta float64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.f += delta
+}
+
+// Set sets v to value.
+func (v *Float) Set(value float64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.f = value
+}
+
+// Map is a string-to-Var map variable that satisfies the Var interface.
+type Map struct {
+ m map[string]Var
+ mu sync.Mutex
+}
+
+// KeyValue represents a single entry in a Map.
+type KeyValue struct {
+ Key string
+ Value Var
+}
+
+func (v *Map) String() string {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ b := new(bytes.Buffer)
+ fmt.Fprintf(b, "{")
+ first := true
+ for key, val := range v.m {
+ if !first {
+ fmt.Fprintf(b, ", ")
+ }
+ fmt.Fprintf(b, "\"%s\": %v", key, val.String())
+ first = false
+ }
+ fmt.Fprintf(b, "}")
+ return b.String()
+}
+
+func (v *Map) Init() *Map {
+ v.m = make(map[string]Var)
+ return v
+}
+
+func (v *Map) Get(key string) Var {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ return v.m[key]
+}
+
+func (v *Map) Set(key string, av Var) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.m[key] = av
+}
+
+func (v *Map) Add(key string, delta int64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ av, ok := v.m[key]
+ if !ok {
+ av = new(Int)
+ v.m[key] = av
+ }
+
+ // Add to Int; ignore otherwise.
+ if iv, ok := av.(*Int); ok {
+ iv.Add(delta)
+ }
+}
+
+// AddFloat adds delta to the *Float value stored under the given map key.
+func (v *Map) AddFloat(key string, delta float64) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ av, ok := v.m[key]
+ if !ok {
+ av = new(Float)
+ v.m[key] = av
+ }
+
+ // Add to Float; ignore otherwise.
+ if iv, ok := av.(*Float); ok {
+ iv.Add(delta)
+ }
+}
+
+// TODO(rsc): Make sure map access in separate thread is safe.
+func (v *Map) iterate(c chan<- KeyValue) {
+ for k, v := range v.m {
+ c <- KeyValue{k, v}
+ }
+ close(c)
+}
+
+func (v *Map) Iter() <-chan KeyValue {
+ c := make(chan KeyValue)
+ go v.iterate(c)
+ return c
+}
+
+// String is a string variable, and satisfies the Var interface.
+type String struct {
+ s string
+}
+
+func (v *String) String() string { return strconv.Quote(v.s) }
+
+func (v *String) Set(value string) { v.s = value }
+
+// IntFunc wraps a func() int64 to create a value that satisfies the Var interface.
+// The function will be called each time the Var is evaluated.
+type IntFunc func() int64
+
+func (v IntFunc) String() string { return strconv.Itoa64(v()) }
+
+// FloatFunc wraps a func() float64 to create a value that satisfies the Var interface.
+// The function will be called each time the Var is evaluated.
+type FloatFunc func() float64
+
+func (v FloatFunc) String() string { return strconv.Ftoa64(v(), 'g', -1) }
+
+// StringFunc wraps a func() string to create value that satisfies the Var interface.
+// The function will be called each time the Var is evaluated.
+type StringFunc func() string
+
+func (f StringFunc) String() string { return strconv.Quote(f()) }
+
+
+// All published variables.
+var vars map[string]Var = make(map[string]Var)
+var mutex sync.Mutex
+
+// Publish declares an named exported variable. This should be called from a
+// package's init function when it creates its Vars. If the name is already
+// registered then this will log.Panic.
+func Publish(name string, v Var) {
+ mutex.Lock()
+ defer mutex.Unlock()
+ if _, existing := vars[name]; existing {
+ log.Panicln("Reuse of exported var name:", name)
+ }
+ vars[name] = v
+}
+
+// Get retrieves a named exported variable.
+func Get(name string) Var {
+ return vars[name]
+}
+
+// RemoveAll removes all exported variables.
+// This is for tests; don't call this on a real server.
+func RemoveAll() {
+ mutex.Lock()
+ defer mutex.Unlock()
+ vars = make(map[string]Var)
+}
+
+// Convenience functions for creating new exported variables.
+
+func NewInt(name string) *Int {
+ v := new(Int)
+ Publish(name, v)
+ return v
+}
+
+func NewFloat(name string) *Float {
+ v := new(Float)
+ Publish(name, v)
+ return v
+}
+
+func NewMap(name string) *Map {
+ v := new(Map).Init()
+ Publish(name, v)
+ return v
+}
+
+func NewString(name string) *String {
+ v := new(String)
+ Publish(name, v)
+ return v
+}
+
+// TODO(rsc): Make sure map access in separate thread is safe.
+func iterate(c chan<- KeyValue) {
+ for k, v := range vars {
+ c <- KeyValue{k, v}
+ }
+ close(c)
+}
+
+func Iter() <-chan KeyValue {
+ c := make(chan KeyValue)
+ go iterate(c)
+ return c
+}
+
+func expvarHandler(w http.ResponseWriter, r *http.Request) {
+ w.SetHeader("content-type", "application/json; charset=utf-8")
+ fmt.Fprintf(w, "{\n")
+ first := true
+ for name, value := range vars {
+ if !first {
+ fmt.Fprintf(w, ",\n")
+ }
+ first = false
+ fmt.Fprintf(w, "%q: %s", name, value)
+ }
+ fmt.Fprintf(w, "\n}\n")
+}
+
+func memstats() string {
+ b, _ := json.MarshalIndent(&runtime.MemStats, "", "\t")
+ return string(b)
+}
+
+func cmdline() string {
+ b, _ := json.Marshal(os.Args)
+ return string(b)
+}
+
+func init() {
+ http.Handle("/debug/vars", http.HandlerFunc(expvarHandler))
+ Publish("cmdline", StringFunc(cmdline))
+ Publish("memstats", StringFunc(memstats))
+}
diff --git a/libgo/go/expvar/expvar_test.go b/libgo/go/expvar/expvar_test.go
new file mode 100644
index 000000000..a8b1a96a9
--- /dev/null
+++ b/libgo/go/expvar/expvar_test.go
@@ -0,0 +1,154 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package expvar
+
+import (
+ "json"
+ "testing"
+)
+
+func TestInt(t *testing.T) {
+ reqs := NewInt("requests")
+ if reqs.i != 0 {
+ t.Errorf("reqs.i = %v, want 0", reqs.i)
+ }
+ if reqs != Get("requests").(*Int) {
+ t.Errorf("Get() failed.")
+ }
+
+ reqs.Add(1)
+ reqs.Add(3)
+ if reqs.i != 4 {
+ t.Errorf("reqs.i = %v, want 4", reqs.i)
+ }
+
+ if s := reqs.String(); s != "4" {
+ t.Errorf("reqs.String() = %q, want \"4\"", s)
+ }
+
+ reqs.Set(-2)
+ if reqs.i != -2 {
+ t.Errorf("reqs.i = %v, want -2", reqs.i)
+ }
+}
+
+func TestFloat(t *testing.T) {
+ reqs := NewFloat("requests-float")
+ if reqs.f != 0.0 {
+ t.Errorf("reqs.f = %v, want 0", reqs.f)
+ }
+ if reqs != Get("requests-float").(*Float) {
+ t.Errorf("Get() failed.")
+ }
+
+ reqs.Add(1.5)
+ reqs.Add(1.25)
+ if reqs.f != 2.75 {
+ t.Errorf("reqs.f = %v, want 2.75", reqs.f)
+ }
+
+ if s := reqs.String(); s != "2.75" {
+ t.Errorf("reqs.String() = %q, want \"4.64\"", s)
+ }
+
+ reqs.Add(-2)
+ if reqs.f != 0.75 {
+ t.Errorf("reqs.f = %v, want 0.75", reqs.f)
+ }
+}
+
+func TestString(t *testing.T) {
+ name := NewString("my-name")
+ if name.s != "" {
+ t.Errorf("name.s = %q, want \"\"", name.s)
+ }
+
+ name.Set("Mike")
+ if name.s != "Mike" {
+ t.Errorf("name.s = %q, want \"Mike\"", name.s)
+ }
+
+ if s := name.String(); s != "\"Mike\"" {
+ t.Errorf("reqs.String() = %q, want \"\"Mike\"\"", s)
+ }
+}
+
+func TestMapCounter(t *testing.T) {
+ colours := NewMap("bike-shed-colours")
+
+ colours.Add("red", 1)
+ colours.Add("red", 2)
+ colours.Add("blue", 4)
+ colours.AddFloat("green", 4.125)
+ if x := colours.m["red"].(*Int).i; x != 3 {
+ t.Errorf("colours.m[\"red\"] = %v, want 3", x)
+ }
+ if x := colours.m["blue"].(*Int).i; x != 4 {
+ t.Errorf("colours.m[\"blue\"] = %v, want 4", x)
+ }
+ if x := colours.m["green"].(*Float).f; x != 4.125 {
+ t.Errorf("colours.m[\"green\"] = %v, want 3.14", x)
+ }
+
+ // colours.String() should be '{"red":3, "blue":4}',
+ // though the order of red and blue could vary.
+ s := colours.String()
+ var j interface{}
+ err := json.Unmarshal([]byte(s), &j)
+ if err != nil {
+ t.Errorf("colours.String() isn't valid JSON: %v", err)
+ }
+ m, ok := j.(map[string]interface{})
+ if !ok {
+ t.Error("colours.String() didn't produce a map.")
+ }
+ red := m["red"]
+ x, ok := red.(float64)
+ if !ok {
+ t.Error("red.Kind() is not a number.")
+ }
+ if x != 3 {
+ t.Errorf("red = %v, want 3", x)
+ }
+}
+
+func TestIntFunc(t *testing.T) {
+ x := int64(4)
+ ix := IntFunc(func() int64 { return x })
+ if s := ix.String(); s != "4" {
+ t.Errorf("ix.String() = %v, want 4", s)
+ }
+
+ x++
+ if s := ix.String(); s != "5" {
+ t.Errorf("ix.String() = %v, want 5", s)
+ }
+}
+
+func TestFloatFunc(t *testing.T) {
+ x := 8.5
+ ix := FloatFunc(func() float64 { return x })
+ if s := ix.String(); s != "8.5" {
+ t.Errorf("ix.String() = %v, want 3.14", s)
+ }
+
+ x -= 1.25
+ if s := ix.String(); s != "7.25" {
+ t.Errorf("ix.String() = %v, want 4.34", s)
+ }
+}
+
+func TestStringFunc(t *testing.T) {
+ x := "hello"
+ sx := StringFunc(func() string { return x })
+ if s, exp := sx.String(), `"hello"`; s != exp {
+ t.Errorf(`sx.String() = %q, want %q`, s, exp)
+ }
+
+ x = "goodbye"
+ if s, exp := sx.String(), `"goodbye"`; s != exp {
+ t.Errorf(`sx.String() = %q, want %q`, s, exp)
+ }
+}