2015-04-21 17:51:01 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2015-04-25 20:54:17 +08:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2015-04-21 17:51:01 +08:00
|
|
|
"runtime"
|
2015-04-25 20:54:17 +08:00
|
|
|
"strings"
|
2015-04-21 17:51:01 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Services []*Service
|
|
|
|
|
|
|
|
// Service represents constantly updating info about single service.
|
|
|
|
type Service struct {
|
2015-04-25 20:54:17 +08:00
|
|
|
Port string
|
|
|
|
Name string
|
|
|
|
|
|
|
|
Cmdline string
|
2015-04-25 21:29:19 +08:00
|
|
|
MemStats *runtime.MemStats
|
|
|
|
|
|
|
|
Values map[string]*Stack
|
2015-04-21 17:51:01 +08:00
|
|
|
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewService returns new Service object.
|
|
|
|
func NewService(port string) *Service {
|
|
|
|
return &Service{
|
|
|
|
Name: port, // we have only port on start, so use it as name until resolved
|
|
|
|
Port: port,
|
2015-04-25 21:29:19 +08:00
|
|
|
|
|
|
|
Values: make(map[string]*Stack),
|
2015-04-21 17:51:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-25 20:54:17 +08:00
|
|
|
// Update updates Service info from Expvar variable.
|
|
|
|
func (s *Service) Update() {
|
|
|
|
expvar := &Expvar{}
|
|
|
|
resp, err := http.Get(s.Addr())
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
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}
|
2015-04-21 17:51:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-25 20:54:17 +08:00
|
|
|
s.Err = expvar.Err
|
2015-04-25 21:29:19 +08:00
|
|
|
s.MemStats = expvar.MemStats
|
2015-04-25 20:54:17 +08:00
|
|
|
|
|
|
|
// Update name and cmdline only if empty
|
|
|
|
if len(s.Cmdline) == 0 {
|
|
|
|
s.Cmdline = strings.Join(expvar.Cmdline, " ")
|
|
|
|
s.Name = BaseCommand(expvar.Cmdline)
|
|
|
|
}
|
2015-04-25 21:29:19 +08:00
|
|
|
|
|
|
|
// Put metrics data
|
|
|
|
mem, ok := s.Values["memory"]
|
|
|
|
if !ok {
|
|
|
|
s.Values["memory"] = NewStack(40)
|
|
|
|
mem = s.Values["memory"]
|
|
|
|
}
|
|
|
|
mem.Push(int(s.MemStats.Alloc) / 1024)
|
2015-04-25 20:54:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
2015-04-21 17:51:01 +08:00
|
|
|
}
|