func StartReadText() { hello := new(Job) hello.text = "hello" hello.i = 0 hello.max = 3 world := new(Job) world.text = "world" world.i = 0 world.max = 5 go ReadText(hello) go ReadText(world) cpus := runtime.GOMAXPROCS(0) fmt.Println(runtime.GOOS, runtime.NumCPU(), runtime.NumCgoCall(), runtime.NumGoroutine(), "list cpu number:", cpus) max := 8 for i := 1; i < max; i++ { go showNumber(i) } //This is because there’s no guarantee as to how //many goroutines, if any, will complete before the end of the main() function runtime.Gosched() fmt.Println("exits!") }
// Prints a summary of go:ngine's *Stats* performance counters when the parent example app exits. func PrintPostLoopSummary() { printStatSummary := func(name string, timing *ng.TimingStats) { fmt.Printf("%v\t\tAvg=%8.3fms\tMax=%8.3fms\n", name, timing.Average()*1000, timing.Max()*1000) } fmt.Printf("Average FPS:\t\t%v (total %v over %v)\n", ng.Stats.AverageFps(), ng.Stats.TotalFrames(), time.Duration(int64(ng.Loop.Time()*1000*1000*1000))) printStatSummary("Full Loop Iteration", &ng.Stats.Frame) printStatSummary("Frame On.EverySec", &ng.Stats.FrameOnSec) printStatSummary("Frame On.AppThread", &ng.Stats.FrameAppThread) printStatSummary("Frame On.WinThread", &ng.Stats.FrameWinThread) printStatSummary("Frame Prep Thread", &ng.Stats.FramePrepThread) printStatSummary("Frame Thread Sync", &ng.Stats.FrameThreadSync) printStatSummary("Frame Render (CPU)", &ng.Stats.FrameRenderCpu) printStatSummary("Frame Render (GPU)", &ng.Stats.FrameRenderGpu) printStatSummary("Frame Render Both", &ng.Stats.FrameRenderBoth) if s := "GC (max. 1x/sec)"; ng.Options.Loop.GcEvery.Frame || ng.Options.Loop.GcEvery.Sec { if ng.Options.Loop.GcEvery.Frame { s = "GC (max 1x/frame)" } printStatSummary(s, &ng.Stats.Gc) if !ng.Options.Loop.GcEvery.Frame { fmt.Printf("Averaged GC/frame cost:\t%1.3fms\n", (ng.Stats.Gc.Average()/ng.Stats.AverageFps())*1000) } } fmt.Printf("Shaders: compiled %v GLSL shader programs over time, which took %v in total.\n", ng.Stats.Programs.NumProgsCompiled, time.Duration(ng.Stats.Programs.TotalTimeCost)) cgoPerFrame, numTotalFrames := int64(0), ng.Stats.TotalFrames() if numTotalFrames != 0 { cgoPerFrame = runtime.NumCgoCall() / int64(ng.Stats.TotalFrames()) } fmt.Printf("CGO calls: pre-loop init %v, loop %v (avg. %v/frame)\n\n", numCgo.preLoop, numCgo.postLoop-numCgo.preLoop, cgoPerFrame) }
func (gui *Gui) setStatsPane() { var memStats runtime.MemStats runtime.ReadMemStats(&memStats) statsPane := gui.getObjectByName("statsPane") statsPane.Set("text", fmt.Sprintf(`###### Mist %s (%s) ####### eth %d (p2p = %d) CPU: # %d Goroutines: # %d CGoCalls: # %d Alloc: %d Heap Alloc: %d CGNext: %x NumGC: %d `, Version, runtime.Version(), eth.ProtocolVersion, 2, runtime.NumCPU, runtime.NumGoroutine(), runtime.NumCgoCall(), memStats.Alloc, memStats.HeapAlloc, memStats.NextGC, memStats.NumGC, )) }
func (metrica *noCgoCallsMetrica) GetValue() (float64, error) { currentValue := runtime.NumCgoCall() value := float64(currentValue - metrica.lastValue) metrica.lastValue = currentValue return value, nil }
func ShowAdmin(res http.ResponseWriter, req *http.Request, base *BaseController) { // TODO: add total transactions male_players := models.GetMalePlayers() female_players := models.GetFemalePlayers() m := &runtime.MemStats{} runtime.ReadMemStats(m) online_records, err := models.GetOnlineRecords() if err != nil { http.Error(res, "Error while getting online records: "+err.Error(), 500) return } views.Parser.ExecuteTemplate(res, "admin.html", &AdminOverviewResponse{ male_players, female_players, models.GetSorcererPlayers(), models.GetDruidPlayers(), models.GetPaladinPlayers(), models.GetKnightPlayers(), models.GetTotalAccounts(), models.GetTotalPlayers(), m, runtime.NumCPU(), runtime.NumGoroutine(), runtime.NumCgoCall(), runtime.Version(), online_records, }) }
func main() { log.Println("Version=", runtime.Version()) log.Println("GOMAXPROCS=", runtime.GOMAXPROCS(0)) log.Println("NumCPUs=", runtime.NumCPU()) log.Println("NumCgoCall=", runtime.NumCgoCall()) log.Println("NumGoroutines=", runtime.NumGoroutine()) debug.PrintStack() }
// SampleEnvironment queries the runtime system for various interesting metrics, // storing the resulting values in the set of metric gauges maintained by // RuntimeStatSampler. This makes runtime statistics more convenient for // consumption by the time series and status systems. // // This method should be called periodically by a higher level system in order // to keep runtime statistics current. func (rsr *RuntimeStatSampler) SampleEnvironment() { // Record memory and call stats from the runtime package. // TODO(mrtracy): memory statistics will not include usage from RocksDB. // Determine an appropriate way to compute total memory usage. numCgoCall := runtime.NumCgoCall() numGoroutine := runtime.NumGoroutine() // It might be useful to call ReadMemStats() more often, but it stops the // world while collecting stats so shouldn't be called too often. ms := runtime.MemStats{} runtime.ReadMemStats(&ms) // Record CPU statistics using syscall package. ru := syscall.Rusage{} if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { log.Errorf("Getrusage failed: %v", err) } // Time statistics can be compared to the total elapsed time to create a // useful percentage of total CPU usage, which would be somewhat less accurate // if calculated later using downsampled time series data. now := rsr.clock.PhysicalNow() dur := float64(now - rsr.lastNow) newUtime := ru.Utime.Nano() newStime := ru.Stime.Nano() uPerc := float64(newUtime-rsr.lastUtime) / dur sPerc := float64(newStime-rsr.lastStime) / dur pausePerc := float64(ms.PauseTotalNs-rsr.lastPauseTime) / dur rsr.lastNow = now rsr.lastUtime = newUtime rsr.lastStime = newStime rsr.lastPauseTime = ms.PauseTotalNs // Log summary of statistics to console, if requested. activeMiB := float64(ms.Alloc) / (1 << 20) cgoRate := float64((numCgoCall-rsr.lastCgoCall)*int64(time.Second)) / dur log.Infof("runtime stats: %d goroutines, %.2fMiB active, %.2fcgo/sec, %.2f/%.2f %%(u/s)time, %.2f %%gc (%dx)", numGoroutine, activeMiB, cgoRate, uPerc, sPerc, pausePerc, ms.NumGC-rsr.lastNumGC) if log.V(2) { log.Infof("memstats: %+v", ms) } if logOSStats != nil { logOSStats() } rsr.lastCgoCall = numCgoCall rsr.lastNumGC = ms.NumGC rsr.cgoCalls.Update(numCgoCall) rsr.goroutines.Update(int64(numGoroutine)) rsr.allocBytes.Update(int64(ms.Alloc)) rsr.gcCount.Update(int64(ms.NumGC)) rsr.gcPauseNS.Update(int64(ms.PauseTotalNs)) rsr.gcPausePercent.Update(pausePerc) rsr.cpuUserNS.Update(newUtime) rsr.cpuUserPercent.Update(uPerc) rsr.cpuSysNS.Update(newStime) rsr.cpuSysPercent.Update(sPerc) }
// capture does a one time collection of DeferStats func (c *Client) capture() { var mem runtime.MemStats var gc debug.GCStats mems := "" if c.GrabMem { runtime.ReadMemStats(&mem) mems = strconv.FormatUint(mem.Alloc, 10) } gcs := "" if c.GrabGC { debug.ReadGCStats(&gc) gcs = strconv.FormatInt(gc.NumGC, 10) } grs := "" if c.GrabGR { grs = strconv.Itoa(runtime.NumGoroutine()) } cgos := "" if c.GrabCgo { cgos = strconv.FormatInt(runtime.NumCgoCall(), 10) } fds := "" if c.GrabFd { fds = strconv.Itoa(openFileCnt()) } ds := DeferStats{ Mem: mems, GoRoutines: grs, Cgos: cgos, Fds: fds, HTTPs: curlist.List(), DBs: Querylist.List(), GC: gcs, } // FIXME // empty our https/dbs curlist.Reset() Querylist.Reset() go func() { b, err := json.Marshal(ds) if err != nil { log.Println(err) } c.BaseClient.Postit(b, c.statsUrl) }() }
// Status will return the current status of this system func (ctx *BroadcastContext) Status() (*BroadcastServerStatus, error) { status := new(BroadcastServerStatus) status.NumGoroutines = runtime.NumGoroutine() status.NumCpu = runtime.NumCPU() status.NumCgoCall = runtime.NumCgoCall() status.NumClients = ctx.ClientSize status.Memory = new(runtime.MemStats) runtime.ReadMemStats(status.Memory) return status, nil }
// GetTimeSeriesData returns a slice of TimeSeriesData updates based on current // runtime statistics. // // Calling this method will query various system packages for runtime statistics // and convert the information to time series data. This is currently done in // one method because it is convenient; however, in the future querying and // recording can be easily separated, similar to the way that NodeStatus is // separated into a monitor and a recorder. func (rsr *RuntimeStatRecorder) GetTimeSeriesData() []ts.TimeSeriesData { data := make([]ts.TimeSeriesData, 0, rsr.lastDataCount) // Record memory and call stats from the runtime package. // TODO(mrtracy): memory statistics will not include usage from RocksDB. // Determine an appropriate way to compute total memory usage. numCgoCall := runtime.NumCgoCall() numGoroutine := runtime.NumGoroutine() ms := runtime.MemStats{} runtime.ReadMemStats(&ms) // Record CPU statistics using syscall package. ru := syscall.Rusage{} if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil { log.Errorf("Getrusage failed: %v", err) } // Time statistics can be compared to the total elapsed time to create a // useful percentage of total CPU usage, which would be somewhat less accurate // if calculated later using downsampled time series data. now := rsr.clock.PhysicalNow() dur := float64(now - rsr.lastNow) newUtime := ru.Utime.Nano() newStime := ru.Stime.Nano() uPerc := float64(newUtime-rsr.lastUtime) / dur sPerc := float64(newStime-rsr.lastStime) / dur pausePerc := float64(ms.PauseTotalNs-rsr.lastPauseTime) / dur rsr.lastNow = now rsr.lastUtime = newUtime rsr.lastStime = newStime rsr.lastPauseTime = ms.PauseTotalNs // Log summary of statistics to console, if requested. if log.V(1) { activeMiB := float64(ms.Alloc) / (1 << 20) cgoRate := float64((numCgoCall-rsr.lastCgoCall)*int64(time.Second)) / dur log.Infof("runtime stats: %d goroutines, %.2fMiB active, %.2fcgo/sec, %.2f/%.2f %%(u/s)time, %.2f %%gc (%dx)", numGoroutine, activeMiB, cgoRate, uPerc, sPerc, pausePerc, ms.NumGC-rsr.lastNumGC) rsr.lastCgoCall = numCgoCall rsr.lastNumGC = ms.NumGC } data = append(data, rsr.record(now, "cgocalls", float64(numCgoCall))) data = append(data, rsr.record(now, "goroutines", float64(numGoroutine))) data = append(data, rsr.record(now, "allocbytes", float64(ms.Alloc))) data = append(data, rsr.record(now, "gc.count", float64(ms.NumGC))) data = append(data, rsr.record(now, "gc.pause.ns", float64(ms.PauseTotalNs))) data = append(data, rsr.record(now, "gc.pause.percent", pausePerc)) data = append(data, rsr.record(now, "cpu.user.ns", float64(newUtime))) data = append(data, rsr.record(now, "cpu.user.percent", uPerc)) data = append(data, rsr.record(now, "cpu.sys.ns", float64(newStime))) data = append(data, rsr.record(now, "cpu.sys.percent", sPerc)) rsr.lastDataCount = len(data) return data }
// a few simple stats from go runtime, in your app, if you want these // add them as a metrics function // // func init() { // metrics.AddMetricsFunction(metrics.GoRuntimeMetrics) // } func GoRuntimeMetrics(snap *Snapshot) { snap.Ints["go_cgocall.ct"] = uint64(runtime.NumCgoCall()) snap.Ints["go_numgoroutine.ct"] = uint64(runtime.NumGoroutine()) // http://weekly.golang.org/pkg/runtime/#MemStats runtime.ReadMemStats(&rtMem) snap.Ints["go_memalloc.avg"] = rtMem.Alloc / 1048576 snap.Ints["go_memtotalloc.avg"] = rtMem.TotalAlloc / 1048576 snap.Ints["go_memsys.avg"] = rtMem.Sys / 1048576 }
func SysInfo(job *Job) ([]byte, error) { return json.Marshal(&systemInfo{ GOOS: runtime.GOOS, GOARCH: runtime.GOARCH, GOROOT: runtime.GOROOT(), Version: runtime.Version(), NumCPU: runtime.NumCPU(), NumGoroutine: runtime.NumGoroutine(), NumCgoCall: runtime.NumCgoCall(), }) }
func main() { go func() { fmt.Println("before") runtime.Goexit() fmt.Println("after") }() fmt.Println(runtime.GOROOT(), runtime.GOMAXPROCS(0), runtime.NumCPU(), runtime.NumCgoCall()) <-time.After(time.Second * 2) }
func RESTGetRuntimeStats(w http.ResponseWriter, r *http.Request) { MustEncode(w, map[string]interface{}{ "currTime": time.Now(), "startTime": StartTime, "go": map[string]interface{}{ "numGoroutine": runtime.NumGoroutine(), "numCgoCall": runtime.NumCgoCall(), "memProfileRate": runtime.MemProfileRate, }, }) }
// golang stats func GoStats() []byte { res := map[string]interface{}{} res["compiler"] = runtime.Compiler res["arch"] = runtime.GOARCH res["os"] = runtime.GOOS res["max_procs"] = runtime.GOMAXPROCS(-1) res["root"] = runtime.GOROOT() res["cgo_call"] = runtime.NumCgoCall() res["goroutine_num"] = runtime.NumGoroutine() res["version"] = runtime.Version() return jsonRes(res) }
func cliDebug(c *minicli.Command) *minicli.Response { return &minicli.Response{ Host: hostname, Header: []string{"Go version", "Goroutines", "CGO calls"}, Tabular: [][]string{ []string{ runtime.Version(), strconv.Itoa(runtime.NumGoroutine()), strconv.FormatInt(runtime.NumCgoCall(), 10), }, }, } }
func (s *runtimeMetrics) Metrics() map[string]interface{} { runtime.ReadMemStats(&s.memStats) return map[string]interface{}{ "Mallocs": CounterValue(s.memStats.Mallocs), "Frees": CounterValue(s.memStats.Frees), "heap/HeapAlloc": GaugeValue(s.memStats.HeapAlloc), "heap/HeapObjects": GaugeValue(s.memStats.HeapObjects), "gc/NumGC": CounterValue(s.memStats.NumGC), "gc/PauseTotalNs": CounterValue(s.memStats.PauseTotalNs), "Goroutines": GaugeValue(runtime.NumGoroutine()), "CgoCalls": CounterValue(runtime.NumCgoCall()), } }
func main() { // var goos string = os.Getenv("GOOS") var goos = runtime.GOOS fmt.Printf("The operating system is: %s\n", goos) path := os.Getenv("PATH") fmt.Printf("Path is %s\n", path) fmt.Println("runtime.Compiler is", runtime.Compiler) fmt.Println("runtime.GOARCH is", runtime.GOARCH) fmt.Println("runtime.NumCPU() is", runtime.NumCPU()) fmt.Println("runtime.NumGgoCall() is", runtime.NumCgoCall()) fmt.Println("runtime.NumGoroutine() is", runtime.NumGoroutine()) fmt.Println("runtime.Version() is", runtime.Version()) }
func (i *info) dumpServer(buf *bytes.Buffer) { buf.WriteString("# Server\r\n") i.dumpPairs(buf, infoPair{"os", i.Server.OS}, infoPair{"process_id", i.Server.ProceessId}, infoPair{"addr", i.app.cfg.Addr}, infoPair{"http_addr", i.app.cfg.HttpAddr}, infoPair{"readonly", i.app.cfg.Readonly}, infoPair{"goroutine_num", runtime.NumGoroutine()}, infoPair{"cgo_call_num", runtime.NumCgoCall()}, infoPair{"resp_client_num", i.app.respClientNum()}, ) }
func GetInfo() interface{} { d := time.Now().Sub(started) return Info{ HasDbXML: has_dbxml, QueueLen: len(chWork), QueueCap: cap(chWork), NumCPU: runtime.NumCPU(), NumCgoCall: runtime.NumCgoCall(), NumGoroutine: runtime.NumGoroutine(), Uptime: d, UptimeString: d.String(), Version: runtime.Version(), } }
func (c *Collector) outputStats() { if c.EnableCPU { // Goroutines c.gaugeFunc("cpu.goroutines", uint64(runtime.NumGoroutine())) // CGo calls c.gaugeFunc("cpu.cgo_calls", uint64(runtime.NumCgoCall())) } if c.EnableMem { m := &runtime.MemStats{} runtime.ReadMemStats(m) // General c.gaugeFunc("mem.alloc", m.Alloc) c.gaugeFunc("mem.total", m.TotalAlloc) c.gaugeFunc("mem.sys", m.Sys) c.gaugeFunc("mem.lookups", m.Lookups) c.gaugeFunc("mem.malloc", m.Mallocs) c.gaugeFunc("mem.frees", m.Frees) // Heap c.gaugeFunc("mem.heap.alloc", m.HeapAlloc) c.gaugeFunc("mem.heap.sys", m.HeapSys) c.gaugeFunc("mem.heap.idle", m.HeapIdle) c.gaugeFunc("mem.heap.inuse", m.HeapInuse) c.gaugeFunc("mem.heap.released", m.HeapReleased) c.gaugeFunc("mem.heap.objects", m.HeapObjects) // Stack c.gaugeFunc("mem.stack.inuse", m.StackInuse) c.gaugeFunc("mem.stack.sys", m.StackSys) c.gaugeFunc("mem.stack.mspan_inuse", m.MSpanInuse) c.gaugeFunc("mem.stack.mspan_sys", m.MSpanSys) c.gaugeFunc("mem.stack.mcache_inuse", m.MCacheInuse) c.gaugeFunc("mem.stack.mcache_sys", m.MCacheSys) c.gaugeFunc("mem.othersys", m.OtherSys) if c.EnableGC { // GC c.gaugeFunc("mem.gc.sys", m.GCSys) c.gaugeFunc("mem.gc.next", m.NextGC) c.gaugeFunc("mem.gc.last", m.LastGC) c.gaugeFunc("mem.gc.pause_total", m.PauseTotalNs) c.gaugeFunc("mem.gc.pause", m.PauseNs[(m.NumGC+255)%256]) c.gaugeFunc("mem.gc.count", uint64(m.NumGC)) } } }
func init() { start := time.Now() Publish("runtime", map[string]interface{}{ "cgocalls": Func(func() interface{} { return runtime.NumCgoCall() }), "goroutines": Func(func() interface{} { return runtime.NumGoroutine() }), "version": runtime.Version(), "memstats": Func(func() interface{} { var ms runtime.MemStats runtime.ReadMemStats(&ms) return &ms }), }) Publish("uptimeSeconds", Func(func() interface{} { return int(time.Now().Sub(start) / time.Second) })) Publish("cmdline", &os.Args) }
// Capture new values for the Go runtime statistics exported in // runtime.MemStats. This is designed to be called in a background // goroutine. Giving a registry which has not been given to // RegisterRuntimeMemStats will panic. func CaptureRuntimeMemStatsOnce(r Registry) { runtime.ReadMemStats(&memStats) r.Get("runtime.MemStats.Alloc").(Gauge).Update(int64(memStats.Alloc)) r.Get("runtime.MemStats.TotalAlloc").(Gauge).Update(int64(memStats.TotalAlloc)) r.Get("runtime.MemStats.Sys").(Gauge).Update(int64(memStats.Sys)) r.Get("runtime.MemStats.Lookups").(Gauge).Update(int64(memStats.Lookups)) r.Get("runtime.MemStats.Mallocs").(Gauge).Update(int64(memStats.Mallocs)) r.Get("runtime.MemStats.Frees").(Gauge).Update(int64(memStats.Frees)) r.Get("runtime.MemStats.HeapAlloc").(Gauge).Update(int64(memStats.HeapAlloc)) r.Get("runtime.MemStats.HeapSys").(Gauge).Update(int64(memStats.HeapSys)) r.Get("runtime.MemStats.HeapIdle").(Gauge).Update(int64(memStats.HeapIdle)) r.Get("runtime.MemStats.HeapInuse").(Gauge).Update(int64(memStats.HeapInuse)) r.Get("runtime.MemStats.HeapReleased").(Gauge).Update(int64(memStats.HeapReleased)) r.Get("runtime.MemStats.HeapObjects").(Gauge).Update(int64(memStats.HeapObjects)) r.Get("runtime.MemStats.StackInuse").(Gauge).Update(int64(memStats.StackInuse)) r.Get("runtime.MemStats.StackSys").(Gauge).Update(int64(memStats.StackSys)) r.Get("runtime.MemStats.MSpanInuse").(Gauge).Update(int64(memStats.MSpanInuse)) r.Get("runtime.MemStats.MSpanSys").(Gauge).Update(int64(memStats.MSpanSys)) r.Get("runtime.MemStats.MCacheInuse").(Gauge).Update(int64(memStats.MCacheInuse)) r.Get("runtime.MemStats.MCacheSys").(Gauge).Update(int64(memStats.MCacheSys)) r.Get("runtime.MemStats.BuckHashSys").(Gauge).Update(int64(memStats.BuckHashSys)) r.Get("runtime.MemStats.NextGC").(Gauge).Update(int64(memStats.NextGC)) r.Get("runtime.MemStats.LastGC").(Gauge).Update(int64(memStats.LastGC)) r.Get("runtime.MemStats.PauseTotalNs").(Gauge).Update(int64(memStats.PauseTotalNs)) // <https://code.google.com/p/go/source/browse/src/pkg/runtime/mgc0.c> for i := uint32(1); i <= memStats.NumGC-numGC; i++ { r.Get("runtime.MemStats.PauseNs").(Histogram).Update(int64(memStats.PauseNs[(memStats.NumGC%256-i)%256])) } r.Get("runtime.MemStats.NumGC").(Gauge).Update(int64(memStats.NumGC)) if memStats.EnableGC { r.Get("runtime.MemStats.EnableGC").(Gauge).Update(1) } else { r.Get("runtime.MemStats.EnableGC").(Gauge).Update(0) } if memStats.EnableGC { r.Get("runtime.MemStats.DebugGC").(Gauge).Update(1) } else { r.Get("runtime.MemStats.DebugGC").(Gauge).Update(0) } r.Get("runtime.NumCgoCall").(Gauge).Update(int64(runtime.NumCgoCall())) r.Get("runtime.NumGoroutine").(Gauge).Update(int64(runtime.NumGoroutine())) }
// Main entry point func main() { // Set defaults for the server configuration Conf = &goserv.BaseConfiguration{ BindAddress: "0.0.0.0", BindPort: 80, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, LogLevel: "info", } // Create a function that returns a struct for use with FuncHandler GetMemStats := func() interface{} { ms := runtime.MemStats{} runtime.ReadMemStats(&ms) return ms } // Bind it http.HandleFunc("/status/memory", goserv.FuncHandler(GetMemStats, true)) // Create a function that returns an interface for use with FuncHandler SysStats := func() interface{} { return map[string]interface{}{ "CPUCount": runtime.NumCPU(), "GoroutineCount": runtime.NumGoroutine(), "CGoCallCount": runtime.NumCgoCall(), "GoVersion": runtime.Version(), } } // Bind it and log http.HandleFunc("/status/sys", goserv.FuncHandler(SysStats, true)) // Bind a struct with StructHandler and use RestrictByIP // middleware to only allow specified IP addresses http.HandleFunc( "/status/config", goserv.RestrictByIP( goserv.StructHandler(Conf, true), []string{"127.0.0.1"})) // Make a new server. server := goserv.NewServer(Conf) // Log that we are listing goserv.Logger.Infof("Listening for connections on %s", server.Addr) // And listen for connections server.ListenAndServe() }
func handleInternalRuntime(arg3 []byte) interface{} { var opts GoRuntimeStateOptions json.Unmarshal(arg3, &opts) state := GoRuntimeState{ NumGoroutines: runtime.NumGoroutine(), NumCPU: runtime.NumCPU(), NumCGo: runtime.NumCgoCall(), } runtime.ReadMemStats(&state.MemStats) if opts.IncludeGoStacks { state.GoStacks = getStacks() } return state }
func (this *runtimeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "must-revalidate,no-cache,no-store") runtime.ReadMemStats(&memstats) js := make(map[string]interface{}) js["gomaxprocs"] = runtime.GOMAXPROCS(0) js["numcgocall"] = runtime.NumCgoCall() js["numcpu"] = runtime.NumCPU() js["numgoroutine"] = runtime.NumGoroutine() js["memstats"] = memstats js1, err := json.Marshal(js) if err != nil { panic(err) } w.Header().Set("Content-Type", "application/json") w.Write([]byte(js1)) }
// Collect memory usage metrics func (mb *SquareMetrics) collectSystemMetrics() { var mem runtime.MemStats update := func(name string, value uint64) { metrics.GetOrRegisterGauge(name, mb.registry).Update(int64(value)) } updateFloat := func(name string, value float64) { metrics.GetOrRegisterGaugeFloat64(name, mb.registry).Update(value) } sample := metrics.NewExpDecaySample(1028, 0.015) gcHistogram := metrics.GetOrRegisterHistogram("runtime.mem.gc.duration", mb.registry, sample) var observedPauses uint32 for range time.Tick(mb.interval) { runtime.ReadMemStats(&mem) update("runtime.mem.alloc", mem.Alloc) update("runtime.mem.total-alloc", mem.TotalAlloc) update("runtime.mem.sys", mem.Sys) update("runtime.mem.lookups", mem.Lookups) update("runtime.mem.mallocs", mem.Mallocs) update("runtime.mem.frees", mem.Frees) update("runtime.mem.heap.alloc", mem.HeapAlloc) update("runtime.mem.heap.sys", mem.HeapSys) update("runtime.mem.heap.idle", mem.HeapIdle) update("runtime.mem.heap.inuse", mem.HeapInuse) update("runtime.mem.heap.released", mem.HeapReleased) update("runtime.mem.heap.objects", mem.HeapObjects) update("runtime.mem.stack.inuse", mem.StackInuse) update("runtime.mem.stack.sys", mem.StackSys) update("runtime.goroutines", uint64(runtime.NumGoroutine())) update("runtime.cgo-calls", uint64(runtime.NumCgoCall())) update("runtime.mem.gc.num-gc", uint64(mem.NumGC)) updateFloat("runtime.mem.gc.cpu-fraction", mem.GCCPUFraction) // Update histogram of GC pauses for ; observedPauses < mem.NumGC; observedPauses++ { gcHistogram.Update(int64(mem.PauseNs[(observedPauses+1)%256])) } } }
// collect & publish to statsd func collect() { tag := "" if hostname, err := os.Hostname(); err == nil { tag += hostname } else { log.Warning(SERVICE, err) } // executable name if exe_name, err := os.Readlink("/proc/self/exe"); err == nil { tag += "." + path.Base(exe_name) } else { tag += fmt.Sprintf(".%v", os.Getpid()) log.Warning(SERVICE, err) } memstats := &runtime.MemStats{} runtime.ReadMemStats(memstats) _statter.Counter(1.0, tag+".NumGoroutine", int(runtime.NumGoroutine())) _statter.Counter(1.0, tag+".NumCgoCall", int(runtime.NumCgoCall())) if memstats.NumGC > 0 { _statter.Counter(1.0, tag+".NumGC", int(memstats.NumGC)) _statter.Timing(1.0, tag+".PauseTotal", time.Duration(memstats.PauseTotalNs)) _statter.Timing(1.0, tag+".LastPause", time.Duration(memstats.PauseNs[(memstats.NumGC+255)%256])) _statter.Counter(1.0, tag+".Alloc", int(memstats.Alloc)) _statter.Counter(1.0, tag+".TotalAlloc", int(memstats.TotalAlloc)) _statter.Counter(1.0, tag+".Sys", int(memstats.Sys)) _statter.Counter(1.0, tag+".Lookups", int(memstats.Lookups)) _statter.Counter(1.0, tag+".Mallocs", int(memstats.Mallocs)) _statter.Counter(1.0, tag+".Frees", int(memstats.Frees)) _statter.Counter(1.0, tag+".HeapAlloc", int(memstats.HeapAlloc)) _statter.Counter(1.0, tag+".HeapSys", int(memstats.HeapSys)) _statter.Counter(1.0, tag+".HeapIdle", int(memstats.HeapIdle)) _statter.Counter(1.0, tag+".HeapInuse", int(memstats.HeapInuse)) _statter.Counter(1.0, tag+".HeapReleased", int(memstats.HeapReleased)) _statter.Counter(1.0, tag+".HeapObjects", int(memstats.HeapObjects)) _statter.Counter(1.0, tag+".StackInuse", int(memstats.StackInuse)) _statter.Counter(1.0, tag+".StackSys", int(memstats.StackSys)) _statter.Counter(1.0, tag+".MSpanInuse", int(memstats.MSpanInuse)) _statter.Counter(1.0, tag+".MSpanSys", int(memstats.MSpanSys)) _statter.Counter(1.0, tag+".MCacheInuse", int(memstats.MCacheInuse)) _statter.Counter(1.0, tag+".MCacheSys", int(memstats.MCacheSys)) _statter.Counter(1.0, tag+".BuckHashSys", int(memstats.BuckHashSys)) _statter.Counter(1.0, tag+".GCSys", int(memstats.GCSys)) _statter.Counter(1.0, tag+".OtherSys", int(memstats.OtherSys)) } }
func restGetRuntime(w http.ResponseWriter, r *http.Request) { jsonEncode(w, map[string]interface{}{ "startTime": startTime, "arch": runtime.GOARCH, "os": runtime.GOOS, "numCPU": runtime.NumCPU(), "go": map[string]interface{}{ "GOMAXPROCS": runtime.GOMAXPROCS(0), "GOROOT": runtime.GOROOT(), "version": runtime.Version(), "numGoroutine": runtime.NumGoroutine(), "numCgoCall": runtime.NumCgoCall(), "compiler": runtime.Compiler, "memProfileRate": runtime.MemProfileRate, }, }) }
// Capture new values for the Go runtime statistics exported in // runtime.MemStats. This is designed to be called in a background // goroutine. Giving a registry which has not been given to // RegisterRuntimeMemStats will panic. If the second parameter is // false, the counters will be left to the lazy updates provided by // the runtime. func CaptureRuntimeMemStats(r Registry, readMemStats bool) { var m runtime.MemStats if readMemStats { runtime.ReadMemStats(&m) } r.Get("runtime.MemStats.Alloc").(Gauge).Update(int64(m.Alloc)) r.Get("runtime.MemStats.TotalAlloc").(Gauge).Update(int64(m.TotalAlloc)) r.Get("runtime.MemStats.Sys").(Gauge).Update(int64(m.Sys)) r.Get("runtime.MemStats.Lookups").(Gauge).Update(int64(m.Lookups)) r.Get("runtime.MemStats.Mallocs").(Gauge).Update(int64(m.Mallocs)) r.Get("runtime.MemStats.Frees").(Gauge).Update(int64(m.Frees)) r.Get("runtime.MemStats.HeapAlloc").(Gauge).Update(int64(m.HeapAlloc)) r.Get("runtime.MemStats.HeapSys").(Gauge).Update(int64(m.HeapSys)) r.Get("runtime.MemStats.HeapIdle").(Gauge).Update(int64(m.HeapIdle)) r.Get("runtime.MemStats.HeapInuse").(Gauge).Update(int64(m.HeapInuse)) r.Get("runtime.MemStats.HeapObjects").(Gauge).Update(int64(m.HeapObjects)) r.Get("runtime.MemStats.StackInuse").(Gauge).Update(int64(m.StackInuse)) r.Get("runtime.MemStats.StackSys").(Gauge).Update(int64(m.StackSys)) r.Get("runtime.MemStats.MSpanInuse").(Gauge).Update(int64(m.MSpanInuse)) r.Get("runtime.MemStats.MSpanSys").(Gauge).Update(int64(m.MSpanSys)) r.Get("runtime.MemStats.MCacheInuse").(Gauge).Update(int64(m.MCacheInuse)) r.Get("runtime.MemStats.MCacheSys").(Gauge).Update(int64(m.MCacheSys)) r.Get("runtime.MemStats.BuckHashSys").(Gauge).Update(int64(m.BuckHashSys)) r.Get("runtime.MemStats.NextGC").(Gauge).Update(int64(m.NextGC)) r.Get("runtime.MemStats.PauseTotalNs").(Gauge).Update(int64(m.PauseTotalNs)) r.Get("runtime.MemStats.PauseNs").(Histogram).Update(int64(m.PauseNs[0])) r.Get("runtime.MemStats.NumGC").(Gauge).Update(int64(m.NumGC)) if m.EnableGC { r.Get("runtime.MemStats.EnableGC").(Gauge).Update(1) } else { r.Get("runtime.MemStats.EnableGC").(Gauge).Update(0) } if m.EnableGC { r.Get("runtime.MemStats.DebugGC").(Gauge).Update(1) } else { r.Get("runtime.MemStats.DebugGC").(Gauge).Update(0) } r.Get("runtime.NumCgoCall").(Gauge).Update(int64(runtime.NumCgoCall())) r.Get("runtime.NumGoroutine").(Gauge).Update(int64(runtime.NumGoroutine())) }