blob: 55c7b40256377f98673aa5bcc25ec0e49a78eaea [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
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) {
Simon Hunt7715e892016-04-12 19:55:32 -070046 $log.debug('bootstrap data', data);
47 loggedInUser = data.user;
Thomas Vachuska20084b72015-03-11 13:46:50 -070048 clusterNodes = data.clusterNodes;
Simon Hunt8b6d2d42015-03-11 13:04:52 -070049 clusterNodes.forEach(function (d, i) {
50 if (d.uiAttached) {
51 clusterIndex = i;
Thomas Vachuska20084b72015-03-11 13:46:50 -070052 $log.info('Connected to cluster node ' + d.ip);
53 // TODO: add connect info to masthead somewhere
Simon Hunt8b6d2d42015-03-11 13:04:52 -070054 }
55 });
56 }
57 };
Simon Hunt20207df2015-03-10 18:30:14 -070058
Steven Burrows530cf462016-04-12 16:04:37 +010059
Simon Hunt20207df2015-03-10 18:30:14 -070060 // ==========================
61 // === Web socket callbacks
62
63 function handleOpen() {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070064 $log.info('Web socket open - ', url);
Thomas Vachuska0af26912016-03-21 21:37:30 -070065 vs && vs.hide();
Simon Hunt8b6d2d42015-03-11 13:04:52 -070066
Simon Hunt4deb0e82015-06-10 16:18:25 -070067 if (fs.debugOn('txrx')) {
68 $log.debug('Sending ' + pendingEvents.length + ' pending event(s)...');
69 }
Simon Hunt20207df2015-03-10 18:30:14 -070070 pendingEvents.forEach(function (ev) {
71 _send(ev);
72 });
73 pendingEvents = [];
Simon Hunt8b6d2d42015-03-11 13:04:52 -070074
75 connectRetries = 0;
Simon Hunt20207df2015-03-10 18:30:14 -070076 wsUp = true;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070077 informListeners(host, url);
Simon Hunt20207df2015-03-10 18:30:14 -070078 }
79
80 // Handles the specified (incoming) message using handler bindings.
81 function handleMessage(msgEvent) {
82 var ev, h;
83
84 try {
85 ev = JSON.parse(msgEvent.data);
Simon Hunt20207df2015-03-10 18:30:14 -070086 } catch (e) {
Simon Hunt2d16fc82015-03-10 20:19:52 -070087 $log.error('Message.data is not valid JSON', msgEvent.data, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070088 return null;
Simon Hunt20207df2015-03-10 18:30:14 -070089 }
Simon Hunt4deb0e82015-06-10 16:18:25 -070090 if (fs.debugOn('txrx')) {
91 $log.debug(' << *Rx* ', ev.event, ev.payload);
92 }
Simon Hunt2d16fc82015-03-10 20:19:52 -070093
94 if (h = handlers[ev.event]) {
95 try {
96 h(ev.payload);
97 } catch (e) {
98 $log.error('Problem handling event:', ev, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070099 return null;
Simon Hunt2d16fc82015-03-10 20:19:52 -0700100 }
101 } else {
102 $log.warn('Unhandled event:', ev);
103 }
104
Simon Hunt20207df2015-03-10 18:30:14 -0700105 }
106
107 function handleClose() {
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700108 var gsucc;
109
Simon Hunt8a0429a2017-01-06 16:52:47 -0800110 $log.warn('Web socket closed');
Thomas Vachuska0af26912016-03-21 21:37:30 -0700111 ls && ls.stop();
Simon Hunt20207df2015-03-10 18:30:14 -0700112 wsUp = false;
113
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700114 if (gsucc = findGuiSuccessor()) {
115 createWebSocket(webSockOpts, gsucc);
116 } else {
117 // If no controllers left to contact, show the Veil...
Thomas Vachuska0af26912016-03-21 21:37:30 -0700118 vs && vs.show([
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700119 'Oops!',
120 'Web-socket connection to server closed...',
121 'Try refreshing the page.'
122 ]);
123 }
Simon Hunt20207df2015-03-10 18:30:14 -0700124 }
125
126
127 // ==============================
128 // === Private Helper Functions
129
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700130 function findGuiSuccessor() {
131 var ncn = clusterNodes.length,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700132 ip, node;
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700133
134 while (connectRetries < ncn && !ip) {
135 connectRetries++;
136 clusterIndex = (clusterIndex + 1) % ncn;
137 node = clusterNodes[clusterIndex];
138 ip = node && node.ip;
139 }
140
141 return ip;
142 }
143
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700144 function informListeners(host, url) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700145 angular.forEach(openListeners, function (lsnr) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700146 lsnr.cb(host, url);
147 });
148 }
149
Simon Hunt20207df2015-03-10 18:30:14 -0700150 function _send(ev) {
Simon Hunt4deb0e82015-06-10 16:18:25 -0700151 if (fs.debugOn('txrx')) {
152 $log.debug(' *Tx* >> ', ev.event, ev.payload);
153 }
Simon Hunt20207df2015-03-10 18:30:14 -0700154 ws.send(JSON.stringify(ev));
155 }
156
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700157 function noHandlersWarn(handlers, caller) {
158 if (!handlers || fs.isEmptyObject(handlers)) {
159 $log.warn('WSS.' + caller + '(): no event handlers');
160 return true;
161 }
162 return false;
163 }
164
Simon Hunt20207df2015-03-10 18:30:14 -0700165 // ===================
166 // === API Functions
167
168 // Required for unit tests to set to known state
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700169 function resetState() {
170 webSockOpts = undefined;
171 ws = null;
172 wsUp = false;
173 host = undefined;
174 url = undefined;
175 pendingEvents = [];
176 handlers = {};
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700177 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 Huntd5b96732016-07-08 13:22:27 -0700254 // TODO: simplify listener handling (see theme.js for sample code)
255
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700256 function addOpenListener(callback) {
257 var id = nextListenerId++,
258 cb = fs.isF(callback),
259 o = { id: id, cb: cb };
260
261 if (cb) {
262 openListeners[id] = o;
263 } else {
264 $log.error('WSS.addOpenListener(): callback not a function');
265 o.error = 'No callback defined';
266 }
267 return o;
268 }
269
270 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700271 var id = fs.isO(lsnr) && lsnr.id,
272 o;
273 if (!id) {
274 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
275 return null;
276 }
277 o = openListeners[id];
278
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700279 if (o) {
280 delete openListeners[id];
281 }
282 }
283
Simon Hunt20207df2015-03-10 18:30:14 -0700284 // Formulates an event message and sends it via the web-socket.
285 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700286 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700287 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700288 event: evType,
Simon Hunt20207df2015-03-10 18:30:14 -0700289 payload: payload || {}
290 };
291
292 if (wsUp) {
293 _send(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700294 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700295 pendingEvents.push(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700296 }
297 }
298
Thomas Vachuska0af26912016-03-21 21:37:30 -0700299 // Binds the veil service as a delegate
300 function setVeilDelegate(vd) {
301 vs = vd;
302 }
303
304 // Binds the loading service as a delegate
305 function setLoadingDelegate(ld) {
306 ls = ld;
307 }
308
Thomas Vachuska329af532015-03-10 02:08:33 -0700309
Simon Hunt20207df2015-03-10 18:30:14 -0700310 // ============================
311 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800312 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800313 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700314 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
Simon Huntbb920fd2015-01-22 17:06:32 -0800315
Thomas Vachuska0af26912016-03-21 21:37:30 -0700316 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700317 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700318 $loc = _$loc_;
319 fs = _fs_;
320 ufs = _ufs_;
321 wsock = _wsock_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800322
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700323 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700324
Simon Hunt1e4a0012015-01-21 11:36:08 -0800325 return {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700326 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700327 createWebSocket: createWebSocket,
328 bindHandlers: bindHandlers,
329 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700330 addOpenListener: addOpenListener,
331 removeOpenListener: removeOpenListener,
Simon Hunt412adc82015-12-11 15:56:20 -0800332 sendEvent: sendEvent,
Thomas Vachuska0af26912016-03-21 21:37:30 -0700333 isConnected: function () { return wsUp; },
Simon Hunt7715e892016-04-12 19:55:32 -0700334 loggedInUser: function () { return loggedInUser || '(no-one)'; },
Thomas Vachuska0af26912016-03-21 21:37:30 -0700335
336 _setVeilDelegate: setVeilDelegate,
337 _setLoadingDelegate: setLoadingDelegate
Simon Hunt1e4a0012015-01-21 11:36:08 -0800338 };
Simon Hunt20207df2015-03-10 18:30:14 -0700339 }
340 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800341
342}());