2018-23-01 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / libgo / go / expvar / expvar.go
blob8290e0bd72b186e74643c382dee80a2b382dd61c
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package expvar provides a standardized interface to public variables, such
6 // as operation counters in servers. It exposes these variables via HTTP at
7 // /debug/vars in JSON format.
8 //
9 // Operations to set or modify these public variables are atomic.
11 // In addition to adding the HTTP handler, this package registers the
12 // following variables:
14 // cmdline os.Args
15 // memstats runtime.Memstats
17 // The package is sometimes only imported for the side effect of
18 // registering its HTTP handler and the above variables. To use it
19 // this way, link this package into your program:
20 // import _ "expvar"
22 package expvar
24 import (
25 "bytes"
26 "encoding/json"
27 "fmt"
28 "log"
29 "math"
30 "net/http"
31 "os"
32 "runtime"
33 "sort"
34 "strconv"
35 "sync"
36 "sync/atomic"
39 // Var is an abstract type for all exported variables.
40 type Var interface {
41 // String returns a valid JSON value for the variable.
42 // Types with String methods that do not return valid JSON
43 // (such as time.Time) must not be used as a Var.
44 String() string
47 // Int is a 64-bit integer variable that satisfies the Var interface.
48 type Int struct {
49 i int64
52 func (v *Int) Value() int64 {
53 return atomic.LoadInt64(&v.i)
56 func (v *Int) String() string {
57 return strconv.FormatInt(atomic.LoadInt64(&v.i), 10)
60 func (v *Int) Add(delta int64) {
61 atomic.AddInt64(&v.i, delta)
64 func (v *Int) Set(value int64) {
65 atomic.StoreInt64(&v.i, value)
68 // Float is a 64-bit float variable that satisfies the Var interface.
69 type Float struct {
70 f uint64
73 func (v *Float) Value() float64 {
74 return math.Float64frombits(atomic.LoadUint64(&v.f))
77 func (v *Float) String() string {
78 return strconv.FormatFloat(
79 math.Float64frombits(atomic.LoadUint64(&v.f)), 'g', -1, 64)
82 // Add adds delta to v.
83 func (v *Float) Add(delta float64) {
84 for {
85 cur := atomic.LoadUint64(&v.f)
86 curVal := math.Float64frombits(cur)
87 nxtVal := curVal + delta
88 nxt := math.Float64bits(nxtVal)
89 if atomic.CompareAndSwapUint64(&v.f, cur, nxt) {
90 return
95 // Set sets v to value.
96 func (v *Float) Set(value float64) {
97 atomic.StoreUint64(&v.f, math.Float64bits(value))
100 // Map is a string-to-Var map variable that satisfies the Var interface.
101 type Map struct {
102 m sync.Map // map[string]Var
103 keysMu sync.RWMutex
104 keys []string // sorted
107 // KeyValue represents a single entry in a Map.
108 type KeyValue struct {
109 Key string
110 Value Var
113 func (v *Map) String() string {
114 var b bytes.Buffer
115 fmt.Fprintf(&b, "{")
116 first := true
117 v.Do(func(kv KeyValue) {
118 if !first {
119 fmt.Fprintf(&b, ", ")
121 fmt.Fprintf(&b, "%q: %v", kv.Key, kv.Value)
122 first = false
124 fmt.Fprintf(&b, "}")
125 return b.String()
128 // Init removes all keys from the map.
129 func (v *Map) Init() *Map {
130 v.keysMu.Lock()
131 defer v.keysMu.Unlock()
132 v.keys = v.keys[:0]
133 v.m.Range(func(k, _ interface{}) bool {
134 v.m.Delete(k)
135 return true
137 return v
140 // updateKeys updates the sorted list of keys in v.keys.
141 func (v *Map) addKey(key string) {
142 v.keysMu.Lock()
143 defer v.keysMu.Unlock()
144 v.keys = append(v.keys, key)
145 sort.Strings(v.keys)
148 func (v *Map) Get(key string) Var {
149 i, _ := v.m.Load(key)
150 av, _ := i.(Var)
151 return av
154 func (v *Map) Set(key string, av Var) {
155 // Before we store the value, check to see whether the key is new. Try a Load
156 // before LoadOrStore: LoadOrStore causes the key interface to escape even on
157 // the Load path.
158 if _, ok := v.m.Load(key); !ok {
159 if _, dup := v.m.LoadOrStore(key, av); !dup {
160 v.addKey(key)
161 return
165 v.m.Store(key, av)
168 // Add adds delta to the *Int value stored under the given map key.
169 func (v *Map) Add(key string, delta int64) {
170 i, ok := v.m.Load(key)
171 if !ok {
172 var dup bool
173 i, dup = v.m.LoadOrStore(key, new(Int))
174 if !dup {
175 v.addKey(key)
179 // Add to Int; ignore otherwise.
180 if iv, ok := i.(*Int); ok {
181 iv.Add(delta)
185 // AddFloat adds delta to the *Float value stored under the given map key.
186 func (v *Map) AddFloat(key string, delta float64) {
187 i, ok := v.m.Load(key)
188 if !ok {
189 var dup bool
190 i, dup = v.m.LoadOrStore(key, new(Float))
191 if !dup {
192 v.addKey(key)
196 // Add to Float; ignore otherwise.
197 if iv, ok := i.(*Float); ok {
198 iv.Add(delta)
202 // Do calls f for each entry in the map.
203 // The map is locked during the iteration,
204 // but existing entries may be concurrently updated.
205 func (v *Map) Do(f func(KeyValue)) {
206 v.keysMu.RLock()
207 defer v.keysMu.RUnlock()
208 for _, k := range v.keys {
209 i, _ := v.m.Load(k)
210 f(KeyValue{k, i.(Var)})
214 // String is a string variable, and satisfies the Var interface.
215 type String struct {
216 s atomic.Value // string
219 func (v *String) Value() string {
220 p, _ := v.s.Load().(string)
221 return p
224 // String implements the Val interface. To get the unquoted string
225 // use Value.
226 func (v *String) String() string {
227 s := v.Value()
228 b, _ := json.Marshal(s)
229 return string(b)
232 func (v *String) Set(value string) {
233 v.s.Store(value)
236 // Func implements Var by calling the function
237 // and formatting the returned value using JSON.
238 type Func func() interface{}
240 func (f Func) Value() interface{} {
241 return f()
244 func (f Func) String() string {
245 v, _ := json.Marshal(f())
246 return string(v)
249 // All published variables.
250 var (
251 vars sync.Map // map[string]Var
252 varKeysMu sync.RWMutex
253 varKeys []string // sorted
256 // Publish declares a named exported variable. This should be called from a
257 // package's init function when it creates its Vars. If the name is already
258 // registered then this will log.Panic.
259 func Publish(name string, v Var) {
260 if _, dup := vars.LoadOrStore(name, v); dup {
261 log.Panicln("Reuse of exported var name:", name)
263 varKeysMu.Lock()
264 defer varKeysMu.Unlock()
265 varKeys = append(varKeys, name)
266 sort.Strings(varKeys)
269 // Get retrieves a named exported variable. It returns nil if the name has
270 // not been registered.
271 func Get(name string) Var {
272 i, _ := vars.Load(name)
273 v, _ := i.(Var)
274 return v
277 // Convenience functions for creating new exported variables.
279 func NewInt(name string) *Int {
280 v := new(Int)
281 Publish(name, v)
282 return v
285 func NewFloat(name string) *Float {
286 v := new(Float)
287 Publish(name, v)
288 return v
291 func NewMap(name string) *Map {
292 v := new(Map).Init()
293 Publish(name, v)
294 return v
297 func NewString(name string) *String {
298 v := new(String)
299 Publish(name, v)
300 return v
303 // Do calls f for each exported variable.
304 // The global variable map is locked during the iteration,
305 // but existing entries may be concurrently updated.
306 func Do(f func(KeyValue)) {
307 varKeysMu.RLock()
308 defer varKeysMu.RUnlock()
309 for _, k := range varKeys {
310 val, _ := vars.Load(k)
311 f(KeyValue{k, val.(Var)})
315 func expvarHandler(w http.ResponseWriter, r *http.Request) {
316 w.Header().Set("Content-Type", "application/json; charset=utf-8")
317 fmt.Fprintf(w, "{\n")
318 first := true
319 Do(func(kv KeyValue) {
320 if !first {
321 fmt.Fprintf(w, ",\n")
323 first = false
324 fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
326 fmt.Fprintf(w, "\n}\n")
329 // Handler returns the expvar HTTP Handler.
331 // This is only needed to install the handler in a non-standard location.
332 func Handler() http.Handler {
333 return http.HandlerFunc(expvarHandler)
336 func cmdline() interface{} {
337 return os.Args
340 func memstats() interface{} {
341 stats := new(runtime.MemStats)
342 runtime.ReadMemStats(stats)
343 return *stats
346 func init() {
347 http.HandleFunc("/debug/vars", expvarHandler)
348 Publish("cmdline", Func(cmdline))
349 Publish("memstats", Func(memstats))