51554e3a6b8a69bc437251e8a02b59b11777ae40
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.websocketmanager2;
19
20 import com.google.common.util.concurrent.ListenableFuture;
21 import java.io.IOException;
22 import java.net.URI;
23 import java.net.URISyntaxException;
24 import java.util.ArrayList;
25 import javax.servlet.ServletException;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
28 import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
29 import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
30 import org.json.JSONObject;
31 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.WebSocketManagerSocket.EventInputCallback;
32 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.utils.AkkaConfig;
33 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.utils.AkkaConfig.ClusterConfig;
34 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.utils.AkkaConfig.ClusterNodeInfo;
35 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.websocket.SyncWebSocketClient;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketEventInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketEventOutput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketEventOutputBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketmanagerService;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
42 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class WebSocketManager extends WebSocketServlet implements WebsocketmanagerService {
47
48     private static final long serialVersionUID = -681665669062744439L;
49
50     private static final Logger LOG = LoggerFactory.getLogger(WebSocketManager.class.getName());
51     private static final String APPLICATION_NAME = WebSocketManager.class.getName();
52     private static final int PORT = 8181;
53     private final EventInputCallback rpcEventInputCallback;
54     private final AkkaConfig akkaConfig;
55     /**
56      * timeout for websocket with no messages in ms
57      */
58     private static final long IDLE_TIMEOUT = 5 * 60 * 1000L;
59
60     private final ArrayList<URI> clusterNodeClients = new ArrayList<>();
61
62     public WebSocketManager() {
63         this(null, null);
64     }
65
66     public WebSocketManager(AkkaConfig akkaconfig, EventInputCallback cb) {
67         super();
68         this.akkaConfig = akkaconfig;
69         if (cb != null) {
70             this.rpcEventInputCallback = cb;
71         } else {
72             this.rpcEventInputCallback = message -> {
73                 LOG.debug("onMessagePushed: " + message);
74                 SyncWebSocketClient client;
75                 for (URI clientURI : WebSocketManager.this.clusterNodeClients) {
76                     client = new SyncWebSocketClient(clientURI);
77                     LOG.debug("try to push message to " + client.getURI());
78                     client.openAndSendAndCloseSync(message);
79                 }
80             };
81         }
82         LOG.info("Create servlet for {}", APPLICATION_NAME);
83     }
84
85     @Override
86     public void configure(WebSocketServletFactory factory) {
87         LOG.info("Configure provider for {}", APPLICATION_NAME);
88         // set a second timeout
89         factory.getPolicy().setIdleTimeout(IDLE_TIMEOUT);
90         factory.getPolicy().setMaxBinaryMessageSize(1);
91         factory.getPolicy().setMaxTextMessageSize(64 * 1024);
92
93         // register Socket as the WebSocket to create on Upgrade
94         factory.register(WebSocketManagerSocket.class);
95
96         AkkaConfig cfg = this.akkaConfig;
97         if (cfg == null) {
98             try {
99                 cfg = AkkaConfig.load();
100             } catch (Exception e) {
101                 LOG.warn("problem loading akka config: " + e.getMessage());
102             }
103         }
104         if (cfg != null && cfg.isCluster()) {
105             this.initWSClients(cfg.getClusterConfig());
106         }
107     }
108
109     // ODL in Dublin version generates ListenableFuture that is child of Future.
110     @Override
111     public ListenableFuture<RpcResult<WebsocketEventOutput>> websocketEvent(WebsocketEventInput input) {
112         LOG.debug("Send message '{}'", input);
113         RpcResultBuilder<WebsocketEventOutput> result;
114
115         final String eventAsXmlString = input.getXmlEvent();
116         if (eventAsXmlString != null) {
117             WebSocketManagerSocket.broadCast(input.getNodeName(), input.getEventType(), eventAsXmlString);
118             try {
119                 JSONObject o = new JSONObject();
120                 o.put(WebSocketManagerSocket.KEY_NODENAME, input.getNodeName());
121                 o.put(WebSocketManagerSocket.KEY_EVENTTYPE, input.getEventType());
122                 o.put(WebSocketManagerSocket.KEY_XMLEVENT, input.getXmlEvent());
123                 this.rpcEventInputCallback.onMessagePushed(o.toString());
124
125                 WebsocketEventOutputBuilder outputBuilder = new WebsocketEventOutputBuilder();
126                 outputBuilder.setResponse("OK");
127                 result = RpcResultBuilder.success(outputBuilder);
128             } catch (Exception err) {
129                 LOG.warn("problem pushing messsage to other nodes: " + err.getMessage());
130                 result = RpcResultBuilder.failed();
131                 result.withError(ErrorType.APPLICATION, "Exception", err);
132             }
133         } else {
134             String msg = "Emtpy event received";
135             LOG.warn(msg);
136             result = RpcResultBuilder.failed();
137             result.withError(ErrorType.APPLICATION, msg);
138         }
139         return result.buildFuture();
140     }
141
142     /**********************************************************
143      * Private functions
144      */
145
146     @Override
147     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
148         if (req.getHeader("Upgrade") != null) {
149             /* Accept upgrade request */
150             resp.setStatus(101);
151             resp.setHeader("Upgrade", "XYZP");
152             resp.setHeader("Connection", "Upgrade");
153             resp.setHeader("OtherHeaderB", "Value");
154         }
155     }
156
157     private void initWSClients(ClusterConfig clusterConfig) {
158         for (ClusterNodeInfo nodeConfig : clusterConfig.getSeedNodes()) {
159             if (clusterConfig.isMe(nodeConfig)) {
160                 continue;
161             }
162             String url = String.format("ws://%s:%d/websocket", nodeConfig.getRemoteAddress(), PORT);
163             try {
164                 LOG.debug("registering ws client for " + url);
165                 clusterNodeClients.add(new URI(url));
166             } catch (URISyntaxException e) {
167                 LOG.warn("problem instantiating wsclient for url: " + url);
168             }
169         }
170     }
171 }