forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations.go
338 lines (269 loc) · 6.78 KB
/
operations.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
package lxd
import (
"encoding/json"
"fmt"
"sync"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/shared/api"
)
// The Operation type represents an ongoing LXD operation (asynchronous processing)
type Operation struct {
api.Operation
r *ProtocolLXD
listener *EventListener
handlerReady bool
handlerLock sync.Mutex
chActive chan bool
}
// AddHandler adds a function to be called whenever an event is received
func (op *Operation) AddHandler(function func(api.Operation)) (*EventTarget, error) {
// Make sure we have a listener setup
err := op.setupListener()
if err != nil {
return nil, err
}
// Make sure we're not racing with ourselves
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// If we're done already, just return
if op.StatusCode.IsFinal() {
return nil, nil
}
// Wrap the function to filter unwanted messages
wrapped := func(data interface{}) {
newOp := op.extractOperation(data)
if newOp == nil {
return
}
function(*newOp)
}
return op.listener.AddHandler([]string{"operation"}, wrapped)
}
// Cancel will request that LXD cancels the operation (if supported)
func (op *Operation) Cancel() error {
return op.r.DeleteOperation(op.ID)
}
// GetWebsocket returns a raw websocket connection from the operation
func (op *Operation) GetWebsocket(secret string) (*websocket.Conn, error) {
return op.r.GetOperationWebsocket(op.ID, secret)
}
// RemoveHandler removes a function to be called whenever an event is received
func (op *Operation) RemoveHandler(target *EventTarget) error {
// Make sure we're not racing with ourselves
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// If the listener is gone, just return
if op.listener == nil {
return nil
}
return op.listener.RemoveHandler(target)
}
// Refresh pulls the current version of the operation and updates the struct
func (op *Operation) Refresh() error {
// Don't bother with a manual update if we are listening for events
if op.handlerReady {
return nil
}
// Get the current version of the operation
newOp, _, err := op.r.GetOperation(op.ID)
if err != nil {
return err
}
// Update the operation struct
op.Operation = *newOp
return nil
}
// Wait lets you wait until the operation reaches a final state
func (op *Operation) Wait() error {
// Check if not done already
if op.StatusCode.IsFinal() {
if op.Err != "" {
return fmt.Errorf(op.Err)
}
return nil
}
// Make sure we have a listener setup
err := op.setupListener()
if err != nil {
return err
}
<-op.chActive
// We're done, parse the result
if op.Err != "" {
return fmt.Errorf(op.Err)
}
return nil
}
func (op *Operation) setupListener() error {
// Make sure we're not racing with ourselves
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// We already have a listener setup
if op.handlerReady {
return nil
}
// Get a new listener
if op.listener == nil {
listener, err := op.r.GetEvents()
if err != nil {
return err
}
op.listener = listener
}
// Setup the handler
chReady := make(chan bool)
_, err := op.listener.AddHandler([]string{"operation"}, func(data interface{}) {
<-chReady
// Get an operation struct out of this data
newOp := op.extractOperation(data)
if newOp == nil {
return
}
// We don't want concurrency while processing events
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// Check if we're done already (because of another event)
if op.listener == nil {
return
}
// Update the struct
op.Operation = *newOp
// And check if we're done
if op.StatusCode.IsFinal() {
op.listener.Disconnect()
op.listener = nil
close(op.chActive)
return
}
})
if err != nil {
op.listener.Disconnect()
op.listener = nil
close(op.chActive)
close(chReady)
return err
}
// Monitor event listener
go func() {
<-chReady
// We don't want concurrency while accessing the listener
op.handlerLock.Lock()
// Check if we're done already (because of another event)
listener := op.listener
if listener == nil {
op.handlerLock.Unlock()
return
}
op.handlerLock.Unlock()
// Wait for the listener or operation to be done
select {
case <-listener.chActive:
op.handlerLock.Lock()
if op.listener != nil {
op.Err = fmt.Sprintf("%v", listener.err)
close(op.chActive)
}
op.handlerLock.Unlock()
case <-op.chActive:
return
}
}()
// And do a manual refresh to avoid races
err = op.Refresh()
if err != nil {
op.listener.Disconnect()
op.listener = nil
close(op.chActive)
close(chReady)
return err
}
// Check if not done already
if op.StatusCode.IsFinal() {
op.listener.Disconnect()
op.listener = nil
close(op.chActive)
op.handlerReady = true
close(chReady)
if op.Err != "" {
return fmt.Errorf(op.Err)
}
return nil
}
// Start processing background updates
op.handlerReady = true
close(chReady)
return nil
}
func (op *Operation) extractOperation(data interface{}) *api.Operation {
// Extract the metadata
meta, ok := data.(map[string]interface{})["metadata"]
if !ok {
return nil
}
// And attempt to decode it as JSON operation data
encoded, err := json.Marshal(meta)
if err != nil {
return nil
}
newOp := api.Operation{}
err = json.Unmarshal(encoded, &newOp)
if err != nil {
return nil
}
// And now check that it's what we want
if newOp.ID != op.ID {
return nil
}
return &newOp
}
// The RemoteOperation type represents an ongoing LXD operation between two servers
type RemoteOperation struct {
targetOp *Operation
handlers []func(api.Operation)
chDone chan bool
chPost chan bool
err error
}
// AddHandler adds a function to be called whenever an event is received
func (op *RemoteOperation) AddHandler(function func(api.Operation)) (*EventTarget, error) {
var err error
var target *EventTarget
// Attach to the existing target operation
if op.targetOp != nil {
target, err = op.targetOp.AddHandler(function)
if err != nil {
return nil, err
}
} else {
// Generate a mock EventTarget
target = &EventTarget{
function: func(interface{}) { function(api.Operation{}) },
types: []string{"operation"},
}
}
// Add the handler to our list
op.handlers = append(op.handlers, function)
return target, nil
}
// CancelTarget attempts to cancel the target operation
func (op *RemoteOperation) CancelTarget() error {
if op.targetOp == nil {
return fmt.Errorf("No associated target operation")
}
return op.targetOp.Cancel()
}
// GetTarget returns the target operation
func (op *RemoteOperation) GetTarget() (*api.Operation, error) {
if op.targetOp == nil {
return nil, fmt.Errorf("No associated target operation")
}
return &op.targetOp.Operation, nil
}
// Wait lets you wait until the operation reaches a final state
func (op *RemoteOperation) Wait() error {
<-op.chDone
if op.chPost != nil {
<-op.chPost
}
return op.err
}