summaryrefslogtreecommitdiff
path: root/pool/supervisor_pool.go
blob: 1a94f6a022d257a2748e7ec319e6904784c38678 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package pool

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/events"
	"github.com/spiral/roadrunner/v2/payload"
	"github.com/spiral/roadrunner/v2/state/process"
	"github.com/spiral/roadrunner/v2/worker"
)

const (
	MB                    = 1024 * 1024
	supervisorName string = "supervisor"
)

// NSEC_IN_SEC nanoseconds in second
const NSEC_IN_SEC int64 = 1000000000 //nolint:stylecheck

type Supervised interface {
	Pool
	// Start used to start watching process for all pool workers
	Start()
}

type supervised struct {
	cfg    *SupervisorConfig
	events events.EventBus
	pool   Pool
	stopCh chan struct{}
	mu     *sync.RWMutex
}

func supervisorWrapper(pool Pool, eb events.EventBus, cfg *SupervisorConfig) Supervised {
	sp := &supervised{
		cfg:    cfg,
		events: eb,
		pool:   pool,
		mu:     &sync.RWMutex{},
		stopCh: make(chan struct{}),
	}

	return sp
}

func (sp *supervised) execWithTTL(_ context.Context, _ *payload.Payload) (*payload.Payload, error) {
	panic("used to satisfy pool interface")
}

func (sp *supervised) Exec(rqs *payload.Payload) (*payload.Payload, error) {
	const op = errors.Op("supervised_exec_with_context")
	if sp.cfg.ExecTTL == 0 {
		return sp.pool.Exec(rqs)
	}

	ctx, cancel := context.WithTimeout(context.Background(), sp.cfg.ExecTTL)
	defer cancel()

	res, err := sp.pool.execWithTTL(ctx, rqs)
	if err != nil {
		return nil, errors.E(op, err)
	}

	return res, nil
}

func (sp *supervised) GetConfig() interface{} {
	return sp.pool.GetConfig()
}

func (sp *supervised) Workers() (workers []worker.BaseProcess) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	return sp.pool.Workers()
}

func (sp *supervised) RemoveWorker(worker worker.BaseProcess) error {
	return sp.pool.RemoveWorker(worker)
}

func (sp *supervised) Destroy(ctx context.Context) {
	sp.pool.Destroy(ctx)
}

func (sp *supervised) Start() {
	go func() {
		watchTout := time.NewTicker(sp.cfg.WatchTick)
		for {
			select {
			case <-sp.stopCh:
				watchTout.Stop()
				return
			// stop here
			case <-watchTout.C:
				sp.mu.Lock()
				sp.control()
				sp.mu.Unlock()
			}
		}
	}()
}

func (sp *supervised) Stop() {
	sp.stopCh <- struct{}{}
}

func (sp *supervised) control() { //nolint:gocognit
	now := time.Now()

	// MIGHT BE OUTDATED
	// It's a copy of the Workers pointers
	workers := sp.pool.Workers()

	for i := 0; i < len(workers); i++ {
		// if worker not in the Ready OR working state
		// skip such worker
		switch workers[i].State().Value() {
		case
			worker.StateInvalid,
			worker.StateErrored,
			worker.StateDestroyed,
			worker.StateInactive,
			worker.StateStopped,
			worker.StateStopping,
			worker.StateKilling:
			continue
		}

		s, err := process.WorkerProcessState(workers[i])
		if err != nil {
			// worker not longer valid for supervision
			continue
		}

		if sp.cfg.TTL != 0 && now.Sub(workers[i].Created()).Seconds() >= sp.cfg.TTL.Seconds() {
			/*
				worker at this point might be in the middle of request execution:

				---> REQ ---> WORKER -----------------> RESP (at this point we should not set the Ready state) ------> | ----> Worker gets between supervisor checks and get killed in the ww.Release
											 ^
				                           TTL Reached, state - invalid                                                |
																														-----> Worker Stopped here
			*/

			if workers[i].State().Value() != worker.StateWorking {
				workers[i].State().Set(worker.StateInvalid)
				_ = workers[i].Stop()
			}
			// just to double check
			workers[i].State().Set(worker.StateInvalid)
			sp.events.Send(events.NewEvent(events.EventTTL, supervisorName, fmt.Sprintf("worker's pid: %d", workers[i].Pid())))
			continue
		}

		if sp.cfg.MaxWorkerMemory != 0 && s.MemoryUsage >= sp.cfg.MaxWorkerMemory*MB {
			/*
				worker at this point might be in the middle of request execution:

				---> REQ ---> WORKER -----------------> RESP (at this point we should not set the Ready state) ------> | ----> Worker gets between supervisor checks and get killed in the ww.Release
											 ^
				                           TTL Reached, state - invalid                                                |
																														-----> Worker Stopped here
			*/

			if workers[i].State().Value() != worker.StateWorking {
				workers[i].State().Set(worker.StateInvalid)
				_ = workers[i].Stop()
			}
			// just to double check
			workers[i].State().Set(worker.StateInvalid)
			sp.events.Send(events.NewEvent(events.EventMaxMemory, supervisorName, fmt.Sprintf("worker's pid: %d", workers[i].Pid())))
			continue
		}

		// firs we check maxWorker idle
		if sp.cfg.IdleTTL != 0 {
			// then check for the worker state
			if workers[i].State().Value() != worker.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
			*/

			// 1610530005534416045 lu
			// lu - now = -7811150814 - nanoseconds
			// 7.8 seconds
			// get last used unix nano
			lu := workers[i].State().LastUsed()
			// worker not used, skip
			if lu == 0 {
				continue
			}

			// convert last used to unixNano and sub time.now to seconds
			// negative number, because lu always in the past, except for the `back to the future` :)
			res := ((int64(lu) - now.UnixNano()) / NSEC_IN_SEC) * -1

			// maxWorkerIdle more than diff between now and last used
			// for example:
			// After exec worker goes to the rest
			// And resting for the 5 seconds
			// IdleTTL is 1 second.
			// After the control check, res will be 5, idle is 1
			// 5 - 1 = 4, more than 0, YOU ARE FIRED (removed). Done.
			if int64(sp.cfg.IdleTTL.Seconds())-res <= 0 {
				/*
					worker at this point might be in the middle of request execution:

					---> REQ ---> WORKER -----------------> RESP (at this point we should not set the Ready state) ------> | ----> Worker gets between supervisor checks and get killed in the ww.Release
												 ^
					                           TTL Reached, state - invalid                                                |
																															-----> Worker Stopped here
				*/

				if workers[i].State().Value() != worker.StateWorking {
					workers[i].State().Set(worker.StateInvalid)
					_ = workers[i].Stop()
				}
				// just to double-check
				workers[i].State().Set(worker.StateInvalid)
				sp.events.Send(events.NewEvent(events.EventIdleTTL, supervisorName, fmt.Sprintf("worker's pid: %d", workers[i].Pid())))
			}
		}
	}
}