blob: 5c9b608635b143632187f6c347b9d3772e34faed [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;
Thomas Vachuska8c0b18a2017-04-14 16:27:33 -070049import org.onosproject.ui.model.topo.UiModelEvent;
Simon Huntd5b96732016-07-08 13:22:27 -070050import org.onosproject.ui.model.topo.UiClusterMember;
51import org.onosproject.ui.model.topo.UiDevice;
Simon Hunt8eac4ae2017-01-20 12:56:45 -080052import org.onosproject.ui.model.topo.UiElement;
Simon Huntd5b96732016-07-08 13:22:27 -070053import org.onosproject.ui.model.topo.UiHost;
54import org.onosproject.ui.model.topo.UiLink;
Simon Hunt977aa052016-07-20 17:08:29 -070055import org.onosproject.ui.model.topo.UiNode;
Simon Huntd5b96732016-07-08 13:22:27 -070056import org.onosproject.ui.model.topo.UiRegion;
Simon Huntc13082f2016-08-03 21:20:23 -070057import org.onosproject.ui.model.topo.UiSynthLink;
Simon Huntd5b96732016-07-08 13:22:27 -070058import org.onosproject.ui.model.topo.UiTopoLayout;
Simon Hunt8f60ff82017-04-24 17:19:30 -070059import org.onosproject.ui.topo.LayoutLocation;
Simon Hunt98189192016-07-29 19:02:27 -070060import org.slf4j.Logger;
61import org.slf4j.LoggerFactory;
Simon Huntd5b96732016-07-08 13:22:27 -070062
Simon Hunt977aa052016-07-20 17:08:29 -070063import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.HashSet;
Simon Huntd5b96732016-07-08 13:22:27 -070066import java.util.List;
Simon Hunt977aa052016-07-20 17:08:29 -070067import java.util.Map;
68import java.util.Set;
Simon Hunt6a8cb4f2016-08-09 15:08:57 -070069import java.util.concurrent.ConcurrentHashMap;
Simon Huntd5b96732016-07-08 13:22:27 -070070
71import static com.google.common.base.Preconditions.checkNotNull;
Simon Huntbc30e682017-02-15 18:39:23 -080072import static org.onosproject.net.AnnotationKeys.GRID_X;
73import static org.onosproject.net.AnnotationKeys.GRID_Y;
Simon Hunt6a8cb4f2016-08-09 15:08:57 -070074import static org.onosproject.net.AnnotationKeys.LATITUDE;
75import static org.onosproject.net.AnnotationKeys.LONGITUDE;
Simon Hunt977aa052016-07-20 17:08:29 -070076import static org.onosproject.ui.model.topo.UiNode.LAYER_DEFAULT;
Simon Hunt8f60ff82017-04-24 17:19:30 -070077import static org.onosproject.ui.topo.LayoutLocation.fromCompactListString;
Simon Huntd5b96732016-07-08 13:22:27 -070078
79/**
80 * Facility for creating JSON messages to send to the topology view in the
81 * Web client.
82 */
Simon Hunt537bc762016-12-20 12:15:13 -080083public class Topo2Jsonifier {
Simon Huntd5b96732016-07-08 13:22:27 -070084
Simon Hunt977aa052016-07-20 17:08:29 -070085 private static final String E_DEF_NOT_LAST =
86 "UiNode.LAYER_DEFAULT not last in layer list";
87 private static final String E_UNKNOWN_UI_NODE =
88 "Unknown subclass of UiNode: ";
89
Simon Hunt2521d5f2017-03-20 18:17:28 -070090 private static final String CONTEXT_KEY_DELIM = "_";
91 private static final String NO_CONTEXT = "";
Simon Huntf0c6f542017-03-22 18:31:18 -070092 private static final String ZOOM_KEY = "layoutZoom";
Simon Hunt2521d5f2017-03-20 18:17:28 -070093
Simon Hunt98189192016-07-29 19:02:27 -070094 private static final String REGION = "region";
95 private static final String DEVICE = "device";
96 private static final String HOST = "host";
Steven Burrows512b6272016-12-19 14:09:45 -050097 private static final String TYPE = "type";
98 private static final String SUBJECT = "subject";
Simon Hunt8eac4ae2017-01-20 12:56:45 -080099 private static final String DATA = "data";
100 private static final String MEMO = "memo";
Simon Hunt98189192016-07-29 19:02:27 -0700101
Simon Hunt95f4b422017-03-03 13:49:05 -0800102 private static final String GEO = "geo";
103 private static final String GRID = "grid";
Simon Hunt8f60ff82017-04-24 17:19:30 -0700104 private static final String PEER_LOCATIONS = "peerLocations";
Simon Hunt95f4b422017-03-03 13:49:05 -0800105
Simon Hunt98189192016-07-29 19:02:27 -0700106 private final Logger log = LoggerFactory.getLogger(getClass());
107
Simon Huntd5b96732016-07-08 13:22:27 -0700108 private final ObjectMapper mapper = new ObjectMapper();
109
Simon Hunt95f4b422017-03-03 13:49:05 -0800110 // preferences are stored per user name...
111 private final String userName;
112
Simon Huntd5b96732016-07-08 13:22:27 -0700113 private ServiceDirectory directory;
114 private ClusterService clusterService;
115 private DeviceService deviceService;
116 private LinkService linkService;
117 private HostService hostService;
118 private MastershipService mastershipService;
119 private IntentService intentService;
120 private FlowRuleService flowService;
121 private StatisticService flowStatsService;
122 private PortStatisticsService portStatsService;
123 private TopologyService topologyService;
124 private TunnelService tunnelService;
Steven Burrows86b74fc2017-02-22 00:15:16 +0000125 private UiExtensionService uiextService;
Simon Hunt95f4b422017-03-03 13:49:05 -0800126 private UiPreferencesService prefService;
Simon Huntd5b96732016-07-08 13:22:27 -0700127
128
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700129 // NOTE: we'll stick this here for now, but maybe there is a better home?
130 // (this is not distributed across the cluster)
131 private static Map<String, ObjectNode> metaUi = new ConcurrentHashMap<>();
132
133
Simon Huntd5b96732016-07-08 13:22:27 -0700134 /**
135 * Creates an instance with a reference to the services directory, so that
136 * additional information about network elements may be looked up on
137 * on the fly.
138 *
139 * @param directory service directory
Simon Hunt95f4b422017-03-03 13:49:05 -0800140 * @param userName logged in user name
Simon Huntd5b96732016-07-08 13:22:27 -0700141 */
Simon Hunt95f4b422017-03-03 13:49:05 -0800142 public Topo2Jsonifier(ServiceDirectory directory, String userName) {
Simon Huntd5b96732016-07-08 13:22:27 -0700143 this.directory = checkNotNull(directory, "Directory cannot be null");
Simon Hunt95f4b422017-03-03 13:49:05 -0800144 this.userName = checkNotNull(userName, "User name cannot be null");
Simon Huntd5b96732016-07-08 13:22:27 -0700145
146 clusterService = directory.get(ClusterService.class);
147 deviceService = directory.get(DeviceService.class);
148 linkService = directory.get(LinkService.class);
149 hostService = directory.get(HostService.class);
150 mastershipService = directory.get(MastershipService.class);
151 intentService = directory.get(IntentService.class);
152 flowService = directory.get(FlowRuleService.class);
153 flowStatsService = directory.get(StatisticService.class);
154 portStatsService = directory.get(PortStatisticsService.class);
155 topologyService = directory.get(TopologyService.class);
156 tunnelService = directory.get(TunnelService.class);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000157 uiextService = directory.get(UiExtensionService.class);
Simon Hunt95f4b422017-03-03 13:49:05 -0800158 prefService = directory.get(UiPreferencesService.class);
Simon Hunt977aa052016-07-20 17:08:29 -0700159 }
Simon Huntd5b96732016-07-08 13:22:27 -0700160
Simon Hunt977aa052016-07-20 17:08:29 -0700161 // for unit testing
162 Topo2Jsonifier() {
Simon Hunt95f4b422017-03-03 13:49:05 -0800163 userName = "(unit-test)";
Simon Huntd5b96732016-07-08 13:22:27 -0700164 }
165
166 private ObjectNode objectNode() {
167 return mapper.createObjectNode();
168 }
169
170 private ArrayNode arrayNode() {
171 return mapper.createArrayNode();
172 }
173
174 private String nullIsEmpty(Object o) {
175 return o == null ? "" : o.toString();
176 }
177
178
179 /**
180 * Returns a JSON representation of the cluster members (ONOS instances).
181 *
182 * @param instances the instance model objects
183 * @return a JSON representation of the data
184 */
185 ObjectNode instances(List<UiClusterMember> instances) {
186 NodeId local = clusterService.getLocalNode().id();
187 ObjectNode payload = objectNode();
188
189 ArrayNode members = arrayNode();
190 payload.set("members", members);
191 for (UiClusterMember member : instances) {
192 members.add(json(member, member.id().equals(local)));
193 }
194
195 return payload;
196 }
197
198 private ObjectNode json(UiClusterMember member, boolean isUiAttached) {
Steven Burrowsad75aa22016-12-14 17:17:24 -0500199 int switchCount = mastershipService.getDevicesOf(member.id()).size();
Simon Huntd5b96732016-07-08 13:22:27 -0700200 return objectNode()
201 .put("id", member.id().toString())
202 .put("ip", member.ip().toString())
203 .put("online", member.isOnline())
204 .put("ready", member.isReady())
205 .put("uiAttached", isUiAttached)
Steven Burrowsad75aa22016-12-14 17:17:24 -0500206 .put("switches", switchCount);
Simon Huntd5b96732016-07-08 13:22:27 -0700207 }
208
209 /**
210 * Returns a JSON representation of the layout to use for displaying in
Simon Huntf836a872016-08-10 17:37:36 -0700211 * the topology view. The identifiers and names of regions from the
212 * current to the root is included, so that the bread-crumb widget can
213 * be rendered.
Simon Huntd5b96732016-07-08 13:22:27 -0700214 *
215 * @param layout the layout to transform
Simon Huntf836a872016-08-10 17:37:36 -0700216 * @param crumbs list of layouts in bread-crumb order
Simon Huntd5b96732016-07-08 13:22:27 -0700217 * @return a JSON representation of the data
218 */
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700219 ObjectNode layout(UiTopoLayout layout, List<UiTopoLayout> crumbs) {
Simon Huntf836a872016-08-10 17:37:36 -0700220 ObjectNode result = objectNode()
Simon Huntd5b96732016-07-08 13:22:27 -0700221 .put("id", layout.id().toString())
222 .put("parent", nullIsEmpty(layout.parent()))
223 .put("region", nullIsEmpty(layout.regionId()))
Simon Huntf836a872016-08-10 17:37:36 -0700224 .put("regionName", UiRegion.safeName(layout.region()));
225 addCrumbs(result, crumbs);
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700226 addBgRef(result, layout);
Simon Huntf836a872016-08-10 17:37:36 -0700227 return result;
Simon Huntd5b96732016-07-08 13:22:27 -0700228 }
229
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700230 private void addBgRef(ObjectNode result, UiTopoLayout layout) {
Steven Burrows86b74fc2017-02-22 00:15:16 +0000231 String mapId = layout.geomap();
232 String sprId = layout.sprites();
233
234 if (mapId != null) {
Simon Hunt95f4b422017-03-03 13:49:05 -0800235 result.put("bgType", GEO).put("bgId", mapId);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000236 addMapParameters(result, mapId);
237 } else if (sprId != null) {
Simon Hunt95f4b422017-03-03 13:49:05 -0800238 result.put("bgType", GRID).put("bgId", sprId);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000239 }
Simon Huntf0c6f542017-03-22 18:31:18 -0700240
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700241 attachZoomData(result, layout);
Simon Hunt95f4b422017-03-03 13:49:05 -0800242 }
243
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700244 private void attachZoomData(ObjectNode result, UiTopoLayout layout) {
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000245
Simon Huntf0c6f542017-03-22 18:31:18 -0700246 ObjectNode zoomData = objectNode();
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000247
Simon Huntf0c6f542017-03-22 18:31:18 -0700248 // first, set configured scale and offset
249 addCfgZoomData(zoomData, layout);
Simon Hunt95f4b422017-03-03 13:49:05 -0800250
Simon Huntf0c6f542017-03-22 18:31:18 -0700251 // next, retrieve user-set zoom data, if we have it
Simon Huntf7e7d4a2017-03-24 15:22:20 -0700252 String rid = layout.regionId().toString();
Simon Huntf0c6f542017-03-22 18:31:18 -0700253 ObjectNode userZoom = metaUi.get(contextKey(rid, ZOOM_KEY));
254 if (userZoom != null) {
255 zoomData.set("usr", userZoom);
Simon Hunt95f4b422017-03-03 13:49:05 -0800256 }
Simon Huntf0c6f542017-03-22 18:31:18 -0700257 result.set("bgZoom", zoomData);
258 }
Steven Burrowsb43c1a92017-03-07 17:13:28 +0000259
Simon Huntf0c6f542017-03-22 18:31:18 -0700260 private void addCfgZoomData(ObjectNode data, UiTopoLayout layout) {
261 ObjectNode zoom = objectNode();
262 zoom.put("scale", layout.scale());
263 zoom.put("offsetX", layout.offsetX());
264 zoom.put("offsetY", layout.offsetY());
265 data.set("cfg", zoom);
Steven Burrows86b74fc2017-02-22 00:15:16 +0000266 }
267
268 private void addMapParameters(ObjectNode result, String mapId) {
269
270 // TODO: This ought to be written more efficiently.
271
272 // ALSO: Should retrieving a UiTopoMap by ID be something that
273 // the UiExtensionService provides, along with other
274 // useful lookups?
275 //
276 // Or should it remain very basic / general?
277 //
278 // return uiextService.getTopoMap(String mapId);
279
280 final UiTopoMap[] map = {null};
281
282 uiextService.getExtensions().forEach(ext -> {
283 UiTopoMapFactory factory = ext.topoMapFactory();
284
285 // TODO: use .stream().filter(...) here
286 if (map[0] == null && factory != null) {
287 List<UiTopoMap> topoMaps = factory.geoMaps();
288
289 topoMaps.forEach(m -> {
290 if (map[0] == null && m.id().equals(mapId)) {
291 map[0] = m;
292 }
293 });
294 }
295 });
296
297 UiTopoMap m = map[0];
298 if (m != null) {
299 result.put("bgDesc", m.description())
300 .put("bgFilePath", m.filePath())
301 .put("bgDefaultScale", m.scale());
302 } else {
303 result.put("bgWarn", "no map registered with id: " + mapId);
Simon Huntbc30e682017-02-15 18:39:23 -0800304 }
305 }
306
Simon Huntf836a872016-08-10 17:37:36 -0700307 private void addCrumbs(ObjectNode result, List<UiTopoLayout> crumbs) {
308 ArrayNode trail = arrayNode();
309 crumbs.forEach(c -> {
310 ObjectNode n = objectNode()
311 .put("id", c.regionId().toString())
312 .put("name", UiRegion.safeName(c.region()));
313 trail.add(n);
314 });
315 result.set("crumbs", trail);
Simon Huntd5b96732016-07-08 13:22:27 -0700316 }
317
318 /**
319 * Returns a JSON representation of the region to display in the topology
320 * view.
321 *
Simon Hunt977aa052016-07-20 17:08:29 -0700322 * @param region the region to transform to JSON
323 * @param subRegions the subregions within this region
Simon Huntc13082f2016-08-03 21:20:23 -0700324 * @param links the links within this region
Simon Huntd5b96732016-07-08 13:22:27 -0700325 * @return a JSON representation of the data
326 */
Simon Huntc13082f2016-08-03 21:20:23 -0700327 ObjectNode region(UiRegion region, Set<UiRegion> subRegions,
328 List<UiSynthLink> links) {
Simon Huntd5b96732016-07-08 13:22:27 -0700329 ObjectNode payload = objectNode();
Simon Huntd5b96732016-07-08 13:22:27 -0700330 if (region == null) {
331 payload.put("note", "no-region");
332 return payload;
333 }
Simon Hunt2521d5f2017-03-20 18:17:28 -0700334
335 String ridStr = region.idAsString();
336
337 payload.put("id", ridStr);
338 payload.set("subregions", jsonSubRegions(ridStr, subRegions));
Simon Huntcd508a62016-10-27 12:47:24 -0700339 payload.set("links", jsonLinks(links));
Simon Huntc13082f2016-08-03 21:20:23 -0700340
Simon Hunt977aa052016-07-20 17:08:29 -0700341 List<String> layerTags = region.layerOrder();
342 List<Set<UiNode>> splitDevices = splitByLayer(layerTags, region.devices());
343 List<Set<UiNode>> splitHosts = splitByLayer(layerTags, region.hosts());
Simon Huntd5b96732016-07-08 13:22:27 -0700344
Simon Hunt2521d5f2017-03-20 18:17:28 -0700345 payload.set("devices", jsonGrouped(ridStr, splitDevices));
346 payload.set("hosts", jsonGrouped(ridStr, splitHosts));
Simon Hunt977aa052016-07-20 17:08:29 -0700347 payload.set("layerOrder", jsonStrings(layerTags));
Simon Huntd5b96732016-07-08 13:22:27 -0700348
Simon Hunt8f60ff82017-04-24 17:19:30 -0700349 if (!region.isRoot()) {
350 addPeerLocations(payload, region.backingRegion());
351 }
352
Simon Huntd5b96732016-07-08 13:22:27 -0700353 return payload;
354 }
355
Simon Hunt2521d5f2017-03-20 18:17:28 -0700356 private ArrayNode jsonSubRegions(String ridStr, Set<UiRegion> subregions) {
Simon Hunt977aa052016-07-20 17:08:29 -0700357 ArrayNode kids = arrayNode();
Simon Hunt2521d5f2017-03-20 18:17:28 -0700358 subregions.forEach(s -> kids.add(jsonClosedRegion(ridStr, s)));
Simon Hunt977aa052016-07-20 17:08:29 -0700359 return kids;
360 }
361
Simon Huntc13082f2016-08-03 21:20:23 -0700362 private JsonNode jsonLinks(List<UiSynthLink> links) {
363 ArrayNode synthLinks = arrayNode();
364 links.forEach(l -> synthLinks.add(json(l)));
365 return synthLinks;
366 }
367
Simon Hunt977aa052016-07-20 17:08:29 -0700368 private ArrayNode jsonStrings(List<String> strings) {
369 ArrayNode array = arrayNode();
370 strings.forEach(array::add);
371 return array;
372 }
373
Simon Hunt2521d5f2017-03-20 18:17:28 -0700374 private ArrayNode jsonGrouped(String ridStr, List<Set<UiNode>> groupedNodes) {
Simon Hunt977aa052016-07-20 17:08:29 -0700375 ArrayNode result = arrayNode();
376 groupedNodes.forEach(g -> {
377 ArrayNode subset = arrayNode();
Simon Hunt2521d5f2017-03-20 18:17:28 -0700378 g.forEach(n -> subset.add(json(ridStr, n)));
Simon Hunt977aa052016-07-20 17:08:29 -0700379 result.add(subset);
380 });
381 return result;
382 }
383
Simon Hunt537bc762016-12-20 12:15:13 -0800384 /**
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800385 * Creates a JSON representation of a UI element.
386 *
387 * @param element the source element
388 * @return a JSON representation of that element
389 */
390 public ObjectNode jsonUiElement(UiElement element) {
391 if (element instanceof UiNode) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700392 return json(NO_CONTEXT, (UiNode) element);
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800393 }
394 if (element instanceof UiLink) {
395 return json((UiLink) element);
396 }
397
398 // TODO: UiClusterMember
399
400 // Unrecognized UiElement class
401 return objectNode()
402 .put("warning", "unknown UiElement... cannot encode")
403 .put("javaclass", element.getClass().toString());
404 }
405
406 /**
Simon Hunt537bc762016-12-20 12:15:13 -0800407 * Creates a JSON representation of a UI model event.
408 *
409 * @param modelEvent the source model event
410 * @return a JSON representation of that event
411 */
412 public ObjectNode jsonEvent(UiModelEvent modelEvent) {
Steven Burrows512b6272016-12-19 14:09:45 -0500413 ObjectNode payload = objectNode();
414 payload.put(TYPE, enumToString(modelEvent.type()));
415 payload.put(SUBJECT, modelEvent.subject().idAsString());
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800416 payload.set(DATA, modelEvent.data());
417 payload.put(MEMO, modelEvent.memo());
Steven Burrows512b6272016-12-19 14:09:45 -0500418 return payload;
419 }
420
421 // TODO: Investigate why we can't do this inline
422 private String enumToString(Enum<?> e) {
423 return e.toString();
424 }
425
Steven Burrowsad75aa22016-12-14 17:17:24 -0500426 // Returns the name of the master node for the specified device id.
427 private String master(DeviceId deviceId) {
428 NodeId master = mastershipService.getMasterFor(deviceId);
429 return master != null ? master.toString() : "";
430 }
Simon Hunt977aa052016-07-20 17:08:29 -0700431
Simon Hunt2521d5f2017-03-20 18:17:28 -0700432 private ObjectNode json(String ridStr, UiNode node) {
Simon Hunt977aa052016-07-20 17:08:29 -0700433 if (node instanceof UiRegion) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700434 return jsonClosedRegion(ridStr, (UiRegion) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700435 }
436 if (node instanceof UiDevice) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700437 return json(ridStr, (UiDevice) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700438 }
439 if (node instanceof UiHost) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700440 return json(ridStr, (UiHost) node);
Simon Hunt977aa052016-07-20 17:08:29 -0700441 }
442 throw new IllegalStateException(E_UNKNOWN_UI_NODE + node.getClass());
443 }
444
Simon Hunt2521d5f2017-03-20 18:17:28 -0700445 private ObjectNode json(String ridStr, UiDevice device) {
Simon Huntd5b96732016-07-08 13:22:27 -0700446 ObjectNode node = objectNode()
Simon Hunt977aa052016-07-20 17:08:29 -0700447 .put("id", device.idAsString())
Simon Hunt98189192016-07-29 19:02:27 -0700448 .put("nodeType", DEVICE)
Simon Huntd5b96732016-07-08 13:22:27 -0700449 .put("type", device.type())
Simon Hunt3d712522016-08-11 11:20:44 -0700450 .put("online", deviceService.isAvailable(device.id()))
Steven Burrowsad75aa22016-12-14 17:17:24 -0500451 .put("master", master(device.id()))
Simon Huntd5b96732016-07-08 13:22:27 -0700452 .put("layer", device.layer());
453
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700454 Device d = device.backingDevice();
455
456 addProps(node, d);
Simon Huntbc30e682017-02-15 18:39:23 -0800457 addGeoGridLocation(node, d);
Simon Hunt2521d5f2017-03-20 18:17:28 -0700458 addMetaUi(node, ridStr, device.idAsString());
Simon Huntd5b96732016-07-08 13:22:27 -0700459
460 return node;
461 }
462
Simon Hunt53612212016-12-04 17:19:52 -0800463 private void addProps(ObjectNode node, Annotated a) {
464 Annotations annot = a.annotations();
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700465 ObjectNode props = objectNode();
466 if (annot != null) {
467 annot.keys().forEach(k -> props.put(k, annot.value(k)));
468 }
469 node.set("props", props);
470 }
Simon Huntd5b96732016-07-08 13:22:27 -0700471
Simon Hunt2521d5f2017-03-20 18:17:28 -0700472 private void addMetaUi(ObjectNode node, String ridStr, String metaInstanceId) {
473 String key = contextKey(ridStr, metaInstanceId);
474 ObjectNode meta = metaUi.get(key);
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700475 if (meta != null) {
476 node.set("metaUi", meta);
477 }
478 }
479
Simon Huntbc30e682017-02-15 18:39:23 -0800480 private void addGeoGridLocation(ObjectNode node, Annotated a) {
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700481 List<String> lngLat = getAnnotValues(a, LONGITUDE, LATITUDE);
Simon Huntbc30e682017-02-15 18:39:23 -0800482 List<String> gridYX = getAnnotValues(a, GRID_Y, GRID_X);
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700483
Simon Huntbc30e682017-02-15 18:39:23 -0800484 if (lngLat != null) {
485 attachLocation(node, "geo", "lng", "lat", lngLat);
486 } else if (gridYX != null) {
487 attachLocation(node, "grid", "gridY", "gridX", gridYX);
488 }
489 }
490
491 private void attachLocation(ObjectNode node, String locType,
492 String keyA, String keyB, List<String> values) {
493 try {
494 double valA = Double.parseDouble(values.get(0));
495 double valB = Double.parseDouble(values.get(1));
496 ObjectNode loc = objectNode()
497 .put("type", locType)
498 .put(keyA, valA)
499 .put(keyB, valB);
500 node.set("location", loc);
501
502 } catch (NumberFormatException e) {
503 log.warn("Invalid {} data: long/Y={}, lat/X={}",
504 locType, values.get(0), values.get(1));
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700505 }
506 }
507
Simon Hunt8f60ff82017-04-24 17:19:30 -0700508 private void addPeerLocations(ObjectNode node, Region r) {
509 String compact = r.annotations().value(PEER_LOCATIONS);
510 if (!Strings.isNullOrEmpty(compact)) {
511 List<LayoutLocation> locs = fromCompactListString(compact);
512
513 ObjectNode o = objectNode();
514 for (LayoutLocation ll : locs) {
515 ObjectNode lnode = objectNode()
516 .put("locType", ll.locType().toString())
517 .put("latOrY", ll.latOrY())
518 .put("longOrX", ll.longOrX());
519 o.set(ll.id(), lnode);
520 }
521
522 node.set(PEER_LOCATIONS, o);
523 }
524 }
525
Steven Burrows583f4be2016-11-04 14:06:50 +0100526 private void addIps(ObjectNode node, Host h) {
527 Set<IpAddress> ips = h.ipAddresses();
528
529 ArrayNode a = arrayNode();
530 for (IpAddress ip : ips) {
531 a.add(ip.toString());
532 }
533
534 node.set("ips", a);
535 }
536
Simon Hunt6a8cb4f2016-08-09 15:08:57 -0700537 // return list of string values from annotated instance, for given keys
538 // return null if any keys are not present
539 List<String> getAnnotValues(Annotated a, String... annotKeys) {
540 List<String> result = new ArrayList<>(annotKeys.length);
541 for (String k : annotKeys) {
542 String v = a.annotations().value(k);
543 if (v == null) {
544 return null;
545 }
546 result.add(v);
547 }
548 return result;
549 }
550
551 // derive JSON object from annotations
552 private ObjectNode props(Annotations annotations) {
553 ObjectNode p = objectNode();
554 if (annotations != null) {
555 annotations.keys().forEach(k -> p.put(k, annotations.value(k)));
556 }
557 return p;
Simon Huntd5b96732016-07-08 13:22:27 -0700558 }
559
Simon Hunt2521d5f2017-03-20 18:17:28 -0700560 private ObjectNode json(String ridStr, UiHost host) {
Steven Burrows583f4be2016-11-04 14:06:50 +0100561 ObjectNode node = objectNode()
Simon Hunt977aa052016-07-20 17:08:29 -0700562 .put("id", host.idAsString())
Simon Hunt98189192016-07-29 19:02:27 -0700563 .put("nodeType", HOST)
Simon Huntd5b96732016-07-08 13:22:27 -0700564 .put("layer", host.layer());
565 // TODO: complete host details
Steven Burrows583f4be2016-11-04 14:06:50 +0100566 Host h = host.backingHost();
567
568 addIps(node, h);
Simon Huntbc30e682017-02-15 18:39:23 -0800569 addProps(node, h);
570 addGeoGridLocation(node, h);
Simon Hunt2521d5f2017-03-20 18:17:28 -0700571 addMetaUi(node, ridStr, host.idAsString());
Steven Burrows583f4be2016-11-04 14:06:50 +0100572
573 return node;
Simon Huntd5b96732016-07-08 13:22:27 -0700574 }
575
Simon Huntc13082f2016-08-03 21:20:23 -0700576 private ObjectNode json(UiSynthLink sLink) {
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800577 return json(sLink.link());
578 }
579
580 private ObjectNode json(UiLink link) {
Simon Hunt3d712522016-08-11 11:20:44 -0700581 ObjectNode data = objectNode()
Simon Hunt8eac4ae2017-01-20 12:56:45 -0800582 .put("id", link.idAsString())
583 .put("epA", link.endPointA())
584 .put("epB", link.endPointB())
585 .put("type", link.type());
586 String pA = link.endPortA();
587 String pB = link.endPortB();
Simon Hunt3d712522016-08-11 11:20:44 -0700588 if (pA != null) {
589 data.put("portA", pA);
590 }
591 if (pB != null) {
592 data.put("portB", pB);
593 }
594 return data;
Simon Huntd5b96732016-07-08 13:22:27 -0700595 }
596
597
Simon Hunt2521d5f2017-03-20 18:17:28 -0700598 private ObjectNode jsonClosedRegion(String ridStr, UiRegion region) {
Steven Burrows482d9502016-09-27 11:24:58 -0700599 ObjectNode node = objectNode()
Simon Huntb1ce2602016-07-23 14:04:31 -0700600 .put("id", region.idAsString())
Simon Huntf836a872016-08-10 17:37:36 -0700601 .put("name", region.name())
Simon Hunt98189192016-07-29 19:02:27 -0700602 .put("nodeType", REGION)
Steven Burrows19e6e4f2016-10-05 13:27:07 -0500603 .put("nDevs", region.deviceCount())
604 .put("nHosts", region.hostCount());
Simon Hunt2521d5f2017-03-20 18:17:28 -0700605 // TODO: device and host counts should take into account any nested
606 // subregions. i.e. should be the sum of all devices/hosts in
Simon Hunt8f60ff82017-04-24 17:19:30 -0700607 // all descendant subregions.
Simon Hunt53612212016-12-04 17:19:52 -0800608
609 Region r = region.backingRegion();
Simon Hunt2521d5f2017-03-20 18:17:28 -0700610 // this is location data, as injected via network configuration script
Simon Huntbc30e682017-02-15 18:39:23 -0800611 addGeoGridLocation(node, r);
Simon Hunt53612212016-12-04 17:19:52 -0800612 addProps(node, r);
Steven Burrows482d9502016-09-27 11:24:58 -0700613
Simon Hunt2521d5f2017-03-20 18:17:28 -0700614 // this may contain location data, as dragged by user
615 // (which should take precedence, over configured data)
616 addMetaUi(node, ridStr, region.idAsString());
Steven Burrows482d9502016-09-27 11:24:58 -0700617 return node;
Simon Hunt977aa052016-07-20 17:08:29 -0700618 }
619
Simon Hunt98189192016-07-29 19:02:27 -0700620 /**
621 * Returns a JSON array representation of a set of regions/devices. Note
622 * that the information is sufficient for showing regions as nodes.
Simon Hunt2521d5f2017-03-20 18:17:28 -0700623 * THe region ID string defines the context (which region) the node is
624 * being displayed in.
Simon Hunt98189192016-07-29 19:02:27 -0700625 *
Simon Hunt2521d5f2017-03-20 18:17:28 -0700626 * @param ridStr region-id string
Simon Huntf0c6f542017-03-22 18:31:18 -0700627 * @param nodes the nodes
Simon Hunt98189192016-07-29 19:02:27 -0700628 * @return a JSON representation of the nodes
629 */
Simon Hunt2521d5f2017-03-20 18:17:28 -0700630 public ArrayNode closedNodes(String ridStr, Set<UiNode> nodes) {
Simon Hunt98189192016-07-29 19:02:27 -0700631 ArrayNode array = arrayNode();
Simon Huntc13082f2016-08-03 21:20:23 -0700632 for (UiNode node : nodes) {
Simon Hunt98189192016-07-29 19:02:27 -0700633 if (node instanceof UiRegion) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700634 array.add(jsonClosedRegion(ridStr, (UiRegion) node));
Simon Hunt98189192016-07-29 19:02:27 -0700635 } else if (node instanceof UiDevice) {
Simon Hunt2521d5f2017-03-20 18:17:28 -0700636 array.add(json(ridStr, (UiDevice) node));
Simon Hunt98189192016-07-29 19:02:27 -0700637 } else {
638 log.warn("Unexpected node instance: {}", node.getClass());
639 }
640 }
641 return array;
642 }
Simon Hunt977aa052016-07-20 17:08:29 -0700643
Simon Hunt977aa052016-07-20 17:08:29 -0700644 // package-private for unit testing
645 List<Set<UiNode>> splitByLayer(List<String> layerTags,
646 Set<? extends UiNode> nodes) {
647 final int nLayers = layerTags.size();
648 if (!layerTags.get(nLayers - 1).equals(LAYER_DEFAULT)) {
649 throw new IllegalArgumentException(E_DEF_NOT_LAST);
650 }
651
652 List<Set<UiNode>> splitList = new ArrayList<>(layerTags.size());
653 Map<String, Set<UiNode>> byLayer = new HashMap<>(layerTags.size());
654
655 for (String tag : layerTags) {
656 Set<UiNode> set = new HashSet<>();
657 byLayer.put(tag, set);
658 splitList.add(set);
659 }
660
661 for (UiNode n : nodes) {
662 String which = n.layer();
663 if (!layerTags.contains(which)) {
664 which = LAYER_DEFAULT;
665 }
666 byLayer.get(which).add(n);
667 }
668
669 return splitList;
670 }
Steven Burrowse7cc3082016-09-27 11:24:58 -0700671
Simon Hunt2521d5f2017-03-20 18:17:28 -0700672
673 private String contextKey(String context, String key) {
674 return context + CONTEXT_KEY_DELIM + key;
675 }
676
Steven Burrowse7cc3082016-09-27 11:24:58 -0700677 /**
678 * Stores the memento for an element.
Simon Hunt2521d5f2017-03-20 18:17:28 -0700679 * This method assumes the payload has an id String, memento ObjectNode.
680 * The region-id string is used as a context within which to store the
681 * memento.
Steven Burrowse7cc3082016-09-27 11:24:58 -0700682 *
Simon Hunt2521d5f2017-03-20 18:17:28 -0700683 * @param ridStr region ID string
Steven Burrowse7cc3082016-09-27 11:24:58 -0700684 * @param payload event payload
685 */
Simon Hunt2521d5f2017-03-20 18:17:28 -0700686 void updateMeta(String ridStr, ObjectNode payload) {
Steven Burrowse7cc3082016-09-27 11:24:58 -0700687
688 String id = JsonUtils.string(payload, "id");
Simon Hunt2521d5f2017-03-20 18:17:28 -0700689 String key = contextKey(ridStr, id);
690 metaUi.put(key, JsonUtils.node(payload, "memento"));
Steven Burrowse7cc3082016-09-27 11:24:58 -0700691
Simon Hunt2521d5f2017-03-20 18:17:28 -0700692 log.debug("Storing metadata for {}", key);
Steven Burrowse7cc3082016-09-27 11:24:58 -0700693 }
Simon Huntd5b96732016-07-08 13:22:27 -0700694}