blob: d6a9148000e594cc29b65aa59160d5ca53049260 [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 */
Sean Condonc13d9562019-04-18 13:24:42 +0100122 static extractNodeName(endPtStr: string): string {
Sean Condon021f0fa2018-12-06 23:31:11 -0800123 const slash: number = endPtStr.indexOf('/');
124 if (slash === -1) {
125 return endPtStr;
126 } else {
127 const afterSlash = endPtStr.substr(slash + 1);
Sean Condonc13d9562019-04-18 13:24:42 +0100128 const beforeSlash = endPtStr.substr(0, slash);
Sean Condon021f0fa2018-12-06 23:31:11 -0800129 if (afterSlash === 'None') {
130 return endPtStr;
Sean Condonc13d9562019-04-18 13:24:42 +0100131 } else if (beforeSlash.split(':').length > 2) {
132 return endPtStr; // Host name with mac address
Sean Condon021f0fa2018-12-06 23:31:11 -0800133 } else {
134 return endPtStr.substr(0, slash);
135 }
136 }
137 }
138
Sean Condonee545762019-03-09 10:43:58 +0000139 /**
140 * Recursive method to compare 2 objects attribute by attribute and update
141 * the first where a change is detected
142 * @param existingNode 1st object
143 * @param updatedNode 2nd object
144 */
Sean Condon28884332019-03-21 14:07:00 +0000145 private static updateObject(existingNode: Object, updatedNode: Object): ChangeSummary {
146 const changed = <ChangeSummary>{numChanges: 0, locationChanged: false};
Sean Condonee545762019-03-09 10:43:58 +0000147 for (const key of Object.keys(updatedNode)) {
148 const o = updatedNode[key];
Sean Condon28884332019-03-21 14:07:00 +0000149 if (['id', 'x', 'y', 'fx', 'fy', 'vx', 'vy', 'index'].some(k => k === key)) {
Sean Condonee545762019-03-09 10:43:58 +0000150 continue;
151 } else if (o && typeof o === 'object' && o.constructor === Object) {
Sean Condon28884332019-03-21 14:07:00 +0000152 const subChanged = ForceSvgComponent.updateObject(existingNode[key], updatedNode[key]);
153 changed.numChanges += subChanged.numChanges;
154 changed.locationChanged = subChanged.locationChanged ? true : changed.locationChanged;
155 } else if (existingNode === undefined) {
156 // Copy the whole object
157 existingNode = updatedNode;
158 changed.locationChanged = true;
159 changed.numChanges++;
Sean Condonee545762019-03-09 10:43:58 +0000160 } else if (existingNode[key] !== updatedNode[key]) {
Sean Condon28884332019-03-21 14:07:00 +0000161 if (['locType', 'latOrY', 'longOrX', 'latitude', 'longitude', 'gridX', 'gridY'].some(k => k === key)) {
162 changed.locationChanged = true;
163 }
164 changed.numChanges++;
Sean Condonee545762019-03-09 10:43:58 +0000165 existingNode[key] = updatedNode[key];
166 }
167 }
168 return changed;
169 }
170
Sean Condon021f0fa2018-12-06 23:31:11 -0800171 @HostListener('window:resize', ['$event'])
172 onResize(event) {
Sean Condon28884332019-03-21 14:07:00 +0000173 this.graph.restartSimulation();
174 this.log.debug('Simulation restart after resize', event);
Sean Condon021f0fa2018-12-06 23:31:11 -0800175 }
176
177 /**
Sean Condon0c577f62018-11-18 22:40:05 +0000178 * After the component is initialized create the Force simulation
Sean Condon021f0fa2018-12-06 23:31:11 -0800179 * The list of devices, hosts and links will not have been receieved back
180 * from the WebSocket yet as this time - they will be updated later through
181 * ngOnChanges()
Sean Condon0c577f62018-11-18 22:40:05 +0000182 */
183 ngOnInit() {
184 // Receiving an initialized simulated graph from our custom d3 service
Sean Condon28884332019-03-21 14:07:00 +0000185 this.graph = new ForceDirectedGraph(SVGCANVAS, this.log);
Sean Condon0c577f62018-11-18 22:40:05 +0000186
187 /** Binding change detection check on each tick
Sean Condon021f0fa2018-12-06 23:31:11 -0800188 * This along with an onPush change detection strategy should enforce
189 * checking only when relevant! This improves scripting computation
190 * duration in a couple of tests I've made, consistently. Also, it makes
191 * sense to avoid unnecessary checks when we are dealing only with
192 * simulations data binding.
Sean Condon0c577f62018-11-18 22:40:05 +0000193 */
194 this.graph.ticker.subscribe((simulation) => {
Sean Condon28884332019-03-21 14:07:00 +0000195 // this.log.debug("Force simulation has ticked. Alpha",
196 // Math.round(simulation.alpha() * 1000) / 1000);
Sean Condon0c577f62018-11-18 22:40:05 +0000197 this.ref.markForCheck();
198 });
Sean Condon28884332019-03-21 14:07:00 +0000199
Sean Condon0c577f62018-11-18 22:40:05 +0000200 this.log.debug('ForceSvgComponent initialized - waiting for nodes and links');
201
Sean Condon0c577f62018-11-18 22:40:05 +0000202 }
203
204 /**
Sean Condon021f0fa2018-12-06 23:31:11 -0800205 * When any one of the inputs get changed by a containing component, this
206 * gets called automatically. In addition this is called manually by
207 * topology.service when a response is received from the WebSocket from the
208 * server
Sean Condon0c577f62018-11-18 22:40:05 +0000209 *
210 * The Devices, Hosts and SubRegions are all added to the Node list for the simulation
211 * The Links are added to the Link list of the simulation.
212 * Before they are added the Links are associated with Nodes based on their endPt
213 *
214 * @param changes - a list of changed @Input(s)
215 */
216 ngOnChanges(changes: SimpleChanges) {
217 if (changes['regionData']) {
218 const devices: Device[] =
219 changes['regionData'].currentValue.devices[this.visibleLayerIdx()];
220 const hosts: Host[] =
221 changes['regionData'].currentValue.hosts[this.visibleLayerIdx()];
222 const subRegions: SubRegion[] = changes['regionData'].currentValue.subRegion;
223 this.graph.nodes = [];
224 if (devices) {
225 this.graph.nodes = devices;
226 }
227 if (hosts) {
228 this.graph.nodes = this.graph.nodes.concat(hosts);
229 }
230 if (subRegions) {
231 this.graph.nodes = this.graph.nodes.concat(subRegions);
232 }
233
Sean Condon28884332019-03-21 14:07:00 +0000234 this.graph.nodes.forEach((n) => this.fixPosition(n));
Sean Condon71910542019-02-16 18:16:42 +0000235
Sean Condon0c577f62018-11-18 22:40:05 +0000236 // Associate the endpoints of each link with a real node
237 this.graph.links = [];
238 for (const linkIdx of Object.keys(this.regionData.links)) {
Sean Condon021f0fa2018-12-06 23:31:11 -0800239 const epA = ForceSvgComponent.extractNodeName(
240 this.regionData.links[linkIdx].epA);
Sean Condon0c577f62018-11-18 22:40:05 +0000241 this.regionData.links[linkIdx].source =
242 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800243 node.id === epA);
244 const epB = ForceSvgComponent.extractNodeName(
245 this.regionData.links[linkIdx].epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000246 this.regionData.links[linkIdx].target =
247 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800248 node.id === epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000249 this.regionData.links[linkIdx].index = Number(linkIdx);
250 }
251
252 this.graph.links = this.regionData.links;
Sean Condon28884332019-03-21 14:07:00 +0000253 if (this.graph.nodes.length > 0) {
254 this.graph.reinitSimulation();
255 }
Sean Condon0c577f62018-11-18 22:40:05 +0000256 this.log.debug('ForceSvgComponent input changed',
257 this.graph.nodes.length, 'nodes,', this.graph.links.length, 'links');
258 }
Sean Condon28884332019-03-21 14:07:00 +0000259 }
Sean Condon021f0fa2018-12-06 23:31:11 -0800260
Sean Condon28884332019-03-21 14:07:00 +0000261 /**
Sean Condon058804c2019-04-16 09:41:52 +0100262 * If instance has a value then mute colors of devices not connected to it
263 * Otherwise if instance does not have a value unmute all
264 * @param instanceName name of the selected instance
265 */
266 changeInstSelection(instanceName: string) {
267 this.log.debug('Mastership changed', instanceName);
268 this.devices.filter((d) => d.device.master !== instanceName)
269 .forEach((d) => {
270 const isMuted = Boolean(instanceName);
271 d.ngOnChanges({'colorMuted': new SimpleChange(!isMuted, isMuted, true)});
272 }
273 );
274 }
275
276 /**
Sean Condon28884332019-03-21 14:07:00 +0000277 * If a node has a fixed location then assign it to fx and fy so
278 * that it doesn't get affected by forces
279 * @param graphNode The node whose location should be processed
280 */
281 private fixPosition(graphNode: Node): void {
282 const loc: Location = <Location>graphNode['location'];
283 const props: DeviceProps = <DeviceProps>graphNode['props'];
284 const metaUi = <MetaUi>graphNode['metaUi'];
285 if (loc && loc.locType === LocationType.GEO) {
286 const position: MetaUi =
287 ZoomUtils.convertGeoToCanvas(
288 <LocMeta>{lng: loc.longOrX, lat: loc.latOrY});
289 graphNode.fx = position.x;
290 graphNode.fy = position.y;
291 this.log.debug('Found node', graphNode.id, 'with', loc.locType);
292 } else if (loc && loc.locType === LocationType.GRID) {
293 graphNode.fx = loc.longOrX;
294 graphNode.fy = loc.latOrY;
295 this.log.debug('Found node', graphNode.id, 'with', loc.locType);
296 } else if (props && props.locType === LocationType.NONE && metaUi) {
297 graphNode.fx = metaUi.x;
298 graphNode.fy = metaUi.y;
299 this.log.debug('Found node', graphNode.id, 'with locType=none and metaUi');
300 } else {
301 graphNode.fx = null;
302 graphNode.fy = null;
303 }
Sean Condon0c577f62018-11-18 22:40:05 +0000304 }
305
306 /**
307 * Get the index of LayerType so it can drive the visibility of nodes and
308 * hosts on layers
309 */
310 visibleLayerIdx(): number {
311 const layerKeys: string[] = Object.keys(LayerType);
312 for (const idx in layerKeys) {
313 if (LayerType[layerKeys[idx]] === this.visibleLayer) {
314 return Number(idx);
315 }
316 }
317 return -1;
318 }
319
320 selectLink(link: RegionLink): void {
321 this.selectedLink = link;
322 this.linkSelected.emit(link);
323 }
324
Sean Condon021f0fa2018-12-06 23:31:11 -0800325 /**
Sean Condond88f3662019-04-03 16:35:30 +0100326 * Iterate through all hosts and devices and links to deselect the previously selected
Sean Condon021f0fa2018-12-06 23:31:11 -0800327 * node. The emit an event to the parent that lets it know the selection has
328 * changed.
Sean Condond88f3662019-04-03 16:35:30 +0100329 *
330 * This function collates all of the nodes that have been selected and passes
331 * a collection of nodes up to the topology component
332 *
Sean Condon021f0fa2018-12-06 23:31:11 -0800333 * @param selectedNode the newly selected node
334 */
Sean Condond88f3662019-04-03 16:35:30 +0100335 updateSelected(selectedNode: SelectedEvent): void {
336 this.log.debug('Node or link ',
Sean Condon64ea7d22019-04-12 19:39:13 +0100337 selectedNode.uiElement ? selectedNode.uiElement.id : '--',
Sean Condond88f3662019-04-03 16:35:30 +0100338 selectedNode.deselecting ? 'deselected' : 'selected',
339 selectedNode.isShift ? 'Multiple' : '');
Sean Condon021f0fa2018-12-06 23:31:11 -0800340
Sean Condond88f3662019-04-03 16:35:30 +0100341 if (selectedNode.isShift && selectedNode.deselecting) {
342 const idx = this.selectedNodes.findIndex((n) =>
343 n.id === selectedNode.uiElement.id
344 );
345 this.selectedNodes.splice(idx, 1);
346 this.log.debug('Removed node', idx);
347
348 } else if (selectedNode.isShift) {
349 this.selectedNodes.push(selectedNode.uiElement);
350
351 } else if (selectedNode.deselecting) {
Sean Condon64ea7d22019-04-12 19:39:13 +0100352 this.devices
353 .forEach((d) => d.deselect());
354 this.hosts
355 .forEach((h) => h.deselect());
356 this.links
357 .forEach((l) => l.deselect());
Sean Condond88f3662019-04-03 16:35:30 +0100358 this.selectedNodes = [];
359
360 } else {
361 const selNodeId = selectedNode.uiElement.id;
362 // Otherwise if shift was not pressed deselect previous
363 this.devices
364 .filter((d) => d.device.id !== selNodeId)
365 .forEach((d) => d.deselect());
366 this.hosts
367 .filter((h) => h.host.id !== selNodeId)
368 .forEach((h) => h.deselect());
369
370 this.links
371 .filter((l) => l.link.id !== selNodeId)
372 .forEach((l) => l.deselect());
373
374 this.selectedNodes = [selectedNode.uiElement];
375 }
Sean Condon91481822019-01-01 13:56:14 +0000376 // Push the changes back up to parent (Topology Component)
Sean Condond88f3662019-04-03 16:35:30 +0100377 this.selectedNodeEvent.emit(this.selectedNodes);
Sean Condon0c577f62018-11-18 22:40:05 +0000378 }
379
Sean Condon021f0fa2018-12-06 23:31:11 -0800380 /**
381 * We want to filter links to show only those not related to hosts if the
Sean Condon50855cf2018-12-23 15:37:42 +0000382 * 'showHosts' flag has been switched off. If 'showHosts' is true, then
Sean Condon021f0fa2018-12-06 23:31:11 -0800383 * display all links.
384 */
Sean Condon50855cf2018-12-23 15:37:42 +0000385 filteredLinks(): Link[] {
Sean Condon021f0fa2018-12-06 23:31:11 -0800386 return this.regionData.links.filter((h) =>
387 this.showHosts ||
388 ((<Host>h.source).nodeType !== 'host' &&
389 (<Host>h.target).nodeType !== 'host'));
Sean Condon0c577f62018-11-18 22:40:05 +0000390 }
Sean Condon50855cf2018-12-23 15:37:42 +0000391
392 /**
393 * When changes happen in the model, then model events are sent up through the
394 * Web Socket
395 * @param type - the type of the change
396 * @param memo - a qualifier on the type
397 * @param subject - the item that the update is for
398 * @param data - the new definition of the item
399 */
400 handleModelEvent(type: ModelEventType, memo: ModelEventMemo, subject: string, data: UiElement): void {
401 switch (type) {
402 case ModelEventType.DEVICE_ADDED_OR_UPDATED:
403 if (memo === ModelEventMemo.ADDED) {
Sean Condon28884332019-03-21 14:07:00 +0000404 this.fixPosition(<Device>data);
Sean Condonee545762019-03-09 10:43:58 +0000405 this.graph.nodes.push(<Device>data);
Sean Condonee5d4b92019-03-11 19:57:34 +0000406 this.regionData.devices[this.visibleLayerIdx()].push(<Device>data);
Sean Condonee545762019-03-09 10:43:58 +0000407 this.log.debug('Device added', (<Device>data).id);
Sean Condon50855cf2018-12-23 15:37:42 +0000408 } else if (memo === ModelEventMemo.UPDATED) {
409 const oldDevice: Device =
410 this.regionData.devices[this.visibleLayerIdx()]
411 .find((d) => d.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000412 const changes = ForceSvgComponent.updateObject(oldDevice, <Device>data);
Sean Condon28884332019-03-21 14:07:00 +0000413 if (changes.numChanges > 0) {
Sean Condonee545762019-03-09 10:43:58 +0000414 this.log.debug('Device ', oldDevice.id, memo, ' - ', changes, 'changes');
Sean Condon28884332019-03-21 14:07:00 +0000415 if (changes.locationChanged) {
416 this.fixPosition(oldDevice);
417 }
Sean Condon058804c2019-04-16 09:41:52 +0100418 const svgDevice: DeviceNodeSvgComponent =
419 this.devices.find((svgdevice) => svgdevice.device.id === subject);
420 svgDevice.ngOnChanges({'device':
421 new SimpleChange(<Device>{}, oldDevice, true)
422 });
Sean Condonee545762019-03-09 10:43:58 +0000423 }
Sean Condon50855cf2018-12-23 15:37:42 +0000424 } else {
425 this.log.warn('Device ', memo, ' - not yet implemented', data);
426 }
Sean Condon50855cf2018-12-23 15:37:42 +0000427 break;
428 case ModelEventType.HOST_ADDED_OR_UPDATED:
429 if (memo === ModelEventMemo.ADDED) {
Sean Condon28884332019-03-21 14:07:00 +0000430 this.fixPosition(<Host>data);
Sean Condonee545762019-03-09 10:43:58 +0000431 this.graph.nodes.push(<Host>data);
Sean Condon28884332019-03-21 14:07:00 +0000432 this.regionData.hosts[this.visibleLayerIdx()].push(<Host>data);
Sean Condonee545762019-03-09 10:43:58 +0000433 this.log.debug('Host added', (<Host>data).id);
Sean Condon50855cf2018-12-23 15:37:42 +0000434 } else if (memo === ModelEventMemo.UPDATED) {
435 const oldHost: Host = this.regionData.hosts[this.visibleLayerIdx()]
436 .find((h) => h.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000437 const changes = ForceSvgComponent.updateObject(oldHost, <Host>data);
Sean Condon28884332019-03-21 14:07:00 +0000438 if (changes.numChanges > 0) {
Sean Condonee545762019-03-09 10:43:58 +0000439 this.log.debug('Host ', oldHost.id, memo, ' - ', changes, 'changes');
Sean Condon28884332019-03-21 14:07:00 +0000440 if (changes.locationChanged) {
441 this.fixPosition(oldHost);
442 }
Sean Condonee545762019-03-09 10:43:58 +0000443 }
Sean Condon50855cf2018-12-23 15:37:42 +0000444 } else {
445 this.log.warn('Host change', memo, ' - unexpected');
446 }
447 break;
448 case ModelEventType.DEVICE_REMOVED:
449 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
450 const removeIdx: number =
451 this.regionData.devices[this.visibleLayerIdx()]
452 .findIndex((d) => d.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000453 this.regionData.devices[this.visibleLayerIdx()].splice(removeIdx, 1);
454 this.removeRelatedLinks(subject);
455 this.log.debug('Device ', subject, 'removed. Links', this.regionData.links);
Sean Condon50855cf2018-12-23 15:37:42 +0000456 } else {
457 this.log.warn('Device removed - unexpected memo', memo);
458 }
459 break;
460 case ModelEventType.HOST_REMOVED:
461 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
462 const removeIdx: number =
463 this.regionData.hosts[this.visibleLayerIdx()]
464 .findIndex((h) => h.id === subject);
Sean Condonee545762019-03-09 10:43:58 +0000465 this.regionData.hosts[this.visibleLayerIdx()].splice(removeIdx, 1);
466 this.removeRelatedLinks(subject);
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100467 this.log.debug('Host ', subject, 'removed');
Sean Condon50855cf2018-12-23 15:37:42 +0000468 } else {
469 this.log.warn('Host removed - unexpected memo', memo);
470 }
471 break;
472 case ModelEventType.LINK_ADDED_OR_UPDATED:
Sean Condonee545762019-03-09 10:43:58 +0000473 if (memo === ModelEventMemo.ADDED &&
474 this.regionData.links.findIndex((l) => l.id === subject) === -1) {
475 const listLen = this.regionData.links.push(<RegionLink>data);
476 const epA = ForceSvgComponent.extractNodeName(
477 this.regionData.links[listLen - 1].epA);
478 this.regionData.links[listLen - 1].source =
479 this.graph.nodes.find((node) =>
480 node.id === epA);
481 const epB = ForceSvgComponent.extractNodeName(
482 this.regionData.links[listLen - 1].epB);
483 this.regionData.links[listLen - 1].target =
484 this.graph.nodes.find((node) =>
485 node.id === epB);
486 this.log.debug('Link added', subject);
487 } else if (memo === ModelEventMemo.UPDATED) {
488 const oldLink = this.regionData.links.find((l) => l.id === subject);
489 const changes = ForceSvgComponent.updateObject(oldLink, <RegionLink>data);
490 this.log.debug('Link ', subject, '. Updated', changes, 'items');
491 } else {
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100492 this.log.warn('Link event ignored', subject, data);
493 }
494 break;
495 case ModelEventType.LINK_REMOVED:
496 if (memo === ModelEventMemo.REMOVED) {
497 const removeIdx = this.regionData.links.findIndex((l) => l.id === subject);
498 this.regionData.links.splice(removeIdx, 1);
499 this.log.debug('Link ', subject, 'removed');
Sean Condonee545762019-03-09 10:43:58 +0000500 }
Sean Condon50855cf2018-12-23 15:37:42 +0000501 break;
502 default:
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100503 this.log.error('Unexpected model event', type, 'for', subject, 'Data', data);
Sean Condon50855cf2018-12-23 15:37:42 +0000504 }
Sean Condon28884332019-03-21 14:07:00 +0000505 this.graph.links = this.regionData.links;
506 this.graph.reinitSimulation();
Sean Condon50855cf2018-12-23 15:37:42 +0000507 }
508
Sean Condonee545762019-03-09 10:43:58 +0000509 private removeRelatedLinks(subject: string) {
510 const len = this.regionData.links.length;
511 for (let i = 0; i < len; i++) {
512 const linkIdx = this.regionData.links.findIndex((l) =>
513 (ForceSvgComponent.extractNodeName(l.epA) === subject ||
514 ForceSvgComponent.extractNodeName(l.epB) === subject));
515 if (linkIdx >= 0) {
516 this.regionData.links.splice(linkIdx, 1);
517 this.log.debug('Link ', linkIdx, 'removed on attempt', i);
518 }
Sean Condon50855cf2018-12-23 15:37:42 +0000519 }
520 }
521
522 /**
523 * When traffic monitoring is turned on (A key) highlights will be sent back
524 * from the WebSocket through the Traffic Service
525 * @param devices - an array of device highlights
526 * @param hosts - an array of host highlights
527 * @param links - an array of link highlights
528 */
Sean Condon64ea7d22019-04-12 19:39:13 +0100529 handleHighlights(devices: Device[], hosts: Host[], links: LinkHighlight[], fadeMs: number = 0): void {
Sean Condon50855cf2018-12-23 15:37:42 +0000530
531 if (devices.length > 0) {
532 this.log.debug(devices.length, 'Devices highlighted');
533 devices.forEach((dh) => {
534 const deviceComponent: DeviceNodeSvgComponent = this.devices.find((d) => d.device.id === dh.id );
535 if (deviceComponent) {
536 deviceComponent.ngOnChanges(
537 {'deviceHighlight': new SimpleChange(<Device>{}, dh, true)}
538 );
539 this.log.debug('Highlighting device', deviceComponent.device.id);
540 } else {
541 this.log.warn('Device component not found', dh.id);
542 }
543 });
544 }
545 if (hosts.length > 0) {
546 this.log.debug(hosts.length, 'Hosts highlighted');
547 hosts.forEach((hh) => {
548 const hostComponent: HostNodeSvgComponent = this.hosts.find((h) => h.host.id === hh.id );
549 if (hostComponent) {
550 hostComponent.ngOnChanges(
551 {'hostHighlight': new SimpleChange(<Host>{}, hh, true)}
552 );
553 this.log.debug('Highlighting host', hostComponent.host.id);
554 }
555 });
556 }
557 if (links.length > 0) {
558 this.log.debug(links.length, 'Links highlighted');
559 links.forEach((lh) => {
Sean Condon64ea7d22019-04-12 19:39:13 +0100560 const linkComponent: LinkSvgComponent =
561 this.links.find((l) => l.link.id === Link.linkIdFromShowHighlights(lh.id) );
Sean Condon5f7d3bc2019-04-15 11:18:34 +0100562 if (linkComponent) { // A link might not be present if hosts viewing is switched off
Sean Condon64ea7d22019-04-12 19:39:13 +0100563 if (fadeMs > 0) {
564 lh.fadems = fadeMs;
565 }
Sean Condon50855cf2018-12-23 15:37:42 +0000566 linkComponent.ngOnChanges(
567 {'linkHighlight': new SimpleChange(<LinkHighlight>{}, lh, true)}
568 );
Sean Condon50855cf2018-12-23 15:37:42 +0000569 }
570 });
571 }
572 }
Sean Condon71910542019-02-16 18:16:42 +0000573
574 /**
575 * As nodes are dragged around the graph, their new location should be sent
576 * back to server
577 * @param klass The class of node e.g. 'host' or 'device'
578 * @param id - the ID of the node
579 * @param newLocation - the new Location of the node
580 */
581 nodeMoved(klass: string, id: string, newLocation: MetaUi) {
Sean Condon28884332019-03-21 14:07:00 +0000582 this.wss.sendEvent('updateMeta2', <UpdateMeta>{
Sean Condon71910542019-02-16 18:16:42 +0000583 id: id,
584 class: klass,
585 memento: newLocation
586 });
587 this.log.debug(klass, id, 'has been moved to', newLocation);
588 }
Sean Condon1ae15802019-03-02 09:07:18 +0000589
Sean Condon9de21352019-04-06 19:22:27 +0100590 /**
591 * If any nodes with fixed positions had been dragged out of place
592 * then put back where they belong
593 * If there are some devices selected reset only these
594 */
595 resetNodeLocations(): number {
596 let numbernodes = 0;
597 if (this.selectedNodes.length > 0) {
598 this.devices
599 .filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
600 .forEach((dev) => {
601 Node.resetNodeLocation(<Node>dev.device);
602 numbernodes++;
603 });
604 this.hosts
605 .filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
606 .forEach((h) => {
607 Host.resetNodeLocation(<Host>h.host);
608 numbernodes++;
609 });
610 } else {
611 this.devices.forEach((dev) => {
612 Node.resetNodeLocation(<Node>dev.device);
613 numbernodes++;
614 });
615 this.hosts.forEach((h) => {
616 Host.resetNodeLocation(<Host>h.host);
617 numbernodes++;
618 });
619 }
620 this.graph.reinitSimulation();
621 return numbernodes;
Sean Condon1ae15802019-03-02 09:07:18 +0000622 }
Sean Condon9de21352019-04-06 19:22:27 +0100623
624 /**
625 * Toggle floating nodes between unpinned and frozen
626 * There may be frozen and unpinned in the selection
627 *
628 * If there are nodes selected toggle only these
629 */
630 unpinOrFreezeNodes(freeze: boolean): number {
631 let numbernodes = 0;
632 if (this.selectedNodes.length > 0) {
633 this.devices
634 .filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
635 .forEach((d) => {
636 Node.unpinOrFreezeNode(<Node>d.device, freeze);
637 numbernodes++;
638 });
639 this.hosts
640 .filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
641 .forEach((h) => {
642 Node.unpinOrFreezeNode(<Node>h.host, freeze);
643 numbernodes++;
644 });
645 } else {
646 this.devices.forEach((d) => {
647 Node.unpinOrFreezeNode(<Node>d.device, freeze);
648 numbernodes++;
649 });
650 this.hosts.forEach((h) => {
651 Node.unpinOrFreezeNode(<Node>h.host, freeze);
652 numbernodes++;
653 });
654 }
655 this.graph.reinitSimulation();
656 return numbernodes;
657 }
658
Sean Condonf4f54a12018-10-10 23:25:46 +0100659}
Sean Condon0c577f62018-11-18 22:40:05 +0000660