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
|
package lxd
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/gorilla/websocket"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
)
// Event handling functions
// getEvents connects to the LXD monitoring interface.
func (r *ProtocolLXD) getEvents(allProjects bool) (*EventListener, error) {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
ctx, cancel := context.WithCancel(context.Background())
// Setup a new listener
listener := EventListener{
r: r,
ctx: ctx,
ctxCancel: cancel,
}
connInfo, _ := r.GetConnectionInfo()
if connInfo.Project == "" {
return nil, fmt.Errorf("Unexpected empty project in connection info")
}
if !allProjects {
listener.projectName = connInfo.Project
}
// There is an existing Go routine for the required project filter, so just add another target.
if r.eventListeners[listener.projectName] != nil {
r.eventListeners[listener.projectName] = append(r.eventListeners[listener.projectName], &listener)
return &listener, nil
}
// Setup a new connection with LXD
var url string
var err error
if allProjects {
url, err = r.setQueryAttributes("/events?all-projects=true")
} else {
url, err = r.setQueryAttributes("/events")
}
if err != nil {
return nil, err
}
// Connect websocket and save.
wsConn, err := r.websocket(url)
if err != nil {
return nil, err
}
r.eventConnsLock.Lock()
r.eventConns[listener.projectName] = wsConn // Save for others to use.
r.eventConnsLock.Unlock()
// Initialize the event listener list if we were able to connect to the events websocket.
r.eventListeners[listener.projectName] = []*EventListener{&listener}
// Spawn a watcher that will close the websocket connection after all
// listeners are gone.
stopCh := make(chan struct{})
go func() {
for {
select {
case <-time.After(time.Minute):
case <-r.ctxConnected.Done():
case <-stopCh:
}
r.eventListenersLock.Lock()
r.eventConnsLock.Lock()
if len(r.eventListeners[listener.projectName]) == 0 {
// We don't need the connection anymore, disconnect and clear.
if r.eventListeners[listener.projectName] != nil {
_ = r.eventConns[listener.projectName].Close()
delete(r.eventConns, listener.projectName)
}
r.eventListeners[listener.projectName] = nil
r.eventListenersLock.Unlock()
r.eventConnsLock.Unlock()
return
}
r.eventListenersLock.Unlock()
r.eventConnsLock.Unlock()
}
}()
// Spawn the listener
go func() {
for {
_, data, err := wsConn.ReadMessage()
if err != nil {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
// Tell all the current listeners about the failure
for _, listener := range r.eventListeners[listener.projectName] {
listener.err = err
listener.ctxCancel()
}
// And remove them all from the list so that when watcher routine runs it will
// close the websocket connection.
r.eventListeners[listener.projectName] = nil
close(stopCh) // Instruct watcher go routine to cleanup.
return
}
// Attempt to unpack the message
event := api.Event{}
err = json.Unmarshal(data, &event)
if err != nil {
continue
}
// Extract the message type
if event.Type == "" {
continue
}
// Send the message to all handlers
r.eventListenersLock.Lock()
for _, listener := range r.eventListeners[listener.projectName] {
listener.targetsLock.Lock()
for _, target := range listener.targets {
if target.types != nil && !shared.StringInSlice(event.Type, target.types) {
continue
}
go target.function(event)
}
listener.targetsLock.Unlock()
}
r.eventListenersLock.Unlock()
}
}()
return &listener, nil
}
// GetEvents gets the events for the project defined on the client.
func (r *ProtocolLXD) GetEvents() (*EventListener, error) {
return r.getEvents(false)
}
// GetEventsAllProjects gets events for all projects.
func (r *ProtocolLXD) GetEventsAllProjects() (*EventListener, error) {
return r.getEvents(true)
}
// SendEvent send an event to the server via the client's event listener connection.
func (r *ProtocolLXD) SendEvent(event api.Event) error {
r.eventConnsLock.Lock()
defer r.eventConnsLock.Unlock()
// Find an available event listener connection.
// It doesn't matter which project the event listener connection is using, as this only affects which
// events are received from the server, not which events we can send to it.
var eventConn *websocket.Conn
for _, eventConn = range r.eventConns {
break
}
if eventConn == nil {
return fmt.Errorf("No available event listener connection")
}
deadline, ok := r.ctx.Deadline()
if !ok {
deadline = time.Now().Add(5 * time.Second)
}
_ = eventConn.SetWriteDeadline(deadline)
return eventConn.WriteJSON(event)
}
|