open-nomad/ui/app/components/topo-viz.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

363 lines
11 KiB
JavaScript
Raw Normal View History

2020-09-03 02:37:13 +00:00
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, set } from '@ember/object';
2020-10-30 21:23:59 +00:00
import { inject as service } from '@ember/service';
Upgrade Ember and friends 3.28 (#12215) * chore: upgrade forward compatible packages * chore: v3.20.2...v3.24.0 * chore: silence string prototype extension deprecation * refact: don't test clicking disabled button job-list Recent test-helper upgrades will guard against clicking disabled buttons as this is not something that real users can do. We need to change our tests accordingly. * fix: await async test helper `expectError` We have to await this async test function otherwise the test's rendering context will be torn down before we run assertions against it. * fix: don't try to click disabled two-step-button Recent test-helper updates prohibit clicking disabled buttons. We need to adapt the tests accordingly. * fix: recommendation-accordion Use up-to-date semantics for handling list-accordion closing in recommendation-accordion. * fixes toggling recommendation-accordion toggle. * fix: simple-unless linting error application.hbs There's no reason to use unless here - we can use if instead. * fix: no-quoteless-attributes recommendation accordion * fix: no-quoteless-attributes recommendation-chart * fix: allow `unless` - global-header.hbs This is a valid use of unless in our opinion. * fix: allow unless in job-diff This is not a great use for unless but we don't want to change this behavior atm. * fix: no-attrs-in-components list-pager There is no need to use this.attrs in classic components. When we will convert to glimmer we will use `@`-instead. * fix: simple-unless job/definition We can convert to a simple if here. * fix: allow inline-styles stats-box component To make linter happy. * fix: disable no-action and no-invalid-interactive Will be adressed in follow-up PRs. * chore: update ember-classic-decorator to latest * chore: upgrade ember-can to latest * chore: upgrade ember-composable-helpers to latest * chore: upgrade ember-concurrency * fix: recomputation deprecation `Trigger` schedule `do` on actions queue to work around recomputation deprecation when triggering Trigger on `did-insert`. * chore: upgrade ember-cli-string-helpers * chore: upgrade ember-copy * chore: upgrade ember-data-model-fragments * chore: upgrade ember-deprecation-workflow * chore: upgrade ember-inline-svg * chore: upgrade ember-modifier * chore: upgrade ember-truth-helpers * chore: upgrade ember-moment & ember-cli-moment-shim * chore: upgrade ember-power-select * chore: upgrade ember-responsive * chore: upgrade ember-sinon * chore: upgrade ember-cli-mirage For now we will stay on 2.2 - upgrades > 2.3 break the build. * chore: upgrade 3.24.0 to 3.28.5 * fix: add missing classic decorators on adapters * fix: missing classic decorators to serializers * fix: don't reopen Ember.Object anymore * fix: remove unused useNativeEvents ember-cli-page-objects doesn't provide this method anymore * fix: add missing attributeBindings for test-selectors ember-test-selectors doesn't provides automatic bindings for data-test-* attributes anymore. * fix: classic decorator for application serializer test * fix: remove `removeContext` from tests. It is unneeded and ember-cli-page-objects doesn't provides this method anymore. * fix: remove deprecations `run.*`-invocations * fix: `collapseWhitespace` in optimize test * fix: make sure to load async relationship before access * fix: dependent keys for relationship computeds We need to add `*.isFulfilled` as dependent keys for computeds that access async relationships. * fix: `computed.read`-invocations use `read` instead * chore: prettify templates * fix: use map instead of mapBy ember-cli-page-object Doesn't work with updated ember-cli-page-object anymore. * fix: remove remaining deprecated `run.*`-calls * chore: add more deprecations deprecation-workflow * fix: `implicit-injection`-deprecation All routes that add watchers will need to inject the store-service as the store service is internally used in watchers. * fix: more implicit injection deprecations * chore: silence implicit-injection deprecation We can tackle the deprecation when we find the time. * fix: new linting errors after upgrade * fix: remove merge conflicts prettierignore * chore: upgrade to run node 12.22 when building binaries
2022-03-08 17:28:36 +00:00
import { next } from '@ember/runloop';
import { scaleLinear } from 'd3-scale';
import { extent, deviation, mean } from 'd3-array';
import { line, curveBasis } from 'd3-shape';
2020-10-30 21:23:59 +00:00
import styleStringProperty from '../utils/properties/style-string';
2020-09-03 02:37:13 +00:00
export default class TopoViz extends Component {
2020-10-30 21:23:59 +00:00
@service system;
@tracked element = null;
2020-09-25 23:37:51 +00:00
@tracked topology = { datacenters: [] };
@tracked activeNode = null;
@tracked activeAllocation = null;
@tracked activeEdges = [];
@tracked edgeOffset = { x: 0, y: 0 };
@tracked viewportColumns = 2;
2020-10-30 21:23:59 +00:00
@tracked highlightAllocation = null;
@tracked tooltipProps = {};
@styleStringProperty('tooltipProps') tooltipStyle;
2020-09-25 23:37:51 +00:00
get isSingleColumn() {
2021-12-28 16:08:12 +00:00
if (this.topology.datacenters.length <= 1 || this.viewportColumns === 1)
return true;
2020-09-25 23:37:51 +00:00
// Compute the coefficient of variance to determine if it would be
// better to stack datacenters or place them in columns
2021-12-28 16:08:12 +00:00
const nodeCounts = this.topology.datacenters.map(
(datacenter) => datacenter.nodes.length
);
2020-09-25 23:37:51 +00:00
const variationCoefficient = deviation(nodeCounts) / mean(nodeCounts);
// The point at which the varation is too extreme for a two column layout
const threshold = 0.5;
2020-09-25 23:37:51 +00:00
if (variationCoefficient > threshold) return true;
return false;
}
2020-09-25 23:37:51 +00:00
get datacenterIsSingleColumn() {
// If there are enough nodes, use two columns of nodes within
// a single column layout of datacenters to increase density.
if (this.viewportColumns === 1) return true;
2021-12-28 16:08:12 +00:00
return (
!this.isSingleColumn ||
(this.isSingleColumn && this.args.nodes.length <= 20)
);
}
// Once a cluster is large enough, the exact details of a node are
// typically irrelevant and a waste of space.
get isDense() {
return this.args.nodes.length > 50;
}
dataForNode(node) {
return {
node,
datacenter: node.datacenter,
memory: node.resources.memory,
cpu: node.resources.cpu,
allocations: [],
2020-10-12 05:58:44 +00:00
isSelected: false,
};
}
dataForAllocation(allocation, node) {
const jobId = allocation.belongsTo('job').id();
return {
allocation,
node,
jobId,
groupKey: JSON.stringify([jobId, allocation.taskGroupName]),
memory: allocation.allocatedResources.memory,
cpu: allocation.allocatedResources.cpu,
memoryPercent: allocation.allocatedResources.memory / node.memory,
cpuPercent: allocation.allocatedResources.cpu / node.cpu,
isSelected: false,
};
}
@action
buildTopology() {
const nodes = this.args.nodes;
const allocations = this.args.allocations;
// Nodes may not have a resources property due to having an old Nomad agent version.
const badNodes = [];
// Wrap nodes in a topo viz specific data structure and build an index to speed up allocation assignment
const nodeContainers = [];
const nodeIndex = {};
2021-12-28 14:45:20 +00:00
nodes.forEach((node) => {
if (!node.resources) {
badNodes.push(node);
return;
}
const container = this.dataForNode(node);
nodeContainers.push(container);
nodeIndex[node.id] = container;
});
// Wrap allocations in a topo viz specific data structure, assign allocations to nodes, and build an allocation
// index keyed off of job and task group
const allocationIndex = {};
2021-12-28 14:45:20 +00:00
allocations.forEach((allocation) => {
const nodeId = allocation.belongsTo('node').id();
const nodeContainer = nodeIndex[nodeId];
// Ignore orphaned allocations and allocations on nodes with an old Nomad agent version.
if (!nodeContainer) return;
2021-12-28 16:08:12 +00:00
const allocationContainer = this.dataForAllocation(
allocation,
nodeContainer
);
nodeContainer.allocations.push(allocationContainer);
const key = allocationContainer.groupKey;
if (!allocationIndex[key]) allocationIndex[key] = [];
allocationIndex[key].push(allocationContainer);
});
// Group nodes into datacenters
2021-12-28 16:08:12 +00:00
const datacentersMap = nodeContainers.reduce(
(datacenters, nodeContainer) => {
if (!datacenters[nodeContainer.datacenter])
datacenters[nodeContainer.datacenter] = [];
datacenters[nodeContainer.datacenter].push(nodeContainer);
return datacenters;
},
{}
);
2020-09-03 02:37:13 +00:00
// Turn hash of datacenters into a sorted array
const datacenters = Object.keys(datacentersMap)
2021-12-28 14:45:20 +00:00
.map((key) => ({ name: key, nodes: datacentersMap[key] }))
2020-09-03 02:37:13 +00:00
.sortBy('name');
const topology = {
datacenters,
allocationIndex,
selectedKey: null,
heightScale: scaleLinear()
.range([15, 40])
.domain(extent(nodeContainers.mapBy('memory'))),
};
this.topology = topology;
if (badNodes.length && this.args.onDataError) {
this.args.onDataError([
{
type: 'filtered-nodes',
context: badNodes,
},
]);
}
}
@action
captureElement(element) {
this.element = element;
this.determineViewportColumns();
}
@action
showNodeDetails(node) {
if (this.activeNode) {
set(this.activeNode, 'isSelected', false);
}
this.activeNode = this.activeNode === node ? null : node;
if (this.activeNode) {
set(this.activeNode, 'isSelected', true);
}
if (this.args.onNodeSelect) this.args.onNodeSelect(this.activeNode);
}
2020-10-30 21:23:59 +00:00
@action showTooltip(allocation, element) {
const bbox = element.getBoundingClientRect();
this.highlightAllocation = allocation;
this.tooltipProps = {
left: window.scrollX + bbox.left + bbox.width / 2,
top: window.scrollY + bbox.top,
2020-10-30 21:23:59 +00:00
};
}
@action hideTooltip() {
this.highlightAllocation = null;
}
@action
associateAllocations(allocation) {
if (this.activeAllocation === allocation) {
this.activeAllocation = null;
this.activeEdges = [];
if (this.topology.selectedKey) {
2021-12-28 16:08:12 +00:00
const selectedAllocations =
this.topology.allocationIndex[this.topology.selectedKey];
if (selectedAllocations) {
2021-12-28 14:45:20 +00:00
selectedAllocations.forEach((allocation) => {
set(allocation, 'isSelected', false);
});
}
set(this.topology, 'selectedKey', null);
}
} else {
if (this.activeNode) {
set(this.activeNode, 'isSelected', false);
}
this.activeNode = null;
this.activeAllocation = allocation;
2021-12-28 16:08:12 +00:00
const selectedAllocations =
this.topology.allocationIndex[this.topology.selectedKey];
if (selectedAllocations) {
2021-12-28 14:45:20 +00:00
selectedAllocations.forEach((allocation) => {
set(allocation, 'isSelected', false);
});
}
set(this.topology, 'selectedKey', allocation.groupKey);
2021-12-28 16:08:12 +00:00
const newAllocations =
this.topology.allocationIndex[this.topology.selectedKey];
if (newAllocations) {
2021-12-28 14:45:20 +00:00
newAllocations.forEach((allocation) => {
set(allocation, 'isSelected', true);
});
}
// Only show the lines if the selected allocations are sparse (low count relative to the client count or low count generally).
2021-12-28 16:08:12 +00:00
if (
newAllocations.length < 10 ||
newAllocations.length < this.args.nodes.length * 0.75
) {
this.computedActiveEdges();
} else {
this.activeEdges = [];
}
}
if (this.args.onAllocationSelect)
2021-12-28 16:08:12 +00:00
this.args.onAllocationSelect(
this.activeAllocation && this.activeAllocation.allocation
);
if (this.args.onNodeSelect) this.args.onNodeSelect(this.activeNode);
}
@action
determineViewportColumns() {
this.viewportColumns = this.element.clientWidth < 900 ? 1 : 2;
}
@action
resizeEdges() {
if (this.activeEdges.length > 0) {
this.computedActiveEdges();
}
}
2020-09-11 19:15:41 +00:00
@action
computedActiveEdges() {
// Wait a render cycle
Upgrade Ember and friends 3.28 (#12215) * chore: upgrade forward compatible packages * chore: v3.20.2...v3.24.0 * chore: silence string prototype extension deprecation * refact: don't test clicking disabled button job-list Recent test-helper upgrades will guard against clicking disabled buttons as this is not something that real users can do. We need to change our tests accordingly. * fix: await async test helper `expectError` We have to await this async test function otherwise the test's rendering context will be torn down before we run assertions against it. * fix: don't try to click disabled two-step-button Recent test-helper updates prohibit clicking disabled buttons. We need to adapt the tests accordingly. * fix: recommendation-accordion Use up-to-date semantics for handling list-accordion closing in recommendation-accordion. * fixes toggling recommendation-accordion toggle. * fix: simple-unless linting error application.hbs There's no reason to use unless here - we can use if instead. * fix: no-quoteless-attributes recommendation accordion * fix: no-quoteless-attributes recommendation-chart * fix: allow `unless` - global-header.hbs This is a valid use of unless in our opinion. * fix: allow unless in job-diff This is not a great use for unless but we don't want to change this behavior atm. * fix: no-attrs-in-components list-pager There is no need to use this.attrs in classic components. When we will convert to glimmer we will use `@`-instead. * fix: simple-unless job/definition We can convert to a simple if here. * fix: allow inline-styles stats-box component To make linter happy. * fix: disable no-action and no-invalid-interactive Will be adressed in follow-up PRs. * chore: update ember-classic-decorator to latest * chore: upgrade ember-can to latest * chore: upgrade ember-composable-helpers to latest * chore: upgrade ember-concurrency * fix: recomputation deprecation `Trigger` schedule `do` on actions queue to work around recomputation deprecation when triggering Trigger on `did-insert`. * chore: upgrade ember-cli-string-helpers * chore: upgrade ember-copy * chore: upgrade ember-data-model-fragments * chore: upgrade ember-deprecation-workflow * chore: upgrade ember-inline-svg * chore: upgrade ember-modifier * chore: upgrade ember-truth-helpers * chore: upgrade ember-moment & ember-cli-moment-shim * chore: upgrade ember-power-select * chore: upgrade ember-responsive * chore: upgrade ember-sinon * chore: upgrade ember-cli-mirage For now we will stay on 2.2 - upgrades > 2.3 break the build. * chore: upgrade 3.24.0 to 3.28.5 * fix: add missing classic decorators on adapters * fix: missing classic decorators to serializers * fix: don't reopen Ember.Object anymore * fix: remove unused useNativeEvents ember-cli-page-objects doesn't provide this method anymore * fix: add missing attributeBindings for test-selectors ember-test-selectors doesn't provides automatic bindings for data-test-* attributes anymore. * fix: classic decorator for application serializer test * fix: remove `removeContext` from tests. It is unneeded and ember-cli-page-objects doesn't provides this method anymore. * fix: remove deprecations `run.*`-invocations * fix: `collapseWhitespace` in optimize test * fix: make sure to load async relationship before access * fix: dependent keys for relationship computeds We need to add `*.isFulfilled` as dependent keys for computeds that access async relationships. * fix: `computed.read`-invocations use `read` instead * chore: prettify templates * fix: use map instead of mapBy ember-cli-page-object Doesn't work with updated ember-cli-page-object anymore. * fix: remove remaining deprecated `run.*`-calls * chore: add more deprecations deprecation-workflow * fix: `implicit-injection`-deprecation All routes that add watchers will need to inject the store-service as the store service is internally used in watchers. * fix: more implicit injection deprecations * chore: silence implicit-injection deprecation We can tackle the deprecation when we find the time. * fix: new linting errors after upgrade * fix: remove merge conflicts prettierignore * chore: upgrade to run node 12.22 when building binaries
2022-03-08 17:28:36 +00:00
next(() => {
const path = line().curve(curveBasis);
// 1. Get the active element
const allocation = this.activeAllocation.allocation;
2021-12-28 16:08:12 +00:00
const activeEl = this.element.querySelector(
`[data-allocation-id="${allocation.id}"]`
);
const activePoint = centerOfBBox(activeEl.getBoundingClientRect());
// 2. Collect the mem and cpu pairs for all selected allocs
2021-12-28 16:08:12 +00:00
const selectedMem = Array.from(
this.element.querySelectorAll('.memory .bar.is-selected')
);
2021-12-28 14:45:20 +00:00
const selectedPairs = selectedMem.map((mem) => {
const id = mem.closest('[data-allocation-id]').dataset.allocationId;
const cpu = mem
2020-09-24 01:54:35 +00:00
.closest('.topo-viz-node')
.querySelector(`.cpu .bar[data-allocation-id="${id}"]`);
return [mem, cpu];
});
2021-12-28 14:45:20 +00:00
const selectedPoints = selectedPairs.map((pair) => {
return pair.map((el) => centerOfBBox(el.getBoundingClientRect()));
});
// 3. For each pair, compute the midpoint of the truncated triangle of points [Mem, Cpu, Active]
2021-12-28 14:45:20 +00:00
selectedPoints.forEach((points) => {
const d1 = pointBetween(points[0], activePoint, 100, 0.5);
const d2 = pointBetween(points[1], activePoint, 100, 0.5);
points.push(midpoint(d1, d2));
});
// 4. Generate curves for each active->mem and active->cpu pair going through the bisector
const curves = [];
// Steps are used to restrict the range of curves. The closer control points are placed, the less
// curvature the curve generator will generate.
const stepsMain = [0, 0.8, 1.0];
// The second prong the fork does not need to retrace the entire path from the activePoint
const stepsSecondary = [0.8, 1.0];
2021-12-28 14:45:20 +00:00
selectedPoints.forEach((points) => {
curves.push(
2021-12-28 16:08:12 +00:00
curveFromPoints(
...pointsAlongPath(activePoint, points[2], stepsMain),
points[0]
),
curveFromPoints(
...pointsAlongPath(activePoint, points[2], stepsSecondary),
points[1]
)
);
});
2021-12-28 14:45:20 +00:00
this.activeEdges = curves.map((curve) => path(curve));
this.edgeOffset = { x: window.scrollX, y: window.scrollY };
});
}
2020-09-03 02:37:13 +00:00
}
function centerOfBBox(bbox) {
return {
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2,
};
}
function dist(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
// Return the point between p1 and p2 at len (or pct if len > dist(p1, p2))
function pointBetween(p1, p2, len, pct) {
const d = dist(p1, p2);
const ratio = d < len ? pct : len / d;
return pointBetweenPct(p1, p2, ratio);
}
function pointBetweenPct(p1, p2, pct) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
return { x: p1.x + dx * pct, y: p1.y + dy * pct };
}
function pointsAlongPath(p1, p2, pcts) {
2021-12-28 14:45:20 +00:00
return pcts.map((pct) => pointBetweenPct(p1, p2, pct));
}
function midpoint(p1, p2) {
return pointBetweenPct(p1, p2, 0.5);
}
function curveFromPoints(...points) {
2021-12-28 14:45:20 +00:00
return points.map((p) => [p.x, p.y]);
}