summaryrefslogtreecommitdiff
path: root/pkg/api/server/idletracker/idletracker.go
blob: 1ee905a99074885bbe9972d6a155937cd8947e31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package idletracker

import (
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
)

type IdleTracker struct {
	http     map[net.Conn]struct{}
	hijacked int
	total    int
	mux      sync.Mutex
	timer    *time.Timer
	Duration time.Duration
}

func NewIdleTracker(idle time.Duration) *IdleTracker {
	return &IdleTracker{
		http:     make(map[net.Conn]struct{}),
		Duration: idle,
		timer:    time.NewTimer(idle),
	}
}

func (t *IdleTracker) ConnState(conn net.Conn, state http.ConnState) {
	t.mux.Lock()
	defer t.mux.Unlock()

	oldActive := t.ActiveConnections()
	logrus.Debugf("IdleTracker %p:%v %d/%d connection(s)", conn, state, oldActive, t.TotalConnections())
	switch state {
	case http.StateNew, http.StateActive:
		t.http[conn] = struct{}{}
		// stop the timer if we transitioned from idle
		if oldActive == 0 {
			t.timer.Stop()
		}
		t.total++
	case http.StateHijacked:
		// hijacked connections are handled elsewhere
		delete(t.http, conn)
		t.hijacked++
	case http.StateIdle, http.StateClosed:
		delete(t.http, conn)
		// Restart the timer if we've become idle
		if oldActive > 0 && len(t.http) == 0 {
			t.timer.Stop()
			t.timer.Reset(t.Duration)
		}
	}
}

func (t *IdleTracker) TrackHijackedClosed() {
	t.mux.Lock()
	defer t.mux.Unlock()

	t.hijacked--
}

func (t *IdleTracker) ActiveConnections() int {
	return len(t.http) + t.hijacked
}

func (t *IdleTracker) TotalConnections() int {
	return t.total
}

func (t *IdleTracker) Done() <-chan time.Time {
	return t.timer.C
}