From c83b04c10c3d1126f295a72f9e6d96bf1924238a Mon Sep 17 00:00:00 2001 From: Mikhail Osipov Date: Fri, 6 Mar 2020 22:29:10 +0300 Subject: add recent command --- pkg/server/tunnel.go | 57 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 12 deletions(-) (limited to 'pkg') diff --git a/pkg/server/tunnel.go b/pkg/server/tunnel.go index 09d275b..01d7c22 100644 --- a/pkg/server/tunnel.go +++ b/pkg/server/tunnel.go @@ -18,6 +18,8 @@ import ( "tunnel/pkg/server/socket" ) +const maxRecentSize = 8 + type metric struct { tx uint64 rx uint64 @@ -28,6 +30,7 @@ type stream struct { t *tunnel env env.Env since time.Time + until time.Time wg sync.WaitGroup in, out socket.Channel pipes []*hook.Pipe @@ -43,6 +46,7 @@ type tunnel struct { args string streams map[int]*stream + recent []*stream mu sync.Mutex wg sync.WaitGroup @@ -167,6 +171,18 @@ func (t *tunnel) newStream(in, out socket.Channel) *stream { return s } +func (t *tunnel) delStream(s *stream) { + t.mu.Lock() + defer t.mu.Unlock() + + delete(t.streams, s.id) + + t.recent = append(t.recent, s) + if len(t.recent) > maxRecentSize { + t.recent = t.recent[len(t.recent) - maxRecentSize:] + } +} + func (s *stream) info() string { d := time.Since(s.since).Milliseconds() @@ -181,9 +197,9 @@ func (s *stream) info() string { func (s *stream) waitAndClose() { s.wg.Wait() - s.t.mu.Lock() - delete(s.t.streams, s.id) - s.t.mu.Unlock() + s.until = time.Now() + + s.t.delStream(s) s.t.wg.Done() @@ -437,20 +453,34 @@ func showTunnels(r *request) { }) } -func showStreams(r *request) { +func showActive(r *request) { foreachTunnel(r.c.s.tunnels, func(t *tunnel) { t.mu.Lock() defer t.mu.Unlock() - if len(t.streams) > 0 { - r.Println(t.id, t.args) + foreachStream(t.streams, func(s *stream) { + r.Println(t.id, s.id, s.in.Origin(), s.out.Origin(), s.info()) + }) + }) +} - foreachStream(t.streams, func(s *stream) { - when := s.since.Format(config.TimeFormat) - r.Println("\t", s.id, when, s.in.Origin(), s.out.Origin(), s.info()) - }) - } +func showRecent(r *request) { + var streams []*stream + + foreachTunnel(r.c.s.tunnels, func(t *tunnel) { + t.mu.Lock() + streams = append(streams, t.recent...) + defer t.mu.Unlock() + }) + + sort.SliceStable(streams, func(i, j int) bool { + return streams[i].until.Before(streams[j].until) }) + + for _, s := range streams { + when := s.until.Format(config.TimeFormat) + r.Println(when, s.t.id, s.id, s.in.Origin(), s.out.Origin(), s.info()) + } } func showHooks(r *request) { @@ -466,6 +496,9 @@ func init() { newCmd(tunnelRename, "rename") newCmd(showHooks, "hooks") - newCmd(showStreams, "streams") + newCmd(showTunnels, "show") + + newCmd(showActive, "active") + newCmd(showRecent, "recent") } -- cgit v1.2.3-70-g09d2