blob: 5922c60c808ea7888c783058ca818b7d4ed7b425 [file] [log] [blame]
Simon Hunt1e4a0012015-01-21 11:36:08 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Simon Hunt1e4a0012015-01-21 11:36:08 -08003 *
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 Huntab34ecb2015-12-11 13:14:48 -080024 var $log, $loc, fs, ufs, wsock, vs, ls;
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
Simon Hunt20207df2015-03-10 18:30:14 -070030 handlers = {}, // event handler bindings
31 pendingEvents = [], // events TX'd while socket not up
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070032 host, // web socket host
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070033 url, // web socket URL
Simon Hunt8b6d2d42015-03-11 13:04:52 -070034 clusterNodes = [], // ONOS instances data for failover
35 clusterIndex = -1, // the instance to which we are connected
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070036 connectRetries = 0, // limit our attempts at reconnecting
37 openListeners = {}, // registered listeners for websocket open()
Simon Hunt7715e892016-04-12 19:55:32 -070038 nextListenerId = 1, // internal ID for open listeners
39 loggedInUser = null; // name of logged-in user
Simon Hunt8b6d2d42015-03-11 13:04:52 -070040
Simon Hunt1169c952017-06-05 11:20:11 -070041 // built-in handlers
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070042 var builtinHandlers = {
Simon Hunt1169c952017-06-05 11:20:11 -070043
Simon Hunt8b6d2d42015-03-11 13:04:52 -070044 bootstrap: function (data) {
Simon Hunt7715e892016-04-12 19:55:32 -070045 $log.debug('bootstrap data', data);
46 loggedInUser = data.user;
Thomas Vachuska20084b72015-03-11 13:46:50 -070047 clusterNodes = data.clusterNodes;
Simon Hunt8b6d2d42015-03-11 13:04:52 -070048 clusterNodes.forEach(function (d, i) {
49 if (d.uiAttached) {
50 clusterIndex = i;
Thomas Vachuska20084b72015-03-11 13:46:50 -070051 $log.info('Connected to cluster node ' + d.ip);
52 // TODO: add connect info to masthead somewhere
Simon Hunt8b6d2d42015-03-11 13:04:52 -070053 }
54 });
Simon Hunt1169c952017-06-05 11:20:11 -070055 },
56
57 error: function (data) {
58 var m = data.message || 'error from server';
59 $log.error(m, data);
60
61 // Unrecoverable error - throw up the veil...
62 vs && vs.show([
63 'Oops!',
64 'Server reports error...',
65 m
66 ]);
Simon Hunt8b6d2d42015-03-11 13:04:52 -070067 }
68 };
Simon Hunt20207df2015-03-10 18:30:14 -070069
Steven Burrows530cf462016-04-12 16:04:37 +010070
Simon Hunt20207df2015-03-10 18:30:14 -070071 // ==========================
72 // === Web socket callbacks
73
74 function handleOpen() {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070075 $log.info('Web socket open - ', url);
Thomas Vachuska0af26912016-03-21 21:37:30 -070076 vs && vs.hide();
Simon Hunt8b6d2d42015-03-11 13:04:52 -070077
Simon Hunt4deb0e82015-06-10 16:18:25 -070078 if (fs.debugOn('txrx')) {
79 $log.debug('Sending ' + pendingEvents.length + ' pending event(s)...');
80 }
Simon Hunt20207df2015-03-10 18:30:14 -070081 pendingEvents.forEach(function (ev) {
82 _send(ev);
83 });
84 pendingEvents = [];
Simon Hunt8b6d2d42015-03-11 13:04:52 -070085
86 connectRetries = 0;
Simon Hunt20207df2015-03-10 18:30:14 -070087 wsUp = true;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070088 informListeners(host, url);
Simon Hunt20207df2015-03-10 18:30:14 -070089 }
90
91 // Handles the specified (incoming) message using handler bindings.
92 function handleMessage(msgEvent) {
93 var ev, h;
94
95 try {
96 ev = JSON.parse(msgEvent.data);
Simon Hunt20207df2015-03-10 18:30:14 -070097 } catch (e) {
Simon Hunt2d16fc82015-03-10 20:19:52 -070098 $log.error('Message.data is not valid JSON', msgEvent.data, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070099 return null;
Simon Hunt20207df2015-03-10 18:30:14 -0700100 }
Simon Hunt4deb0e82015-06-10 16:18:25 -0700101 if (fs.debugOn('txrx')) {
102 $log.debug(' << *Rx* ', ev.event, ev.payload);
103 }
Simon Hunt2d16fc82015-03-10 20:19:52 -0700104
105 if (h = handlers[ev.event]) {
106 try {
107 h(ev.payload);
108 } catch (e) {
109 $log.error('Problem handling event:', ev, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700110 return null;
Simon Hunt2d16fc82015-03-10 20:19:52 -0700111 }
112 } else {
113 $log.warn('Unhandled event:', ev);
114 }
115
Simon Hunt20207df2015-03-10 18:30:14 -0700116 }
117
118 function handleClose() {
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700119 var gsucc;
120
Simon Hunt8a0429a2017-01-06 16:52:47 -0800121 $log.warn('Web socket closed');
Thomas Vachuska0af26912016-03-21 21:37:30 -0700122 ls && ls.stop();
Simon Hunt20207df2015-03-10 18:30:14 -0700123 wsUp = false;
124
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700125 if (gsucc = findGuiSuccessor()) {
126 createWebSocket(webSockOpts, gsucc);
127 } else {
128 // If no controllers left to contact, show the Veil...
Thomas Vachuska0af26912016-03-21 21:37:30 -0700129 vs && vs.show([
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700130 'Oops!',
131 'Web-socket connection to server closed...',
132 'Try refreshing the page.'
133 ]);
134 }
Simon Hunt20207df2015-03-10 18:30:14 -0700135 }
136
137
138 // ==============================
139 // === Private Helper Functions
140
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700141 function findGuiSuccessor() {
142 var ncn = clusterNodes.length,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700143 ip, node;
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700144
145 while (connectRetries < ncn && !ip) {
146 connectRetries++;
147 clusterIndex = (clusterIndex + 1) % ncn;
148 node = clusterNodes[clusterIndex];
149 ip = node && node.ip;
150 }
151
152 return ip;
153 }
154
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700155 function informListeners(host, url) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700156 angular.forEach(openListeners, function (lsnr) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700157 lsnr.cb(host, url);
158 });
159 }
160
Simon Hunt20207df2015-03-10 18:30:14 -0700161 function _send(ev) {
Simon Hunt4deb0e82015-06-10 16:18:25 -0700162 if (fs.debugOn('txrx')) {
163 $log.debug(' *Tx* >> ', ev.event, ev.payload);
164 }
Simon Hunt20207df2015-03-10 18:30:14 -0700165 ws.send(JSON.stringify(ev));
166 }
167
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700168 function noHandlersWarn(handlers, caller) {
169 if (!handlers || fs.isEmptyObject(handlers)) {
170 $log.warn('WSS.' + caller + '(): no event handlers');
171 return true;
172 }
173 return false;
174 }
175
Simon Hunt20207df2015-03-10 18:30:14 -0700176 // ===================
177 // === API Functions
178
179 // Required for unit tests to set to known state
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700180 function resetState() {
181 webSockOpts = undefined;
182 ws = null;
183 wsUp = false;
184 host = undefined;
185 url = undefined;
186 pendingEvents = [];
187 handlers = {};
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700188 clusterNodes = [];
189 clusterIndex = -1;
190 connectRetries = 0;
191 openListeners = {};
192 nextListenerId = 1;
193 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800194
Simon Hunt20207df2015-03-10 18:30:14 -0700195 // Currently supported opts:
196 // wsport: web socket port (other than default 8181)
Simon Hunt1169c952017-06-05 11:20:11 -0700197 // host: if defined, is the host address to use
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700198 function createWebSocket(opts, _host_) {
Simon Hunt20207df2015-03-10 18:30:14 -0700199 var wsport = (opts && opts.wsport) || null;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700200
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700201 webSockOpts = opts; // preserved for future calls
Simon Hunt20207df2015-03-10 18:30:14 -0700202
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700203 host = _host_ || $loc.host();
204 url = ufs.wsUrl('core', wsport, _host_);
Simon Hunt20207df2015-03-10 18:30:14 -0700205
206 $log.debug('Attempting to open websocket to: ' + url);
207 ws = wsock.newWebSocket(url);
208 if (ws) {
209 ws.onopen = handleOpen;
210 ws.onmessage = handleMessage;
211 ws.onclose = handleClose;
Simon Hunt1169c952017-06-05 11:20:11 -0700212
213 sendEvent('authentication', {token: onosAuth});
Simon Hunt20207df2015-03-10 18:30:14 -0700214 }
215 // Note: Wsock logs an error if the new WebSocket call fails
Simon Hunt2d16fc82015-03-10 20:19:52 -0700216 return url;
Simon Hunt20207df2015-03-10 18:30:14 -0700217 }
218
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700219 // Binds the message handlers to their message type (event type) as
220 // specified in the given map. Note that keys are the event IDs; values
221 // are either:
222 // * the event handler function, or
223 // * an API object which has an event handler for the key
224 //
Thomas Vachuska329af532015-03-10 02:08:33 -0700225 function bindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700226 var m,
Thomas Vachuska329af532015-03-10 02:08:33 -0700227 dups = [];
Simon Hunt970e7fd2015-01-22 17:46:28 -0800228
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700229 if (noHandlersWarn(handlerMap, 'bindHandlers')) {
230 return null;
231 }
232 m = d3.map(handlerMap);
233
Simon Hunt20207df2015-03-10 18:30:14 -0700234 m.forEach(function (eventId, api) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700235 var fn = fs.isF(api) || fs.isF(api[eventId]);
Thomas Vachuska329af532015-03-10 02:08:33 -0700236 if (!fn) {
Simon Hunt20207df2015-03-10 18:30:14 -0700237 $log.warn(eventId + ' handler not a function');
Thomas Vachuska329af532015-03-10 02:08:33 -0700238 return;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800239 }
Thomas Vachuska329af532015-03-10 02:08:33 -0700240
Simon Hunt20207df2015-03-10 18:30:14 -0700241 if (handlers[eventId]) {
242 dups.push(eventId);
Thomas Vachuska329af532015-03-10 02:08:33 -0700243 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700244 handlers[eventId] = fn;
Thomas Vachuska329af532015-03-10 02:08:33 -0700245 }
246 });
247 if (dups.length) {
248 $log.warn('duplicate bindings ignored:', dups);
249 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800250 }
251
Thomas Vachuska329af532015-03-10 02:08:33 -0700252 // Unbinds the specified message handlers.
Simon Hunt20207df2015-03-10 18:30:14 -0700253 // Expected that the same map will be used, but we only care about keys
Thomas Vachuska329af532015-03-10 02:08:33 -0700254 function unbindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700255 var m;
256
257 if (noHandlersWarn(handlerMap, 'unbindHandlers')) {
258 return null;
259 }
260 m = d3.map(handlerMap);
Simon Hunt20207df2015-03-10 18:30:14 -0700261
262 m.forEach(function (eventId) {
263 delete handlers[eventId];
Thomas Vachuska329af532015-03-10 02:08:33 -0700264 });
265 }
Simon Huntacf410b2015-01-23 10:05:48 -0800266
Simon Huntd5b96732016-07-08 13:22:27 -0700267 // TODO: simplify listener handling (see theme.js for sample code)
268
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700269 function addOpenListener(callback) {
270 var id = nextListenerId++,
271 cb = fs.isF(callback),
272 o = { id: id, cb: cb };
273
274 if (cb) {
275 openListeners[id] = o;
276 } else {
277 $log.error('WSS.addOpenListener(): callback not a function');
278 o.error = 'No callback defined';
279 }
280 return o;
281 }
282
283 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700284 var id = fs.isO(lsnr) && lsnr.id,
285 o;
286 if (!id) {
287 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
288 return null;
289 }
290 o = openListeners[id];
291
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700292 if (o) {
293 delete openListeners[id];
294 }
295 }
296
Simon Hunt20207df2015-03-10 18:30:14 -0700297 // Formulates an event message and sends it via the web-socket.
298 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700299 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700300 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700301 event: evType,
Simon Hunt20207df2015-03-10 18:30:14 -0700302 payload: payload || {}
303 };
304
305 if (wsUp) {
306 _send(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700307 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700308 pendingEvents.push(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700309 }
310 }
311
Thomas Vachuska0af26912016-03-21 21:37:30 -0700312 // Binds the veil service as a delegate
313 function setVeilDelegate(vd) {
314 vs = vd;
315 }
316
317 // Binds the loading service as a delegate
318 function setLoadingDelegate(ld) {
319 ls = ld;
320 }
321
Thomas Vachuska329af532015-03-10 02:08:33 -0700322
Simon Hunt20207df2015-03-10 18:30:14 -0700323 // ============================
324 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800325 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800326 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700327 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
Simon Huntbb920fd2015-01-22 17:06:32 -0800328
Thomas Vachuska0af26912016-03-21 21:37:30 -0700329 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700330 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700331 $loc = _$loc_;
332 fs = _fs_;
333 ufs = _ufs_;
334 wsock = _wsock_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800335
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700336 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700337
Simon Hunt1e4a0012015-01-21 11:36:08 -0800338 return {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700339 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700340 createWebSocket: createWebSocket,
341 bindHandlers: bindHandlers,
342 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700343 addOpenListener: addOpenListener,
344 removeOpenListener: removeOpenListener,
Simon Hunt412adc82015-12-11 15:56:20 -0800345 sendEvent: sendEvent,
Thomas Vachuska0af26912016-03-21 21:37:30 -0700346 isConnected: function () { return wsUp; },
Simon Hunt7715e892016-04-12 19:55:32 -0700347 loggedInUser: function () { return loggedInUser || '(no-one)'; },
Thomas Vachuska0af26912016-03-21 21:37:30 -0700348
349 _setVeilDelegate: setVeilDelegate,
350 _setLoadingDelegate: setLoadingDelegate
Simon Hunt1e4a0012015-01-21 11:36:08 -0800351 };
Simon Hunt20207df2015-03-10 18:30:14 -0700352 }
353 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800354
355}());