2019-08-06 19:53:14 +03:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"runtime"
|
|
|
|
"time"
|
|
|
|
|
2019-11-27 19:12:39 +03:00
|
|
|
"github.com/micro/go-micro/debug/log"
|
|
|
|
|
2019-08-06 19:53:14 +03:00
|
|
|
proto "github.com/micro/go-micro/debug/proto"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2019-11-26 20:04:44 +03:00
|
|
|
// DefaultHandler is default debug handler
|
2019-08-06 19:53:14 +03:00
|
|
|
DefaultHandler = newDebug()
|
|
|
|
)
|
|
|
|
|
2019-11-26 20:04:44 +03:00
|
|
|
type Debug struct {
|
|
|
|
started int64
|
2019-11-28 14:05:35 +03:00
|
|
|
proto.DebugHandler
|
2019-11-27 20:31:35 +03:00
|
|
|
log.Log
|
2019-11-26 20:04:44 +03:00
|
|
|
}
|
|
|
|
|
2019-08-06 19:53:14 +03:00
|
|
|
func newDebug() *Debug {
|
|
|
|
return &Debug{
|
|
|
|
started: time.Now().Unix(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Debug) Health(ctx context.Context, req *proto.HealthRequest, rsp *proto.HealthResponse) error {
|
|
|
|
rsp.Status = "ok"
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Debug) Stats(ctx context.Context, req *proto.StatsRequest, rsp *proto.StatsResponse) error {
|
|
|
|
var mstat runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&mstat)
|
|
|
|
|
|
|
|
rsp.Started = uint64(d.started)
|
|
|
|
rsp.Uptime = uint64(time.Now().Unix() - d.started)
|
|
|
|
rsp.Memory = mstat.Alloc
|
|
|
|
rsp.Gc = mstat.PauseTotalNs
|
|
|
|
rsp.Threads = uint64(runtime.NumGoroutine())
|
|
|
|
return nil
|
|
|
|
}
|
2019-11-26 18:39:55 +03:00
|
|
|
|
2019-11-27 21:38:26 +03:00
|
|
|
func (d *Debug) Logs(ctx context.Context, req *proto.LogRequest, stream proto.Debug_LogsStream) error {
|
|
|
|
var records []log.Record
|
|
|
|
since := time.Unix(0, req.Since)
|
|
|
|
if !since.IsZero() {
|
|
|
|
records = d.Log.Read(log.Since(since))
|
|
|
|
} else {
|
|
|
|
records = d.Log.Read(log.Count(int(req.Count)))
|
|
|
|
}
|
|
|
|
|
|
|
|
defer stream.Close()
|
|
|
|
|
|
|
|
// TODO: figure out the stream later on
|
|
|
|
for _, record := range records {
|
|
|
|
metadata := make(map[string]string)
|
|
|
|
for k, v := range record.Metadata {
|
|
|
|
metadata[k] = v
|
|
|
|
}
|
|
|
|
|
|
|
|
recLog := &proto.Log{
|
|
|
|
Timestamp: record.Timestamp.UnixNano(),
|
|
|
|
Value: record.Value.(string),
|
|
|
|
Metadata: metadata,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := stream.Send(recLog); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-26 18:39:55 +03:00
|
|
|
return nil
|
|
|
|
}
|