blob: 85deaa1dd6c9a5e56716eed858e262912ab01dd9 [file] [log] [blame]
Simon Huntd5b96732016-07-08 13:22:27 -07001/*
2 * Copyright 2016-present 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
17package org.onosproject.ui.impl.topo;
18
Simon Huntc13082f2016-08-03 21:20:23 -070019import com.fasterxml.jackson.databind.JsonNode;
Simon Huntd5b96732016-07-08 13:22:27 -070020import com.fasterxml.jackson.databind.ObjectMapper;
21import com.fasterxml.jackson.databind.node.ArrayNode;
22import com.fasterxml.jackson.databind.node.ObjectNode;
Simon Hunt8f60ff82017-04-24 17:19:30 -070023import com.google.common.base.Strings;
Simon Huntd5b96732016-07-08 13:22:27 -070024import org.onlab.osgi.ServiceDirectory;
Steven Burrows583f4be2016-11-04 14:06:50 +010025import org.onlab.packet.IpAddress;
Simon Huntd5b96732016-07-08 13:22:27 -070026import org.onosproject.cluster.ClusterService;
27import org.onosproject.cluster.NodeId;
28import org.onosproject.incubator.net.PortStatisticsService;
29import org.onosproject.incubator.net.tunnel.TunnelService;
30import org.onosproject.mastership.MastershipService;
Simon Hunt6a8cb4f2016-08-09 15:08:57 -070031import org.onosproject.net.Annotated;
32import org.onosproject.net.Annotations;
33import org.onosproject.net.Device;
Steven Burrowsad75aa22016-12-14 17:17:24 -050034import org.onosproject.net.DeviceId;
Steven Burrows583f4be2016-11-04 14:06:50 +010035import org.onosproject.net.Host;
Simon Huntd5b96732016-07-08 13:22:27 -070036import org.onosproject.net.device.DeviceService;
37import org.onosproject.net.flow.FlowRuleService;
38import org.onosproject.net.host.HostService;
39import org.onosproject.net.intent.IntentService;
40import org.onosproject.net.link.LinkService;
Simon Hunt53612212016-12-04 17:19:52 -080041import org.onosproject.net.region.Region;
Simon Huntd5b96732016-07-08 13:22:27 -070042import org.onosproject.net.statistic.StatisticService;
43import org.onosproject.net.topology.TopologyService;
Steven Burrowse7cc3082016-09-27 11:24:58 -070044import org.onosproject.ui.JsonUtils;
Steven Burrows86b74fc2017-02-22 00:15:16 +000045import org.onosproject.ui.UiExtensionService;
Simon Hunt95f4b422017-03-03 13:49:05 -080046import org.onosproject.ui.UiPreferencesService;
Steven Burrows86b74fc2017-02-22 00:15:16 +000047import org.onosproject.ui.UiTopoMap;
48import org.onosproject.ui.UiTopoMapFactory;
Simon Huntd5b96732016-07-08 13:22:27 -070049import org.onosproject.ui.model.topo.UiClusterMember;
50import org.onosproject.ui.model.topo.UiDevice;
Simon Hunt8eac4ae2017-01-20 12:56:45 -080051import org.onosproject.ui.model.topo.UiElement;
Simon Huntd5b96732016-07-08 13:22:27 -070052import org.onosproject.ui.model.topo.UiHost;
53import org.onosproject.ui.model.topo.UiLink;
Simon Huntcf76a652017-05-12 18:28:24 -070054import org.onosproject.ui.model.topo.UiLinkId;
Simon Huntbf59db22017-05-12 13:26:35 -070055import org.onosproject.ui.model.topo.UiModelEvent;
Simon Hunt977aa052016-07-20 17:08:29 -070056import org.onosproject.ui.model.topo.UiNode;
Simon Huntd5b96732016-07-08 13:22:27 -070057import org.onosproject.ui.model.topo.UiRegion;
Simon Huntc13082f2016-08-03 21:20:23 -070058import org.onosproject.ui.model.topo.UiSynthLink;
Simon Huntd5b96732016-07-08 13:22:27 -070059import org.onosproject.ui.model.topo.UiTopoLayout;
Simon Hunt8f60ff82017-04-24 17:19:30 -070060import org.onosproject.ui.topo.LayoutLocation;
Simon Hunt98189192016-07-29 19:02:27 -070061import org.slf4j.Logger;
62import org.slf4j.LoggerFactory;
Simon Huntd5b96732016-07-08 13:22:27 -070063
Simon Hunt977aa052016-07-20 17:08:29 -070064import java.util.ArrayList;
65import java.util.HashMap;
66import java.util.HashSet;
Simon Huntd5b96732016-07-08 13:22:27 -070067import java.util.List;
Simon Hunt977aa052016-07-20 17:08:29 -070068import java.util.Map;
69import java.util.Set;
Simon Hunt6a8cb4f2016-08-09 15:08:57 -070070import java.util.concurrent.ConcurrentHashMap;
Simon Huntd5b96732016-07-08 13:22:27 -070071
72import static com.google.common.base.Preconditions.checkNotNull;
Simon Huntbc30e682017-02-15 18:39:23 -080073import static org.onosproject.net.AnnotationKeys.GRID_X;
74import static org.onosproject.net.AnnotationKeys.GRID_Y;
Simon Hunt6a8cb4f2016-08-09 15:08:57 -070075import static org.onosproject.net.AnnotationKeys.LATITUDE;
76import static org.onosproject.net.AnnotationKeys.LONGITUDE;
Simon Hunt977aa052016-07-20 17:08:29 -070077import static org.onosproject.ui.model.topo.UiNode.LAYER_DEFAULT;
Simon Hunt8f60ff82017-04-24 17:19:30 -070078import static org.onosproject.ui.topo.LayoutLocation.fromCompactListString;
Simon Huntd5b96732016-07-08 13:22:27 -070079
80/**
81 * Facility for creating JSON messages to send to the topology view in the
82 * Web client.
83 */
Simon Hunt537bc762016-12-20 12:15:13 -080084public class Topo2Jsonifier {
Simon Huntd5b96732016-07-08 13:22:27 -070085
Simon Hunt977aa052016-07-20 17:08:29 -070086 private static final String E_DEF_NOT_LAST =
87 "UiNode.LAYER_DEFAULT not last in layer list";
88 private static final String E_UNKNOWN_UI_NODE =
89 "Unknown subclass of UiNode: ";
90
Simon Hunt2521d5f2017-03-20 18:17:28 -070091 private static final String CONTEXT_KEY_DELIM = "_";
92 private static final String NO_CONTEXT = "";
Simon Huntf0c6f542017-03-22 18:31:18 -070093 private static final String ZOOM_KEY = "layoutZoom";
Simon Hunt2521d5f2017-03-20 18:17:28 -070094
Simon Hunt98189192016-07-29 19:02:27 -070095 private static final String REGION = "region";
96 private static final String DEVICE = "device";
97 private static final String HOST = "host";
Steven Burrows512b6272016-12-19 14:09:45 -050098 private static final String TYPE = "type";
99 private static final String SUBJECT = "subject";
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800100 private static final String DATA = "data";
101 private static final String MEMO = "memo";
Simon Hunt98189192016-07-29 19:02:27 -0700102
Simon Hunt95f4b422017-03-03 13:49:05 -0800103 private static final String GEO = "geo";
104 private static final String GRID = "grid";
Simon Hunt8f60ff82017-04-24 17:19:30 -0700105 private static final String PEER_LOCATIONS = "peerLocations";
Simon Huntf27a9292017-05-04 17:36:26 -0700106 private static final String LOCATION = "location";
107 private static final String LOC_TYPE = "locType";
108 private static final String LAT_OR_Y = "latOrY";
109 private static final String LONG_OR_X = "longOrX";
Simon Hunt95f4b422017-03-03 13:49:05 -0800110
Simon Hunt98189192016-07-29 19:02:27 -0700111 private final Logger log = LoggerFactory.getLogger(getClass());
112
Simon Huntd5b96732016-07-08 13:22:27 -0700113 private final ObjectMapper mapper = new ObjectMapper();
114
Simon Hunt95f4b422017-03-03 13:49:05 -0800115 // preferences are stored per user name...
116 private final String userName;
117
Simon Huntd5b96732016-07-08 13:22:27 -0700118 private ServiceDirectory directory;
119 private ClusterService clusterService;
120 private DeviceService deviceService;
121 private LinkService linkService;
122 private HostService hostService;
123 private MastershipService mastershipService;
124 private IntentService intentService;
125 private FlowRuleService flowService;
126 private StatisticService flowStatsService;
127 private PortStatisticsService portStatsService;
128 private TopologyService topologyService;
129 private TunnelService tunnelService;
Steven Burrows86b74fc2017-02-22 00:15:16 +0000130 private UiExtensionService uiextService;
Simon Hunt95f4b422017-03-03 13:49:05 -0800131 private UiPreferencesService prefService;
Simon Huntd5b96732016-07-08 13:22:27 -0700132
133
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700134 // NOTE: we'll stick this here for now, but maybe there is a better home?
135 // (this is not distributed across the cluster)
136 private static Map<String, ObjectNode> metaUi = new ConcurrentHashMap<>();
137
138
Simon Huntd5b96732016-07-08 13:22:27 -0700139 /**
140 * Creates an instance with a reference to the services directory, so that
141 * additional information about network elements may be looked up on
142 * on the fly.
143 *
144 * @param directory service directory
Simon Hunt95f4b422017-03-03 13:49:05 -0800145 * @param userName logged in user name
Simon Huntd5b96732016-07-08 13:22:27 -0700146 */
Simon Hunt95f4b422017-03-03 13:49:05 -0800147 public Topo2Jsonifier(ServiceDirectory directory, String userName) {
Simon Huntd5b96732016-07-08 13:22:27 -0700148 this.directory = checkNotNull(directory, "Directory cannot be null");
Simon Hunt95f4b422017-03-03 13:49:05 -0800149 this.userName = checkNotNull(userName, "User name cannot be null");
Simon Huntd5b96732016-07-08 13:22:27 -0700150
151 clusterService = directory.get(ClusterService.class);
152 deviceService = directory.get(DeviceService.class);
153 linkService = directory.get(LinkService.class);
154 hostService = directory.get(HostService.class);
155 mastershipService = directory.get(MastershipService.class);
156 intentService = directory.get(IntentService.class);
157 flowService = directory.get(FlowRuleService.class);
158 flowStatsService = directory.get(StatisticService.class);
159 portStatsService = directory.get(PortStatisticsService.class);
160 topologyService = directory.get(TopologyService.class);
161 tunnelService = directory.get(TunnelService.class);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000162 uiextService = directory.get(UiExtensionService.class);
Simon Hunt95f4b422017-03-03 13:49:05 -0800163 prefService = directory.get(UiPreferencesService.class);
Simon Hunt977aa052016-07-20 17:08:29 -0700164 }
Simon Huntd5b96732016-07-08 13:22:27 -0700165
Simon Hunt977aa052016-07-20 17:08:29 -0700166 // for unit testing
167 Topo2Jsonifier() {
Simon Hunt95f4b422017-03-03 13:49:05 -0800168 userName = "(unit-test)";
Simon Huntd5b96732016-07-08 13:22:27 -0700169 }
170
171 private ObjectNode objectNode() {
172 return mapper.createObjectNode();
173 }
174
175 private ArrayNode arrayNode() {
176 return mapper.createArrayNode();
177 }
178
179 private String nullIsEmpty(Object o) {
180 return o == null ? "" : o.toString();
181 }
182
183
184 /**
185 * Returns a JSON representation of the cluster members (ONOS instances).
186 *
187 * @param instances the instance model objects
188 * @return a JSON representation of the data
189 */
190 ObjectNode instances(List<UiClusterMember> instances) {
191 NodeId local = clusterService.getLocalNode().id();
192 ObjectNode payload = objectNode();
193
194 ArrayNode members = arrayNode();
195 payload.set("members", members);
196 for (UiClusterMember member : instances) {
197 members.add(json(member, member.id().equals(local)));
198 }
199
200 return payload;
201 }
202
203 private ObjectNode json(UiClusterMember member, boolean isUiAttached) {
Steven Burrowsad75aa22016-12-14 17:17:24 -0500204 int switchCount = mastershipService.getDevicesOf(member.id()).size();
Simon Huntd5b96732016-07-08 13:22:27 -0700205 return objectNode()
206 .put("id", member.id().toString())
207 .put("ip", member.ip().toString())
208 .put("online", member.isOnline())
209 .put("ready", member.isReady())
210 .put("uiAttached", isUiAttached)
Steven Burrowsad75aa22016-12-14 17:17:24 -0500211 .put("switches", switchCount);
Simon Huntd5b96732016-07-08 13:22:27 -0700212 }
213
214 /**
215 * Returns a JSON representation of the layout to use for displaying in
Simon Huntf836a872016-08-10 17:37:36 -0700216 * the topology view. The identifiers and names of regions from the
217 * current to the root is included, so that the bread-crumb widget can
218 * be rendered.
Simon Huntd5b96732016-07-08 13:22:27 -0700219 *
220 * @param layout the layout to transform
Simon Huntf836a872016-08-10 17:37:36 -0700221 * @param crumbs list of layouts in bread-crumb order
Simon Huntd5b96732016-07-08 13:22:27 -0700222 * @return a JSON representation of the data
223 */
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700224 ObjectNode layout(UiTopoLayout layout, List<UiTopoLayout> crumbs) {
Simon Huntf836a872016-08-10 17:37:36 -0700225 ObjectNode result = objectNode()
Simon Huntd5b96732016-07-08 13:22:27 -0700226 .put("id", layout.id().toString())
227 .put("parent", nullIsEmpty(layout.parent()))
228 .put("region", nullIsEmpty(layout.regionId()))
Simon Huntf836a872016-08-10 17:37:36 -0700229 .put("regionName", UiRegion.safeName(layout.region()));
230 addCrumbs(result, crumbs);
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700231 addBgRef(result, layout);
Simon Huntf836a872016-08-10 17:37:36 -0700232 return result;
Simon Huntd5b96732016-07-08 13:22:27 -0700233 }
234
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700235 private void addBgRef(ObjectNode result, UiTopoLayout layout) {
Steven Burrows86b74fc2017-02-22 00:15:16 +0000236 String mapId = layout.geomap();
237 String sprId = layout.sprites();
238
239 if (mapId != null) {
Simon Hunt95f4b422017-03-03 13:49:05 -0800240 result.put("bgType", GEO).put("bgId", mapId);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000241 addMapParameters(result, mapId);
242 } else if (sprId != null) {
Simon Hunt95f4b422017-03-03 13:49:05 -0800243 result.put("bgType", GRID).put("bgId", sprId);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000244 }
Simon Huntf0c6f542017-03-22 18:31:18 -0700245
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700246 attachZoomData(result, layout);
Simon Hunt95f4b422017-03-03 13:49:05 -0800247 }
248
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700249 private void attachZoomData(ObjectNode result, UiTopoLayout layout) {
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000250
Simon Huntf0c6f542017-03-22 18:31:18 -0700251 ObjectNode zoomData = objectNode();
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000252
Simon Huntf0c6f542017-03-22 18:31:18 -0700253 // first, set configured scale and offset
254 addCfgZoomData(zoomData, layout);
Simon Hunt95f4b422017-03-03 13:49:05 -0800255
Simon Huntf0c6f542017-03-22 18:31:18 -0700256 // next, retrieve user-set zoom data, if we have it
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700257 String rid = layout.regionId().toString();
Simon Huntf0c6f542017-03-22 18:31:18 -0700258 ObjectNode userZoom = metaUi.get(contextKey(rid, ZOOM_KEY));
259 if (userZoom != null) {
260 zoomData.set("usr", userZoom);
Simon Hunt95f4b422017-03-03 13:49:05 -0800261 }
Simon Huntf0c6f542017-03-22 18:31:18 -0700262 result.set("bgZoom", zoomData);
263 }
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000264
Simon Huntf0c6f542017-03-22 18:31:18 -0700265 private void addCfgZoomData(ObjectNode data, UiTopoLayout layout) {
266 ObjectNode zoom = objectNode();
267 zoom.put("scale", layout.scale());
268 zoom.put("offsetX", layout.offsetX());
269 zoom.put("offsetY", layout.offsetY());
270 data.set("cfg", zoom);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000271 }
272
273 private void addMapParameters(ObjectNode result, String mapId) {
274
275 // TODO: This ought to be written more efficiently.
276
277 // ALSO: Should retrieving a UiTopoMap by ID be something that
278 // the UiExtensionService provides, along with other
279 // useful lookups?
280 //
281 // Or should it remain very basic / general?
282 //
283 // return uiextService.getTopoMap(String mapId);
284
285 final UiTopoMap[] map = {null};
286
287 uiextService.getExtensions().forEach(ext -> {
288 UiTopoMapFactory factory = ext.topoMapFactory();
289
290 // TODO: use .stream().filter(...) here
291 if (map[0] == null && factory != null) {
292 List<UiTopoMap> topoMaps = factory.geoMaps();
293
294 topoMaps.forEach(m -> {
295 if (map[0] == null && m.id().equals(mapId)) {
296 map[0] = m;
297 }
298 });
299 }
300 });
301
302 UiTopoMap m = map[0];
303 if (m != null) {
304 result.put("bgDesc", m.description())
305 .put("bgFilePath", m.filePath())
306 .put("bgDefaultScale", m.scale());
307 } else {
308 result.put("bgWarn", "no map registered with id: " + mapId);
Simon Huntbc30e682017-02-15 18:39:23 -0800309 }
310 }
311
Simon Huntf836a872016-08-10 17:37:36 -0700312 private void addCrumbs(ObjectNode result, List<UiTopoLayout> crumbs) {
313 ArrayNode trail = arrayNode();
314 crumbs.forEach(c -> {
315 ObjectNode n = objectNode()
316 .put("id", c.regionId().toString())
317 .put("name", UiRegion.safeName(c.region()));
318 trail.add(n);
319 });
320 result.set("crumbs", trail);
Simon Huntd5b96732016-07-08 13:22:27 -0700321 }
322
323 /**
324 * Returns a JSON representation of the region to display in the topology
325 * view.
326 *
Simon Hunt977aa052016-07-20 17:08:29 -0700327 * @param region the region to transform to JSON
328 * @param subRegions the subregions within this region
Simon Huntc13082f2016-08-03 21:20:23 -0700329 * @param links the links within this region
Simon Huntd5b96732016-07-08 13:22:27 -0700330 * @return a JSON representation of the data
331 */
Simon Huntc13082f2016-08-03 21:20:23 -0700332 ObjectNode region(UiRegion region, Set<UiRegion> subRegions,
333 List<UiSynthLink> links) {
Simon Huntd5b96732016-07-08 13:22:27 -0700334 ObjectNode payload = objectNode();
Simon Huntd5b96732016-07-08 13:22:27 -0700335 if (region == null) {
336 payload.put("note", "no-region");
337 return payload;
338 }
Simon Hunt2521d5f2017-03-20 18:17:28 -0700339
340 String ridStr = region.idAsString();
341
342 payload.put("id", ridStr);
343 payload.set("subregions", jsonSubRegions(ridStr, subRegions));
Simon Huntcd508a62016-10-27 12:47:24 -0700344 payload.set("links", jsonLinks(links));
Simon Huntc13082f2016-08-03 21:20:23 -0700345
Simon Hunt977aa052016-07-20 17:08:29 -0700346 List<String> layerTags = region.layerOrder();
347 List<Set<UiNode>> splitDevices = splitByLayer(layerTags, region.devices());
348 List<Set<UiNode>> splitHosts = splitByLayer(layerTags, region.hosts());
Simon Huntd5b96732016-07-08 13:22:27 -0700349
Simon Hunt2521d5f2017-03-20 18:17:28 -0700350 payload.set("devices", jsonGrouped(ridStr, splitDevices));
351 payload.set("hosts", jsonGrouped(ridStr, splitHosts));
Simon Hunt977aa052016-07-20 17:08:29 -0700352 payload.set("layerOrder", jsonStrings(layerTags));
Simon Huntd5b96732016-07-08 13:22:27 -0700353
Simon Hunt8f60ff82017-04-24 17:19:30 -0700354 if (!region.isRoot()) {
355 addPeerLocations(payload, region.backingRegion());
356 }
357
Simon Huntd5b96732016-07-08 13:22:27 -0700358 return payload;
359 }
360
Simon Hunt2521d5f2017-03-20 18:17:28 -0700361 private ArrayNode jsonSubRegions(String ridStr, Set<UiRegion> subregions) {
Simon Hunt977aa052016-07-20 17:08:29 -0700362 ArrayNode kids = arrayNode();
Simon Hunt2521d5f2017-03-20 18:17:28 -0700363 subregions.forEach(s -> kids.add(jsonClosedRegion(ridStr, s)));
Simon Hunt977aa052016-07-20 17:08:29 -0700364 return kids;
365 }
366
Simon Huntbf59db22017-05-12 13:26:35 -0700367 protected JsonNode jsonLinks(List<UiSynthLink> links) {
Simon Huntcf76a652017-05-12 18:28:24 -0700368 return collateSynthLinks(links);
Simon Huntc13082f2016-08-03 21:20:23 -0700369 }
370
Simon Hunt977aa052016-07-20 17:08:29 -0700371 private ArrayNode jsonStrings(List<String> strings) {
372 ArrayNode array = arrayNode();
373 strings.forEach(array::add);
374 return array;
375 }
376
Simon Hunt2521d5f2017-03-20 18:17:28 -0700377 private ArrayNode jsonGrouped(String ridStr, List<Set<UiNode>> groupedNodes) {
Simon Hunt977aa052016-07-20 17:08:29 -0700378 ArrayNode result = arrayNode();
379 groupedNodes.forEach(g -> {
380 ArrayNode subset = arrayNode();
Simon Hunt2521d5f2017-03-20 18:17:28 -0700381 g.forEach(n -> subset.add(json(ridStr, n)));
Simon Hunt977aa052016-07-20 17:08:29 -0700382 result.add(subset);
383 });
384 return result;
385 }
386
Simon Hunt537bc762016-12-20 12:15:13 -0800387 /**
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800388 * Creates a JSON representation of a UI element.
389 *
390 * @param element the source element
391 * @return a JSON representation of that element
392 */
393 public ObjectNode jsonUiElement(UiElement element) {
394 if (element instanceof UiNode) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700395 return json(NO_CONTEXT, (UiNode) element);
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800396 }
397 if (element instanceof UiLink) {
398 return json((UiLink) element);
399 }
400
401 // TODO: UiClusterMember
402
403 // Unrecognized UiElement class
404 return objectNode()
405 .put("warning", "unknown UiElement... cannot encode")
406 .put("javaclass", element.getClass().toString());
407 }
408
409 /**
Simon Hunt537bc762016-12-20 12:15:13 -0800410 * Creates a JSON representation of a UI model event.
411 *
412 * @param modelEvent the source model event
413 * @return a JSON representation of that event
414 */
415 public ObjectNode jsonEvent(UiModelEvent modelEvent) {
Steven Burrows512b6272016-12-19 14:09:45 -0500416 ObjectNode payload = objectNode();
417 payload.put(TYPE, enumToString(modelEvent.type()));
418 payload.put(SUBJECT, modelEvent.subject().idAsString());
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800419 payload.set(DATA, modelEvent.data());
420 payload.put(MEMO, modelEvent.memo());
Steven Burrows512b6272016-12-19 14:09:45 -0500421 return payload;
422 }
423
424 // TODO: Investigate why we can't do this inline
425 private String enumToString(Enum<?> e) {
426 return e.toString();
427 }
428
Steven Burrowsad75aa22016-12-14 17:17:24 -0500429 // Returns the name of the master node for the specified device id.
430 private String master(DeviceId deviceId) {
431 NodeId master = mastershipService.getMasterFor(deviceId);
432 return master != null ? master.toString() : "";
433 }
Simon Hunt977aa052016-07-20 17:08:29 -0700434
Simon Hunt2521d5f2017-03-20 18:17:28 -0700435 private ObjectNode json(String ridStr, UiNode node) {
Simon Hunt977aa052016-07-20 17:08:29 -0700436 if (node instanceof UiRegion) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700437 return jsonClosedRegion(ridStr, (UiRegion) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700438 }
439 if (node instanceof UiDevice) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700440 return json(ridStr, (UiDevice) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700441 }
442 if (node instanceof UiHost) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700443 return json(ridStr, (UiHost) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700444 }
445 throw new IllegalStateException(E_UNKNOWN_UI_NODE + node.getClass());
446 }
447
Simon Hunt2521d5f2017-03-20 18:17:28 -0700448 private ObjectNode json(String ridStr, UiDevice device) {
Simon Huntd5b96732016-07-08 13:22:27 -0700449 ObjectNode node = objectNode()
Simon Hunt977aa052016-07-20 17:08:29 -0700450 .put("id", device.idAsString())
Simon Hunt98189192016-07-29 19:02:27 -0700451 .put("nodeType", DEVICE)
Simon Huntd5b96732016-07-08 13:22:27 -0700452 .put("type", device.type())
Simon Hunt3d712522016-08-11 11:20:44 -0700453 .put("online", deviceService.isAvailable(device.id()))
Steven Burrowsad75aa22016-12-14 17:17:24 -0500454 .put("master", master(device.id()))
Simon Huntd5b96732016-07-08 13:22:27 -0700455 .put("layer", device.layer());
456
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700457 Device d = device.backingDevice();
458
459 addProps(node, d);
Simon Huntbc30e682017-02-15 18:39:23 -0800460 addGeoGridLocation(node, d);
Simon Hunt2521d5f2017-03-20 18:17:28 -0700461 addMetaUi(node, ridStr, device.idAsString());
Simon Huntd5b96732016-07-08 13:22:27 -0700462
463 return node;
464 }
465
Simon Hunt53612212016-12-04 17:19:52 -0800466 private void addProps(ObjectNode node, Annotated a) {
467 Annotations annot = a.annotations();
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700468 ObjectNode props = objectNode();
469 if (annot != null) {
470 annot.keys().forEach(k -> props.put(k, annot.value(k)));
471 }
472 node.set("props", props);
473 }
Simon Huntd5b96732016-07-08 13:22:27 -0700474
Simon Hunt2521d5f2017-03-20 18:17:28 -0700475 private void addMetaUi(ObjectNode node, String ridStr, String metaInstanceId) {
476 String key = contextKey(ridStr, metaInstanceId);
477 ObjectNode meta = metaUi.get(key);
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700478 if (meta != null) {
479 node.set("metaUi", meta);
480 }
481 }
482
Simon Huntbc30e682017-02-15 18:39:23 -0800483 private void addGeoGridLocation(ObjectNode node, Annotated a) {
Simon Huntf27a9292017-05-04 17:36:26 -0700484 List<String> latLongData = getAnnotValues(a, LATITUDE, LONGITUDE);
485 List<String> gridYXdata = getAnnotValues(a, GRID_Y, GRID_X);
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700486
Simon Huntf27a9292017-05-04 17:36:26 -0700487 if (latLongData != null) {
488 attachLocation(node, GEO, latLongData);
489 } else if (gridYXdata != null) {
490 attachLocation(node, GRID, gridYXdata);
Simon Huntbc30e682017-02-15 18:39:23 -0800491 }
492 }
493
494 private void attachLocation(ObjectNode node, String locType,
Simon Huntf27a9292017-05-04 17:36:26 -0700495 List<String> values) {
Simon Huntbc30e682017-02-15 18:39:23 -0800496 try {
Simon Huntf27a9292017-05-04 17:36:26 -0700497 double latOrY = Double.parseDouble(values.get(0));
498 double longOrX = Double.parseDouble(values.get(1));
Simon Huntbc30e682017-02-15 18:39:23 -0800499 ObjectNode loc = objectNode()
Simon Huntf27a9292017-05-04 17:36:26 -0700500 .put(LOC_TYPE, locType)
501 .put(LAT_OR_Y, latOrY)
502 .put(LONG_OR_X, longOrX);
503 node.set(LOCATION, loc);
Simon Huntbc30e682017-02-15 18:39:23 -0800504
505 } catch (NumberFormatException e) {
Simon Huntf27a9292017-05-04 17:36:26 -0700506 log.warn("Invalid {} data: lat/Y={}, long/X={}",
Simon Huntbf59db22017-05-12 13:26:35 -0700507 locType, values.get(0), values.get(1));
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700508 }
509 }
510
Simon Hunt8f60ff82017-04-24 17:19:30 -0700511 private void addPeerLocations(ObjectNode node, Region r) {
512 String compact = r.annotations().value(PEER_LOCATIONS);
513 if (!Strings.isNullOrEmpty(compact)) {
514 List<LayoutLocation> locs = fromCompactListString(compact);
515
516 ObjectNode o = objectNode();
517 for (LayoutLocation ll : locs) {
518 ObjectNode lnode = objectNode()
Simon Huntbf59db22017-05-12 13:26:35 -0700519 .put(LOC_TYPE, ll.locType().toString())
520 .put(LAT_OR_Y, ll.latOrY())
521 .put(LONG_OR_X, ll.longOrX());
Simon Hunt8f60ff82017-04-24 17:19:30 -0700522 o.set(ll.id(), lnode);
523 }
524
525 node.set(PEER_LOCATIONS, o);
526 }
527 }
528
Steven Burrows583f4be2016-11-04 14:06:50 +0100529 private void addIps(ObjectNode node, Host h) {
530 Set<IpAddress> ips = h.ipAddresses();
531
532 ArrayNode a = arrayNode();
533 for (IpAddress ip : ips) {
534 a.add(ip.toString());
535 }
536
537 node.set("ips", a);
538 }
539
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700540 // return list of string values from annotated instance, for given keys
541 // return null if any keys are not present
542 List<String> getAnnotValues(Annotated a, String... annotKeys) {
543 List<String> result = new ArrayList<>(annotKeys.length);
544 for (String k : annotKeys) {
545 String v = a.annotations().value(k);
546 if (v == null) {
547 return null;
548 }
549 result.add(v);
550 }
551 return result;
552 }
553
554 // derive JSON object from annotations
555 private ObjectNode props(Annotations annotations) {
556 ObjectNode p = objectNode();
557 if (annotations != null) {
558 annotations.keys().forEach(k -> p.put(k, annotations.value(k)));
559 }
560 return p;
Simon Huntd5b96732016-07-08 13:22:27 -0700561 }
562
Simon Hunt2521d5f2017-03-20 18:17:28 -0700563 private ObjectNode json(String ridStr, UiHost host) {
Steven Burrows583f4be2016-11-04 14:06:50 +0100564 ObjectNode node = objectNode()
Simon Hunt977aa052016-07-20 17:08:29 -0700565 .put("id", host.idAsString())
Simon Hunt98189192016-07-29 19:02:27 -0700566 .put("nodeType", HOST)
Simon Huntd5b96732016-07-08 13:22:27 -0700567 .put("layer", host.layer());
568 // TODO: complete host details
Steven Burrows583f4be2016-11-04 14:06:50 +0100569 Host h = host.backingHost();
570
571 addIps(node, h);
Simon Huntbc30e682017-02-15 18:39:23 -0800572 addProps(node, h);
573 addGeoGridLocation(node, h);
Simon Hunt2521d5f2017-03-20 18:17:28 -0700574 addMetaUi(node, ridStr, host.idAsString());
Steven Burrows583f4be2016-11-04 14:06:50 +0100575
576 return node;
Simon Huntd5b96732016-07-08 13:22:27 -0700577 }
578
Simon Huntcf76a652017-05-12 18:28:24 -0700579 private ArrayNode collateSynthLinks(List<UiSynthLink> links) {
580 Map<UiLinkId, Set<UiSynthLink>> collation = new HashMap<>();
Simon Huntbf59db22017-05-12 13:26:35 -0700581
Simon Huntcf76a652017-05-12 18:28:24 -0700582 // first, group together the synthlinks into sets per ID...
583 for (UiSynthLink sl : links) {
584 UiLinkId id = sl.link().id();
585 Set<UiSynthLink> rollup =
586 collation.computeIfAbsent(id, k -> new HashSet<>());
587 rollup.add(sl);
588 }
589
590 // now add json nodes per set, and return the array of them
591 ArrayNode array = arrayNode();
592 for (UiLinkId id : collation.keySet()) {
593 array.add(json(collation.get(id)));
594 }
595 return array;
Simon Huntbf59db22017-05-12 13:26:35 -0700596 }
597
Simon Huntcf76a652017-05-12 18:28:24 -0700598 private ObjectNode json(Set<UiSynthLink> memberSet) {
599 ArrayNode rollup = arrayNode();
600 ObjectNode node = null;
601
602 boolean first = true;
603 for (UiSynthLink member : memberSet) {
604 UiLink link = member.link();
605 if (first) {
606 node = json(link);
607 first = false;
608 }
609 rollup.add(json(member.original()));
610 }
611 if (node != null) {
612 node.set("rollup", rollup);
613 }
614 return node;
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800615 }
616
617 private ObjectNode json(UiLink link) {
Simon Hunt3d712522016-08-11 11:20:44 -0700618 ObjectNode data = objectNode()
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800619 .put("id", link.idAsString())
620 .put("epA", link.endPointA())
621 .put("epB", link.endPointB())
622 .put("type", link.type());
623 String pA = link.endPortA();
624 String pB = link.endPortB();
Simon Hunt3d712522016-08-11 11:20:44 -0700625 if (pA != null) {
626 data.put("portA", pA);
627 }
628 if (pB != null) {
629 data.put("portB", pB);
630 }
631 return data;
Simon Huntd5b96732016-07-08 13:22:27 -0700632 }
633
634
Simon Hunt2521d5f2017-03-20 18:17:28 -0700635 private ObjectNode jsonClosedRegion(String ridStr, UiRegion region) {
Steven Burrows482d9502016-09-27 11:24:58 -0700636 ObjectNode node = objectNode()
Simon Huntb1ce2602016-07-23 14:04:31 -0700637 .put("id", region.idAsString())
Simon Huntf836a872016-08-10 17:37:36 -0700638 .put("name", region.name())
Simon Hunt98189192016-07-29 19:02:27 -0700639 .put("nodeType", REGION)
Steven Burrows19e6e4f2016-10-05 13:27:07 -0500640 .put("nDevs", region.deviceCount())
641 .put("nHosts", region.hostCount());
Simon Hunt2521d5f2017-03-20 18:17:28 -0700642 // TODO: device and host counts should take into account any nested
643 // subregions. i.e. should be the sum of all devices/hosts in
Simon Hunt8f60ff82017-04-24 17:19:30 -0700644 // all descendant subregions.
Simon Hunt53612212016-12-04 17:19:52 -0800645
646 Region r = region.backingRegion();
Simon Hunt0ee20bf2017-05-10 19:59:17 -0700647 if (r != null) {
648 // add data injected via network configuration script
649 addGeoGridLocation(node, r);
650 addProps(node, r);
651 }
Steven Burrows482d9502016-09-27 11:24:58 -0700652
Simon Hunt2521d5f2017-03-20 18:17:28 -0700653 // this may contain location data, as dragged by user
654 // (which should take precedence, over configured data)
655 addMetaUi(node, ridStr, region.idAsString());
Steven Burrows482d9502016-09-27 11:24:58 -0700656 return node;
Simon Hunt977aa052016-07-20 17:08:29 -0700657 }
658
Simon Hunt98189192016-07-29 19:02:27 -0700659 /**
660 * Returns a JSON array representation of a set of regions/devices. Note
661 * that the information is sufficient for showing regions as nodes.
Simon Hunt2521d5f2017-03-20 18:17:28 -0700662 * THe region ID string defines the context (which region) the node is
663 * being displayed in.
Simon Hunt98189192016-07-29 19:02:27 -0700664 *
Simon Hunt2521d5f2017-03-20 18:17:28 -0700665 * @param ridStr region-id string
Simon Huntf0c6f542017-03-22 18:31:18 -0700666 * @param nodes the nodes
Simon Hunt98189192016-07-29 19:02:27 -0700667 * @return a JSON representation of the nodes
668 */
Simon Hunt2521d5f2017-03-20 18:17:28 -0700669 public ArrayNode closedNodes(String ridStr, Set<UiNode> nodes) {
Simon Hunt98189192016-07-29 19:02:27 -0700670 ArrayNode array = arrayNode();
Simon Huntc13082f2016-08-03 21:20:23 -0700671 for (UiNode node : nodes) {
Simon Hunt98189192016-07-29 19:02:27 -0700672 if (node instanceof UiRegion) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700673 array.add(jsonClosedRegion(ridStr, (UiRegion) node));
Simon Hunt98189192016-07-29 19:02:27 -0700674 } else if (node instanceof UiDevice) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700675 array.add(json(ridStr, (UiDevice) node));
Simon Hunt98189192016-07-29 19:02:27 -0700676 } else {
677 log.warn("Unexpected node instance: {}", node.getClass());
678 }
679 }
680 return array;
681 }
Simon Hunt977aa052016-07-20 17:08:29 -0700682
Simon Hunt977aa052016-07-20 17:08:29 -0700683 // package-private for unit testing
684 List<Set<UiNode>> splitByLayer(List<String> layerTags,
685 Set<? extends UiNode> nodes) {
686 final int nLayers = layerTags.size();
687 if (!layerTags.get(nLayers - 1).equals(LAYER_DEFAULT)) {
688 throw new IllegalArgumentException(E_DEF_NOT_LAST);
689 }
690
691 List<Set<UiNode>> splitList = new ArrayList<>(layerTags.size());
692 Map<String, Set<UiNode>> byLayer = new HashMap<>(layerTags.size());
693
694 for (String tag : layerTags) {
695 Set<UiNode> set = new HashSet<>();
696 byLayer.put(tag, set);
697 splitList.add(set);
698 }
699
700 for (UiNode n : nodes) {
701 String which = n.layer();
702 if (!layerTags.contains(which)) {
703 which = LAYER_DEFAULT;
704 }
705 byLayer.get(which).add(n);
706 }
707
708 return splitList;
709 }
Steven Burrowse7cc3082016-09-27 11:24:58 -0700710
Simon Hunt2521d5f2017-03-20 18:17:28 -0700711
712 private String contextKey(String context, String key) {
713 return context + CONTEXT_KEY_DELIM + key;
714 }
715
Steven Burrowse7cc3082016-09-27 11:24:58 -0700716 /**
717 * Stores the memento for an element.
Simon Hunt2521d5f2017-03-20 18:17:28 -0700718 * This method assumes the payload has an id String, memento ObjectNode.
719 * The region-id string is used as a context within which to store the
720 * memento.
Steven Burrowse7cc3082016-09-27 11:24:58 -0700721 *
Simon Hunt2521d5f2017-03-20 18:17:28 -0700722 * @param ridStr region ID string
Steven Burrowse7cc3082016-09-27 11:24:58 -0700723 * @param payload event payload
724 */
Simon Hunt2521d5f2017-03-20 18:17:28 -0700725 void updateMeta(String ridStr, ObjectNode payload) {
Steven Burrowse7cc3082016-09-27 11:24:58 -0700726
727 String id = JsonUtils.string(payload, "id");
Simon Hunt2521d5f2017-03-20 18:17:28 -0700728 String key = contextKey(ridStr, id);
729 metaUi.put(key, JsonUtils.node(payload, "memento"));
Steven Burrowse7cc3082016-09-27 11:24:58 -0700730
Simon Hunt2521d5f2017-03-20 18:17:28 -0700731 log.debug("Storing metadata for {}", key);
Steven Burrowse7cc3082016-09-27 11:24:58 -0700732 }
Simon Huntd5b96732016-07-08 13:22:27 -0700733}