blob: e39a7f946f8036a6f77b13f60d385464cc760f2b [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 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()
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');
Simon Huntab34ecb2015-12-11 13:14:48 -0800108 ls.stop();
Simon Hunt20207df2015-03-10 18:30:14 -0700109 wsUp = false;
110
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700111 if (gsucc = findGuiSuccessor()) {
112 createWebSocket(webSockOpts, gsucc);
113 } else {
114 // If no controllers left to contact, show the Veil...
115 vs.show([
116 'Oops!',
117 'Web-socket connection to server closed...',
118 'Try refreshing the page.'
119 ]);
120 }
Simon Hunt20207df2015-03-10 18:30:14 -0700121 }
122
123
124 // ==============================
125 // === Private Helper Functions
126
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700127 function findGuiSuccessor() {
128 var ncn = clusterNodes.length,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700129 ip, node;
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700130
131 while (connectRetries < ncn && !ip) {
132 connectRetries++;
133 clusterIndex = (clusterIndex + 1) % ncn;
134 node = clusterNodes[clusterIndex];
135 ip = node && node.ip;
136 }
137
138 return ip;
139 }
140
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700141 function informListeners(host, url) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700142 angular.forEach(openListeners, function (lsnr) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700143 lsnr.cb(host, url);
144 });
145 }
146
Simon Hunt20207df2015-03-10 18:30:14 -0700147 function _send(ev) {
Simon Hunt4deb0e82015-06-10 16:18:25 -0700148 if (fs.debugOn('txrx')) {
149 $log.debug(' *Tx* >> ', ev.event, ev.payload);
150 }
Simon Hunt20207df2015-03-10 18:30:14 -0700151 ws.send(JSON.stringify(ev));
152 }
153
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700154 function noHandlersWarn(handlers, caller) {
155 if (!handlers || fs.isEmptyObject(handlers)) {
156 $log.warn('WSS.' + caller + '(): no event handlers');
157 return true;
158 }
159 return false;
160 }
161
Simon Hunt20207df2015-03-10 18:30:14 -0700162 // ===================
163 // === API Functions
164
165 // Required for unit tests to set to known state
Thomas Vachuska329af532015-03-10 02:08:33 -0700166 function resetSid() {
167 sid = 0;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800168 }
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 = {};
177 sid = 0;
178 clusterNodes = [];
179 clusterIndex = -1;
180 connectRetries = 0;
181 openListeners = {};
182 nextListenerId = 1;
183 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800184
Simon Hunt20207df2015-03-10 18:30:14 -0700185 // Currently supported opts:
186 // wsport: web socket port (other than default 8181)
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700187 // host: if defined, is the host address to use
188 function createWebSocket(opts, _host_) {
Simon Hunt20207df2015-03-10 18:30:14 -0700189 var wsport = (opts && opts.wsport) || null;
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700190
Simon Hunt8b6d2d42015-03-11 13:04:52 -0700191 webSockOpts = opts; // preserved for future calls
Simon Hunt20207df2015-03-10 18:30:14 -0700192
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700193 host = _host_ || $loc.host();
194 url = ufs.wsUrl('core', wsport, _host_);
Simon Hunt20207df2015-03-10 18:30:14 -0700195
196 $log.debug('Attempting to open websocket to: ' + url);
197 ws = wsock.newWebSocket(url);
198 if (ws) {
199 ws.onopen = handleOpen;
200 ws.onmessage = handleMessage;
201 ws.onclose = handleClose;
202 }
203 // Note: Wsock logs an error if the new WebSocket call fails
Simon Hunt2d16fc82015-03-10 20:19:52 -0700204 return url;
Simon Hunt20207df2015-03-10 18:30:14 -0700205 }
206
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700207 // Binds the message handlers to their message type (event type) as
208 // specified in the given map. Note that keys are the event IDs; values
209 // are either:
210 // * the event handler function, or
211 // * an API object which has an event handler for the key
212 //
Thomas Vachuska329af532015-03-10 02:08:33 -0700213 function bindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700214 var m,
Thomas Vachuska329af532015-03-10 02:08:33 -0700215 dups = [];
Simon Hunt970e7fd2015-01-22 17:46:28 -0800216
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700217 if (noHandlersWarn(handlerMap, 'bindHandlers')) {
218 return null;
219 }
220 m = d3.map(handlerMap);
221
Simon Hunt20207df2015-03-10 18:30:14 -0700222 m.forEach(function (eventId, api) {
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700223 var fn = fs.isF(api) || fs.isF(api[eventId]);
Thomas Vachuska329af532015-03-10 02:08:33 -0700224 if (!fn) {
Simon Hunt20207df2015-03-10 18:30:14 -0700225 $log.warn(eventId + ' handler not a function');
Thomas Vachuska329af532015-03-10 02:08:33 -0700226 return;
Simon Hunt970e7fd2015-01-22 17:46:28 -0800227 }
Thomas Vachuska329af532015-03-10 02:08:33 -0700228
Simon Hunt20207df2015-03-10 18:30:14 -0700229 if (handlers[eventId]) {
230 dups.push(eventId);
Thomas Vachuska329af532015-03-10 02:08:33 -0700231 } else {
Simon Hunt20207df2015-03-10 18:30:14 -0700232 handlers[eventId] = fn;
Thomas Vachuska329af532015-03-10 02:08:33 -0700233 }
234 });
235 if (dups.length) {
236 $log.warn('duplicate bindings ignored:', dups);
237 }
Simon Hunt970e7fd2015-01-22 17:46:28 -0800238 }
239
Thomas Vachuska329af532015-03-10 02:08:33 -0700240 // Unbinds the specified message handlers.
Simon Hunt20207df2015-03-10 18:30:14 -0700241 // Expected that the same map will be used, but we only care about keys
Thomas Vachuska329af532015-03-10 02:08:33 -0700242 function unbindHandlers(handlerMap) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700243 var m;
244
245 if (noHandlersWarn(handlerMap, 'unbindHandlers')) {
246 return null;
247 }
248 m = d3.map(handlerMap);
Simon Hunt20207df2015-03-10 18:30:14 -0700249
250 m.forEach(function (eventId) {
251 delete handlers[eventId];
Thomas Vachuska329af532015-03-10 02:08:33 -0700252 });
253 }
Simon Huntacf410b2015-01-23 10:05:48 -0800254
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700255 function addOpenListener(callback) {
256 var id = nextListenerId++,
257 cb = fs.isF(callback),
258 o = { id: id, cb: cb };
259
260 if (cb) {
261 openListeners[id] = o;
262 } else {
263 $log.error('WSS.addOpenListener(): callback not a function');
264 o.error = 'No callback defined';
265 }
266 return o;
267 }
268
269 function removeOpenListener(lsnr) {
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700270 var id = fs.isO(lsnr) && lsnr.id,
271 o;
272 if (!id) {
273 $log.warn('WSS.removeOpenListener(): invalid listener', lsnr);
274 return null;
275 }
276 o = openListeners[id];
277
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700278 if (o) {
279 delete openListeners[id];
280 }
281 }
282
Simon Hunt20207df2015-03-10 18:30:14 -0700283 // Formulates an event message and sends it via the web-socket.
284 // If the websocket is not up yet, we store it in a pending list.
Thomas Vachuska329af532015-03-10 02:08:33 -0700285 function sendEvent(evType, payload) {
Simon Hunt20207df2015-03-10 18:30:14 -0700286 var ev = {
Thomas Vachuska329af532015-03-10 02:08:33 -0700287 event: evType,
288 sid: ++sid,
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
299
Simon Hunt20207df2015-03-10 18:30:14 -0700300 // ============================
301 // ===== Definition of module
Simon Hunt584122a2015-01-21 15:32:40 -0800302 angular.module('onosRemote')
Simon Huntbb920fd2015-01-22 17:06:32 -0800303 .factory('WebSocketService',
Simon Hunt20207df2015-03-10 18:30:14 -0700304 ['$log', '$location', 'FnService', 'UrlFnService', 'WSock',
Simon Huntab34ecb2015-12-11 13:14:48 -0800305 'VeilService', 'LoadingService',
Simon Huntbb920fd2015-01-22 17:06:32 -0800306
Simon Huntab34ecb2015-12-11 13:14:48 -0800307 function (_$log_, _$loc_, _fs_, _ufs_, _wsock_, _vs_, _ls_) {
Thomas Vachuska329af532015-03-10 02:08:33 -0700308 $log = _$log_;
Simon Hunt20207df2015-03-10 18:30:14 -0700309 $loc = _$loc_;
310 fs = _fs_;
311 ufs = _ufs_;
312 wsock = _wsock_;
313 vs = _vs_;
Simon Huntab34ecb2015-12-11 13:14:48 -0800314 ls = _ls_;
Simon Hunt1e4a0012015-01-21 11:36:08 -0800315
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700316 bindHandlers(builtinHandlers);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700317
Simon Hunt1e4a0012015-01-21 11:36:08 -0800318 return {
Thomas Vachuska329af532015-03-10 02:08:33 -0700319 resetSid: resetSid,
Bri Prebilic Cole6ed04eb2015-04-27 16:26:03 -0700320 resetState: resetState,
Thomas Vachuska329af532015-03-10 02:08:33 -0700321 createWebSocket: createWebSocket,
322 bindHandlers: bindHandlers,
323 unbindHandlers: unbindHandlers,
Simon Hunt3b9ad04d2015-03-11 15:26:02 -0700324 addOpenListener: addOpenListener,
325 removeOpenListener: removeOpenListener,
Simon Hunt412adc82015-12-11 15:56:20 -0800326 sendEvent: sendEvent,
327 isConnected: function () { return wsUp; }
Simon Hunt1e4a0012015-01-21 11:36:08 -0800328 };
Simon Hunt20207df2015-03-10 18:30:14 -0700329 }
330 ]);
Simon Hunt1e4a0012015-01-21 11:36:08 -0800331
332}());