reqlog.go 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package commands

import (
	"strings"
	"sync"
	"time"
)

type ReqLogEntry struct {
	StartTime time.Time
	EndTime   time.Time
	Active    bool
	Command   string
	Options   map[string]interface{}
	Args      []string
	ID        int

	req Request
	log *ReqLog
}

func (r *ReqLogEntry) Finish() {
23 24 25
	log := r.log
	log.lock.Lock()
	defer log.lock.Unlock()
26 27 28 29

	r.Active = false
	r.EndTime = time.Now()
	r.log.maybeCleanup()
30 31 32 33 34

	// remove references to save memory
	r.req = nil
	r.log = nil

35 36 37 38 39 40 41 42 43 44 45 46
}

func (r *ReqLogEntry) Copy() *ReqLogEntry {
	out := *r
	out.log = nil
	return &out
}

type ReqLog struct {
	Requests []*ReqLogEntry
	nextID   int
	lock     sync.Mutex
47
	keep     time.Duration
48 49 50 51 52 53 54 55 56 57 58
}

func (rl *ReqLog) Add(req Request) *ReqLogEntry {
	rl.lock.Lock()
	defer rl.lock.Unlock()

	rle := &ReqLogEntry{
		StartTime: time.Now(),
		Active:    true,
		Command:   strings.Join(req.Path(), "/"),
		Options:   req.Options(),
59
		Args:      req.StringArguments(),
60 61 62 63 64 65 66 67 68 69
		ID:        rl.nextID,
		req:       req,
		log:       rl,
	}

	rl.nextID++
	rl.Requests = append(rl.Requests, rle)
	return rle
}

70 71 72
func (rl *ReqLog) ClearInactive() {
	rl.lock.Lock()
	defer rl.lock.Unlock()
73 74 75 76
	k := rl.keep
	rl.keep = 0
	rl.cleanup()
	rl.keep = k
77 78
}

79 80 81
func (rl *ReqLog) maybeCleanup() {
	// only do it every so often or it might
	// become a perf issue
82
	if len(rl.Requests)%10 == 0 {
83 84 85 86 87
		rl.cleanup()
	}
}

func (rl *ReqLog) cleanup() {
88 89 90 91 92 93
	i := 0
	now := time.Now()
	for j := 0; j < len(rl.Requests); j++ {
		rj := rl.Requests[j]
		if rj.Active || rl.Requests[j].EndTime.Add(rl.keep).After(now) {
			rl.Requests[i] = rl.Requests[j]
94 95 96
			i++
		}
	}
97 98 99 100 101 102 103
	rl.Requests = rl.Requests[:i]
}

func (rl *ReqLog) SetKeepTime(t time.Duration) {
	rl.lock.Lock()
	defer rl.lock.Unlock()
	rl.keep = t
104 105
}

Jeromy's avatar
Jeromy committed
106
// Report generates a copy of all the entries in the requestlog
107 108 109 110 111 112 113 114 115 116 117
func (rl *ReqLog) Report() []*ReqLogEntry {
	rl.lock.Lock()
	defer rl.lock.Unlock()
	out := make([]*ReqLogEntry, len(rl.Requests))

	for i, e := range rl.Requests {
		out[i] = e.Copy()
	}

	return out
}