/
server.go
266 lines (226 loc) · 6.94 KB
/
server.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
/*
* Copyright (C) 2016 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 server
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/connetos/anywatch/api"
"github.com/connetos/anywatch/common"
"github.com/connetos/anywatch/flow"
"github.com/connetos/anywatch/flow/ondemand"
"github.com/connetos/anywatch/flow/probes"
shttp "github.com/connetos/anywatch/http"
"github.com/connetos/anywatch/logging"
"github.com/connetos/anywatch/topology/graph"
)
// OnDemandProbeServer describes an ondemand probe server based on websocket
type OnDemandProbeServer struct {
sync.RWMutex
graph.DefaultGraphListener
shttp.DefaultWSClientEventHandler
Graph *graph.Graph
Probes *probes.FlowProbeBundle
WSAsyncClientPool *shttp.WSAsyncClientPool
fta *flow.TableAllocator
activeProbes map[graph.Identifier]*flow.Table
captures map[graph.Identifier]*api.Capture
}
func (o *OnDemandProbeServer) isActive(n *graph.Node) bool {
o.RLock()
defer o.RUnlock()
_, active := o.activeProbes[n.ID]
return active
}
func (o *OnDemandProbeServer) getProbe(n *graph.Node, capture *api.Capture) (*probes.FlowProbe, error) {
tp, _ := n.GetFieldString("Type")
capType := ""
if capture.Type != "" {
types := common.CaptureTypes[tp].Allowed
for _, t := range types {
if t == capture.Type {
capType = t
break
}
}
if capType == "" {
return nil, fmt.Errorf("Capture type %v not allowed on this node: %v", capture, n)
}
} else {
// no capture type defined for this type of node, ex: ovsport
c, ok := common.CaptureTypes[tp]
if !ok {
return nil, nil
}
capType = c.Default
}
probe := o.Probes.GetProbe(capType)
if probe == nil {
return nil, fmt.Errorf("Unable to find probe for this capture type: %v", capType)
}
fprobe := probe.(*probes.FlowProbe)
return fprobe, nil
}
func (o *OnDemandProbeServer) registerProbe(n *graph.Node, capture *api.Capture) bool {
name, _ := n.GetFieldString("Name")
if name == "" {
logging.GetLogger().Debugf("Unable to register flow probe, name of node unknown %s", n.ID)
return false
}
logging.GetLogger().Debugf("Attempting to register probe on node %s", name)
if o.isActive(n) {
logging.GetLogger().Debugf("A probe already exists for %s", n.ID)
return false
}
if _, err := n.GetFieldString("Type"); err != nil {
logging.GetLogger().Infof("Unable to register flow probe type of node unknown %v", n)
return false
}
tid, _ := n.GetFieldString("TID")
if tid == "" {
logging.GetLogger().Infof("Unable to register flow probe without node TID %v", n)
return false
}
o.Lock()
defer o.Unlock()
fprobe, err := o.getProbe(n, capture)
if fprobe == nil {
if err != nil {
logging.GetLogger().Error(err.Error())
}
return false
}
ft := o.fta.Alloc(fprobe.AsyncFlowPipeline)
ft.SetNodeTID(tid)
if err := fprobe.RegisterProbe(n, capture, ft); err != nil {
logging.GetLogger().Debugf("Failed to register flow probe: %s", err.Error())
o.fta.Release(ft)
return false
}
o.activeProbes[n.ID] = ft
o.captures[n.ID] = capture
logging.GetLogger().Debugf("New active probe on: %v(%v)", n, capture)
return true
}
func (o *OnDemandProbeServer) unregisterProbe(n *graph.Node) bool {
if !o.isActive(n) {
return false
}
o.Lock()
c := o.captures[n.ID]
o.Unlock()
fprobe, err := o.getProbe(n, c)
if fprobe == nil {
if err != nil {
logging.GetLogger().Error(err.Error())
}
return false
}
if err := fprobe.UnregisterProbe(n); err != nil {
logging.GetLogger().Debugf("Failed to unregister flow probe: %s", err.Error())
}
o.Lock()
o.fta.Release(o.activeProbes[n.ID])
delete(o.activeProbes, n.ID)
delete(o.captures, n.ID)
o.Unlock()
return true
}
// OnMessage websocket message, valid message type are CaptureStart, CaptureStop
func (o *OnDemandProbeServer) OnMessage(c *shttp.WSAsyncClient, msg shttp.WSMessage) {
var query ondemand.CaptureQuery
if err := json.Unmarshal([]byte(*msg.Obj), &query); err != nil {
logging.GetLogger().Errorf("Unable to decode capture %v", msg)
return
}
status := http.StatusBadRequest
o.Graph.Lock()
switch msg.Type {
case "CaptureStart":
n := o.Graph.GetNode(graph.Identifier(query.NodeID))
if n == nil {
logging.GetLogger().Errorf("Unknown node %s for new capture", query.NodeID)
status = http.StatusNotFound
break
}
status = http.StatusOK
if _, err := n.GetFieldString("Capture.ID"); err == nil {
logging.GetLogger().Debugf("Capture already started on node %s", n.ID)
} else {
if ok := o.registerProbe(n, &query.Capture); ok {
t := o.Graph.StartMetadataTransaction(n)
t.AddMetadata("Capture.ID", query.Capture.UUID)
t.Commit()
} else {
status = http.StatusInternalServerError
}
}
case "CaptureStop":
n := o.Graph.GetNode(graph.Identifier(query.NodeID))
if n == nil {
logging.GetLogger().Errorf("Unknown node %s for new capture", query.NodeID)
status = http.StatusNotFound
break
}
status = http.StatusOK
if ok := o.unregisterProbe(n); ok {
metadata := n.Metadata()
delete(metadata, "Capture")
o.Graph.SetMetadata(n, metadata)
} else {
status = http.StatusInternalServerError
}
}
// be sure to unlock before sending message
o.Graph.Unlock()
reply := msg.Reply(&query, msg.Type+"Reply", status)
c.SendWSMessage(reply)
}
// OnNodeDeleted graph event
func (o *OnDemandProbeServer) OnNodeDeleted(n *graph.Node) {
if _, err := n.GetFieldString("Capture.ID"); err != nil {
return
}
o.unregisterProbe(n)
}
// Start the probe
func (o *OnDemandProbeServer) Start() error {
o.Graph.AddEventListener(o)
o.WSAsyncClientPool.AddEventHandler(o, []string{ondemand.Namespace})
return nil
}
// Stop the probe
func (o *OnDemandProbeServer) Stop() {
o.Graph.RemoveEventListener(o)
}
// NewOnDemandProbeServer creates a new Ondemand probes server based on graph and websocket
func NewOnDemandProbeServer(fb *probes.FlowProbeBundle, g *graph.Graph, wspool *shttp.WSAsyncClientPool) (*OnDemandProbeServer, error) {
return &OnDemandProbeServer{
Graph: g,
Probes: fb,
WSAsyncClientPool: wspool,
fta: fb.FlowTableAllocator,
activeProbes: make(map[graph.Identifier]*flow.Table),
captures: make(map[graph.Identifier]*api.Capture),
}, nil
}