blob: 1c03d6fd6b66d135a1b0d6a0344004f7a8ce9863 [file] [log] [blame]
Simon Hunt1e4a0012015-01-21 11:36:08 -08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 ONOS GUI -- Remote -- Web Socket Service
19 */
20(function () {
21 'use strict';
22
Thomas Vachuska329af532015-03-10 02:08:33 -070023 // injected refs
Simon Hunt20207df2015-03-10 18:30:14 -070024 var $log, $loc, fs, ufs, wsock, vs;
Simon Hunt1e4a0012015-01-21 11:36:08 -080025
Thomas Vachuska329af532015-03-10 02:08:33 -070026 // internal state
Simon Hunt8b6d2d42015-03-11 13:04:52 -070027 var webSockOpts, // web socket options
28 ws = null, // web socket reference
Simon Hunt20207df2015-03-10 18:30:14 -070029 wsUp = false, // web socket is good to go
30 sid = 0, // event sequence identifier
31 handlers = {}, // event handler bindings
32 pendingEvents = [], // events TX'd while socket not up
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070033 host, // web socket host
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070034 url, // web socket URL
Simon Hunt8b6d2d42015-03-11 13:04:52 -070035 clusterNodes = [], // ONOS instances data for failover
36 clusterIndex = -1, // the instance to which we are connected
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070037 connectRetries = 0, // limit our attempts at reconnecting
38 openListeners = {}, // registered listeners for websocket open()
39 nextListenerId = 1; // internal ID for open listeners
Simon Hunt8b6d2d42015-03-11 13:04:52 -070040
41 // =======================
42 // === Bootstrap Handler
Simon Huntacf410b2015-01-23 10:05:48 -080043
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070044 var builtinHandlers = {
Simon Hunt8b6d2d42015-03-11 13:04:52 -070045 bootstrap: function (data) {
Thomas Vachuska20084b72015-03-11 13:46:50 -070046 clusterNodes = data.clusterNodes;
Simon Hunt8b6d2d42015-03-11 13:04:52 -070047 clusterNodes.forEach(function (d, i) {
48 if (d.uiAttached) {
49 clusterIndex = i;
Thomas Vachuska20084b72015-03-11 13:46:50 -070050 $log.info('Connected to cluster node ' + d.ip);
51 // TODO: add connect info to masthead somewhere
Simon Hunt8b6d2d42015-03-11 13:04:52 -070052 }
53 });
54 }
55 };
Simon Hunt20207df2015-03-10 18:30:14 -070056
57 // ==========================
58 // === Web socket callbacks
59
60 function handleOpen() {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070061 $log.info('Web socket open - ', url);
Simon Hunt8b6d2d42015-03-11 13:04:52 -070062 vs.hide();
63
Simon Hunt4deb0e82015-06-10 16:18:25 -070064 if (fs.debugOn('txrx')) {
65 $log.debug('Sending ' + pendingEvents.length + ' pending event(s)...');
66 }
Simon Hunt20207df2015-03-10 18:30:14 -070067 pendingEvents.forEach(function (ev) {
68 _send(ev);
69 });
70 pendingEvents = [];
Simon Hunt8b6d2d42015-03-11 13:04:52 -070071
72 connectRetries = 0;
Simon Hunt20207df2015-03-10 18:30:14 -070073 wsUp = true;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070074 informListeners(host, url);
Simon Hunt20207df2015-03-10 18:30:14 -070075 }
76
77 // Handles the specified (incoming) message using handler bindings.
78 function handleMessage(msgEvent) {
79 var ev, h;
80
81 try {
82 ev = JSON.parse(msgEvent.data);
Simon Hunt20207df2015-03-10 18:30:14 -070083 } catch (e) {
Simon Hunt2d16fc82015-03-10 20:19:52 -070084 $log.error('Message.data is not valid JSON', msgEvent.data, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070085 return null;
Simon Hunt20207df2015-03-10 18:30:14 -070086 }
Simon Hunt4deb0e82015-06-10 16:18:25 -070087 if (fs.debugOn('txrx')) {
88 $log.debug(' << *Rx* ', ev.event, ev.payload);
89 }
Simon Hunt2d16fc82015-03-10 20:19:52 -070090
91 if (h = handlers[ev.event]) {
92 try {
93 h(ev.payload);
94 } catch (e) {
95 $log.error('Problem handling event:', ev, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070096 return null;
Simon Hunt2d16fc82015-03-10 20:19:52 -070097 }
98 } else {
99 $log.warn('Unhandled event:', ev);
100 }
101
Simon Hunt20207df2015-03-10 18:30:14 -0700102 }
103
104 function handleClose() {
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700105 var gsucc;
106
Simon Hunt20207df2015-03-10 18:30:14 -0700107 $log.info('Web socket closed');
108 wsUp = false;
109
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700110 if (gsucc = findGuiSuccessor()) {
111 createWebSocket(webSockOpts, gsucc);
112 } else {
113 // If no controllers left to contact, show the Veil...
114 vs.show([
115 'Oops!',
116 'Web-socket connection to server closed...',
117 'Try refreshing the page.'
118 ]);
119 }
Simon Hunt20207df2015-03-10 18:30:14 -0700120 }
121
122
123 // ==============================
124 // === Private Helper Functions
125
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700126 function findGuiSuccessor() {
127 var ncn = clusterNodes.length,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700128 ip, node;
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700129
130 while (connectRetries < ncn && !ip) {
131 connectRetries++;
132 clusterIndex = (clusterIndex + 1) % ncn;
133 node = clusterNodes[clusterIndex];
134 ip = node && node.ip;
135 }
136
137 return ip;
138 }
139
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700140 function informListeners(host, url) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700141 angular.forEach(openListeners, function (lsnr) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700142 lsnr.cb(host, url);
143 });
144 }
145
Simon Hunt20207df2015-03-10 18:30:14 -0700146 function _send(ev) {
Simon Hunt4deb0e82015-06-10 16:18:25 -0700147 if (fs.debugOn('txrx')) {
148 $log.debug(' *Tx* >> ', ev.event, ev.payload);
149 }
Simon Hunt20207df2015-03-10 18:30:14 -0700150 ws.send(JSON.stringify(ev));
151 }
152
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700153 function noHandlersWarn(handlers, caller) {
154 if (!handlers || fs.isEmptyObject(handlers)) {
155 $log.warn('WSS.' + caller + '(): no event handlers');
156 return true;
157 }
158 return false;
159 }
160
Simon Hunt20207df2015-03-10 18:30:14 -0700161 // ===================
162 // === API Functions
163
164 // Required for unit tests to set to known state
Thomas Vachuska329af532015-03-10 02:08:33 -0700165 function resetSid() {
166 sid = 0;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800167 }
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700168 function resetState() {
169 webSockOpts = undefined;
170 ws = null;
171 wsUp = false;
172 host = undefined;
173 url = undefined;
174 pendingEvents = [];
175 handlers = {};
176 sid = 0;
177 clusterNodes = [];
178 clusterIndex = -1;
179 connectRetries = 0;
180 openListeners = {};
181 nextListenerId = 1;
182 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800183
Simon Hunt20207df2015-03-10 18:30:14 -0700184 // Currently supported opts:
185 // wsport: web socket port (other than default 8181)
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700186 // host: if defined, is the host address to use
187 function createWebSocket(opts, _host_) {
Simon Hunt20207df2015-03-10 18:30:14 -0700188 var wsport = (opts && opts.wsport) || null;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700189
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700190 webSockOpts = opts; // preserved for future calls
Simon Hunt20207df2015-03-10 18:30:14 -0700191
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700192 host = _host_ || $loc.host();
193 url = ufs.wsUrl('core', wsport, _host_);
Simon Hunt20207df2015-03-10 18:30:14 -0700194
195 $log.debug('Attempting to open websocket to: ' + url);
196 ws = wsock.newWebSocket(url);
197 if (ws) {
198 ws.onopen = handleOpen;
199 ws.onmessage = handleMessage;
200 ws.onclose = handleClose;
201 }
202 // Note: Wsock logs an error if the new WebSocket call fails
Simon Hunt2d16fc82015-03-10 20:19:52 -0700203 return url;
Simon Hunt20207df2015-03-10 18:30:14 -0700204 }
205
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700206 // Binds the message handlers to their message type (event type) as
207 // specified in the given map. Note that keys are the event IDs; values
208 // are either:
209 // * the event handler function, or
210 // * an API object which has an event handler for the key
211 //
Thomas Vachuska329af532015-03-10 02:08:33 -0700212 function bindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700213 var m,
Thomas Vachuska329af532015-03-10 02:08:33 -0700214 dups = [];
Simon Hunt970e7fd2015-01-22 17:46:28 -0800215
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700216 if (noHandlersWarn(handlerMap, 'bindHandlers')) {
217 return null;
218 }
219 m = d3.map(handlerMap);
220
Simon Hunt20207df2015-03-10 18:30:14 -0700221 m.forEach(function (eventId, api) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700222 var fn = fs.isF(api) || fs.isF(api[eventId]);
Thomas Vachuska329af532015-03-10 02:08:33 -0700223 if (!fn) {
Simon Hunt20207df2015-03-10 18:30:14 -0700224 $log.warn(eventId + ' handler not a function');
Thomas Vachuska329af532015-03-10 02:08:33 -0700225 return;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800226 }
Thomas Vachuska329af532015-03-10 02:08:33 -0700227
Simon Hunt20207df2015-03-10 18:30:14 -0700228 if (handlers[eventId]) {
229 dups.push(eventId);
Thomas Vachuska329af532015-03-10 02:08:33 -0700230 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700231 handlers[eventId] = fn;
Thomas Vachuska329af532015-03-10 02:08:33 -0700232 }
233 });
234 if (dups.length) {
235 $log.warn('duplicate bindings ignored:', dups);
236 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800237 }
238
Thomas Vachuska329af532015-03-10 02:08:33 -0700239 // Unbinds the specified message handlers.
Simon Hunt20207df2015-03-10 18:30:14 -0700240 // Expected that the same map will be used, but we only care about keys
Thomas Vachuska329af532015-03-10 02:08:33 -0700241 function unbindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700242 var m;
243
244 if (noHandlersWarn(handlerMap, 'unbindHandlers')) {
245 return null;
246 }
247 m = d3.map(handlerMap);
Simon Hunt20207df2015-03-10 18:30:14 -0700248
249 m.forEach(function (eventId) {
250 delete handlers[eventId];
Thomas Vachuska329af532015-03-10 02:08:33 -0700251 });
252 }
Simon Huntacf410b2015-01-23 10:05:48 -0800253
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700254 function addOpenListener(callback) {
255 var id = nextListenerId++,
256 cb = fs.isF(callback),
257 o = { id: id, cb: cb };
258
259 if (cb) {
260 openListeners[id] = o;
261 } else {
262 $log.error('WSS.addOpenListener(): callback not a function');
263 o.error = 'No callback defined';
264 }
265 return o;
266 }
267
268 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700269 var id = fs.isO(lsnr) && lsnr.id,
270 o;
271 if (!id) {
272 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
273 return null;
274 }
275 o = openListeners[id];
276
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700277 if (o) {
278 delete openListeners[id];
279 }
280 }
281
Simon Hunt20207df2015-03-10 18:30:14 -0700282 // Formulates an event message and sends it via the web-socket.
283 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700284 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700285 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700286 event: evType,
287 sid: ++sid,
Simon Hunt20207df2015-03-10 18:30:14 -0700288 payload: payload || {}
289 };
290
291 if (wsUp) {
292 _send(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700293 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700294 pendingEvents.push(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700295 }
296 }
297
298
Simon Hunt20207df2015-03-10 18:30:14 -0700299 // ============================
300 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800301 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800302 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700303 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
304 'VeilService',
Simon Huntbb920fd2015-01-22 17:06:32 -0800305
Simon Hunt20207df2015-03-10 18:30:14 -0700306 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_, _vs_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700307 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700308 $loc = _$loc_;
309 fs = _fs_;
310 ufs = _ufs_;
311 wsock = _wsock_;
312 vs = _vs_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800313
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700314 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700315
Simon Hunt1e4a0012015-01-21 11:36:08 -0800316 return {
Thomas Vachuska329af532015-03-10 02:08:33 -0700317 resetSid: resetSid,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700318 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700319 createWebSocket: createWebSocket,
320 bindHandlers: bindHandlers,
321 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700322 addOpenListener: addOpenListener,
323 removeOpenListener: removeOpenListener,
Thomas Vachuska329af532015-03-10 02:08:33 -0700324 sendEvent: sendEvent
Simon Hunt1e4a0012015-01-21 11:36:08 -0800325 };
Simon Hunt20207df2015-03-10 18:30:14 -0700326 }
327 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800328
329}());