blob: 6f70d3ab5d0ecd5065f81a10f24ea38e57545438 [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
18(function () {
19 'use strict';
20
21 const express = require('express');
22 const config = require('./config/config.js').service;
23 const bodyParser = require('body-parser');
24 const cors = require('cors');
25 const socketIo = require('./controllers/websocket.js');
26 const eventrouter = require('./controllers/eventrouter.js');
27 const workflowLoader = require('./workflows/loader.js');
28 const logger = require('./config/logger.js');
29 const rest_probe = require('./controllers/rest_probe.js');
30
31 const app = express();
32
33 // Apply middlewares
34 app.use(cors());
35 app.use(bodyParser.json());
36
37 // Set a router for intake interface
38 app.use('/', rest_probe.getRouter());
39
40 const startServer = (port) => {
41 // if is running just return it
42 if(app.server) {
43 return app.server;
44 }
45
46 const server = app.listen(port || config.port, () => {
47 logger.info(`Express is listening to http://localhost:${port || config.port}`);
48
49 // once server is ready setup WebSocket
50 socketIo.create(server);
51
52 // load built-in workflows
53 let workflows = workflowLoader.loadAllWorkflows();
54 for(let workflow in workflows) {
55 eventrouter.addWorkflow(workflow);
56 }
57 });
58 app.server = server;
59 return server;
60 };
61
62 const stopServer = () => {
63 if(app.server) {
64 socketIo.destroy();
65 app.server.close();
66 app.server = undefined;
67 eventrouter.destroy();
68 }
69 }
70
71 if(!module.parent) {
72 startServer();
73 }
74
75 module.exports = {
76 serviceEvents: eventrouter.serviceEvents,
77 app: app,
78 start: startServer,
79 stop: stopServer
80 };
81})();