blob: 6112449a87441e808c68d0b6ece63e6943b063d4 [file] [log] [blame]
Illyoung Choi59820ed2019-06-24 17:01:00 -07001/*
2 * Copyright 2019-present Open Networking Foundation
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(function () {
18 'use strict';
19
20 const socketio = require('socket.io');
Illyoung Choi59820ed2019-06-24 17:01:00 -070021 const client = require('../types/client.js');
22 const eventrouter = require('./eventrouter.js');
23 const logger = require('../config/logger.js');
24
25 let io;
26 const createSocketIO = (server) => {
27 // INSTANTIATE SOCKET.IO
Illyoung Choib4fc0d82019-07-16 10:29:39 -070028 io = socketio.listen(server, {
29 pingInterval: 500,
30 pingTimeout: 2000,
31 });
Illyoung Choi59820ed2019-06-24 17:01:00 -070032
33 // set io to eventrouter
34 //eventrouter.setIO(io);
35
36 // LISTEN TO "CONNECTION" EVENT (FROM SOCKET.IO)
37 io.on('connection', (socket) => {
38 let query = socket.handshake.query;
39 logger.log('debug', `connect ${JSON.stringify(query)}`);
40 let added = false;
41
42 // make a client
43 let c = client.Client.fromObj(query);
44 c.setSocket(socket);
45
46 if(!c.validate()) {
47 logger.log('warn', `client validation failed - ${JSON.stringify(query)}`);
48 return;
49 }
50
51 // register the client for management
52 if(eventrouter.addClient(c)) {
53 // Send a greeting message to the client
54 socket.emit(eventrouter.serviceEvents.GREETING, {
55 to: c.getId(),
56 message: 'Welcome to CORD Workflow Control Service'
57 });
58
59 added = true;
60 }
61 else {
62 logger.log('warn', `client could not be added - ${JSON.stringify(query)}`);
63 socket.disconnect(true);
64 }
65
66 // set a disconnect event handler
67 socket.on('disconnect', (reason) => {
68 logger.log('debug', `disconnect ${reason} ${JSON.stringify(query)}`);
69 if(added) {
70 eventrouter.removeClient(c.getId());
71 }
72 });
73 });
74 };
75
76 const destroySocketIO = () => {
77 io.close();
78 };
79
80 const getSocketIO = () => io;
81
82 module.exports = {
83 create: createSocketIO,
84 destroy: destroySocketIO,
85 get: getSocketIO
86 };
87
88 // USAGE
89 // const socketIo = require('./controllers/websocket.js');
90 // const socket = socketIo.get();
91 // socket.emit('eventName', data);
92
Illyoung Choib4fc0d82019-07-16 10:29:39 -070093})();