blob: 0f370cf80d0ef0643199807e9d19e8b6de003828 [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
Steven Burrows530cf462016-04-12 16:04:37 +010060
Simon Hunt20207df2015-03-10 18:30:14 -070061 // ==========================
62 // === Web socket callbacks
63
64 function handleOpen() {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070065 $log.info('Web socket open - ', url);
Thomas Vachuska0af26912016-03-21 21:37:30 -070066 vs && vs.hide();
Simon Hunt8b6d2d42015-03-11 13:04:52 -070067
Simon Hunt4deb0e82015-06-10 16:18:25 -070068 if (fs.debugOn('txrx')) {
69 $log.debug('Sending ' + pendingEvents.length + ' pending event(s)...');
70 }
Simon Hunt20207df2015-03-10 18:30:14 -070071 pendingEvents.forEach(function (ev) {
72 _send(ev);
73 });
74 pendingEvents = [];
Simon Hunt8b6d2d42015-03-11 13:04:52 -070075
76 connectRetries = 0;
Simon Hunt20207df2015-03-10 18:30:14 -070077 wsUp = true;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -070078 informListeners(host, url);
Simon Hunt20207df2015-03-10 18:30:14 -070079 }
80
81 // Handles the specified (incoming) message using handler bindings.
82 function handleMessage(msgEvent) {
83 var ev, h;
84
85 try {
86 ev = JSON.parse(msgEvent.data);
Simon Hunt20207df2015-03-10 18:30:14 -070087 } catch (e) {
Simon Hunt2d16fc82015-03-10 20:19:52 -070088 $log.error('Message.data is not valid JSON', msgEvent.data, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -070089 return null;
Simon Hunt20207df2015-03-10 18:30:14 -070090 }
Simon Hunt4deb0e82015-06-10 16:18:25 -070091 if (fs.debugOn('txrx')) {
92 $log.debug(' << *Rx* ', ev.event, ev.payload);
93 }
Simon Hunt2d16fc82015-03-10 20:19:52 -070094
95 if (h = handlers[ev.event]) {
96 try {
97 h(ev.payload);
98 } catch (e) {
99 $log.error('Problem handling event:', ev, e);
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700100 return null;
Simon Hunt2d16fc82015-03-10 20:19:52 -0700101 }
102 } else {
103 $log.warn('Unhandled event:', ev);
104 }
105
Simon Hunt20207df2015-03-10 18:30:14 -0700106 }
107
108 function handleClose() {
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700109 var gsucc;
110
Simon Hunt20207df2015-03-10 18:30:14 -0700111 $log.info('Web socket closed');
Thomas Vachuska0af26912016-03-21 21:37:30 -0700112 ls && ls.stop();
Simon Hunt20207df2015-03-10 18:30:14 -0700113 wsUp = false;
114
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700115 if (gsucc = findGuiSuccessor()) {
116 createWebSocket(webSockOpts, gsucc);
117 } else {
118 // If no controllers left to contact, show the Veil...
Thomas Vachuska0af26912016-03-21 21:37:30 -0700119 vs && vs.show([
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700120 'Oops!',
121 'Web-socket connection to server closed...',
122 'Try refreshing the page.'
123 ]);
124 }
Simon Hunt20207df2015-03-10 18:30:14 -0700125 }
126
127
128 // ==============================
129 // === Private Helper Functions
130
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700131 function findGuiSuccessor() {
132 var ncn = clusterNodes.length,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700133 ip, node;
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700134
135 while (connectRetries < ncn && !ip) {
136 connectRetries++;
137 clusterIndex = (clusterIndex + 1) % ncn;
138 node = clusterNodes[clusterIndex];
139 ip = node && node.ip;
140 }
141
142 return ip;
143 }
144
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700145 function informListeners(host, url) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700146 angular.forEach(openListeners, function (lsnr) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700147 lsnr.cb(host, url);
148 });
149 }
150
Simon Hunt20207df2015-03-10 18:30:14 -0700151 function _send(ev) {
Simon Hunt4deb0e82015-06-10 16:18:25 -0700152 if (fs.debugOn('txrx')) {
153 $log.debug(' *Tx* >> ', ev.event, ev.payload);
154 }
Simon Hunt20207df2015-03-10 18:30:14 -0700155 ws.send(JSON.stringify(ev));
156 }
157
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700158 function noHandlersWarn(handlers, caller) {
159 if (!handlers || fs.isEmptyObject(handlers)) {
160 $log.warn('WSS.' + caller + '(): no event handlers');
161 return true;
162 }
163 return false;
164 }
165
Simon Hunt20207df2015-03-10 18:30:14 -0700166 // ===================
167 // === API Functions
168
169 // Required for unit tests to set to known state
Thomas Vachuska329af532015-03-10 02:08:33 -0700170 function resetSid() {
171 sid = 0;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800172 }
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700173 function resetState() {
174 webSockOpts = undefined;
175 ws = null;
176 wsUp = false;
177 host = undefined;
178 url = undefined;
179 pendingEvents = [];
180 handlers = {};
181 sid = 0;
182 clusterNodes = [];
183 clusterIndex = -1;
184 connectRetries = 0;
185 openListeners = {};
186 nextListenerId = 1;
187 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800188
Simon Hunt20207df2015-03-10 18:30:14 -0700189 // Currently supported opts:
190 // wsport: web socket port (other than default 8181)
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700191 // host: if defined, is the host address to use
192 function createWebSocket(opts, _host_) {
Simon Hunt20207df2015-03-10 18:30:14 -0700193 var wsport = (opts && opts.wsport) || null;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700194
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700195 webSockOpts = opts; // preserved for future calls
Simon Hunt20207df2015-03-10 18:30:14 -0700196
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700197 host = _host_ || $loc.host();
198 url = ufs.wsUrl('core', wsport, _host_);
Simon Hunt20207df2015-03-10 18:30:14 -0700199
200 $log.debug('Attempting to open websocket to: ' + url);
201 ws = wsock.newWebSocket(url);
202 if (ws) {
203 ws.onopen = handleOpen;
204 ws.onmessage = handleMessage;
205 ws.onclose = handleClose;
206 }
207 // Note: Wsock logs an error if the new WebSocket call fails
Simon Hunt2d16fc82015-03-10 20:19:52 -0700208 return url;
Simon Hunt20207df2015-03-10 18:30:14 -0700209 }
210
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700211 // Binds the message handlers to their message type (event type) as
212 // specified in the given map. Note that keys are the event IDs; values
213 // are either:
214 // * the event handler function, or
215 // * an API object which has an event handler for the key
216 //
Thomas Vachuska329af532015-03-10 02:08:33 -0700217 function bindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700218 var m,
Thomas Vachuska329af532015-03-10 02:08:33 -0700219 dups = [];
Simon Hunt970e7fd2015-01-22 17:46:28 -0800220
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700221 if (noHandlersWarn(handlerMap, 'bindHandlers')) {
222 return null;
223 }
224 m = d3.map(handlerMap);
225
Simon Hunt20207df2015-03-10 18:30:14 -0700226 m.forEach(function (eventId, api) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700227 var fn = fs.isF(api) || fs.isF(api[eventId]);
Thomas Vachuska329af532015-03-10 02:08:33 -0700228 if (!fn) {
Simon Hunt20207df2015-03-10 18:30:14 -0700229 $log.warn(eventId + ' handler not a function');
Thomas Vachuska329af532015-03-10 02:08:33 -0700230 return;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800231 }
Thomas Vachuska329af532015-03-10 02:08:33 -0700232
Simon Hunt20207df2015-03-10 18:30:14 -0700233 if (handlers[eventId]) {
234 dups.push(eventId);
Thomas Vachuska329af532015-03-10 02:08:33 -0700235 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700236 handlers[eventId] = fn;
Thomas Vachuska329af532015-03-10 02:08:33 -0700237 }
238 });
239 if (dups.length) {
240 $log.warn('duplicate bindings ignored:', dups);
241 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800242 }
243
Thomas Vachuska329af532015-03-10 02:08:33 -0700244 // Unbinds the specified message handlers.
Simon Hunt20207df2015-03-10 18:30:14 -0700245 // Expected that the same map will be used, but we only care about keys
Thomas Vachuska329af532015-03-10 02:08:33 -0700246 function unbindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700247 var m;
248
249 if (noHandlersWarn(handlerMap, 'unbindHandlers')) {
250 return null;
251 }
252 m = d3.map(handlerMap);
Simon Hunt20207df2015-03-10 18:30:14 -0700253
254 m.forEach(function (eventId) {
255 delete handlers[eventId];
Thomas Vachuska329af532015-03-10 02:08:33 -0700256 });
257 }
Simon Huntacf410b2015-01-23 10:05:48 -0800258
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700259 function addOpenListener(callback) {
260 var id = nextListenerId++,
261 cb = fs.isF(callback),
262 o = { id: id, cb: cb };
263
264 if (cb) {
265 openListeners[id] = o;
266 } else {
267 $log.error('WSS.addOpenListener(): callback not a function');
268 o.error = 'No callback defined';
269 }
270 return o;
271 }
272
273 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700274 var id = fs.isO(lsnr) && lsnr.id,
275 o;
276 if (!id) {
277 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
278 return null;
279 }
280 o = openListeners[id];
281
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700282 if (o) {
283 delete openListeners[id];
284 }
285 }
286
Simon Hunt20207df2015-03-10 18:30:14 -0700287 // Formulates an event message and sends it via the web-socket.
288 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700289 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700290 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700291 event: evType,
292 sid: ++sid,
Simon Hunt20207df2015-03-10 18:30:14 -0700293 payload: payload || {}
294 };
295
296 if (wsUp) {
297 _send(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700298 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700299 pendingEvents.push(ev);
Thomas Vachuska329af532015-03-10 02:08:33 -0700300 }
301 }
302
Thomas Vachuska0af26912016-03-21 21:37:30 -0700303 // Binds the veil service as a delegate
304 function setVeilDelegate(vd) {
305 vs = vd;
306 }
307
308 // Binds the loading service as a delegate
309 function setLoadingDelegate(ld) {
310 ls = ld;
311 }
312
Thomas Vachuska329af532015-03-10 02:08:33 -0700313
Simon Hunt20207df2015-03-10 18:30:14 -0700314 // ============================
315 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800316 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800317 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700318 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
Simon Huntbb920fd2015-01-22 17:06:32 -0800319
Thomas Vachuska0af26912016-03-21 21:37:30 -0700320 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700321 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700322 $loc = _$loc_;
323 fs = _fs_;
324 ufs = _ufs_;
325 wsock = _wsock_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800326
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700327 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700328
Simon Hunt1e4a0012015-01-21 11:36:08 -0800329 return {
Thomas Vachuska329af532015-03-10 02:08:33 -0700330 resetSid: resetSid,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700331 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700332 createWebSocket: createWebSocket,
333 bindHandlers: bindHandlers,
334 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700335 addOpenListener: addOpenListener,
336 removeOpenListener: removeOpenListener,
Simon Hunt412adc82015-12-11 15:56:20 -0800337 sendEvent: sendEvent,
Thomas Vachuska0af26912016-03-21 21:37:30 -0700338 isConnected: function () { return wsUp; },
Simon Hunt7715e892016-04-12 19:55:32 -0700339 loggedInUser: function () { return loggedInUser || '(no-one)'; },
Thomas Vachuska0af26912016-03-21 21:37:30 -0700340
341 _setVeilDelegate: setVeilDelegate,
342 _setLoadingDelegate: setLoadingDelegate
Simon Hunt1e4a0012015-01-21 11:36:08 -0800343 };
Simon Hunt20207df2015-03-10 18:30:14 -0700344 }
345 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800346
347}());