This repository was archived by the owner on Nov 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathpool.go
412 lines (354 loc) · 9.69 KB
/
pool.go
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package strategy
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"github.com/intelsdi-x/snap/control/plugin"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/ctypes"
"github.com/intelsdi-x/snap/core/serror"
)
var (
// This defines the maximum running instances of a loaded plugin.
// It is initialized at runtime via the cli.
MaximumRunningPlugins = 3
)
var (
ErrBadType = errors.New("bad plugin type")
ErrBadStrategy = errors.New("bad strategy")
ErrPoolEmpty = errors.New("plugin pool is empty")
)
type Pool interface {
RoutingAndCaching
Count() int
Eligible() bool
Insert(a AvailablePlugin) error
Kill(id uint32, reason string)
Plugins() MapAvailablePlugin
RLock()
RUnlock()
SelectAndKill(taskID, reason string)
SelectAP(taskID string, configID map[string]ctypes.ConfigValue) (AvailablePlugin, serror.SnapError)
Strategy() RoutingAndCaching
Subscribe(taskID string)
SubscriptionCount() int
Unsubscribe(taskID string)
Version() int
RestartCount() int
IncRestartCount()
KillAll(string)
}
type AvailablePlugin interface {
core.AvailablePlugin
CacheTTL() time.Duration
CheckHealth()
ConcurrencyCount() int
Exclusive() bool
Kill(r string) error
RoutingStrategy() plugin.RoutingStrategyType
SetID(id uint32)
String() string
Type() plugin.PluginType
Stop(string) error
IsRemote() bool
SetIsRemote(bool)
}
type subscription struct {
Version int
TaskID string
}
type pool struct {
// used to coordinate changes to a pool
*sync.RWMutex
// the version of the plugins in the pool.
// subscriptions uses this.
version int
// key is the primary key used in availablePlugins:
// {plugin_type}:{plugin_name}:{plugin_version}
key string
// The subscriptions to this pool.
subs map[string]*subscription
// The plugins in the pool.
// the primary key is an increasing --> uint from
// snapteld epoch (`service snapteld start`).
plugins MapAvailablePlugin
pidCounter uint32
// The max size which this pool may grow.
max int
// The number of subscriptions per running instance
concurrencyCount int
// The routing and caching strategy declared by the plugin.
// strategy RoutingAndCaching
RoutingAndCaching
// restartCount the restart count of available plugins
// when the DeadAvailablePluginEvent occurs
restartCount int
}
func NewPool(key string, plugins ...AvailablePlugin) (Pool, error) {
versl := strings.Split(key, core.Separator)
ver, err := strconv.Atoi(versl[len(versl)-1])
if err != nil {
return nil, err
}
p := &pool{
RWMutex: &sync.RWMutex{},
version: ver,
key: key,
subs: map[string]*subscription{},
plugins: MapAvailablePlugin{},
max: MaximumRunningPlugins,
concurrencyCount: 1,
}
if len(plugins) > 0 {
for _, plg := range plugins {
p.Insert(plg)
}
}
return p, nil
}
// Version returns the version
func (p *pool) Version() int {
return p.version
}
// Plugins returns a map of plugin ids to the AvailablePlugin
func (p *pool) Plugins() MapAvailablePlugin {
return p.plugins
}
// Strategy returns the routing strategy
func (p *pool) Strategy() RoutingAndCaching {
return p.RoutingAndCaching
}
// RestartCount returns the restart count of a pool
func (p *pool) RestartCount() int {
return p.restartCount
}
func (p *pool) IncRestartCount() {
p.Lock()
defer p.Unlock()
p.restartCount++
}
// Insert inserts an AvailablePlugin into the pool
func (p *pool) Insert(a AvailablePlugin) error {
if a.Type() != plugin.CollectorPluginType && a.Type() != plugin.ProcessorPluginType && a.Type() != plugin.PublisherPluginType && a.Type() != plugin.StreamCollectorPluginType {
return ErrBadType
}
// If an empty pool is created, it does not have
// any available plugins from which to retrieve
// concurrency count or exclusivity. We ensure it
// is set correctly on an insert.
if len(p.plugins) == 0 {
if err := p.applyPluginMeta(a); err != nil {
return err
}
}
a.SetID(p.generatePID())
p.plugins[a.ID()] = a
return nil
}
// applyPluginMeta is called when the first plugin is added to the pool
func (p *pool) applyPluginMeta(a AvailablePlugin) error {
// Checking if plugin is exclusive
// (only one instance should be running).
if a.Exclusive() {
p.max = 1
}
// Set the cache TTL
cacheTTL := GlobalCacheExpiration
// if the plugin exposes a default TTL that is greater the the global default use it
if a.CacheTTL() != 0 && a.CacheTTL() > GlobalCacheExpiration {
cacheTTL = a.CacheTTL()
}
// Set the concurrency count
p.concurrencyCount = a.ConcurrencyCount()
// Set the routing and caching strategy
switch a.RoutingStrategy() {
case plugin.DefaultRouting:
p.RoutingAndCaching = NewLRU(cacheTTL)
case plugin.StickyRouting:
p.RoutingAndCaching = NewSticky(cacheTTL)
p.concurrencyCount = 1
case plugin.ConfigRouting:
p.RoutingAndCaching = NewConfigBased(cacheTTL)
default:
return ErrBadStrategy
}
return nil
}
// subscribe adds a subscription to the pool.
// Using subscribe is idempotent.
func (p *pool) Subscribe(taskID string) {
p.Lock()
defer p.Unlock()
if _, exists := p.subs[taskID]; !exists {
// Version is the last item in the key, so we split here
// to retrieve it for the subscription.
p.subs[taskID] = &subscription{
TaskID: taskID,
Version: p.version,
}
}
}
// unsubscribe removes a subscription from the pool.
// Using unsubscribe is idempotent.
func (p *pool) Unsubscribe(taskID string) {
p.Lock()
defer p.Unlock()
delete(p.subs, taskID)
}
// Eligible returns a bool indicating whether the pool is eligible to grow
func (p *pool) Eligible() bool {
p.RLock()
defer p.RUnlock()
// optimization: don't even bother with concurrency
// count if we have already reached pool max
if len(p.plugins) >= p.max {
return false
}
// Check if pool is eligible and number of plugins is less than maximum allowed
if len(p.subs) > p.concurrencyCount*len(p.plugins) {
return true
}
return false
}
// kill kills and removes the available plugin from its pool.
// Using kill is idempotent.
func (p *pool) Kill(id uint32, reason string) {
p.Lock()
defer p.Unlock()
ap, ok := p.plugins[id]
if ok {
ap.Kill(reason)
delete(p.plugins, id)
}
}
// Kill all instances of a plugin
func (p *pool) KillAll(reason string) {
for id, rp := range p.plugins {
log.WithFields(log.Fields{
"_block": "KillAll",
"reason": reason,
}).Debug(fmt.Sprintf("handling 'KillAll' for pool '%v', killing plugin '%v:%v'", p.String(), rp.Name(), rp.Version()))
if err := rp.Stop(reason); err != nil {
log.WithFields(log.Fields{
"_block": "KillAll",
"reason": reason,
}).Error(err)
}
p.Kill(id, reason)
}
}
// SelectAndKill selects, kills and removes the available plugin from the pool
func (p *pool) SelectAndKill(id, reason string) {
rp, err := p.Remove(p.plugins.Values(), id)
if err != nil {
log.WithFields(log.Fields{
"_block": "SelectAndKill",
"taskID": id,
"reason": reason,
}).Error(err)
return
}
if err := rp.Stop(reason); err != nil {
log.WithFields(log.Fields{
"_block": "SelectAndKill",
"taskID": id,
"reason": reason,
}).Error(err)
}
if err := rp.Kill(reason); err != nil {
log.WithFields(log.Fields{
"_block": "SelectAndKill",
"taskID": id,
"reason": reason,
}).Error(err)
}
p.remove(rp.ID())
}
// remove removes an available plugin from the the pool.
// using remove is idempotent.
func (p *pool) remove(id uint32) {
p.Lock()
defer p.Unlock()
delete(p.plugins, id)
}
// Count returns the number of plugins in the pool
func (p *pool) Count() int {
p.RLock()
defer p.RUnlock()
return len(p.plugins)
}
// NOTE: The data returned by subscriptions should be constant and read only.
func (p *pool) subscriptions() map[string]*subscription {
p.RLock()
defer p.RUnlock()
return p.subs
}
// SubscriptionCount returns the number of subscriptions in the pool
func (p *pool) SubscriptionCount() int {
p.RLock()
defer p.RUnlock()
return len(p.subs)
}
// SelectAP selects an available plugin from the pool
// the method is not thread safe, it should be protected outside of the body
func (p *pool) SelectAP(taskID string, config map[string]ctypes.ConfigValue) (AvailablePlugin, serror.SnapError) {
aps := p.plugins.Values()
var id string
switch p.Strategy().String() {
case "least-recently-used":
id = ""
case "sticky":
id = taskID
case "config-based":
id = idFromCfg(config)
default:
return nil, serror.New(ErrBadStrategy)
}
ap, err := p.Select(aps, id)
if err != nil {
return nil, serror.New(err)
}
return ap, nil
}
func idFromCfg(cfg map[string]ctypes.ConfigValue) string {
//TODO: check for nil map
var buff bytes.Buffer
enc := gob.NewEncoder(&buff)
err := enc.Encode(cfg)
if err != nil {
return ""
}
return string(buff.Bytes())
}
// generatePID returns the next available pid for the pool
func (p *pool) generatePID() uint32 {
atomic.AddUint32(&p.pidCounter, 1)
return p.pidCounter
}
// CacheTTL returns the cacheTTL for the pool
func (p *pool) CacheTTL(taskID string) (time.Duration, error) {
if len(p.plugins) == 0 {
return 0, ErrPoolEmpty
}
return p.RoutingAndCaching.CacheTTL(taskID)
}