summaryrefslogtreecommitdiff
path: root/pool_supervisor.go
blob: cadf5f9c23c32aab6db992317808693decb36430 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package roadrunner

import (
	"context"
	"errors"
	"fmt"
	"time"
)

const MB = 1024 * 1024

type Supervisor interface {
	Attach(pool Pool)
	StartWatching() error
	StopWatching()
	Detach()
}

type staticPoolSupervisor struct {
	// maxWorkerMemory in MB
	maxWorkerMemory uint64
	// maxPoolMemory in MB
	maxPoolMemory uint64
	// maxWorkerTTL in seconds
	maxWorkerTTL uint64
	// maxWorkerIdle in seconds
	maxWorkerIdle uint64

	// watchTimeout in seconds
	watchTimeout uint64
	stopCh       chan struct{}

	pool Pool
}

/*
The arguments are:
maxWorkerMemory - maximum memory allowed for a single worker
maxPoolMemory - maximum pool memory allowed for a pool of a workers
maxTtl - maximum ttl for the worker after which it will be killed and replaced
maxIdle - maximum time to live for the worker in Ready state
watchTimeout - time between watching for the workers/pool status
*/
// TODO might be just wrap the pool and return ControlledPool with included Pool interface
func NewStaticPoolSupervisor(maxWorkerMemory, maxPoolMemory, maxTtl, maxIdle, watchTimeout uint64) Supervisor {
	if maxWorkerMemory == 0 {
		// just set to a big number, 5GB
		maxPoolMemory = 5000 * MB
	}
	if watchTimeout == 0 {
		watchTimeout = 60
	}
	return &staticPoolSupervisor{
		maxWorkerMemory: maxWorkerMemory,
		maxPoolMemory:   maxPoolMemory,
		maxWorkerTTL:    maxTtl,
		maxWorkerIdle:   maxIdle,
		stopCh:          make(chan struct{}),
	}
}

func (sps *staticPoolSupervisor) Attach(pool Pool) {
	sps.pool = pool
}

func (sps *staticPoolSupervisor) StartWatching() error {
	go func() {
		watchTout := time.NewTicker(time.Second * time.Duration(sps.watchTimeout))
		for {
			select {
			case <-sps.stopCh:
				watchTout.Stop()
				return
			// stop here
			case <-watchTout.C:
				err := sps.control()
				if err != nil {
					sps.pool.Events() <- PoolEvent{Payload: err}
				}
			}
		}
	}()
	return nil
}

func (sps *staticPoolSupervisor) StopWatching() {
	sps.stopCh <- struct{}{}
}

func (sps *staticPoolSupervisor) Detach() {

}

func (sps *staticPoolSupervisor) control() error {
	if sps.pool == nil {
		return errors.New("pool should be attached")
	}
	now := time.Now()
	ctx := context.TODO()

	// THIS IS A COPY OF WORKERS
	workers := sps.pool.Workers(ctx)
	var totalUsedMemory uint64

	for i := 0; i < len(workers); i++ {
		if workers[i].State().Value() == StateInvalid {
			continue
		}

		s, err := WorkerProcessState(workers[i])
		if err != nil {
			panic(err)
			// push to pool events??
		}

		if sps.maxWorkerTTL != 0 && now.Sub(workers[i].Created()).Seconds() >= float64(sps.maxWorkerTTL) {
			err = sps.pool.RemoveWorker(ctx, workers[i])
			if err != nil {
				return err
			}

			// after remove worker we should exclude it from further analysis
			workers = append(workers[:i], workers[i+1:]...)
		}

		if sps.maxWorkerMemory != 0 && s.MemoryUsage >= sps.maxWorkerMemory*MB {
			// TODO events
			sps.pool.Events() <- PoolEvent{Payload: fmt.Errorf("max allowed memory reached (%vMB)", sps.maxWorkerMemory)}
			err = sps.pool.RemoveWorker(ctx, workers[i])
			if err != nil {
				return err
			}
			workers = append(workers[:i], workers[i+1:]...)
			continue
		}

		// firs we check maxWorker idle
		if sps.maxWorkerIdle != 0 {
			// then check for the worker state
			if workers[i].State().Value() != StateReady {
				continue
			}
			/*
				Calculate idle time
				If worker in the StateReady, we read it LastUsed timestamp as UnixNano uint64
				2. For example maxWorkerIdle is equal to 5sec, then, if (time.Now - LastUsed) > maxWorkerIdle
				we are guessing that worker overlap idle time and has to be killed
			*/
			// get last used unix nano
			lu := workers[i].State().LastUsed()
			// convert last used to unixNano and sub time.now
			res := int64(lu) - now.UnixNano()
			// maxWorkerIdle more than diff between now and last used
			if int64(sps.maxWorkerIdle)-res <= 0 {
				sps.pool.Events() <- PoolEvent{Payload: fmt.Errorf("max allowed worker idle time elapsed. actual idle time: %v, max idle time: %v", sps.maxWorkerIdle, res)}
				err = sps.pool.RemoveWorker(ctx, workers[i])
				if err != nil {
					return err
				}
				workers = append(workers[:i], workers[i+1:]...)
			}
		}

		// the very last step is to calculate pool memory usage (except excluded workers)
		totalUsedMemory += s.MemoryUsage
	}

	// if current usage more than max allowed pool memory usage
	if totalUsedMemory > sps.maxPoolMemory {
		// destroy pool
		totalUsedMemory = 0
		sps.pool.Destroy(ctx)
	}

	return nil
}