blob: af0ca2ba58bb70525e1dcdd1cc57998be26b42bc [file] [log] [blame]
Sean Condonf4f54a12018-10-10 23:25:46 +01001/*
Sean Condon91481822019-01-01 13:56:14 +00002 * Copyright 2019-present Open Networking Foundation
Sean Condonf4f54a12018-10-10 23:25:46 +01003 *
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 */
Sean Condon0c577f62018-11-18 22:40:05 +000016import {
17 ChangeDetectionStrategy,
18 ChangeDetectorRef,
19 Component,
20 EventEmitter,
21 HostListener,
22 Input,
23 OnChanges,
24 OnInit,
Sean Condon021f0fa2018-12-06 23:31:11 -080025 Output,
26 QueryList,
Sean Condon50855cf2018-12-23 15:37:42 +000027 SimpleChange,
Sean Condon021f0fa2018-12-06 23:31:11 -080028 SimpleChanges,
29 ViewChildren
Sean Condon0c577f62018-11-18 22:40:05 +000030} from '@angular/core';
Sean Condon058804c2019-04-16 09:41:52 +010031import {LocMeta, LogService, MetaUi, SvgUtilService, WebSocketService, ZoomUtils} from 'gui2-fw-lib';
Sean Condon1ae15802019-03-02 09:07:18 +000032import {
Sean Condon5f7d3bc2019-04-15 11:18:34 +010033 Device,
34 DeviceProps,
Sean Condon0c577f62018-11-18 22:40:05 +000035 ForceDirectedGraph,
Sean Condon50855cf2018-12-23 15:37:42 +000036 Host,
37 HostLabelToggle,
Sean Condon0c577f62018-11-18 22:40:05 +000038 LabelToggle,
39 LayerType,
Sean Condon50855cf2018-12-23 15:37:42 +000040 Link,
41 LinkHighlight,
Sean Condon1ae15802019-03-02 09:07:18 +000042 Location,
Sean Condon50855cf2018-12-23 15:37:42 +000043 ModelEventMemo,
44 ModelEventType,
Sean Condon28884332019-03-21 14:07:00 +000045 Node,
Sean Condond88f3662019-04-03 16:35:30 +010046 Options,
Sean Condon0c577f62018-11-18 22:40:05 +000047 Region,
48 RegionLink,
Sean Condon50855cf2018-12-23 15:37:42 +000049 SubRegion,
50 UiElement
Sean Condon0c577f62018-11-18 22:40:05 +000051} from './models';
Sean Condonee545762019-03-09 10:43:58 +000052import {LocationType} from '../backgroundsvg/backgroundsvg.component';
Sean Condonff85fbe2019-03-16 14:28:46 +000053import {DeviceNodeSvgComponent} from './visuals/devicenodesvg/devicenodesvg.component';
Sean Condon5f7d3bc2019-04-15 11:18:34 +010054import {HostNodeSvgComponent} from './visuals/hostnodesvg/hostnodesvg.component';
55import {LinkSvgComponent} from './visuals/linksvg/linksvg.component';
Sean Condond88f3662019-04-03 16:35:30 +010056import {SelectedEvent} from './visuals/nodevisual';
Sean Condon71910542019-02-16 18:16:42 +000057
58interface UpdateMeta {
59 id: string;
60 class: string;
61 memento: MetaUi;
62}
Sean Condonaa4366d2018-11-02 14:29:01 +000063
Sean Condon28884332019-03-21 14:07:00 +000064const SVGCANVAS = <Options>{
65 width: 1000,
66 height: 1000
67};
68
69interface ChangeSummary {
70 numChanges: number;
71 locationChanged: boolean;
72}
73
Sean Condonf4f54a12018-10-10 23:25:46 +010074/**
75 * ONOS GUI -- Topology Forces Graph Layer View.
Sean Condon0c577f62018-11-18 22:40:05 +000076 *
77 * The regionData is set by Topology Service on WebSocket topo2CurrentRegion callback
78 * This drives the whole Force graph
Sean Condonf4f54a12018-10-10 23:25:46 +010079 */
80@Component({
81 selector: '[onos-forcesvg]',
82 templateUrl: './forcesvg.component.html',
Sean Condon0c577f62018-11-18 22:40:05 +000083 styleUrls: ['./forcesvg.component.css'],
84 changeDetection: ChangeDetectionStrategy.OnPush,
Sean Condonf4f54a12018-10-10 23:25:46 +010085})
Sean Condon0c577f62018-11-18 22:40:05 +000086export class ForceSvgComponent implements OnInit, OnChanges {
Sean Condonff85fbe2019-03-16 14:28:46 +000087 @Input() deviceLabelToggle: LabelToggle.Enum = LabelToggle.Enum.NONE;
88 @Input() hostLabelToggle: HostLabelToggle.Enum = HostLabelToggle.Enum.NONE;
Sean Condonb2c483c2019-01-16 20:28:55 +000089 @Input() showHosts: boolean = false;
90 @Input() highlightPorts: boolean = true;
91 @Input() onosInstMastership: string = '';
92 @Input() visibleLayer: LayerType = LayerType.LAYER_DEFAULT;
93 @Input() selectedLink: RegionLink = null;
Sean Condon1ae15802019-03-02 09:07:18 +000094 @Input() scale: number = 1;
Sean Condon0c577f62018-11-18 22:40:05 +000095 @Input() regionData: Region = <Region>{devices: [ [], [], [] ], hosts: [ [], [], [] ], links: []};
Sean Condonb2c483c2019-01-16 20:28:55 +000096 @Output() linkSelected = new EventEmitter<RegionLink>();
Sean Condond88f3662019-04-03 16:35:30 +010097 @Output() selectedNodeEvent = new EventEmitter<UiElement[]>();
Sean Condonff85fbe2019-03-16 14:28:46 +000098 public graph: ForceDirectedGraph;
Sean Condond88f3662019-04-03 16:35:30 +010099 private selectedNodes: UiElement[] = [];
Sean Condonf4f54a12018-10-10 23:25:46 +0100100
Sean Condon021f0fa2018-12-06 23:31:11 -0800101 // References to the children of this component - these are created in the
102 // template view with the *ngFor and we get them by a query here
Sean Condon0c577f62018-11-18 22:40:05 +0000103 @ViewChildren(DeviceNodeSvgComponent) devices: QueryList<DeviceNodeSvgComponent>;
Sean Condon021f0fa2018-12-06 23:31:11 -0800104 @ViewChildren(HostNodeSvgComponent) hosts: QueryList<HostNodeSvgComponent>;
Sean Condon50855cf2018-12-23 15:37:42 +0000105 @ViewChildren(LinkSvgComponent) links: QueryList<LinkSvgComponent>;
Sean Condonf4f54a12018-10-10 23:25:46 +0100106
Sean Condon0c577f62018-11-18 22:40:05 +0000107 constructor(
108 protected log: LogService,
Sean Condon71910542019-02-16 18:16:42 +0000109 private ref: ChangeDetectorRef,
110 protected wss: WebSocketService
Sean Condon0c577f62018-11-18 22:40:05 +0000111 ) {
112 this.selectedLink = null;
113 this.log.debug('ForceSvgComponent constructed');
114 }
115
116 /**
Sean Condon021f0fa2018-12-06 23:31:11 -0800117 * Utility for extracting a node name from an endpoint string
118 * In some cases - have to remove the port number from the end of a device
119 * name
120 * @param endPtStr The end point name
121 */
122 private static extractNodeName(endPtStr: string): string {
123 const slash: number = endPtStr.indexOf('/');
124 if (slash === -1) {
125 return endPtStr;
126 } else {
127 const afterSlash = endPtStr.substr(slash + 1);
128 if (afterSlash === 'None') {
129 return endPtStr;
130 } else {
131 return endPtStr.substr(0, slash);
132 }
133 }
134 }
135
Sean Condonee545762019-03-09 10:43:58 +0000136 /**
137 * Recursive method to compare 2 objects attribute by attribute and update
138 * the first where a change is detected
139 * @param existingNode 1st object
140 * @param updatedNode 2nd object
141 */
Sean Condon28884332019-03-21 14:07:00 +0000142 private static updateObject(existingNode: Object, updatedNode: Object): ChangeSummary {
143 const changed = <ChangeSummary>{numChanges: 0, locationChanged: false};
Sean Condonee545762019-03-09 10:43:58 +0000144 for (const key of Object.keys(updatedNode)) {
145 const o = updatedNode[key];
Sean Condon28884332019-03-21 14:07:00 +0000146 if (['id', 'x', 'y', 'fx', 'fy', 'vx', 'vy', 'index'].some(k => k === key)) {
Sean Condonee545762019-03-09 10:43:58 +0000147 continue;
148 } else if (o && typeof o === 'object' && o.constructor === Object) {
Sean Condon28884332019-03-21 14:07:00 +0000149 const subChanged = ForceSvgComponent.updateObject(existingNode[key], updatedNode[key]);
150 changed.numChanges += subChanged.numChanges;
151 changed.locationChanged = subChanged.locationChanged ? true : changed.locationChanged;
152 } else if (existingNode === undefined) {
153 // Copy the whole object
154 existingNode = updatedNode;
155 changed.locationChanged = true;
156 changed.numChanges++;
Sean Condonee545762019-03-09 10:43:58 +0000157 } else if (existingNode[key] !== updatedNode[key]) {
Sean Condon28884332019-03-21 14:07:00 +0000158 if (['locType', 'latOrY', 'longOrX', 'latitude', 'longitude', 'gridX', 'gridY'].some(k => k === key)) {
159 changed.locationChanged = true;
160 }
161 changed.numChanges++;
Sean Condonee545762019-03-09 10:43:58 +0000162 existingNode[key] = updatedNode[key];
163 }
164 }
165 return changed;
166 }
167
Sean Condon021f0fa2018-12-06 23:31:11 -0800168 @HostListener('window:resize', ['$event'])
169 onResize(event) {
Sean Condon28884332019-03-21 14:07:00 +0000170 this.graph.restartSimulation();
171 this.log.debug('Simulation restart after resize', event);
Sean Condon021f0fa2018-12-06 23:31:11 -0800172 }
173
174 /**
Sean Condon0c577f62018-11-18 22:40:05 +0000175 * After the component is initialized create the Force simulation
Sean Condon021f0fa2018-12-06 23:31:11 -0800176 * The list of devices, hosts and links will not have been receieved back
177 * from the WebSocket yet as this time - they will be updated later through
178 * ngOnChanges()
Sean Condon0c577f62018-11-18 22:40:05 +0000179 */
180 ngOnInit() {
181 // Receiving an initialized simulated graph from our custom d3 service
Sean Condon28884332019-03-21 14:07:00 +0000182 this.graph = new ForceDirectedGraph(SVGCANVAS, this.log);
Sean Condon0c577f62018-11-18 22:40:05 +0000183
184 /** Binding change detection check on each tick
Sean Condon021f0fa2018-12-06 23:31:11 -0800185 * This along with an onPush change detection strategy should enforce
186 * checking only when relevant! This improves scripting computation
187 * duration in a couple of tests I've made, consistently. Also, it makes
188 * sense to avoid unnecessary checks when we are dealing only with
189 * simulations data binding.
Sean Condon0c577f62018-11-18 22:40:05 +0000190 */
191 this.graph.ticker.subscribe((simulation) => {
Sean Condon28884332019-03-21 14:07:00 +0000192 // this.log.debug("Force simulation has ticked. Alpha",
193 // Math.round(simulation.alpha() * 1000) / 1000);
Sean Condon0c577f62018-11-18 22:40:05 +0000194 this.ref.markForCheck();
195 });
Sean Condon28884332019-03-21 14:07:00 +0000196
Sean Condon0c577f62018-11-18 22:40:05 +0000197 this.log.debug('ForceSvgComponent initialized - waiting for nodes and links');
198
Sean Condon0c577f62018-11-18 22:40:05 +0000199 }
200
201 /**
Sean Condon021f0fa2018-12-06 23:31:11 -0800202 * When any one of the inputs get changed by a containing component, this
203 * gets called automatically. In addition this is called manually by
204 * topology.service when a response is received from the WebSocket from the
205 * server
Sean Condon0c577f62018-11-18 22:40:05 +0000206 *
207 * The Devices, Hosts and SubRegions are all added to the Node list for the simulation
208 * The Links are added to the Link list of the simulation.
209 * Before they are added the Links are associated with Nodes based on their endPt
210 *
211 * @param changes - a list of changed @Input(s)
212 */
213 ngOnChanges(changes: SimpleChanges) {
214 if (changes['regionData']) {
215 const devices: Device[] =
216 changes['regionData'].currentValue.devices[this.visibleLayerIdx()];
217 const hosts: Host[] =
218 changes['regionData'].currentValue.hosts[this.visibleLayerIdx()];
219 const subRegions: SubRegion[] = changes['regionData'].currentValue.subRegion;
220 this.graph.nodes = [];
221 if (devices) {
222 this.graph.nodes = devices;
223 }
224 if (hosts) {
225 this.graph.nodes = this.graph.nodes.concat(hosts);
226 }
227 if (subRegions) {
228 this.graph.nodes = this.graph.nodes.concat(subRegions);
229 }
230
Sean Condon28884332019-03-21 14:07:00 +0000231 this.graph.nodes.forEach((n) => this.fixPosition(n));
Sean Condon71910542019-02-16 18:16:42 +0000232
Sean Condon0c577f62018-11-18 22:40:05 +0000233 // Associate the endpoints of each link with a real node
234 this.graph.links = [];
235 for (const linkIdx of Object.keys(this.regionData.links)) {
Sean Condon021f0fa2018-12-06 23:31:11 -0800236 const epA = ForceSvgComponent.extractNodeName(
237 this.regionData.links[linkIdx].epA);
Sean Condon0c577f62018-11-18 22:40:05 +0000238 this.regionData.links[linkIdx].source =
239 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800240 node.id === epA);
241 const epB = ForceSvgComponent.extractNodeName(
242 this.regionData.links[linkIdx].epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000243 this.regionData.links[linkIdx].target =
244 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800245 node.id === epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000246 this.regionData.links[linkIdx].index = Number(linkIdx);
247 }
248
249 this.graph.links = this.regionData.links;
Sean Condon28884332019-03-21 14:07:00 +0000250 if (this.graph.nodes.length > 0) {
251 this.graph.reinitSimulation();
252 }
Sean Condon0c577f62018-11-18 22:40:05 +0000253 this.log.debug('ForceSvgComponent input changed',
254 this.graph.nodes.length, 'nodes,', this.graph.links.length, 'links');
255 }
Sean Condon28884332019-03-21 14:07:00 +0000256 }
Sean Condon021f0fa2018-12-06 23:31:11 -0800257
Sean Condon28884332019-03-21 14:07:00 +0000258 /**
Sean Condon058804c2019-04-16 09:41:52 +0100259 * If instance has a value then mute colors of devices not connected to it
260 * Otherwise if instance does not have a value unmute all
261 * @param instanceName name of the selected instance
262 */
263 changeInstSelection(instanceName: string) {
264 this.log.debug('Mastership changed', instanceName);
265 this.devices.filter((d) => d.device.master !== instanceName)
266 .forEach((d) => {
267 const isMuted = Boolean(instanceName);
268 d.ngOnChanges({'colorMuted': new SimpleChange(!isMuted, isMuted, true)});
269 }
270 );
271 }
272
273 /**
Sean Condon28884332019-03-21 14:07:00 +0000274 * If a node has a fixed location then assign it to fx and fy so
275 * that it doesn't get affected by forces
276 * @param graphNode The node whose location should be processed
277 */
278 private fixPosition(graphNode: Node): void {
279 const loc: Location = <Location>graphNode['location'];
280 const props: DeviceProps = <DeviceProps>graphNode['props'];
281 const metaUi = <MetaUi>graphNode['metaUi'];
282 if (loc && loc.locType === LocationType.GEO) {
283 const position: MetaUi =
284 ZoomUtils.convertGeoToCanvas(
285 <LocMeta>{lng: loc.longOrX, lat: loc.latOrY});
286 graphNode.fx = position.x;
287 graphNode.fy = position.y;
288 this.log.debug('Found node', graphNode.id, 'with', loc.locType);
289 } else if (loc && loc.locType === LocationType.GRID) {
290 graphNode.fx = loc.longOrX;
291 graphNode.fy = loc.latOrY;
292 this.log.debug('Found node', graphNode.id, 'with', loc.locType);
293 } else if (props && props.locType === LocationType.NONE && metaUi) {
294 graphNode.fx = metaUi.x;
295 graphNode.fy = metaUi.y;
296 this.log.debug('Found node', graphNode.id, 'with locType=none and metaUi');
297 } else {
298 graphNode.fx = null;
299 graphNode.fy = null;
300 }
Sean Condon0c577f62018-11-18 22:40:05 +0000301 }
302
303 /**
304 * Get the index of LayerType so it can drive the visibility of nodes and
305 * hosts on layers
306 */
307 visibleLayerIdx(): number {
308 const layerKeys: string[] = Object.keys(LayerType);
309 for (const idx in layerKeys) {
310 if (LayerType[layerKeys[idx]] === this.visibleLayer) {
311 return Number(idx);
312 }
313 }
314 return -1;
315 }
316
317 selectLink(link: RegionLink): void {
318 this.selectedLink = link;
319 this.linkSelected.emit(link);
320 }
321
Sean Condon021f0fa2018-12-06 23:31:11 -0800322 /**
Sean Condond88f3662019-04-03 16:35:30 +0100323 * Iterate through all hosts and devices and links to deselect the previously selected
Sean Condon021f0fa2018-12-06 23:31:11 -0800324 * node. The emit an event to the parent that lets it know the selection has
325 * changed.
Sean Condond88f3662019-04-03 16:35:30 +0100326 *
327 * This function collates all of the nodes that have been selected and passes
328 * a collection of nodes up to the topology component
329 *
Sean Condon021f0fa2018-12-06 23:31:11 -0800330 * @param selectedNode the newly selected node
331 */
Sean Condond88f3662019-04-03 16:35:30 +0100332 updateSelected(selectedNode: SelectedEvent): void {
333 this.log.debug('Node or link ',
Sean Condon64ea7d22019-04-12 19:39:13 +0100334 selectedNode.uiElement ? selectedNode.uiElement.id : '--',
Sean Condond88f3662019-04-03 16:35:30 +0100335 selectedNode.deselecting ? 'deselected' : 'selected',
336 selectedNode.isShift ? 'Multiple' : '');
Sean Condon021f0fa2018-12-06 23:31:11 -0800337
Sean Condond88f3662019-04-03 16:35:30 +0100338 if (selectedNode.isShift && selectedNode.deselecting) {
339 const idx = this.selectedNodes.findIndex((n) =>
340 n.id === selectedNode.uiElement.id
341 );
342 this.selectedNodes.splice(idx, 1);
343 this.log.debug('Removed node', idx);
344
345 } else if (selectedNode.isShift) {
346 this.selectedNodes.push(selectedNode.uiElement);
347
348 } else if (selectedNode.deselecting) {
Sean Condon64ea7d22019-04-12 19:39:13 +0100349 this.devices
350 .forEach((d) => d.deselect());
351 this.hosts
352 .forEach((h) => h.deselect());
353 this.links
354 .forEach((l) => l.deselect());
Sean Condond88f3662019-04-03 16:35:30 +0100355 this.selectedNodes = [];
356
357 } else {
358 const selNodeId = selectedNode.uiElement.id;
359 // Otherwise if shift was not pressed deselect previous
360 this.devices
361 .filter((d) => d.device.id !== selNodeId)
362 .forEach((d) => d.deselect());
363 this.hosts
364 .filter((h) => h.host.id !== selNodeId)
365 .forEach((h) => h.deselect());
366
367 this.links
368 .filter((l) => l.link.id !== selNodeId)
369 .forEach((l) => l.deselect());
370
371 this.selectedNodes = [selectedNode.uiElement];
372 }
Sean Condon91481822019-01-01 13:56:14 +0000373 // Push the changes back up to parent (Topology Component)
Sean Condond88f3662019-04-03 16:35:30 +0100374 this.selectedNodeEvent.emit(this.selectedNodes);
Sean Condon0c577f62018-11-18 22:40:05 +0000375 }
376
Sean Condon021f0fa2018-12-06 23:31:11 -0800377 /**
378 * We want to filter links to show only those not related to hosts if the
Sean Condon50855cf2018-12-23 15:37:42 +0000379 * 'showHosts' flag has been switched off. If 'showHosts' is true, then
Sean Condon021f0fa2018-12-06 23:31:11 -0800380 * display all links.
381 */
Sean Condon50855cf2018-12-23 15:37:42 +0000382 filteredLinks(): Link[] {
Sean Condon021f0fa2018-12-06 23:31:11 -0800383 return this.regionData.links.filter((h) =>
384 this.showHosts ||
385 ((<Host>h.source).nodeType !== 'host' &&
386 (<Host>h.target).nodeType !== 'host'));
Sean Condon0c577f62018-11-18 22:40:05 +0000387 }
Sean Condon50855cf2018-12-23 15:37:42 +0000388
389 /**
390 * When changes happen in the model, then model events are sent up through the
391 * Web Socket
392 * @param type - the type of the change
393 * @param memo - a qualifier on the type
394 * @param subject - the item that the update is for
395 * @param data - the new definition of the item
396 */
397 handleModelEvent(type: ModelEventType, memo: ModelEventMemo, subject: string, data: UiElement): void {
398 switch (type) {
399 case ModelEventType.DEVICE_ADDED_OR_UPDATED:
400 if (memo === ModelEventMemo.ADDED) {
Sean Condon28884332019-03-21 14:07:00 +0000401 this.fixPosition(<Device>data);
Sean Condonee545762019-03-09 10:43:58 +0000402 this.graph.nodes.push(<Device>data);
Sean Condonee5d4b92019-03-11 19:57:34 +0000403 this.regionData.devices[this.visibleLayerIdx()].push(<Device>data);
Sean Condonee545762019-03-09 10:43:58 +0000404 this.log.debug('Device added', (<Device>data).id);
Sean Condon50855cf2018-12-23 15:37:42 +0000405 } else if (memo === ModelEventMemo.UPDATED) {
406 const oldDevice: Device =
407 this.regionData.devices[this.visibleLayerIdx()]
408 .find((d) => d.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000409 const changes = ForceSvgComponent.updateObject(oldDevice, <Device>data);
Sean Condon28884332019-03-21 14:07:00 +0000410 if (changes.numChanges > 0) {
Sean Condonee545762019-03-09 10:43:58 +0000411 this.log.debug('Device ', oldDevice.id, memo, ' - ', changes, 'changes');
Sean Condon28884332019-03-21 14:07:00 +0000412 if (changes.locationChanged) {
413 this.fixPosition(oldDevice);
414 }
Sean Condon058804c2019-04-16 09:41:52 +0100415 const svgDevice: DeviceNodeSvgComponent =
416 this.devices.find((svgdevice) => svgdevice.device.id === subject);
417 svgDevice.ngOnChanges({'device':
418 new SimpleChange(<Device>{}, oldDevice, true)
419 });
Sean Condonee545762019-03-09 10:43:58 +0000420 }
Sean Condon50855cf2018-12-23 15:37:42 +0000421 } else {
422 this.log.warn('Device ', memo, ' - not yet implemented', data);
423 }
Sean Condon50855cf2018-12-23 15:37:42 +0000424 break;
425 case ModelEventType.HOST_ADDED_OR_UPDATED:
426 if (memo === ModelEventMemo.ADDED) {
Sean Condon28884332019-03-21 14:07:00 +0000427 this.fixPosition(<Host>data);
Sean Condonee545762019-03-09 10:43:58 +0000428 this.graph.nodes.push(<Host>data);
Sean Condon28884332019-03-21 14:07:00 +0000429 this.regionData.hosts[this.visibleLayerIdx()].push(<Host>data);
Sean Condonee545762019-03-09 10:43:58 +0000430 this.log.debug('Host added', (<Host>data).id);
Sean Condon50855cf2018-12-23 15:37:42 +0000431 } else if (memo === ModelEventMemo.UPDATED) {
432 const oldHost: Host = this.regionData.hosts[this.visibleLayerIdx()]
433 .find((h) => h.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000434 const changes = ForceSvgComponent.updateObject(oldHost, <Host>data);
Sean Condon28884332019-03-21 14:07:00 +0000435 if (changes.numChanges > 0) {
Sean Condonee545762019-03-09 10:43:58 +0000436 this.log.debug('Host ', oldHost.id, memo, ' - ', changes, 'changes');
Sean Condon28884332019-03-21 14:07:00 +0000437 if (changes.locationChanged) {
438 this.fixPosition(oldHost);
439 }
Sean Condonee545762019-03-09 10:43:58 +0000440 }
Sean Condon50855cf2018-12-23 15:37:42 +0000441 } else {
442 this.log.warn('Host change', memo, ' - unexpected');
443 }
444 break;
445 case ModelEventType.DEVICE_REMOVED:
446 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
447 const removeIdx: number =
448 this.regionData.devices[this.visibleLayerIdx()]
449 .findIndex((d) => d.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000450 this.regionData.devices[this.visibleLayerIdx()].splice(removeIdx, 1);
451 this.removeRelatedLinks(subject);
452 this.log.debug('Device ', subject, 'removed. Links', this.regionData.links);
Sean Condon50855cf2018-12-23 15:37:42 +0000453 } else {
454 this.log.warn('Device removed - unexpected memo', memo);
455 }
456 break;
457 case ModelEventType.HOST_REMOVED:
458 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
459 const removeIdx: number =
460 this.regionData.hosts[this.visibleLayerIdx()]
461 .findIndex((h) => h.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000462 this.regionData.hosts[this.visibleLayerIdx()].splice(removeIdx, 1);
463 this.removeRelatedLinks(subject);
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100464 this.log.debug('Host ', subject, 'removed');
Sean Condon50855cf2018-12-23 15:37:42 +0000465 } else {
466 this.log.warn('Host removed - unexpected memo', memo);
467 }
468 break;
469 case ModelEventType.LINK_ADDED_OR_UPDATED:
Sean Condonee545762019-03-09 10:43:58 +0000470 if (memo === ModelEventMemo.ADDED &&
471 this.regionData.links.findIndex((l) => l.id === subject) === -1) {
472 const listLen = this.regionData.links.push(<RegionLink>data);
473 const epA = ForceSvgComponent.extractNodeName(
474 this.regionData.links[listLen - 1].epA);
475 this.regionData.links[listLen - 1].source =
476 this.graph.nodes.find((node) =>
477 node.id === epA);
478 const epB = ForceSvgComponent.extractNodeName(
479 this.regionData.links[listLen - 1].epB);
480 this.regionData.links[listLen - 1].target =
481 this.graph.nodes.find((node) =>
482 node.id === epB);
483 this.log.debug('Link added', subject);
484 } else if (memo === ModelEventMemo.UPDATED) {
485 const oldLink = this.regionData.links.find((l) => l.id === subject);
486 const changes = ForceSvgComponent.updateObject(oldLink, <RegionLink>data);
487 this.log.debug('Link ', subject, '. Updated', changes, 'items');
488 } else {
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100489 this.log.warn('Link event ignored', subject, data);
490 }
491 break;
492 case ModelEventType.LINK_REMOVED:
493 if (memo === ModelEventMemo.REMOVED) {
494 const removeIdx = this.regionData.links.findIndex((l) => l.id === subject);
495 this.regionData.links.splice(removeIdx, 1);
496 this.log.debug('Link ', subject, 'removed');
Sean Condonee545762019-03-09 10:43:58 +0000497 }
Sean Condon50855cf2018-12-23 15:37:42 +0000498 break;
499 default:
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100500 this.log.error('Unexpected model event', type, 'for', subject, 'Data', data);
Sean Condon50855cf2018-12-23 15:37:42 +0000501 }
Sean Condon28884332019-03-21 14:07:00 +0000502 this.graph.links = this.regionData.links;
503 this.graph.reinitSimulation();
Sean Condon50855cf2018-12-23 15:37:42 +0000504 }
505
Sean Condonee545762019-03-09 10:43:58 +0000506 private removeRelatedLinks(subject: string) {
507 const len = this.regionData.links.length;
508 for (let i = 0; i < len; i++) {
509 const linkIdx = this.regionData.links.findIndex((l) =>
510 (ForceSvgComponent.extractNodeName(l.epA) === subject ||
511 ForceSvgComponent.extractNodeName(l.epB) === subject));
512 if (linkIdx >= 0) {
513 this.regionData.links.splice(linkIdx, 1);
514 this.log.debug('Link ', linkIdx, 'removed on attempt', i);
515 }
Sean Condon50855cf2018-12-23 15:37:42 +0000516 }
517 }
518
519 /**
520 * When traffic monitoring is turned on (A key) highlights will be sent back
521 * from the WebSocket through the Traffic Service
522 * @param devices - an array of device highlights
523 * @param hosts - an array of host highlights
524 * @param links - an array of link highlights
525 */
Sean Condon64ea7d22019-04-12 19:39:13 +0100526 handleHighlights(devices: Device[], hosts: Host[], links: LinkHighlight[], fadeMs: number = 0): void {
Sean Condon50855cf2018-12-23 15:37:42 +0000527
528 if (devices.length > 0) {
529 this.log.debug(devices.length, 'Devices highlighted');
530 devices.forEach((dh) => {
531 const deviceComponent: DeviceNodeSvgComponent = this.devices.find((d) => d.device.id === dh.id );
532 if (deviceComponent) {
533 deviceComponent.ngOnChanges(
534 {'deviceHighlight': new SimpleChange(<Device>{}, dh, true)}
535 );
536 this.log.debug('Highlighting device', deviceComponent.device.id);
537 } else {
538 this.log.warn('Device component not found', dh.id);
539 }
540 });
541 }
542 if (hosts.length > 0) {
543 this.log.debug(hosts.length, 'Hosts highlighted');
544 hosts.forEach((hh) => {
545 const hostComponent: HostNodeSvgComponent = this.hosts.find((h) => h.host.id === hh.id );
546 if (hostComponent) {
547 hostComponent.ngOnChanges(
548 {'hostHighlight': new SimpleChange(<Host>{}, hh, true)}
549 );
550 this.log.debug('Highlighting host', hostComponent.host.id);
551 }
552 });
553 }
554 if (links.length > 0) {
555 this.log.debug(links.length, 'Links highlighted');
556 links.forEach((lh) => {
Sean Condon64ea7d22019-04-12 19:39:13 +0100557 const linkComponent: LinkSvgComponent =
558 this.links.find((l) => l.link.id === Link.linkIdFromShowHighlights(lh.id) );
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100559 if (linkComponent) { // A link might not be present if hosts viewing is switched off
Sean Condon64ea7d22019-04-12 19:39:13 +0100560 if (fadeMs > 0) {
561 lh.fadems = fadeMs;
562 }
Sean Condon50855cf2018-12-23 15:37:42 +0000563 linkComponent.ngOnChanges(
564 {'linkHighlight': new SimpleChange(<LinkHighlight>{}, lh, true)}
565 );
Sean Condon50855cf2018-12-23 15:37:42 +0000566 }
567 });
568 }
569 }
Sean Condon71910542019-02-16 18:16:42 +0000570
571 /**
572 * As nodes are dragged around the graph, their new location should be sent
573 * back to server
574 * @param klass The class of node e.g. 'host' or 'device'
575 * @param id - the ID of the node
576 * @param newLocation - the new Location of the node
577 */
578 nodeMoved(klass: string, id: string, newLocation: MetaUi) {
Sean Condon28884332019-03-21 14:07:00 +0000579 this.wss.sendEvent('updateMeta2', <UpdateMeta>{
Sean Condon71910542019-02-16 18:16:42 +0000580 id: id,
581 class: klass,
582 memento: newLocation
583 });
584 this.log.debug(klass, id, 'has been moved to', newLocation);
585 }
Sean Condon1ae15802019-03-02 09:07:18 +0000586
Sean Condon9de21352019-04-06 19:22:27 +0100587 /**
588 * If any nodes with fixed positions had been dragged out of place
589 * then put back where they belong
590 * If there are some devices selected reset only these
591 */
592 resetNodeLocations(): number {
593 let numbernodes = 0;
594 if (this.selectedNodes.length > 0) {
595 this.devices
596 .filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
597 .forEach((dev) => {
598 Node.resetNodeLocation(<Node>dev.device);
599 numbernodes++;
600 });
601 this.hosts
602 .filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
603 .forEach((h) => {
604 Host.resetNodeLocation(<Host>h.host);
605 numbernodes++;
606 });
607 } else {
608 this.devices.forEach((dev) => {
609 Node.resetNodeLocation(<Node>dev.device);
610 numbernodes++;
611 });
612 this.hosts.forEach((h) => {
613 Host.resetNodeLocation(<Host>h.host);
614 numbernodes++;
615 });
616 }
617 this.graph.reinitSimulation();
618 return numbernodes;
Sean Condon1ae15802019-03-02 09:07:18 +0000619 }
Sean Condon9de21352019-04-06 19:22:27 +0100620
621 /**
622 * Toggle floating nodes between unpinned and frozen
623 * There may be frozen and unpinned in the selection
624 *
625 * If there are nodes selected toggle only these
626 */
627 unpinOrFreezeNodes(freeze: boolean): number {
628 let numbernodes = 0;
629 if (this.selectedNodes.length > 0) {
630 this.devices
631 .filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
632 .forEach((d) => {
633 Node.unpinOrFreezeNode(<Node>d.device, freeze);
634 numbernodes++;
635 });
636 this.hosts
637 .filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
638 .forEach((h) => {
639 Node.unpinOrFreezeNode(<Node>h.host, freeze);
640 numbernodes++;
641 });
642 } else {
643 this.devices.forEach((d) => {
644 Node.unpinOrFreezeNode(<Node>d.device, freeze);
645 numbernodes++;
646 });
647 this.hosts.forEach((h) => {
648 Node.unpinOrFreezeNode(<Node>h.host, freeze);
649 numbernodes++;
650 });
651 }
652 this.graph.reinitSimulation();
653 return numbernodes;
654 }
655
Sean Condonf4f54a12018-10-10 23:25:46 +0100656}
Sean Condon0c577f62018-11-18 22:40:05 +0000657