1
0
mirror of https://github.com/divan/expvarmon.git synced 2025-04-27 13:48:55 +08:00

Refactoring

This commit is contained in:
Ivan Daniluk 2015-04-25 15:54:17 +03:00
parent d73f7f469f
commit 676cbb2081
10 changed files with 145 additions and 97 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
termstats termstats
*.swp

15
cmdline.go Normal file
View File

@ -0,0 +1,15 @@
package main
import (
"path/filepath"
)
// BaseCommand returns cleaned command name from Cmdline array.
//
// I.e. "./some.service/binary.name -arg 1 -arg" will be "binary.name".
func BaseCommand(cmdline []string) string {
if len(cmdline) == 0 {
return ""
}
return filepath.Base(cmdline[0])
}

31
data.go Normal file
View File

@ -0,0 +1,31 @@
package main
import "time"
// Data represents data to be passed to UI.
type Data struct {
Services Services
TotalMemory *Stack
LastTimestamp time.Time
}
// NewData inits and return new data object.
func NewData() *Data {
return &Data{
TotalMemory: NewStack(140),
}
}
// FindService returns existing service by port.
func (d *Data) FindService(port string) *Service {
if d.Services == nil {
return nil
}
for _, service := range d.Services {
if service.Port == port {
return service
}
}
return nil
}

View File

@ -2,16 +2,13 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/http"
"runtime" "runtime"
) )
// Expvars holds all vars we support via expvars. It implements Source interface.
const ExpvarsUrl = "/debug/vars" const ExpvarsUrl = "/debug/vars"
// ExpvarsSource implements Source interface for retrieving Expvars.
type ExpvarsSource struct { type ExpvarsSource struct {
Ports []string Ports []string
} }
@ -19,9 +16,8 @@ type ExpvarsSource struct {
type Expvars map[string]Expvar type Expvars map[string]Expvar
type Expvar struct { type Expvar struct {
MemStats *runtime.MemStats `json:"memstats"` MemStats *runtime.MemStats `json:"memstats"`
Cmdline []string `json:"cmdline"` Cmdline []string `json:"cmdline"`
Goroutines int64 `json:"goroutines,omitempty"`
Err error `json:"-,omitempty"` Err error `json:"-,omitempty"`
} }
@ -32,37 +28,6 @@ func NewExpvarsSource(ports []string) *ExpvarsSource {
} }
} }
func (e *ExpvarsSource) Update() (interface{}, error) {
vars := make(Expvars)
for _, port := range e.Ports {
addr := fmt.Sprintf("http://localhost:%s%s", port, ExpvarsUrl)
resp, err := http.Get(addr)
if err != nil {
expvar := &Expvar{}
expvar.Err = err
vars[port] = *expvar
continue
}
if resp.StatusCode == http.StatusNotFound {
expvar := &Expvar{}
expvar.Err = fmt.Errorf("Page not found. Did you import expvars?")
vars[port] = *expvar
continue
}
defer resp.Body.Close()
expvar, err := ParseExpvar(resp.Body)
if err != nil {
expvar = &Expvar{}
expvar.Err = err
}
vars[port] = *expvar
}
return vars, nil
}
// ParseExpvar unmarshals data to Expvar variable. // ParseExpvar unmarshals data to Expvar variable.
func ParseExpvar(r io.Reader) (*Expvar, error) { func ParseExpvar(r io.Reader) (*Expvar, error) {
var vars Expvar var vars Expvar

6
expvars_advanced.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,10 @@ import (
"testing" "testing"
) )
const expvarsTestFile = "./expvars.json" const (
expvarsTestFile = "./expvars.json"
expvarsAdvTestFile = "./expvars_advanced.json"
)
func TestExpvars(t *testing.T) { func TestExpvars(t *testing.T) {
file, err := os.Open(expvarsTestFile) file, err := os.Open(expvarsTestFile)
@ -23,3 +26,36 @@ func TestExpvars(t *testing.T) {
t.Fatalf("Cmdline should have 3 items, but has %d", len(vars.Cmdline)) t.Fatalf("Cmdline should have 3 items, but has %d", len(vars.Cmdline))
} }
} }
/*
func TestExpvarsAdvanced(t *testing.T) {
file, err := os.Open(expvarsAdvTestFile)
if err != nil {
t.Fatalf("cannot open test file %v", err)
}
defer file.Close()
vars, err := ParseExpvar(file)
if err != nil {
t.Fatal(err)
}
if len(vars.Vars) != 4 {
t.Fatalf("vars should have 2 items, but has %d", len(vars.Vars))
}
if int(vars.Vars["goroutines"].(float64)) != 10 {
t.Logf("Expecting 'goroutines' to be %d, but got %d", 10, vars.Vars["goroutines"])
}
counters := vars.Vars["counters"].(map[string]interface{})
counterA := counters["A"].(float64)
counterB := counters["B"].(float64)
if counterA != 123.12 {
t.Logf("Expecting 'counter.A' to be %f, but got %f", 123.12, counterA)
}
if int(counterB) != 245342 {
t.Logf("Expecting 'counter.B' to be %d, but got %d", 245342, counterB)
}
}
*/

