blob: c571f8f9ea32243a94e2d3a32a998ee929b2ec38 [file] [log] [blame]
Thomas Vachuska3553b302015-03-07 14:49:43 -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 */
16package org.onosproject.ui.impl;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070019import com.fasterxml.jackson.databind.node.ArrayNode;
Thomas Vachuska3553b302015-03-07 14:49:43 -080020import com.fasterxml.jackson.databind.node.ObjectNode;
21import org.eclipse.jetty.websocket.WebSocket;
22import org.onlab.osgi.ServiceDirectory;
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -070023import org.onosproject.cluster.ClusterService;
24import org.onosproject.cluster.ControllerNode;
Thomas Vachuska3553b302015-03-07 14:49:43 -080025import org.onosproject.ui.UiConnection;
26import org.onosproject.ui.UiExtensionService;
Thomas Vachuska329af532015-03-10 02:08:33 -070027import org.onosproject.ui.UiMessageHandlerFactory;
Simon Hunta0ddb022015-05-01 09:53:01 -070028import org.onosproject.ui.UiMessageHandler;
Thomas Vachuska3553b302015-03-07 14:49:43 -080029import org.slf4j.Logger;
30import org.slf4j.LoggerFactory;
31
32import java.io.IOException;
33import java.util.HashMap;
34import java.util.Map;
35
36/**
37 * Web socket capable of interacting with the GUI.
38 */
39public class UiWebSocket
40 implements UiConnection, WebSocket.OnTextMessage, WebSocket.OnControl {
41
42 private static final Logger log = LoggerFactory.getLogger(UiWebSocket.class);
43
Simon Huntda580882015-05-12 20:58:18 -070044 private static final long MAX_AGE_MS = 15_000;
Thomas Vachuska3553b302015-03-07 14:49:43 -080045
46 private static final byte PING = 0x9;
47 private static final byte PONG = 0xA;
48 private static final byte[] PING_DATA = new byte[]{(byte) 0xde, (byte) 0xad};
49
50 private final ServiceDirectory directory;
51
52 private Connection connection;
53 private FrameConnection control;
54
55 private final ObjectMapper mapper = new ObjectMapper();
56
57 private long lastActive = System.currentTimeMillis();
58
Simon Hunta0ddb022015-05-01 09:53:01 -070059 private Map<String, UiMessageHandler> handlers;
Thomas Vachuska3553b302015-03-07 14:49:43 -080060
61 /**
62 * Creates a new web-socket for serving data to GUI.
63 *
64 * @param directory service directory
65 */
66 public UiWebSocket(ServiceDirectory directory) {
67 this.directory = directory;
68 }
69
70 /**
71 * Issues a close on the connection.
72 */
73 synchronized void close() {
74 destroyHandlers();
75 if (connection.isOpen()) {
76 connection.close();
77 }
78 }
79
80 /**
81 * Indicates if this connection is idle.
82 *
83 * @return true if idle or closed
84 */
85 synchronized boolean isIdle() {
Simon Huntda580882015-05-12 20:58:18 -070086 long quietFor = System.currentTimeMillis() - lastActive;
87 boolean idle = quietFor > MAX_AGE_MS;
Thomas Vachuska3553b302015-03-07 14:49:43 -080088 if (idle || (connection != null && !connection.isOpen())) {
Simon Huntda580882015-05-12 20:58:18 -070089 log.debug("IDLE (or closed) websocket [{} ms]", quietFor);
Thomas Vachuska3553b302015-03-07 14:49:43 -080090 return true;
91 } else if (connection != null) {
92 try {
93 control.sendControl(PING, PING_DATA, 0, PING_DATA.length);
94 } catch (IOException e) {
95 log.warn("Unable to send ping message due to: ", e);
96 }
97 }
98 return false;
99 }
100
101 @Override
102 public void onOpen(Connection connection) {
103 log.info("GUI client connected");
104 this.connection = connection;
105 this.control = (FrameConnection) connection;
106 createHandlers();
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700107 sendInstanceData();
Thomas Vachuska3553b302015-03-07 14:49:43 -0800108 }
109
110 @Override
111 public synchronized void onClose(int closeCode, String message) {
112 destroyHandlers();
Simon Huntda580882015-05-12 20:58:18 -0700113 log.info("GUI client disconnected [close-code={}, message={}]",
114 closeCode, message);
Thomas Vachuska3553b302015-03-07 14:49:43 -0800115 }
116
117 @Override
118 public boolean onControl(byte controlCode, byte[] data, int offset, int length) {
119 lastActive = System.currentTimeMillis();
120 return true;
121 }
122
123 @Override
124 public void onMessage(String data) {
125 lastActive = System.currentTimeMillis();
126 try {
127 ObjectNode message = (ObjectNode) mapper.reader().readTree(data);
Thomas Vachuska329af532015-03-10 02:08:33 -0700128 String type = message.path("event").asText("unknown");
Simon Hunta0ddb022015-05-01 09:53:01 -0700129 UiMessageHandler handler = handlers.get(type);
Thomas Vachuska3553b302015-03-07 14:49:43 -0800130 if (handler != null) {
131 handler.process(message);
132 } else {
133 log.warn("No GUI message handler for type {}", type);
134 }
135 } catch (Exception e) {
136 log.warn("Unable to parse GUI message {} due to {}", data, e);
137 log.debug("Boom!!!", e);
138 }
139 }
140
141 @Override
Thomas Vachuska35fa3d42015-04-30 10:11:47 -0700142 public synchronized void sendMessage(ObjectNode message) {
Thomas Vachuska3553b302015-03-07 14:49:43 -0800143 try {
144 if (connection.isOpen()) {
145 connection.sendMessage(message.toString());
146 }
147 } catch (IOException e) {
148 log.warn("Unable to send message {} to GUI due to {}", message, e);
149 log.debug("Boom!!!", e);
150 }
151 }
152
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700153 @Override
Thomas Vachuska35fa3d42015-04-30 10:11:47 -0700154 public synchronized void sendMessage(String type, long sid, ObjectNode payload) {
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700155 ObjectNode message = mapper.createObjectNode();
156 message.put("event", type);
157 if (sid > 0) {
158 message.put("sid", sid);
159 }
160 message.set("payload", payload);
161 sendMessage(message);
162
163 }
164
Thomas Vachuska3553b302015-03-07 14:49:43 -0800165 // Creates new message handlers.
Thomas Vachuska35fa3d42015-04-30 10:11:47 -0700166 private synchronized void createHandlers() {
Thomas Vachuska3553b302015-03-07 14:49:43 -0800167 handlers = new HashMap<>();
168 UiExtensionService service = directory.get(UiExtensionService.class);
Thomas Vachuska329af532015-03-10 02:08:33 -0700169 service.getExtensions().forEach(ext -> {
170 UiMessageHandlerFactory factory = ext.messageHandlerFactory();
171 if (factory != null) {
172 factory.newHandlers().forEach(handler -> {
173 handler.init(this, directory);
174 handler.messageTypes().forEach(type -> handlers.put(type, handler));
175 });
176 }
177 });
Thomas Vachuska3553b302015-03-07 14:49:43 -0800178 }
179
180 // Destroys message handlers.
181 private synchronized void destroyHandlers() {
182 handlers.forEach((type, handler) -> handler.destroy());
183 handlers.clear();
184 }
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700185
186 // Sends cluster node/instance information to allow GUI to fail-over.
187 private void sendInstanceData() {
188 ClusterService service = directory.get(ClusterService.class);
189 ArrayNode instances = mapper.createArrayNode();
190
191 for (ControllerNode node : service.getNodes()) {
192 ObjectNode instance = mapper.createObjectNode()
193 .put("id", node.id().toString())
194 .put("ip", node.ip().toString())
195 .put("uiAttached", node.equals(service.getLocalNode()));
196 instances.add(instance);
197 }
198
199 ObjectNode payload = mapper.createObjectNode();
Thomas Vachuska20084b72015-03-11 13:46:50 -0700200 payload.set("clusterNodes", instances);
201 sendMessage("bootstrap", 0, payload);
Thomas Vachuskab6acc7b2015-03-11 09:11:21 -0700202 }
203
Thomas Vachuska3553b302015-03-07 14:49:43 -0800204}
205