forked from intelsdi-x/snap
/
session.go
305 lines (257 loc) · 7.33 KB
/
session.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
/*
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
import (
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/intelsdi-x/snap/control/plugin/cpolicy"
"github.com/intelsdi-x/snap/control/plugin/encoding"
"github.com/intelsdi-x/snap/control/plugin/encrypter"
"github.com/intelsdi-x/snap/core/cdata"
"github.com/intelsdi-x/snap/core/ctypes"
)
// Session interface
type Session interface {
Ping([]byte, *[]byte) error
Kill([]byte, *[]byte) error
GetConfigPolicy([]byte, *[]byte) error
Logger() *log.Logger
ListenAddress() string
SetListenAddress(string)
ListenPort() string
Token() string
KillChan() chan int
ResetHeartbeat()
generateResponse(r *Response) []byte
heartbeatWatch(killChan chan int)
isDaemon() bool
SetKey(SetKeyArgs, *[]byte) error
Encode(interface{}) ([]byte, error)
Decode([]byte, interface{}) error
}
// Arguments passed to ping
type PingArgs struct{}
type KillArgs struct {
Reason string
}
// Started plugin session state
type SessionState struct {
*Arg
*encrypter.Encrypter
encoding.Encoder
LastPing time.Time
plugin Plugin
token string
listenAddress string
killChan chan int
logger *log.Logger
privateKey *rsa.PrivateKey
encoder encoding.Encoder
}
type GetConfigPolicyArgs struct{}
type GetConfigPolicyReply struct {
Policy *cpolicy.ConfigPolicy
}
// GetConfigPolicy returns the plugin's policy
func (s *SessionState) GetConfigPolicy(args []byte, reply *[]byte) error {
defer catchPluginPanic(s.Logger())
s.logger.Println("GetConfigPolicy called")
policy, err := s.plugin.GetConfigPolicy()
if err != nil {
return errors.New(fmt.Sprintf("GetConfigPolicy call error : %s", err.Error()))
}
r := GetConfigPolicyReply{Policy: policy}
*reply, err = s.Encode(r)
if err != nil {
return err
}
return nil
}
// Ping returns nothing in normal operation
func (s *SessionState) Ping(arg []byte, reply *[]byte) error {
// For now we return nil. We can return an error if we are shutting
// down or otherwise in a state we should signal poor health.
// Reply should contain any context.
s.ResetHeartbeat()
s.logger.Println("Ping received")
*reply = []byte{}
return nil
}
// Kill will stop a running plugin
func (s *SessionState) Kill(args []byte, reply *[]byte) error {
a := &KillArgs{}
err := s.Decode(args, a)
if err != nil {
return err
}
s.logger.Printf("Kill called by agent, reason: %s\n", a.Reason)
go func() {
time.Sleep(time.Second * 2)
s.killChan <- 0
}()
*reply = []byte{}
return nil
}
// Logger gets the SessionState logger
func (s *SessionState) Logger() *log.Logger {
return s.logger
}
// ListenAddress gets the SessionState listen address
func (s *SessionState) ListenAddress() string {
return s.listenAddress
}
//ListenPort gets the SessionState listen port
func (s *SessionState) ListenPort() string {
return s.listenPort
}
// SetListenAddress sets SessionState listen address
func (s *SessionState) SetListenAddress(a string) {
s.listenAddress = a
}
func (s *SessionState) ResetHeartbeat() {
s.LastPing = time.Now()
}
// Token gets the SessionState token
func (s *SessionState) Token() string {
return s.token
}
// KillChan gets the SessionState killchan
func (s *SessionState) KillChan() chan int {
return s.killChan
}
func (s *SessionState) isDaemon() bool {
return !s.NoDaemon
}
type SetKeyArgs struct {
Key []byte
}
func (s *SessionState) SetKey(args SetKeyArgs, reply *[]byte) error {
s.logger.Println("SetKey called")
out, err := s.DecryptKey(args.Key)
if err != nil {
return err
}
s.Key = out
return nil
}
func (s *SessionState) generateResponse(r *Response) []byte {
// Add common plugin response properties
r.ListenAddress = s.listenAddress
r.Token = s.token
rs, _ := json.Marshal(r)
return rs
}
func (s *SessionState) heartbeatWatch(killChan chan int) {
s.logger.Println("Heartbeat started")
count := 0
for {
if time.Since(s.LastPing) >= s.PingTimeoutDuration {
count++
s.logger.Printf("Heartbeat timeout %v of %v. (Duration between checks %v)", count, PingTimeoutLimit, s.PingTimeoutDuration)
if count >= PingTimeoutLimit {
s.logger.Println("Heartbeat timeout expired!")
defer close(killChan)
return
}
} else {
s.logger.Println("Heartbeat timeout reset")
// Reset count
count = 0
}
time.Sleep(s.PingTimeoutDuration)
}
}
// NewSessionState takes the plugin args and returns a SessionState
// returns State or error and returnCode:
// 0 - ok
// 2 - error when unmarshaling pluginArgs
// 3 - cannot open error files
func NewSessionState(pluginArgsMsg string, plugin Plugin, meta *PluginMeta) (*SessionState, error, int) {
pluginArg := &Arg{}
err := json.Unmarshal([]byte(pluginArgsMsg), pluginArg)
if err != nil {
return nil, err, 2
}
// If no port was provided we let the OS select a port for us.
// This is safe as address is returned in the Response and keep
// alive prevents unattended plugins.
if pluginArg.listenPort == "" {
pluginArg.listenPort = "0"
}
// If no PingTimeoutDuration was provided we need to set it
if pluginArg.PingTimeoutDuration == 0 {
pluginArg.PingTimeoutDuration = PingTimeoutDurationDefault
}
// Generate random token for this session
rb := make([]byte, 32)
rand.Read(rb)
rs := base64.URLEncoding.EncodeToString(rb)
// Initialize a logger based on PluginLogPath
truncOrAppend := os.O_TRUNC // truncate log file explicitly given by user
// Empty or /tmp means use default tmp log (needs to be removed post-aAtruncOrAppendpha)
if pluginArg.PluginLogPath == "" || pluginArg.PluginLogPath == "/tmp" {
pluginArg.PluginLogPath = "/tmp/snap_plugin.log"
truncOrAppend = os.O_APPEND
}
lf, err := os.OpenFile(pluginArg.PluginLogPath, os.O_WRONLY|os.O_CREATE|truncOrAppend, 0666)
if err != nil {
return nil, errors.New(fmt.Sprintf("error opening log file: %v", err)), 3
}
logger := log.New(lf, ">>>", log.Ldate|log.Ltime)
var enc encoding.Encoder
switch meta.RPCType {
case JSONRPC:
enc = encoding.NewJsonEncoder()
case NativeRPC:
enc = encoding.NewGobEncoder()
}
ss := &SessionState{
Arg: pluginArg,
Encoder: enc,
plugin: plugin,
token: rs,
killChan: make(chan int),
logger: logger,
}
if !meta.Unsecure {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err, 2
}
encrypt := encrypter.New(nil, key)
enc.SetEncrypter(encrypt)
ss.Encrypter = encrypt
ss.privateKey = key
}
return ss, nil, 0
}
func init() {
gob.Register(*(&ctypes.ConfigValueInt{}))
gob.Register(*(&ctypes.ConfigValueStr{}))
gob.Register(*(&ctypes.ConfigValueFloat{}))
gob.Register(*(&ctypes.ConfigValueBool{}))
gob.Register(cpolicy.NewPolicyNode())
gob.Register(&cdata.ConfigDataNode{})
gob.Register(&cpolicy.StringRule{})
gob.Register(&cpolicy.IntRule{})
gob.Register(&cpolicy.FloatRule{})
}