blob: 940cdec760d5f983afcecd9bd793ec8923c20000 [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
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()
Simon Hunt7715e892016-04-12 19:55:32 -070039 nextListenerId = 1, // internal ID for open listeners
40 loggedInUser = null; // name of logged-in user
Simon Hunt8b6d2d42015-03-11 13:04:52 -070041
42 // =======================
43 // === Bootstrap Handler
Simon Huntacf410b2015-01-23 10:05:48 -080044
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070045 var builtinHandlers = {
Simon Hunt8b6d2d42015-03-11 13:04:52 -070046 bootstrap: function (data) {
Simon Hunt7715e892016-04-12 19:55:32 -070047 $log.debug('bootstrap data', data);
48 loggedInUser = data.user;
Thomas Vachuska20084b72015-03-11 13:46:50 -070049 clusterNodes = data.clusterNodes;
Simon Hunt8b6d2d42015-03-11 13:04:52 -070050 clusterNodes.forEach(function (d, i) {
51 if (d.uiAttached) {
52 clusterIndex = i;
Thomas Vachuska20084b72015-03-11 13:46:50 -070053 $log.info('Connected to cluster node ' + d.ip);
54 // TODO: add connect info to masthead somewhere
Simon Hunt8b6d2d42015-03-11 13:04:52 -070055 }
56 });
57 }
58 };
Simon Hunt20207df2015-03-10 18:30:14 -070059
60 // ==========================
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 Hunt20207df2015-03-10 18:30:14 -0700110 $log.info('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
Thomas Vachuska329af532015-03-10 02:08:33 -0700169 function resetSid() {
170 sid = 0;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800171 }
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700172 function resetState() {
173 webSockOpts = undefined;
174 ws = null;
175 wsUp = false;
176 host = undefined;
177 url = undefined;
178 pendingEvents = [];
179 handlers = {};
180 sid = 0;
181 clusterNodes = [];
182 clusterIndex = -1;
183 connectRetries = 0;
184 openListeners = {};
185 nextListenerId = 1;
186 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800187
Simon Hunt20207df2015-03-10 18:30:14 -0700188 // Currently supported opts:
189 // wsport: web socket port (other than default 8181)
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700190 // host: if defined, is the host address to use
191 function createWebSocket(opts, _host_) {
Simon Hunt20207df2015-03-10 18:30:14 -0700192 var wsport = (opts && opts.wsport) || null;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700193
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700194 webSockOpts = opts; // preserved for future calls
Simon Hunt20207df2015-03-10 18:30:14 -0700195
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700196 host = _host_ || $loc.host();
197 url = ufs.wsUrl('core', wsport, _host_);
Simon Hunt20207df2015-03-10 18:30:14 -0700198
199 $log.debug('Attempting to open websocket to: ' + url);
200 ws = wsock.newWebSocket(url);
201 if (ws) {
202 ws.onopen = handleOpen;
203 ws.onmessage = handleMessage;
204 ws.onclose = handleClose;
205 }
206 // Note: Wsock logs an error if the new WebSocket call fails
Simon Hunt2d16fc82015-03-10 20:19:52 -0700207 return url;
Simon Hunt20207df2015-03-10 18:30:14 -0700208 }
209
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700210 // Binds the message handlers to their message type (event type) as
211 // specified in the given map. Note that keys are the event IDs; values
212 // are either:
213 // * the event handler function, or
214 // * an API object which has an event handler for the key
215 //
Thomas Vachuska329af532015-03-10 02:08:33 -0700216 function bindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700217 var m,
Thomas Vachuska329af532015-03-10 02:08:33 -0700218 dups = [];
Simon Hunt970e7fd2015-01-22 17:46:28 -0800219
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700220 if (noHandlersWarn(handlerMap, 'bindHandlers')) {
221 return null;
222 }
223 m = d3.map(handlerMap);
224
Simon Hunt20207df2015-03-10 18:30:14 -0700225 m.forEach(function (eventId, api) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700226 var fn = fs.isF(api) || fs.isF(api[eventId]);
Thomas Vachuska329af532015-03-10 02:08:33 -0700227 if (!fn) {
Simon Hunt20207df2015-03-10 18:30:14 -0700228 $log.warn(eventId + ' handler not a function');
Thomas Vachuska329af532015-03-10 02:08:33 -0700229 return;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800230 }
Thomas Vachuska329af532015-03-10 02:08:33 -0700231
Simon Hunt20207df2015-03-10 18:30:14 -0700232 if (handlers[eventId]) {
233 dups.push(eventId);
Thomas Vachuska329af532015-03-10 02:08:33 -0700234 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700235 handlers[eventId] = fn;
Thomas Vachuska329af532015-03-10 02:08:33 -0700236 }
237 });
238 if (dups.length) {
239 $log.warn('duplicate bindings ignored:', dups);
240 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800241 }
242
Thomas Vachuska329af532015-03-10 02:08:33 -0700243 // Unbinds the specified message handlers.
Simon Hunt20207df2015-03-10 18:30:14 -0700244 // Expected that the same map will be used, but we only care about keys
Thomas Vachuska329af532015-03-10 02:08:33 -0700245 function unbindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700246 var m;
247
248 if (noHandlersWarn(handlerMap, 'unbindHandlers')) {
249 return null;
250 }
251 m = d3.map(handlerMap);
Simon Hunt20207df2015-03-10 18:30:14 -0700252
253 m.forEach(function (eventId) {
254 delete handlers[eventId];
Thomas Vachuska329af532015-03-10 02:08:33 -0700255 });
256 }
Simon Huntacf410b2015-01-23 10:05:48 -0800257
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700258 function addOpenListener(callback) {
259 var id = nextListenerId++,
260 cb = fs.isF(callback),
261 o = { id: id, cb: cb };
262
263 if (cb) {
264 openListeners[id] = o;
265 } else {
266 $log.error('WSS.addOpenListener(): callback not a function');
267 o.error = 'No callback defined';
268 }
269 return o;
270 }
271
272 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700273 var id = fs.isO(lsnr) && lsnr.id,
274 o;
275 if (!id) {
276 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
277 return null;
278 }
279 o = openListeners[id];
280
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700281 if (o) {
282 delete openListeners[id];
283 }
284 }
285
Simon Hunt20207df2015-03-10 18:30:14 -0700286 // Formulates an event message and sends it via the web-socket.
287 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700288 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700289 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700290 event: evType,
291 sid: ++sid,
Simon Hunt20207df2015-03-10 18:30:14 -0700292 payload: payload || {}
293 };
294
295 if (wsUp) {
296 _send(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700297 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700298 pendingEvents.push(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700299 }
300 }
301
Thomas Vachuska0af26912016-03-21 21:37:30 -0700302 // Binds the veil service as a delegate
303 function setVeilDelegate(vd) {
304 vs = vd;
305 }
306
307 // Binds the loading service as a delegate
308 function setLoadingDelegate(ld) {
309 ls = ld;
310 }
311
Thomas Vachuska329af532015-03-10 02:08:33 -0700312
Simon Hunt20207df2015-03-10 18:30:14 -0700313 // ============================
314 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800315 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800316 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700317 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
Simon Huntbb920fd2015-01-22 17:06:32 -0800318
Thomas Vachuska0af26912016-03-21 21:37:30 -0700319 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700320 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700321 $loc = _$loc_;
322 fs = _fs_;
323 ufs = _ufs_;
324 wsock = _wsock_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800325
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700326 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700327
Simon Hunt1e4a0012015-01-21 11:36:08 -0800328 return {
Thomas Vachuska329af532015-03-10 02:08:33 -0700329 resetSid: resetSid,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700330 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700331 createWebSocket: createWebSocket,
332 bindHandlers: bindHandlers,
333 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700334 addOpenListener: addOpenListener,
335 removeOpenListener: removeOpenListener,
Simon Hunt412adc82015-12-11 15:56:20 -0800336 sendEvent: sendEvent,
Thomas Vachuska0af26912016-03-21 21:37:30 -0700337 isConnected: function () { return wsUp; },
Simon Hunt7715e892016-04-12 19:55:32 -0700338 loggedInUser: function () { return loggedInUser || '(no-one)'; },
Thomas Vachuska0af26912016-03-21 21:37:30 -0700339
340 _setVeilDelegate: setVeilDelegate,
341 _setLoadingDelegate: setLoadingDelegate
Simon Hunt1e4a0012015-01-21 11:36:08 -0800342 };
Simon Hunt20207df2015-03-10 18:30:14 -0700343 }
344 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800345
346}());