blob: 7b66f36e9f89210051cdd612a2407c5f6be68446 [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 Condon71910542019-02-16 18:16:42 +000031import {LogService, WebSocketService} from 'gui2-fw-lib';
Sean Condon0c577f62018-11-18 22:40:05 +000032import {
33 Device,
34 ForceDirectedGraph,
Sean Condon50855cf2018-12-23 15:37:42 +000035 Host,
36 HostLabelToggle,
Sean Condon0c577f62018-11-18 22:40:05 +000037 LabelToggle,
38 LayerType,
Sean Condon50855cf2018-12-23 15:37:42 +000039 Link,
40 LinkHighlight,
Sean Condon71910542019-02-16 18:16:42 +000041 Location, LocMeta,
42 MetaUi,
Sean Condon50855cf2018-12-23 15:37:42 +000043 ModelEventMemo,
44 ModelEventType,
Sean Condon0c577f62018-11-18 22:40:05 +000045 Region,
46 RegionLink,
Sean Condon50855cf2018-12-23 15:37:42 +000047 SubRegion,
48 UiElement
Sean Condon0c577f62018-11-18 22:40:05 +000049} from './models';
Sean Condon50855cf2018-12-23 15:37:42 +000050import {
51 DeviceNodeSvgComponent,
52 HostNodeSvgComponent,
53 LinkSvgComponent
54} from './visuals';
Sean Condon71910542019-02-16 18:16:42 +000055import {
56 BackgroundSvgComponent,
57 LocationType
58} from '../backgroundsvg/backgroundsvg.component';
59
60interface UpdateMeta {
61 id: string;
62 class: string;
63 memento: MetaUi;
64}
Sean Condonaa4366d2018-11-02 14:29:01 +000065
Sean Condonf4f54a12018-10-10 23:25:46 +010066/**
67 * ONOS GUI -- Topology Forces Graph Layer View.
Sean Condon0c577f62018-11-18 22:40:05 +000068 *
69 * The regionData is set by Topology Service on WebSocket topo2CurrentRegion callback
70 * This drives the whole Force graph
Sean Condonf4f54a12018-10-10 23:25:46 +010071 */
72@Component({
73 selector: '[onos-forcesvg]',
74 templateUrl: './forcesvg.component.html',
Sean Condon0c577f62018-11-18 22:40:05 +000075 styleUrls: ['./forcesvg.component.css'],
76 changeDetection: ChangeDetectionStrategy.OnPush,
Sean Condonf4f54a12018-10-10 23:25:46 +010077})
Sean Condon0c577f62018-11-18 22:40:05 +000078export class ForceSvgComponent implements OnInit, OnChanges {
Sean Condon021f0fa2018-12-06 23:31:11 -080079 @Input() deviceLabelToggle: LabelToggle = LabelToggle.NONE;
80 @Input() hostLabelToggle: HostLabelToggle = HostLabelToggle.NONE;
Sean Condonb2c483c2019-01-16 20:28:55 +000081 @Input() showHosts: boolean = false;
82 @Input() highlightPorts: boolean = true;
83 @Input() onosInstMastership: string = '';
84 @Input() visibleLayer: LayerType = LayerType.LAYER_DEFAULT;
85 @Input() selectedLink: RegionLink = null;
Sean Condon0c577f62018-11-18 22:40:05 +000086 @Input() regionData: Region = <Region>{devices: [ [], [], [] ], hosts: [ [], [], [] ], links: []};
Sean Condonb2c483c2019-01-16 20:28:55 +000087 @Output() linkSelected = new EventEmitter<RegionLink>();
88 @Output() selectedNodeEvent = new EventEmitter<UiElement>();
Sean Condon021f0fa2018-12-06 23:31:11 -080089 private graph: ForceDirectedGraph;
Sean Condon0c577f62018-11-18 22:40:05 +000090 private _options: { width, height } = { width: 800, height: 600 };
Sean Condonf4f54a12018-10-10 23:25:46 +010091
Sean Condon021f0fa2018-12-06 23:31:11 -080092 // References to the children of this component - these are created in the
93 // template view with the *ngFor and we get them by a query here
Sean Condon0c577f62018-11-18 22:40:05 +000094 @ViewChildren(DeviceNodeSvgComponent) devices: QueryList<DeviceNodeSvgComponent>;
Sean Condon021f0fa2018-12-06 23:31:11 -080095 @ViewChildren(HostNodeSvgComponent) hosts: QueryList<HostNodeSvgComponent>;
Sean Condon50855cf2018-12-23 15:37:42 +000096 @ViewChildren(LinkSvgComponent) links: QueryList<LinkSvgComponent>;
Sean Condonf4f54a12018-10-10 23:25:46 +010097
Sean Condon0c577f62018-11-18 22:40:05 +000098 constructor(
99 protected log: LogService,
Sean Condon71910542019-02-16 18:16:42 +0000100 private ref: ChangeDetectorRef,
101 protected wss: WebSocketService
Sean Condon0c577f62018-11-18 22:40:05 +0000102 ) {
103 this.selectedLink = null;
104 this.log.debug('ForceSvgComponent constructed');
105 }
106
107 /**
Sean Condon021f0fa2018-12-06 23:31:11 -0800108 * Utility for extracting a node name from an endpoint string
109 * In some cases - have to remove the port number from the end of a device
110 * name
111 * @param endPtStr The end point name
112 */
113 private static extractNodeName(endPtStr: string): string {
114 const slash: number = endPtStr.indexOf('/');
115 if (slash === -1) {
116 return endPtStr;
117 } else {
118 const afterSlash = endPtStr.substr(slash + 1);
119 if (afterSlash === 'None') {
120 return endPtStr;
121 } else {
122 return endPtStr.substr(0, slash);
123 }
124 }
125 }
126
127 @HostListener('window:resize', ['$event'])
128 onResize(event) {
129 this.graph.initSimulation(this.options);
130 this.log.debug('Simulation reinit after resize', event);
131 }
132
133 /**
Sean Condon0c577f62018-11-18 22:40:05 +0000134 * After the component is initialized create the Force simulation
Sean Condon021f0fa2018-12-06 23:31:11 -0800135 * The list of devices, hosts and links will not have been receieved back
136 * from the WebSocket yet as this time - they will be updated later through
137 * ngOnChanges()
Sean Condon0c577f62018-11-18 22:40:05 +0000138 */
139 ngOnInit() {
140 // Receiving an initialized simulated graph from our custom d3 service
Sean Condon50855cf2018-12-23 15:37:42 +0000141 this.graph = new ForceDirectedGraph(this.options, this.log);
Sean Condon0c577f62018-11-18 22:40:05 +0000142
143 /** Binding change detection check on each tick
Sean Condon021f0fa2018-12-06 23:31:11 -0800144 * This along with an onPush change detection strategy should enforce
145 * checking only when relevant! This improves scripting computation
146 * duration in a couple of tests I've made, consistently. Also, it makes
147 * sense to avoid unnecessary checks when we are dealing only with
148 * simulations data binding.
Sean Condon0c577f62018-11-18 22:40:05 +0000149 */
150 this.graph.ticker.subscribe((simulation) => {
151 // this.log.debug("Force simulation has ticked", simulation);
152 this.ref.markForCheck();
153 });
154 this.log.debug('ForceSvgComponent initialized - waiting for nodes and links');
155
Sean Condon0c577f62018-11-18 22:40:05 +0000156 }
157
158 /**
Sean Condon021f0fa2018-12-06 23:31:11 -0800159 * When any one of the inputs get changed by a containing component, this
160 * gets called automatically. In addition this is called manually by
161 * topology.service when a response is received from the WebSocket from the
162 * server
Sean Condon0c577f62018-11-18 22:40:05 +0000163 *
164 * The Devices, Hosts and SubRegions are all added to the Node list for the simulation
165 * The Links are added to the Link list of the simulation.
166 * Before they are added the Links are associated with Nodes based on their endPt
167 *
168 * @param changes - a list of changed @Input(s)
169 */
170 ngOnChanges(changes: SimpleChanges) {
171 if (changes['regionData']) {
172 const devices: Device[] =
173 changes['regionData'].currentValue.devices[this.visibleLayerIdx()];
174 const hosts: Host[] =
175 changes['regionData'].currentValue.hosts[this.visibleLayerIdx()];
176 const subRegions: SubRegion[] = changes['regionData'].currentValue.subRegion;
177 this.graph.nodes = [];
178 if (devices) {
179 this.graph.nodes = devices;
180 }
181 if (hosts) {
182 this.graph.nodes = this.graph.nodes.concat(hosts);
183 }
184 if (subRegions) {
185 this.graph.nodes = this.graph.nodes.concat(subRegions);
186 }
187
Sean Condon71910542019-02-16 18:16:42 +0000188 // If a node has a fixed location then assign it to fx and fy so
189 // that it doesn't get affected by forces
190 this.graph.nodes
191 .forEach((n) => {
192 const loc: Location = <Location>n['location'];
193 if (loc && loc.locType === LocationType.GEO) {
194 const position: MetaUi =
195 BackgroundSvgComponent.convertGeoToCanvas(
196 <LocMeta>{lng: loc.longOrX, lat: loc.latOrY});
197 n.fx = position.x;
198 n.fy = position.y;
199 this.log.debug('Found node', n.id, 'with', loc.locType);
200 }
201 });
202
Sean Condon0c577f62018-11-18 22:40:05 +0000203 // Associate the endpoints of each link with a real node
204 this.graph.links = [];
205 for (const linkIdx of Object.keys(this.regionData.links)) {
Sean Condon021f0fa2018-12-06 23:31:11 -0800206 const epA = ForceSvgComponent.extractNodeName(
207 this.regionData.links[linkIdx].epA);
Sean Condon0c577f62018-11-18 22:40:05 +0000208 this.regionData.links[linkIdx].source =
209 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800210 node.id === epA);
211 const epB = ForceSvgComponent.extractNodeName(
212 this.regionData.links[linkIdx].epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000213 this.regionData.links[linkIdx].target =
214 this.graph.nodes.find((node) =>
Sean Condon021f0fa2018-12-06 23:31:11 -0800215 node.id === epB);
Sean Condon0c577f62018-11-18 22:40:05 +0000216 this.regionData.links[linkIdx].index = Number(linkIdx);
217 }
218
219 this.graph.links = this.regionData.links;
220
221 this.graph.initSimulation(this.options);
222 this.graph.initNodes();
Sean Condon50855cf2018-12-23 15:37:42 +0000223 this.graph.initLinks();
Sean Condon0c577f62018-11-18 22:40:05 +0000224 this.log.debug('ForceSvgComponent input changed',
225 this.graph.nodes.length, 'nodes,', this.graph.links.length, 'links');
226 }
Sean Condon021f0fa2018-12-06 23:31:11 -0800227
Sean Condon021f0fa2018-12-06 23:31:11 -0800228 this.ref.markForCheck();
Sean Condon0c577f62018-11-18 22:40:05 +0000229 }
230
231 /**
232 * Get the index of LayerType so it can drive the visibility of nodes and
233 * hosts on layers
234 */
235 visibleLayerIdx(): number {
236 const layerKeys: string[] = Object.keys(LayerType);
237 for (const idx in layerKeys) {
238 if (LayerType[layerKeys[idx]] === this.visibleLayer) {
239 return Number(idx);
240 }
241 }
242 return -1;
243 }
244
245 selectLink(link: RegionLink): void {
246 this.selectedLink = link;
247 this.linkSelected.emit(link);
248 }
249
250 get options() {
251 return this._options = {
252 width: window.innerWidth,
253 height: window.innerHeight
254 };
255 }
256
Sean Condon021f0fa2018-12-06 23:31:11 -0800257 /**
258 * Iterate through all hosts and devices to deselect the previously selected
259 * node. The emit an event to the parent that lets it know the selection has
260 * changed.
261 * @param selectedNode the newly selected node
262 */
Sean Condon50855cf2018-12-23 15:37:42 +0000263 updateSelected(selectedNode: UiElement): void {
Sean Condon91481822019-01-01 13:56:14 +0000264 this.log.debug('Node or link selected', selectedNode ? selectedNode.id : 'none');
Sean Condon021f0fa2018-12-06 23:31:11 -0800265 this.devices
266 .filter((d) =>
267 selectedNode === undefined || d.device.id !== selectedNode.id)
268 .forEach((d) => d.deselect());
269 this.hosts
270 .filter((h) =>
271 selectedNode === undefined || h.host.id !== selectedNode.id)
272 .forEach((h) => h.deselect());
273
Sean Condon50855cf2018-12-23 15:37:42 +0000274 this.links
275 .filter((l) =>
276 selectedNode === undefined || l.link.id !== selectedNode.id)
277 .forEach((l) => l.deselect());
Sean Condon91481822019-01-01 13:56:14 +0000278 // Push the changes back up to parent (Topology Component)
Sean Condon021f0fa2018-12-06 23:31:11 -0800279 this.selectedNodeEvent.emit(selectedNode);
Sean Condon0c577f62018-11-18 22:40:05 +0000280 }
281
Sean Condon021f0fa2018-12-06 23:31:11 -0800282 /**
283 * We want to filter links to show only those not related to hosts if the
Sean Condon50855cf2018-12-23 15:37:42 +0000284 * 'showHosts' flag has been switched off. If 'showHosts' is true, then
Sean Condon021f0fa2018-12-06 23:31:11 -0800285 * display all links.
286 */
Sean Condon50855cf2018-12-23 15:37:42 +0000287 filteredLinks(): Link[] {
Sean Condon021f0fa2018-12-06 23:31:11 -0800288 return this.regionData.links.filter((h) =>
289 this.showHosts ||
290 ((<Host>h.source).nodeType !== 'host' &&
291 (<Host>h.target).nodeType !== 'host'));
Sean Condon0c577f62018-11-18 22:40:05 +0000292 }
Sean Condon50855cf2018-12-23 15:37:42 +0000293
294 /**
295 * When changes happen in the model, then model events are sent up through the
296 * Web Socket
297 * @param type - the type of the change
298 * @param memo - a qualifier on the type
299 * @param subject - the item that the update is for
300 * @param data - the new definition of the item
301 */
302 handleModelEvent(type: ModelEventType, memo: ModelEventMemo, subject: string, data: UiElement): void {
303 switch (type) {
304 case ModelEventType.DEVICE_ADDED_OR_UPDATED:
305 if (memo === ModelEventMemo.ADDED) {
306 this.regionData.devices[this.visibleLayerIdx()].push(<Device>data);
307 } else if (memo === ModelEventMemo.UPDATED) {
308 const oldDevice: Device =
309 this.regionData.devices[this.visibleLayerIdx()]
310 .find((d) => d.id === subject);
311 this.compareDevice(oldDevice, <Device>data);
312 } else {
313 this.log.warn('Device ', memo, ' - not yet implemented', data);
314 }
315 this.log.warn('Device ', memo, ' - not yet implemented', data);
316 break;
317 case ModelEventType.HOST_ADDED_OR_UPDATED:
318 if (memo === ModelEventMemo.ADDED) {
319 this.regionData.hosts[this.visibleLayerIdx()].push(<Host>data);
320 this.log.warn('Host added - not yet implemented', data);
321 } else if (memo === ModelEventMemo.UPDATED) {
322 const oldHost: Host = this.regionData.hosts[this.visibleLayerIdx()]
323 .find((h) => h.id === subject);
324 this.compareHost(oldHost, <Host>data);
325 this.log.warn('Host updated - not yet implemented', data);
326 } else {
327 this.log.warn('Host change', memo, ' - unexpected');
328 }
329 break;
330 case ModelEventType.DEVICE_REMOVED:
331 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
332 const removeIdx: number =
333 this.regionData.devices[this.visibleLayerIdx()]
334 .findIndex((d) => d.id === subject);
335 const removeCmpt: DeviceNodeSvgComponent =
336 this.devices.find((dc) => dc.device.id === subject);
337 this.log.warn('Device ', subject, 'removed - not yet implemented', removeIdx, removeCmpt.device.id);
338 } else {
339 this.log.warn('Device removed - unexpected memo', memo);
340 }
341 break;
342 case ModelEventType.HOST_REMOVED:
343 if (memo === ModelEventMemo.REMOVED || memo === undefined) {
344 const removeIdx: number =
345 this.regionData.hosts[this.visibleLayerIdx()]
346 .findIndex((h) => h.id === subject);
347 const removeCmpt: HostNodeSvgComponent =
348 this.hosts.find((hc) => hc.host.id === subject);
349 this.log.warn('Host ', subject, 'removed - not yet implemented', removeIdx, removeCmpt.host.id);
350 } else {
351 this.log.warn('Host removed - unexpected memo', memo);
352 }
353 break;
354 case ModelEventType.LINK_ADDED_OR_UPDATED:
355 this.log.warn('link added or updated - not yet implemented', subject);
356 break;
357 default:
358 this.log.error('Unexpected model event', type, 'for', subject);
359 }
360 }
361
362 private compareDevice(oldDevice: Device, updatedDevice: Device) {
363 if (oldDevice.master !== updatedDevice.master) {
364 this.log.debug('Mastership has changed for', updatedDevice.id, 'to', updatedDevice.master);
365 }
366 if (oldDevice.online !== updatedDevice.online) {
367 this.log.debug('Status has changed for', updatedDevice.id, 'to', updatedDevice.online);
368 }
369 }
370
371 private compareHost(oldHost: Host, updatedHost: Host) {
372 if (oldHost.configured !== updatedHost.configured) {
373 this.log.debug('Configured has changed for', updatedHost.id, 'to', updatedHost.configured);
374 }
375 }
376
377 /**
378 * When traffic monitoring is turned on (A key) highlights will be sent back
379 * from the WebSocket through the Traffic Service
380 * @param devices - an array of device highlights
381 * @param hosts - an array of host highlights
382 * @param links - an array of link highlights
383 */
384 handleHighlights(devices: Device[], hosts: Host[], links: LinkHighlight[]): void {
385
386 if (devices.length > 0) {
387 this.log.debug(devices.length, 'Devices highlighted');
388 devices.forEach((dh) => {
389 const deviceComponent: DeviceNodeSvgComponent = this.devices.find((d) => d.device.id === dh.id );
390 if (deviceComponent) {
391 deviceComponent.ngOnChanges(
392 {'deviceHighlight': new SimpleChange(<Device>{}, dh, true)}
393 );
394 this.log.debug('Highlighting device', deviceComponent.device.id);
395 } else {
396 this.log.warn('Device component not found', dh.id);
397 }
398 });
399 }
400 if (hosts.length > 0) {
401 this.log.debug(hosts.length, 'Hosts highlighted');
402 hosts.forEach((hh) => {
403 const hostComponent: HostNodeSvgComponent = this.hosts.find((h) => h.host.id === hh.id );
404 if (hostComponent) {
405 hostComponent.ngOnChanges(
406 {'hostHighlight': new SimpleChange(<Host>{}, hh, true)}
407 );
408 this.log.debug('Highlighting host', hostComponent.host.id);
409 }
410 });
411 }
412 if (links.length > 0) {
413 this.log.debug(links.length, 'Links highlighted');
414 links.forEach((lh) => {
415 const linkComponent: LinkSvgComponent = this.links.find((l) => l.link.id === lh.id );
416 if (linkComponent) { // A link might not be present is hosts viewing is switched off
417 linkComponent.ngOnChanges(
418 {'linkHighlight': new SimpleChange(<LinkHighlight>{}, lh, true)}
419 );
420 // this.log.debug('Highlighting link', linkComponent.link.id, lh.css, lh.label);
421 }
422 });
423 }
424 }
Sean Condon71910542019-02-16 18:16:42 +0000425
426 /**
427 * As nodes are dragged around the graph, their new location should be sent
428 * back to server
429 * @param klass The class of node e.g. 'host' or 'device'
430 * @param id - the ID of the node
431 * @param newLocation - the new Location of the node
432 */
433 nodeMoved(klass: string, id: string, newLocation: MetaUi) {
434 this.wss.sendEvent('updateMeta', <UpdateMeta>{
435 id: id,
436 class: klass,
437 memento: newLocation
438 });
439 this.log.debug(klass, id, 'has been moved to', newLocation);
440 }
Sean Condonf4f54a12018-10-10 23:25:46 +0100441}
Sean Condon0c577f62018-11-18 22:40:05 +0000442