forked from intelsdi-x/snap
/
plugin.go
443 lines (386 loc) · 10.9 KB
/
plugin.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
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 plugin
// WARNING! Do not import "fmt" and print from a plugin to stdout!
import (
"bytes"
"crypto/rsa"
"encoding/json"
"fmt"
"io" // Don't use "fmt.Print*"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
"regexp"
"runtime"
"time"
log "github.com/Sirupsen/logrus"
"github.com/intelsdi-x/snap/control/plugin/cpolicy"
)
// Plugin type
type PluginType int
// Returns string for matching enum plugin type
func (p PluginType) String() string {
return types[p]
}
const (
CollectorPluginType PluginType = iota
ProcessorPluginType
PublisherPluginType
)
type RoutingStrategyType int
// Returns string for matching enum RoutingStrategy type
func (p RoutingStrategyType) String() string {
return routingStrategyTypes[p]
}
const (
// DefaultRouting is a least recently used strategy.
DefaultRouting RoutingStrategyType = iota
// StickyRouting is a one-to-one strategy.
// Using this strategy a tasks requests are sent to the same running instance of a plugin.
StickyRouting
// ConfigRouting is routing to plugins based on the config provided to the plugin.
// Using this strategy enables a running database plugin that has the same connection info between
// two tasks to be shared.
ConfigRouting
)
// Plugin response states
type PluginResponseState int
const (
PluginSuccess PluginResponseState = iota
PluginFailure
)
type RPCType int
const (
NativeRPC RPCType = iota
JSONRPC
GRPC
)
var (
// Timeout settings
// How much time must elapse before a lack of Ping results in a timeout
PingTimeoutDurationDefault = time.Millisecond * 1500
// How many successive PingTimeouts must occur to equal a failure.
PingTimeoutLimit = 3
// Array matching plugin type enum to a string
// note: in string representation we use lower case
types = [...]string{
"collector",
"processor",
"publisher",
}
routingStrategyTypes = [...]string{
"least-recently-used",
"sticky",
"config",
}
)
type Plugin interface {
GetConfigPolicy() (*cpolicy.ConfigPolicy, error)
}
// PluginMeta for plugin
type PluginMeta struct {
Name string
Version int
Type PluginType
RPCType RPCType
RPCVersion int
// AcceptedContentTypes are types accepted by this plugin in priority order.
// snap.* means any snap type.
AcceptedContentTypes []string
// ReturnedContentTypes are content types returned in priority order.
// This is only applicable on processors.
ReturnedContentTypes []string
// ConcurrencyCount is the max number concurrent calls the plugin may take.
// If there are 5 tasks using the plugin and concurrency count is 2 there
// will be 3 plugins running.
ConcurrencyCount int
// Exclusive results in a single instance of the plugin running regardless
// the number of tasks using the plugin.
Exclusive bool
// Unsecure results in unencrypted communication with this plugin.
Unsecure bool
// CacheTTL will override the default cache TTL for the provided plugin.
CacheTTL time.Duration
// RoutingStrategy will override the routing strategy this plugin requires.
// The default routing strategy round-robin.
RoutingStrategy RoutingStrategyType
}
type metaOp func(m *PluginMeta)
// ConcurrencyCount is an option that can be be provided to the func NewPluginMeta.
func ConcurrencyCount(cc int) metaOp {
return func(m *PluginMeta) {
m.ConcurrencyCount = cc
}
}
// Exclusive is an option that can be be provided to the func NewPluginMeta.
func Exclusive(e bool) metaOp {
return func(m *PluginMeta) {
m.Exclusive = e
}
}
// Unsecure is an option that can be be provided to the func NewPluginMeta.
func Unsecure(e bool) metaOp {
return func(m *PluginMeta) {
m.Unsecure = e
}
}
// RoutingStrategy is an option that can be be provided to the func NewPluginMeta.
func RoutingStrategy(r RoutingStrategyType) metaOp {
return func(m *PluginMeta) {
m.RoutingStrategy = r
}
}
// CacheTTL is an option that can be be provided to the func NewPluginMeta.
func CacheTTL(t time.Duration) metaOp {
return func(m *PluginMeta) {
m.CacheTTL = t
}
}
// NewPluginMeta constructs and returns a PluginMeta struct
func NewPluginMeta(name string, version int, pluginType PluginType, acceptContentTypes, returnContentTypes []string, opts ...metaOp) *PluginMeta {
// An empty accepted content type default to "snap.*"
if len(acceptContentTypes) == 0 {
acceptContentTypes = append(acceptContentTypes, "snap.*")
}
// Validate content type formats
for _, s := range acceptContentTypes {
b, e := regexp.MatchString(`^[a-z0-9*]+\.[a-z0-9*]+$`, s)
if e != nil {
panic(e)
}
if !b {
panic(fmt.Sprintf("Bad accept content type [%s] for [%d] [%s]", name, version, s))
}
}
for _, s := range returnContentTypes {
b, e := regexp.MatchString(`^[a-z0-9*]+\.[a-z0-9*]+$`, s)
if e != nil {
panic(e)
}
if !b {
panic(fmt.Sprintf("Bad return content type [%s] for [%d] [%s]", name, version, s))
}
}
p := &PluginMeta{
Name: name,
Version: version,
Type: pluginType,
AcceptedContentTypes: acceptContentTypes,
ReturnedContentTypes: returnContentTypes,
//set the default for concurrency count to 1
ConcurrencyCount: 1,
}
for _, opt := range opts {
opt(p)
}
return p
}
// Arguments passed to startup of Plugin
type Arg struct {
// Plugin log level
LogLevel log.Level
// Ping timeout duration
PingTimeoutDuration time.Duration
NoDaemon bool
// The listen port
listenPort string
}
func NewArg(logLevel int) Arg {
return Arg{
LogLevel: log.Level(logLevel),
PingTimeoutDuration: PingTimeoutDurationDefault,
}
}
// Response from started plugin
type Response struct {
Meta PluginMeta
ListenAddress string
Token string
Type PluginType
// State is a signal from plugin to control that it passed
// its own loading requirements
State PluginResponseState
ErrorMessage string
PublicKey *rsa.PublicKey
}
// Start starts a plugin where:
// PluginMeta - base information about plugin
// Plugin - CollectorPlugin, ProcessorPlugin or PublisherPlugin
// requestString - plugins arguments (marshaled json of control/plugin Arg struct)
// returns an error and exitCode (exitCode from SessionState initilization or plugin termination code)
func Start(m *PluginMeta, c Plugin, requestString string) (error, int) {
s, sErr, retCode := NewSessionState(requestString, c, m)
if sErr != nil {
return sErr, retCode
}
var (
r *Response
exitCode int = 0
)
switch m.Type {
case CollectorPluginType:
// Create our proxy
proxy := &collectorPluginProxy{
Plugin: c.(CollectorPlugin),
Session: s,
}
// Register the proxy under the "Collector" namespace
rpc.RegisterName("Collector", proxy)
r = &Response{
Type: CollectorPluginType,
State: PluginSuccess,
Meta: *m,
}
if !m.Unsecure {
r.PublicKey = &s.privateKey.PublicKey
}
case PublisherPluginType:
r = &Response{
Type: PublisherPluginType,
State: PluginSuccess,
Meta: *m,
}
if !m.Unsecure {
r.PublicKey = &s.privateKey.PublicKey
}
// Create our proxy
proxy := &publisherPluginProxy{
Plugin: c.(PublisherPlugin),
Session: s,
}
// Register the proxy under the "Publisher" namespace
rpc.RegisterName("Publisher", proxy)
case ProcessorPluginType:
r = &Response{
Type: ProcessorPluginType,
State: PluginSuccess,
Meta: *m,
}
if !m.Unsecure {
r.PublicKey = &s.privateKey.PublicKey
}
// Create our proxy
proxy := &processorPluginProxy{
Plugin: c.(ProcessorPlugin),
Session: s,
}
// Register the proxy under the "Publisher" namespace
rpc.RegisterName("Processor", proxy)
}
// Register common plugin methods used for utility reasons
e := rpc.Register(s)
if e != nil {
if e.Error() != "rpc: service already defined: SessionState" {
s.Logger().Error(e.Error())
return e, 2
}
}
l, err := net.Listen("tcp", "127.0.0.1:"+s.ListenPort())
if err != nil {
s.Logger().Error(err.Error())
panic(err)
}
s.SetListenAddress(l.Addr().String())
s.Logger().Debugf("Listening %s\n", l.Addr())
s.Logger().Debugf("Session token %s\n", s.Token())
switch r.Meta.RPCType {
case JSONRPC:
rpc.HandleHTTP()
http.HandleFunc("/rpc", func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
w.Header().Set("Content-Type", "application/json")
if req.ContentLength == 0 {
encoder := json.NewEncoder(w)
encoder.Encode(&struct {
Id interface{} `json:"id"`
Result interface{} `json:"result"`
Error interface{} `json:"error"`
}{
Id: nil,
Result: nil,
Error: "rpc: method request ill-formed",
})
return
}
res := NewRPCRequest(req.Body).Call()
io.Copy(w, res)
})
go http.Serve(l, nil)
case NativeRPC:
go func() {
for {
conn, err := l.Accept()
if err != nil {
panic(err)
}
go rpc.ServeConn(conn)
}
}()
default:
panic("Unsupported RPC type")
}
resp := s.generateResponse(r)
// Output response to stdout
fmt.Println(string(resp))
s.Logger().Println(string(resp))
go s.heartbeatWatch(s.KillChan())
if s.isDaemon() {
exitCode = <-s.KillChan() // Closing of channel kills
}
return nil, exitCode
}
// rpcRequest represents a RPC request.
// rpcRequest implements the io.ReadWriteCloser interface.
type rpcRequest struct {
r io.Reader // holds the JSON formated RPC request
rw io.ReadWriter // holds the JSON formated RPC response
done chan bool // signals then end of the RPC request
}
// NewRPCRequest returns a new rpcRequest.
func NewRPCRequest(r io.Reader) *rpcRequest {
var buf bytes.Buffer
done := make(chan bool)
return &rpcRequest{r, &buf, done}
}
// Read implements the io.ReadWriteCloser Read method.
func (r *rpcRequest) Read(p []byte) (n int, err error) {
return r.r.Read(p)
}
// Write implements the io.ReadWriteCloser Write method.
func (r *rpcRequest) Write(p []byte) (n int, err error) {
n, err = r.rw.Write(p)
defer func(done chan bool) { done <- true }(r.done)
return
}
// Close implements the io.ReadWriteCloser Close method.
func (r *rpcRequest) Close() error {
return nil
}
// Call invokes the RPC request, waits for it to complete, and returns the results.
func (r *rpcRequest) Call() io.Reader {
go jsonrpc.ServeConn(r)
<-r.done
return r.rw
}
func catchPluginPanic(l *log.Logger) {
if err := recover(); err != nil {
trace := make([]byte, 4096)
count := runtime.Stack(trace, true)
l.Printf("Recover from panic: %s\n", err)
l.Printf("Stack of %d bytes: %s\n", count, trace)
panic(err)
}
}