34
main.go
View File

@ -3,8 +3,6 @@ package main
import ( import (
"flag" "flag"
"log" "log"
"path/filepath"
"strings"
"time" "time"
"github.com/gizak/termui" "github.com/gizak/termui"
@ -24,7 +22,7 @@ func main() {
} }
data := *NewData() data := *NewData()
var source Source = NewExpvarsSource(ports) var source = NewExpvarsSource(ports)
for _, port := range ports { for _, port := range ports {
service := NewService(port) service := NewService(port)
data.Services = append(data.Services, service) data.Services = append(data.Services, service)
@ -41,31 +39,17 @@ func main() {
evtCh := termui.EventCh() evtCh := termui.EventCh()
update := func() { update := func() {
d, err := source.Update() for _, port := range source.Ports {
if err != nil { service := data.FindService(port)
log.Println("[ERROR] Cannot update data from source:", err) if service == nil {
return continue
}
switch source.(type) {
case *ExpvarsSource:
dat := d.(Expvars)
for _, port := range source.(*ExpvarsSource).Ports {
service := data.FindService(port)
if service == nil {
continue
}
service.Err = dat[port].Err
service.Memstats = dat[port].MemStats
service.Goroutines = dat[port].Goroutines
service.Cmdline = strings.Join(dat[port].Cmdline, " ")
if dat[port].Cmdline != nil {
service.Name = filepath.Base(dat[port].Cmdline[0])
}
} }
service.Update()
} }
data.LastTimestamp = time.Now() data.LastTimestamp = time.Now()
ui.Update(data) ui.Update(data)
} }
update() update()

View File

@ -1,33 +1,21 @@
package main package main
import ( import (
"fmt"
"net/http"
"runtime" "runtime"
"time" "strings"
) )
// Data represents data to be passed to UI.
type Data struct {
Services Services
TotalMemory *Stack
LastTimestamp time.Time
}
func NewData() *Data {
return &Data{
TotalMemory: NewStack(140),
}
}
type Services []*Service type Services []*Service
// Service represents constantly updating info about single service. // Service represents constantly updating info about single service.
type Service struct { type Service struct {
Name string Port string
Port string Name string
IsAlive bool
Cmdline string Cmdline string
Memstats *runtime.MemStats Memstats *runtime.MemStats
Goroutines int64
Err error Err error
} }
@ -40,15 +28,35 @@ func NewService(port string) *Service {
} }
} }
func (d *Data) FindService(port string) *Service { // Update updates Service info from Expvar variable.
if d.Services == nil { func (s *Service) Update() {
return nil expvar := &Expvar{}
} resp, err := http.Get(s.Addr())
for _, service := range d.Services { defer resp.Body.Close()
if service.Port == port { if err != nil {
return service expvar.Err = err
} else if resp.StatusCode == http.StatusNotFound {
expvar.Err = fmt.Errorf("Vars not found. Did you import expvars?")
} else {
expvar, err = ParseExpvar(resp.Body)
if err != nil {
expvar = &Expvar{Err: err}
} }
} }
return nil s.Err = expvar.Err
s.Memstats = expvar.MemStats
// Update name and cmdline only if empty
if len(s.Cmdline) == 0 {
s.Cmdline = strings.Join(expvar.Cmdline, " ")
s.Name = BaseCommand(expvar.Cmdline)
}
}
// Addr returns fully qualified host:port pair for service.
//
// If host is not specified, 'localhost' is used.
func (s Service) Addr() string {
return fmt.Sprintf("http://localhost:%s%s", s.Port, ExpvarsUrl)
} }

View File

@ -27,9 +27,11 @@ func (u *DummyUI) Update(data Data) {
fmt.Printf("%s/%s ", alloc, sys) fmt.Printf("%s/%s ", alloc, sys)
} }
if service.Goroutines != 0 { /*
fmt.Printf("goroutines: %d", service.Goroutines) if service.Goroutines != 0 {
} fmt.Printf("goroutines: %d", service.Goroutines)
}
*/
fmt.Printf("\n") fmt.Printf("\n")
} }
} }

View File

@ -78,11 +78,11 @@ func (t *TermUI) Update(data Data) {
name := fmt.Sprintf("[R] %s", service.Name) name := fmt.Sprintf("[R] %s", service.Name)
meminfos := fmt.Sprintf("%s/%s", alloc, heap) meminfos := fmt.Sprintf("%s/%s", alloc, heap)
goroutine := fmt.Sprintf("%d", service.Goroutines) //goroutine := fmt.Sprintf("%d", service.Goroutines)
names.Items = append(names.Items, name) names.Items = append(names.Items, name)
meminfo.Items = append(meminfo.Items, meminfos) meminfo.Items = append(meminfo.Items, meminfos)
goroutines.Items = append(goroutines.Items, goroutine) //goroutines.Items = append(goroutines.Items, goroutine)
} }
data.TotalMemory.Push(int(totalAlloc / 1024)) data.TotalMemory.Push(int(totalAlloc / 1024))