aboutsummaryrefslogtreecommitdiffstats
path: root/webapp/src/app/pages/monitoring/monitoring-config.component.ts
blob: 2a5a84b8d6bd28bb7efdbe93e4c9183bc534fb61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/**
* @license
* Copyright (C) 2017-2019 "IoT.bzh"
* Author Sebastien Douheret <sebastien@iot.bzh>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { Component, OnInit, AfterViewInit, ViewEncapsulation, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import * as d3 from 'd3';
import { Router } from '@angular/router';

import { MonitoringService, AglTopology } from '../../@core-xds/services/monitoring.service';
import { AlertService } from '../../@core-xds/services/alert.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subscription } from 'rxjs/Subscription';

interface WsCheckbox {
  topo: AglTopology;
  value: boolean;
  tooltip: string;
}

@Component({
  selector: 'xds-monitoring',
  styleUrls: ['./monitoring-config.component.scss'],
  templateUrl: './monitoring-config.component.html',
  encapsulation: ViewEncapsulation.None,  // workaround about https://github.com/angular/angular/issues/7845
})
export class MonitoringConfigComponent implements OnInit, AfterViewInit {

  aglTopoInit = new BehaviorSubject(false);
  // FIXME: use Map instead of array and use '| keyvalue' for ngfor loop (but angular > 6.1 requested)
  // daemonCheckboxes: Map<string, WsCheckbox> = new Map<string, WsCheckbox>();
  daemonCheckboxes: WsCheckbox[] = [];
  starting = false;
  stopping = false;

  private graph: any;
  private svg: any;
  private links = [];
  private _aglTopoSub: Subscription;

  constructor(@Inject(DOCUMENT) private document: Document,
    private router: Router,
    private monitoringSvr: MonitoringService,
    private alert: AlertService,
  ) {

  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.getAGLTopo();
    this.aglTopoInit.next(true);
  }

  getAGLTopo() {
    if (this._aglTopoSub !== undefined) {
      this._aglTopoSub.unsubscribe();
    }

    this._aglTopoSub = this.monitoringSvr.getTopo().subscribe(topo => {
      this.graphAGLBindings(topo);
      this.createCheckboxes(topo);
    });
  }

  onStartTrace() {
    this.starting = true;

    const dmArr = [];
    this.daemonCheckboxes.forEach(dm => dm.value && dmArr.push(dm.topo.pid));

    this.monitoringSvr.startTrace({ pids: dmArr }).subscribe(res => {
      // console.log('Trace Started: res', res);

      this.monitoringSvr.startLowCollector(null).subscribe((/*res*/) => {
        // console.log('Low Collector Started: res', res);
        this.alert.info('Monitoring successfully started');
        this.starting = false;

      }, err => {
        this.starting = false;
        this.alert.error(err);
      });

    }, err => {
      this.starting = false;
      this.alert.error(err);
    });
  }

  onStopTrace() {
    this.stopping = true;
    this.monitoringSvr.stopTrace({}).subscribe(res => {
      // console.log('Trace Stopped: res', res);

      this.monitoringSvr.stopLowCollector().subscribe((/*res*/) => {
        // console.log('Low Collector Stopped: res', res);
        this.alert.info('Monitoring successfully started');
        this.stopping = false;

      }, err => {
        this.stopping = false;
        this.alert.error(err);
      });

    }, err => {
      this.stopping = false;
      this.alert.error(err);
    });
  }

  showGraph() {
    this.router.navigate([`/pages/monitoring/graph`]);
  }

  isStartBtnDisable(): boolean {
    return this.starting;
  }

  isStopBtnDisable(): boolean {
    return this.stopping;
  }

  isDaemonDisabled(name: string): boolean {
    let sts = false;
    // FIXME - better to use map
    // with Map
    // if (this.daemonCheckboxes.has(name)) {
    //   sts = this.daemonCheckboxes[name].value;
    // }
    this.daemonCheckboxes.forEach(e => {
      if (e.topo.name === name) {
        sts = true;
      }
    });
    return sts;
  }

  private createCheckboxes(topo: AglTopology[]) {

    // let newDaemonChB: Map<string, WsCheckbox> = new Map<string, WsCheckbox>();
    const newDaemonChB: WsCheckbox[] = [];
    let prevVal = false;
    this.daemonCheckboxes.forEach(e => {
      if (e.topo.name === name) {
        prevVal = e.value;
      }
    });
    topo.forEach(elem => {
      // with Map
      // newDaemonChB.set(elem.name, {
      newDaemonChB.push({
        topo: Object.assign({}, elem),
        value: prevVal,
        tooltip: 'Daemon binding ' + elem.name + ' (pid ' + elem.pid + ')',
      });
    });

    this.daemonCheckboxes = newDaemonChB;
  }


  // Compute the distinct nodes from the links.
  // Based on http://bl.ocks.org/mbostock/1153292
  private graphAGLBindings(topo: AglTopology[]) {

    const ws_link: { [id: string]: string[] } = {};
    let ii = 1;
    topo.forEach(elem => {
      if (elem.name === 'null') {
        elem.name = 'Daemon-' + String(ii++);
      }
      if (elem.ws_clients && elem.ws_clients instanceof Array) {
        elem.ws_clients.forEach((ws: string) => {
          if (ws_link[ws]) {
            ws_link[ws].push(elem.name);
          } else {
            ws_link[ws] = [elem.name];
          }
        });
      }
      if (elem.ws_servers && elem.ws_servers instanceof Array) {
        elem.ws_servers.forEach((ws: string) => {
          if (ws_link[ws]) {
            ws_link[ws].push(elem.name);
          } else {
            ws_link[ws] = [elem.name];
          }
        });
      }
    });

    const nodes = {};
    this.links = [];
    ii = 1;
    topo.forEach(elem => {
      let almostOne = false;
      if (elem.ws_clients && elem.ws_clients.length) {
        elem.ws_clients.forEach(wsCli => {
          ws_link[wsCli].forEach(appName => {
            if (appName !== elem.name) {
              almostOne = true;
              this.links.push({ source: elem.name, target: appName, type: 'ws-client' });
            }
          });
        });
      }
      if (elem.ws_servers && elem.ws_servers.length) {
        elem.ws_servers.forEach(wsSvr => {
          ws_link[wsSvr].forEach(appName => {
            if (appName !== elem.name) {
              almostOne = true;
              this.links.push({ source: elem.name, target: appName, type: 'ws-server' });
            }
          });
        });
      }
      if (!almostOne) {
        const name = '???-' + String(ii++);
        this.links.push({
          source: elem.isServer ? name : elem.name,
          target: elem.isServer ? elem.name : name,
          type: 'not-connected',
        });
      }
    });

    this.links.forEach(function (link) {
      link.source = nodes[link.source] || (nodes[link.source] = {
        name: link.source,
      });
      link.target = nodes[link.target] || (nodes[link.target] = {
        name: link.target,
      });
    });

    const width = this.document.getElementById('graph').clientWidth,
      height = this.document.getElementById('graph').clientHeight;

    // Delete previous graph
    if (this.svg) {
      this.svg.remove();
    }

    // Create new graph
    const force = d3.layout.force()
      .nodes(d3.values(nodes))
      .links(this.links)
      .size([width, height])
      .linkDistance(120)
      .charge(-600)
      .on('tick', tick)
      .start();
    // const force = d3.forceSimulation()

    this.graph = d3.select('#graph');
    this.svg = this.graph.append('svg')
      .attr('width', width)
      .attr('height', height);

    // Define the div for the tooltip
    /*
    const divTooltip = d3.select('#graph').append('div')
      .attr('class', 'tooltip')
      .style('opacity', 0);
    */

    // Per-type markers, as they don't inherit styles.
    this.svg.append('defs').selectAll('marker')
      .data(['ws-server', 'ws-client', 'not-connected'])
      .enter().append('marker')
      .attr('id', function (d) {
        return d;
      })
      .attr('viewBox', '0 -5 10 10')
      .attr('refX', 15)
      .attr('refY', -1.5)
      .attr('markerWidth', 12)
      .attr('markerHeight', 12)
      .attr('orient', 'auto')
      .append('path')
      .attr('d', 'M0,-5L10,0L0,5');

    const path = this.svg.append('g').selectAll('path')
      .data(force.links())
      .enter().append('path')
      .attr('class', function (d) {
        return 'link ' + d.type;
      })
      .attr('marker-end', function (d) {
        return 'url(#' + d.type + ')';
      });

    const circle = this.svg.append('g').selectAll('circle')
      .data(force.nodes())
      .enter().append('circle')
      .attr('r', 12)
      .call(force.drag);

    const text = this.svg.append('g').selectAll('text')
      .data(force.nodes())
      .enter().append('text')
      .attr('x', 20)
      .attr('y', '.31em')
      .text(function (d) {
        return d.name;
      });

    /* TODO - SEB
        circle.on('mouseover', d => {
          divTooltip.transition()
            .duration(200)
            .style('opacity', .9);
            divTooltip.html('This is a Tooltip <br/>' + d.close)
            .style('left', (d3.event.pageX) + 'px')
            .style('top', (d3.event.pageY - 28) + 'px');
        });

        //  Tooltip Object
        const tooltip = d3.select('body')
          .append('div').attr('id', 'tooltip')
          .style('position', 'absolute')
          .style('z-index', '10')
          .style('visibility', 'hidden')
          .text('a simple tooltip');
    */

    // Use elliptical arc path segments to doubly-encode directionally.
    function tick() {
      path.attr('d', linkArc);
      circle.attr('transform', transform);
      text.attr('transform', transform);
    }

    function linkArc(d) {
      const dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy);
      return 'M' + d.source.x + ',' + d.source.y + 'A' + dr + ',' + dr + ' 0 0,1 ' + d.target.x + ',' + d.target.y;
    }

    function transform(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    }
  }
}