summaryrefslogtreecommitdiff
path: root/supervisor_pool.go
blob: e23abdd1636127518c7ac4d95fbee8b1e92c61be (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
package roadrunner

import (
	"context"
	"sync"
	"time"

	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/util"
)

const MB = 1024 * 1024

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

type supervisedPool struct {
	cfg    *SupervisorConfig
	events *util.EventHandler
	pool   Pool
	stopCh chan struct{}
	mu     *sync.RWMutex
}

func newPoolWatcher(pool Pool, events *util.EventHandler, cfg *SupervisorConfig) SupervisedPool {
	sp := &supervisedPool{
		cfg:    cfg,
		events: events,
		pool:   pool,
		mu:     &sync.RWMutex{},
		stopCh: make(chan struct{}),
	}
	return sp
}

type ttlExec struct {
	err error
	p   Payload
}

func (sp *supervisedPool) ExecWithContext(ctx context.Context, rqs Payload) (Payload, error) {
	const op = errors.Op("exec_supervised")
	if sp.cfg.ExecTTL == 0 {
		return sp.pool.Exec(rqs)
	}

	c := make(chan ttlExec, 1)
	ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(sp.cfg.ExecTTL))
	defer cancel()
	go func() {
		res, err := sp.pool.ExecWithContext(ctx, rqs)
		if err != nil {
			c <- ttlExec{
				err: errors.E(op, err),
				p:   EmptyPayload,
			}
		}

		c <- ttlExec{
			err: nil,
			p:   res,
		}
	}()

	for {
		select {
		case <-ctx.Done():
			return EmptyPayload, errors.E(op, errors.TimeOut, ctx.Err())
		case res := <-c:
			if res.err != nil {
				return EmptyPayload, res.err
			}

			return res.p, nil
		}
	}
}

func (sp *supervisedPool) Exec(p Payload) (Payload, error) {
	const op = errors.Op("supervised exec")
	rsp, err := sp.pool.Exec(p)
	if err != nil {
		return EmptyPayload, errors.E(op, err)
	}
	return rsp, nil
}

func (sp *supervisedPool) AddListener(listener util.EventListener) {
	sp.pool.AddListener(listener)
}

func (sp *supervisedPool) GetConfig() Config {
	return sp.pool.GetConfig()
}

func (sp *supervisedPool) Workers() (workers []WorkerBase) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	return sp.pool.Workers()
}

func (sp *supervisedPool) RemoveWorker(ctx context.Context, worker WorkerBase) error {
	return sp.pool.RemoveWorker(ctx, worker)
}

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

func (sp *supervisedPool) Start() {
	go func() {
		watchTout := time.NewTicker(time.Second * time.Duration(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 *supervisedPool) Stop() {
	sp.stopCh <- struct{}{}
}

func (sp *supervisedPool) control() {
	now := time.Now()
	ctx := context.TODO()
	const op = errors.Op("supervised pool control tick")

	// THIS IS A COPY OF WORKERS
	workers := sp.pool.Workers()

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

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

		if sp.cfg.TTL != 0 && now.Sub(workers[i].Created()).Seconds() >= float64(sp.cfg.TTL) {
			err = sp.pool.RemoveWorker(ctx, workers[i])
			if err != nil {
				sp.events.Push(PoolEvent{Event: EventSupervisorError, Payload: errors.E(op, err)})
				return
			} else {
				sp.events.Push(PoolEvent{Event: EventTTL, Payload: workers[i]})
			}

			continue
		}

		if sp.cfg.MaxWorkerMemory != 0 && s.MemoryUsage >= sp.cfg.MaxWorkerMemory*MB {
			err = sp.pool.RemoveWorker(ctx, workers[i])
			if err != nil {
				sp.events.Push(PoolEvent{Event: EventSupervisorError, Payload: errors.E(op, err)})
				return
			} else {
				sp.events.Push(PoolEvent{Event: EventMaxMemory, Payload: workers[i]})
			}

			continue
		}

		// firs we check maxWorker idle
		if sp.cfg.IdleTTL != 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 sp.cfg.IdleTTL-uint64(res) <= 0 {
				err = sp.pool.RemoveWorker(ctx, workers[i])
				if err != nil {
					sp.events.Push(PoolEvent{Event: EventSupervisorError, Payload: errors.E(op, err)})
					return
				} else {
					sp.events.Push(PoolEvent{Event: EventIdleTTL, Payload: workers[i]})
				}
			}
		}
	}
}