reqlog.go 1.99 KB
Newer Older
1 2 3 4 5 6 7
package commands

import (
	"sync"
	"time"
)

Jan Winkelmann's avatar
Jan Winkelmann committed
8
// ReqLogEntry is an entry in the request log
9 10 11 12 13 14 15 16 17 18 19 20
type ReqLogEntry struct {
	StartTime time.Time
	EndTime   time.Time
	Active    bool
	Command   string
	Options   map[string]interface{}
	Args      []string
	ID        int

	log *ReqLog
}

Jan Winkelmann's avatar
Jan Winkelmann committed
21
// Copy returns a copy of the ReqLogEntry
22 23 24 25 26 27
func (r *ReqLogEntry) Copy() *ReqLogEntry {
	out := *r
	out.log = nil
	return &out
}

Jan Winkelmann's avatar
Jan Winkelmann committed
28
// ReqLog is a log of requests
29 30 31 32
type ReqLog struct {
	Requests []*ReqLogEntry
	nextID   int
	lock     sync.Mutex
33
	keep     time.Duration
34 35
}

Jan Winkelmann's avatar
Jan Winkelmann committed
36 37 38 39 40
// AddEntry adds an entry to the log
func (rl *ReqLog) AddEntry(rle *ReqLogEntry) {
	rl.lock.Lock()
	defer rl.lock.Unlock()

41 42
	rl.nextID++
	rl.Requests = append(rl.Requests, rle)
Jan Winkelmann's avatar
Jan Winkelmann committed
43 44 45 46

	if rle == nil || !rle.Active {
		rl.maybeCleanup()
	}
47 48
}

Jan Winkelmann's avatar
Jan Winkelmann committed
49
// ClearInactive removes stale entries
50 51 52
func (rl *ReqLog) ClearInactive() {
	rl.lock.Lock()
	defer rl.lock.Unlock()
Jan Winkelmann's avatar
Jan Winkelmann committed
53

54 55 56 57
	k := rl.keep
	rl.keep = 0
	rl.cleanup()
	rl.keep = k
58 59
}

60 61 62
func (rl *ReqLog) maybeCleanup() {
	// only do it every so often or it might
	// become a perf issue
63
	if len(rl.Requests)%10 == 0 {
64 65 66 67 68
		rl.cleanup()
	}
}

func (rl *ReqLog) cleanup() {
69 70 71 72 73 74
	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]
75 76 77
			i++
		}
	}
78 79 80
	rl.Requests = rl.Requests[:i]
}

Jan Winkelmann's avatar
Jan Winkelmann committed
81
// SetKeepTime sets a duration after which an entry will be considered inactive
82 83 84 85
func (rl *ReqLog) SetKeepTime(t time.Duration) {
	rl.lock.Lock()
	defer rl.lock.Unlock()
	rl.keep = t
86 87
}

Jeromy's avatar
Jeromy committed
88
// Report generates a copy of all the entries in the requestlog
89 90 91 92 93 94 95 96 97 98 99
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
}
Jan Winkelmann's avatar
Jan Winkelmann committed
100 101 102 103 104 105 106 107 108 109 110

// Finish marks an entry in the log as finished
func (rl *ReqLog) Finish(rle *ReqLogEntry) {
	rl.lock.Lock()
	defer rl.lock.Unlock()

	rle.Active = false
	rle.EndTime = time.Now()

	rl.maybeCleanup()
}