Kubernetes plugin: UI revamp (#3918)

* initial revamp, no error reporting

* initial error detection

* more error detection

* add microsite page

* minor fixes

* add HPA error detection

* refactor error reporting; add tests

* fix import

* add changeseet

* empty error state

* prettier yaml file

* Update plugins/kubernetes/src/components/KubernetesDrawer/KubernetesDrawer.tsx

Co-authored-by: Patrik Oldsberg <poldsberg@gmail.com>

* Update plugins/kubernetes/src/components/KubernetesDrawer/KubernetesDrawer.tsx

Co-authored-by: Patrik Oldsberg <poldsberg@gmail.com>

* PR feedback

* revert odd change

* make patch change

* fix test

* Apply suggestions from code review

Co-authored-by: Fredrik Adelöw <freben@gmail.com>

* prettier

* pr feedback

Co-authored-by: Patrik Oldsberg <poldsberg@gmail.com>
Co-authored-by: Fredrik Adelöw <freben@gmail.com>
This commit is contained in:
Matthew Clarke
2021-01-11 16:50:30 +00:00
committed by GitHub
parent ab11e705c9
commit 5a9a7e7c26
57 changed files with 3589 additions and 1054 deletions
@@ -18,6 +18,17 @@ spec:
containers:
- name: nginx
image: nginx:1.14.2
args:
- bash
- -c
- yes > /dev/null & yes > /dev/null & yes > /dev/null
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '50m'
ports:
- containerPort: 80
@@ -44,14 +55,134 @@ spec:
image: nginx:1.14.2
ports:
- containerPort: 80
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '500m'
- name: side-car
image: nginx:1.14.2
ports:
- containerPort: 81
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '500m'
- name: other-side-car
image: nginx:1.14.2
ports:
- containerPort: 82
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '500m'
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: dice-roller-bad-config
labels:
'backstage.io/kubernetes-id': dice-roller
spec:
selector:
matchLabels:
app: dice-roller-bad-config
replicas: 2
template:
metadata:
labels:
app: dice-roller-bad-config
'backstage.io/kubernetes-id': dice-roller
spec:
containers:
- name: nginx
image: nginx:6000000
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '500m'
ports:
- containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: dice-roller-big
labels:
'backstage.io/kubernetes-id': dice-roller
spec:
selector:
matchLabels:
app: dice-roller-big
replicas: 1
template:
metadata:
labels:
app: dice-roller-big
'backstage.io/kubernetes-id': dice-roller
spec:
containers:
- name: nginx
image: nginx:1.14.2
resources:
requests:
memory: '64Mi'
cpu: '100000m'
limits:
memory: '128Mi'
cpu: '100000m'
ports:
- containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: dice-roller-bad-cm
labels:
'backstage.io/kubernetes-id': dice-roller
spec:
selector:
matchLabels:
app: dice-roller-bad-cm
replicas: 1
template:
metadata:
labels:
app: dice-roller-bad-cm
'backstage.io/kubernetes-id': dice-roller
spec:
containers:
- name: nginx
image: nginx:1.14.2
env:
- name: SOME_ENV_VAR
valueFrom:
configMapKeyRef:
name: some-cm
key: some-key
resources:
requests:
memory: '64Mi'
cpu: '50m'
limits:
memory: '128Mi'
cpu: '500m'
ports:
- containerPort: 80
---
apiVersion: autoscaling/v1
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="282" height="173" fill="none" viewBox="0 0 282 173"><path fill="#000" fill-opacity=".05" fill-rule="evenodd" d="M16.4571 45.1637C11.0514 46.1711 7.48574 51.3699 8.49306 56.7756C9.50039 62.1814 14.6992 65.747 20.105 64.7397L27.5528 63.3518C25.4791 65.5835 24.4525 68.7347 25.0535 71.9596C26.0608 77.3653 31.2596 80.931 36.6654 79.9236L89.691 70.0427C89.7016 70.1067 89.7129 70.1708 89.7249 70.2349C90.3258 73.4598 92.4185 76.0298 95.1569 77.3647L91.9031 77.971C86.4974 78.9784 82.9318 84.1772 83.9391 89.583C84.9464 94.9887 90.1452 98.5543 95.551 97.547L250.098 68.7482C255.504 67.7409 259.069 62.5421 258.062 57.1363C257.461 53.9114 255.368 51.3414 252.63 50.0065L257.835 49.0366C263.241 48.0292 266.807 42.8304 265.799 37.4247C264.792 32.0189 259.593 28.4533 254.187 29.4606L161.492 46.7338C161.481 46.6697 161.47 46.6056 161.458 46.5415C160.857 43.3166 158.764 40.7466 156.026 39.4117L165.025 37.7347C170.431 36.7274 173.997 31.5286 172.989 26.1228C171.982 20.7171 166.783 17.1514 161.378 18.1588L16.4571 45.1637ZM24.3031 122.54C23.2958 117.134 26.8614 111.936 32.2672 110.928L190.856 81.3762C196.262 80.3688 201.461 83.9345 202.468 89.3402C203.476 94.746 199.91 99.9448 194.504 100.952L189.963 101.798C190.493 102.057 190.999 102.362 191.474 102.708L246.43 92.4677C251.835 91.4604 257.034 95.026 258.041 100.432C258.642 103.657 257.616 106.808 255.542 109.04L256.649 108.833C262.055 107.826 267.253 111.392 268.261 116.797C269.268 122.203 265.702 127.402 260.297 128.409L95.5591 159.107C90.1534 160.114 84.9545 156.549 83.9472 151.143C82.9399 145.737 86.5055 140.538 91.9113 139.531L103.94 137.29C103.41 137.031 102.904 136.726 102.429 136.38L29.1002 150.044C23.6944 151.051 18.4956 147.486 17.4882 142.08C16.4809 136.674 20.0465 131.475 25.4523 130.468L29.7352 129.67C26.9967 128.335 24.904 125.765 24.3031 122.54Z" clip-rule="evenodd"/><g filter="url(#filter0_d)"><path fill="#EEE" d="M232.896 31.2403H51.2975C49.1452 31.2403 47.4005 32.983 47.4005 35.1327V46.8101C47.4005 48.9598 49.1452 50.7025 51.2975 50.7025H232.896C235.048 50.7025 236.793 48.9598 236.793 46.8101V35.1327C236.793 32.983 235.048 31.2403 232.896 31.2403Z"/><mask id="mask0" width="190" height="114" x="47" y="31" mask-type="alpha" maskUnits="userSpaceOnUse"><path fill="#404040" d="M232.896 31.2403H51.2975C49.1452 31.2403 47.4005 32.983 47.4005 35.1327V141.007C47.4005 143.157 49.1452 144.9 51.2975 144.9H232.896C235.048 144.9 236.793 143.157 236.793 141.007V35.1327C236.793 32.983 235.048 31.2403 232.896 31.2403Z"/></mask><g mask="url(#mask0)"><path fill="#EEE" d="M239.91 42.1391H47.4005V150.349H239.91V42.1391Z"/></g></g><circle cx="188" cy="55" r="6" fill="#69DDC7"/><circle cx="91" cy="92" r="6" fill="#69DDC7"/><path fill="#69DDC7" d="M121 114L95.5 88L86.5 96L121 130L192.5 59L183.5 51L121 114Z"/><defs><filter id="filter0_d" width="229.392" height="153.66" x="29.401" y="15.24" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dx="2" dy="4"/><feGaussianBlur stdDeviation="10"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend in2="BackgroundImageFix" mode="normal" result="effect1_dropShadow"/><feBlend in="SourceGraphic" in2="effect1_dropShadow" mode="normal" result="shape"/></filter></defs></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

+1
View File
@@ -40,6 +40,7 @@
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@material-ui/lab": "4.0.0-alpha.45",
"js-yaml": "^4.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "6.0.0-beta.0",
@@ -1,41 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import { ConfigMaps } from './ConfigMaps';
import * as configmapFixture from './__fixtures__/configmap.json';
import { wrapInTestApp } from '@backstage/test-utils';
describe('ConfigMaps', () => {
it('should render configmap', async () => {
const { getByText } = render(
wrapInTestApp(
<ConfigMaps configMaps={(configmapFixture as any).default} />,
),
);
// title
expect(getByText('dice-roller')).toBeInTheDocument();
expect(getByText('Config Map')).toBeInTheDocument();
// values
expect(getByText('Immutable')).toBeInTheDocument();
expect(getByText('false')).toBeInTheDocument();
expect(getByText('Data')).toBeInTheDocument();
expect(getByText('Foo: bar')).toBeInTheDocument(); // TODO wish this wasn't upper case
});
});
@@ -1,51 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { Grid } from '@material-ui/core';
import { V1ConfigMap } from '@kubernetes/client-node';
import { InfoCard, StructuredMetadataTable } from '@backstage/core';
type ConfigMapsProps = {
configMaps: V1ConfigMap[];
children?: React.ReactNode;
};
export const ConfigMaps = ({ configMaps }: ConfigMapsProps) => {
return (
<Grid container>
{configMaps.map((cm, i) => {
return (
<Grid item key={i}>
<InfoCard
title={cm.metadata?.name ?? 'un-named service'}
subheader="Config Map"
>
<div>
<StructuredMetadataTable
metadata={{
immutable: `${cm.immutable === true}`,
data: cm.data,
}}
/>
</div>
</InfoCard>
</Grid>
);
})}
</Grid>
);
};
@@ -1,46 +0,0 @@
[
{
"data": {
"foo": "bar"
},
"metadata": {
"annotations": {
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"data\":{\"foo\":\"bar\"},\"kind\":\"ConfigMap\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"}}\n"
},
"creationTimestamp": "2020-09-24T11:39:26.000Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:data": {
".": {},
"f:foo": {}
},
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {}
},
"f:labels": {
".": {},
"f:backstage.io/kubernetes-id": {}
}
}
},
"manager": "kubectl",
"operation": "Update",
"time": "2020-09-24T11:39:26.000Z"
}
],
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "503867",
"selfLink": "/api/v1/namespaces/default/configmaps/dice-roller",
"uid": "e9efe5ee-53b9-4422-aef2-877a03c73d5f"
}
}
]
@@ -1,220 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React, { Fragment } from 'react';
import { Chip, Grid } from '@material-ui/core';
import {
StatusAborted,
StatusError,
StatusOK,
SubvalueCell,
Table,
TableColumn,
} from '@backstage/core';
import {
V1ComponentCondition,
V1Deployment,
V1Pod,
V1ReplicaSet,
} from '@kubernetes/client-node';
import { V1OwnerReference } from '@kubernetes/client-node/dist/gen/model/v1OwnerReference';
import { DeploymentTriple } from '../../types/types';
const renderCondition = (condition: V1ComponentCondition | undefined) => {
if (!condition) {
return <StatusAborted />;
}
const status = condition.status;
if (status === 'True') {
return <StatusOK />;
} else if (status === 'False') {
return <StatusError />;
}
return <StatusAborted />;
};
const columns: TableColumn<V1Pod>[] = [
{
title: 'name',
highlight: true,
width: '20%',
render: (pod: V1Pod) => pod.metadata?.name ?? 'un-named pod',
},
{
title: 'images',
width: '20%',
render: (pod: V1Pod) => {
const containerStatuses = pod.status?.containerStatuses ?? [];
return containerStatuses.map((cs, i) => {
return <Chip key={i} label={`${cs.name}=${cs.image}`} size="small" />;
});
},
},
{
title: 'phase',
render: (pod: V1Pod) => pod.status?.phase ?? 'unknown',
},
{
title: 'containers ready',
align: 'center',
render: (pod: V1Pod) => {
const containerStatuses = pod.status?.containerStatuses ?? [];
const containersReady = containerStatuses.filter(cs => cs.ready).length;
return `${containersReady}/${containerStatuses.length}`;
},
},
{
title: 'total restarts',
render: (pod: V1Pod) => {
const containerStatuses = pod.status?.containerStatuses ?? [];
return containerStatuses?.reduce((a, b) => a + b.restartCount, 0);
},
type: 'numeric',
},
{
title: 'status',
width: '20%',
render: (pod: V1Pod) => {
const containerStatuses = pod.status?.containerStatuses ?? [];
const errors = containerStatuses.reduce((accum, next) => {
if (next.state === undefined) {
return accum;
}
const waiting = next.state.waiting;
const terminated = next.state.terminated;
const renderCell = (reason: string | undefined) => (
<Fragment key={`${pod.metadata?.name}-${next.name}`}>
<SubvalueCell
value={<StatusError>Container: {next.name}</StatusError>}
subvalue={reason}
/>
<br />
</Fragment>
);
if (waiting) {
accum.push(renderCell(waiting.reason));
}
if (terminated) {
accum.push(renderCell(terminated.reason));
}
return accum;
}, [] as React.ReactNode[]);
if (errors.length === 0) {
return <StatusOK>OK</StatusOK>;
}
return errors;
},
},
{
title: 'Pod Initialized',
align: 'center',
render: (pod: V1Pod) => {
const conditions = pod.status?.conditions ?? [];
return renderCondition(conditions.find(c => c.type === 'Initialized'));
},
},
{
title: 'Pod Ready',
align: 'center',
render: (pod: V1Pod) => {
const conditions = pod.status?.conditions ?? [];
return renderCondition(conditions.find(c => c.type === 'Ready'));
},
},
{
title: 'Containers Ready',
align: 'center',
render: (pod: V1Pod) => {
const conditions = pod.status?.conditions ?? [];
return renderCondition(
conditions.find(c => c.type === 'ContainersReady'),
);
},
},
{
title: 'Pod Scheduled',
align: 'center',
render: (pod: V1Pod) => {
const conditions = pod.status?.conditions ?? [];
return renderCondition(conditions.find(c => c.type === 'PodScheduled'));
},
},
];
type DeploymentTablesProps = {
deploymentTriple: DeploymentTriple;
children?: React.ReactNode;
};
export const DeploymentTables = ({
deploymentTriple,
}: DeploymentTablesProps) => {
const isOwnedBy = (
ownerReferences: V1OwnerReference[],
obj: V1Pod | V1ReplicaSet | V1Deployment,
): boolean => {
return ownerReferences?.some(or => or.name === obj.metadata?.name);
};
return (
<Grid
container
direction="column"
justify="flex-start"
alignItems="flex-start"
>
{deploymentTriple.deployments.map((deployment, i) => (
<Grid container item key={i} xs>
{deploymentTriple.replicaSets
// Filter out replica sets with no replicas
.filter(rs => rs.status && rs.status.replicas > 0)
// Find the replica sets this deployment owns
.filter(rs =>
isOwnedBy(rs.metadata?.ownerReferences ?? [], deployment),
)
.map((rs, j) => {
// Find the pods this replica set owns and render them in the table
const ownedPods = deploymentTriple.pods.filter(pod =>
isOwnedBy(pod.metadata?.ownerReferences ?? [], rs),
);
return (
<Grid item key={j} xs>
<Table
options={{ paging: false, padding: 'dense', search: false }}
data={ownedPods}
columns={columns}
title={deployment.metadata?.name ?? ''}
subtitle="Deployment"
/>
</Grid>
);
})}
</Grid>
))}
</Grid>
);
};
@@ -0,0 +1,50 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import * as deployments from './__fixtures__/2-deployments.json';
import { wrapInTestApp } from '@backstage/test-utils';
import { DeploymentDrawer } from './DeploymentDrawer';
describe('DeploymentDrawer', () => {
it('should render deployment drawer', async () => {
const { getByText, getAllByText } = render(
wrapInTestApp(
<DeploymentDrawer
deployment={(deployments as any).deployments[0]}
expanded
/>,
),
);
expect(getAllByText('dice-roller')).toHaveLength(2);
expect(getAllByText('Deployment')).toHaveLength(2);
expect(getByText('YAML')).toBeInTheDocument();
expect(getByText('Strategy')).toBeInTheDocument();
expect(getByText('Rolling Update:')).toBeInTheDocument();
expect(getByText('Max Surge: 25%')).toBeInTheDocument();
expect(getByText('Max Unavailable: 25%')).toBeInTheDocument();
expect(getByText('Type: RollingUpdate')).toBeInTheDocument();
expect(getByText('Min Ready Seconds')).toBeInTheDocument();
expect(getByText('???')).toBeInTheDocument();
expect(getByText('Progress Deadline Seconds')).toBeInTheDocument();
expect(getByText('600')).toBeInTheDocument();
expect(getByText('Progressing')).toBeInTheDocument();
expect(getByText('Available')).toBeInTheDocument();
expect(getAllByText('True')).toHaveLength(2);
});
});
@@ -0,0 +1,72 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { V1Deployment } from '@kubernetes/client-node';
import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer';
import { renderCondition } from '../../utils/pod';
import { Typography, Grid } from '@material-ui/core';
export const DeploymentDrawer = ({
deployment,
expanded,
}: {
deployment: V1Deployment;
expanded?: boolean;
}) => {
return (
<KubernetesDrawer
object={deployment}
expanded={expanded}
kind="Deployment"
renderObject={(deployment: V1Deployment) => {
const conditions = (deployment.status?.conditions ?? [])
.map(renderCondition)
.reduce((accum, next) => {
accum[next[0]] = next[1];
return accum;
}, {} as { [key: string]: React.ReactNode });
return {
strategy: deployment.spec?.strategy ?? '???',
minReadySeconds: deployment.spec?.minReadySeconds ?? '???',
progressDeadlineSeconds:
deployment.spec?.progressDeadlineSeconds ?? '???',
...conditions,
};
}}
>
<Grid
container
direction="column"
justify="flex-start"
alignItems="flex-start"
spacing={0}
>
<Grid item>
<Typography variant="h5">
{deployment.metadata?.name ?? 'unknown object'}
</Typography>
</Grid>
<Grid item>
<Typography color="textSecondary" variant="body1">
Deployment
</Typography>
</Grid>
</Grid>
</KubernetesDrawer>
);
};
@@ -16,26 +16,32 @@
import React from 'react';
import { render } from '@testing-library/react';
import { DeploymentTables } from './DeploymentTables';
import { DeploymentsAccordions } from './DeploymentsAccordions';
import * as twoDeployFixture from './__fixtures__/2-deployments.json';
import { wrapInTestApp } from '@backstage/test-utils';
describe('DeploymentTables', () => {
describe('DeploymentsAccordions', () => {
it('should render 2 deployments', async () => {
const { getByText } = render(
wrapInTestApp(
<DeploymentTables deploymentTriple={twoDeployFixture as any} />,
<DeploymentsAccordions
deploymentResources={twoDeployFixture as any}
clusterPodNamesWithErrors={
new Set(['dice-roller-canary-7d64cd756c-vtbdx'])
}
/>,
),
);
// title
expect(getByText('dice-roller')).toBeInTheDocument();
expect(getByText('dice-roller-canary')).toBeInTheDocument();
expect(getByText('10 pods')).toBeInTheDocument();
expect(getByText('No pods with errors')).toBeInTheDocument();
expect(getByText('min replicas 10 / max replicas 15')).toBeInTheDocument();
expect(getByText('current CPU usage: 30%')).toBeInTheDocument();
expect(getByText('target CPU usage: 50%')).toBeInTheDocument();
// pod names
expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument();
expect(
getByText('dice-roller-canary-7d64cd756c-55rfq'),
).toBeInTheDocument();
expect(getByText('dice-roller-canary')).toBeInTheDocument();
expect(getByText('2 pods')).toBeInTheDocument();
expect(getByText('1 pod with errors')).toBeInTheDocument();
});
});
@@ -0,0 +1,221 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { DeploymentResources } from '../../types/types';
import React from 'react';
import {
Accordion,
AccordionDetails,
AccordionSummary,
Divider,
Grid,
Typography,
} from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { V1OwnerReference } from '@kubernetes/client-node/dist/gen/model/v1OwnerReference';
import {
V1Deployment,
V1Pod,
V1ReplicaSet,
V1HorizontalPodAutoscaler,
} from '@kubernetes/client-node';
import { StatusError, StatusOK } from '@backstage/core';
import { PodsTable } from '../Pods';
import { DeploymentDrawer } from './DeploymentDrawer';
import { HorizontalPodAutoscalerDrawer } from '../HorizontalPodAutoscalers';
type DeploymentsAccordionsProps = {
deploymentResources: DeploymentResources;
clusterPodNamesWithErrors: Set<string>;
children?: React.ReactNode;
};
export const DeploymentsAccordions = ({
deploymentResources,
clusterPodNamesWithErrors,
}: DeploymentsAccordionsProps) => {
const isOwnedBy = (
ownerReferences: V1OwnerReference[],
obj: V1Pod | V1ReplicaSet | V1Deployment,
): boolean => {
return ownerReferences?.some(or => or.name === obj.metadata?.name);
};
return (
<Grid
container
direction="column"
justify="flex-start"
alignItems="flex-start"
>
{deploymentResources.deployments.map((deployment, i) => (
<Grid container item key={i} xs>
{deploymentResources.replicaSets
// Filter out replica sets with no replicas
.filter(rs => rs.status && rs.status.replicas > 0)
// Find the replica sets this deployment owns
.filter(rs =>
isOwnedBy(rs.metadata?.ownerReferences ?? [], deployment),
)
.map((rs, j) => {
// Find the pods this replica set owns and render them in the table
const ownedPods = deploymentResources.pods.filter(pod =>
isOwnedBy(pod.metadata?.ownerReferences ?? [], rs),
);
const matchingHpa = deploymentResources.horizontalPodAutoscalers.find(
(hpa: V1HorizontalPodAutoscaler) => {
return (
(hpa.spec?.scaleTargetRef?.kind ?? '').toLowerCase() ===
'deployment' &&
(hpa.spec?.scaleTargetRef?.name ?? '') ===
(deployment.metadata?.name ?? 'unknown-deployment')
);
},
);
return (
<Grid item key={j} xs>
<DeploymentAccordion
deployment={deployment}
ownedPods={ownedPods}
matchingHpa={matchingHpa}
clusterPodNamesWithErrors={clusterPodNamesWithErrors}
/>
</Grid>
);
})}
</Grid>
))}
</Grid>
);
};
type DeploymentAccordionProps = {
deployment: V1Deployment;
ownedPods: V1Pod[];
matchingHpa?: V1HorizontalPodAutoscaler;
clusterPodNamesWithErrors: Set<string>;
children?: React.ReactNode;
};
const DeploymentAccordion = ({
deployment,
ownedPods,
matchingHpa,
clusterPodNamesWithErrors,
}: DeploymentAccordionProps) => {
const podsWithErrors = ownedPods.filter(p =>
clusterPodNamesWithErrors.has(p.metadata?.name ?? ''),
);
return (
<Accordion TransitionProps={{ unmountOnExit: true }}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<DeploymentSummary
deployment={deployment}
numberOfCurrentPods={ownedPods.length}
numberOfPodsWithErrors={podsWithErrors.length}
hpa={matchingHpa}
/>
</AccordionSummary>
<AccordionDetails>
<PodsTable pods={ownedPods} />
</AccordionDetails>
</Accordion>
);
};
type DeploymentSummaryProps = {
deployment: V1Deployment;
numberOfCurrentPods: number;
numberOfPodsWithErrors: number;
hpa?: V1HorizontalPodAutoscaler;
children?: React.ReactNode;
};
const DeploymentSummary = ({
deployment,
numberOfCurrentPods,
numberOfPodsWithErrors,
hpa,
}: DeploymentSummaryProps) => {
return (
<Grid container direction="row" justify="flex-start" alignItems="center">
<Grid xs={3} item>
<DeploymentDrawer deployment={deployment} />
</Grid>
<Grid item xs={1}>
<Divider style={{ height: '5em' }} orientation="vertical" />
</Grid>
{hpa && (
<Grid item xs={3}>
<HorizontalPodAutoscalerDrawer hpa={hpa}>
<Grid
item
container
direction="column"
justify="flex-start"
alignItems="flex-start"
spacing={0}
>
<Grid item>
<Typography variant="subtitle2">
min replicas {hpa.spec?.minReplicas ?? '?'} / max replicas{' '}
{hpa.spec?.maxReplicas ?? '?'}
</Typography>
</Grid>
<Grid item>
<Typography variant="subtitle2">
current CPU usage:{' '}
{hpa.status?.currentCPUUtilizationPercentage ?? '?'}%
</Typography>
</Grid>
<Grid item>
<Typography variant="subtitle2">
target CPU usage:{' '}
{hpa.spec?.targetCPUUtilizationPercentage ?? '?'}%
</Typography>
</Grid>
</Grid>
</HorizontalPodAutoscalerDrawer>
</Grid>
)}
<Grid
item
container
xs={3}
direction="column"
justify="flex-start"
alignItems="flex-start"
>
<Grid item>
<StatusOK>{numberOfCurrentPods} pods</StatusOK>
</Grid>
<Grid item>
{numberOfPodsWithErrors > 0 ? (
<StatusError>
{numberOfPodsWithErrors} pod
{numberOfPodsWithErrors > 1 ? 's' : ''} with errors
</StatusError>
) : (
<StatusOK>No pods with errors</StatusOK>
)}
</Grid>
</Grid>
</Grid>
);
};
@@ -4431,5 +4431,89 @@
"updatedReplicas": 2
}
}
],
"horizontalPodAutoscalers": [
{
"apiVersion": "autoscaling/v1",
"kind": "HorizontalPodAutoscaler",
"metadata": {
"annotations": {
"autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"True\",\"lastTransitionTime\":\"2021-01-05T10:26:04Z\",\"reason\":\"SucceededGetScale\",\"message\":\"the HPA controller was able to get the target's current scale\"},{\"type\":\"ScalingActive\",\"status\":\"False\",\"lastTransitionTime\":\"2021-01-05T10:26:04Z\",\"reason\":\"FailedGetResourceMetric\",\"message\":\"the HPA was unable to compute the replica count: unable to get metrics for resource cpu: no metrics returned from resource metrics API\"}]",
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"autoscaling/v1\",\"kind\":\"HorizontalPodAutoscaler\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"maxReplicas\":15,\"minReplicas\":10,\"scaleTargetRef\":{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"name\":\"dice-roller\"},\"targetCPUUtilizationPercentage\":50}}\n"
},
"creationTimestamp": "2021-01-05T10:25:48Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"managedFields": [
{
"apiVersion": "autoscaling/v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {}
},
"f:labels": {
".": {},
"f:backstage.io/kubernetes-id": {}
}
},
"f:spec": {
"f:maxReplicas": {},
"f:minReplicas": {},
"f:scaleTargetRef": {
"f:apiVersion": {},
"f:kind": {},
"f:name": {}
},
"f:targetCPUUtilizationPercentage": {}
}
},
"manager": "kubectl-client-side-apply",
"operation": "Update",
"time": "2021-01-05T10:25:48Z"
},
{
"apiVersion": "autoscaling/v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
"f:autoscaling.alpha.kubernetes.io/conditions": {}
}
},
"f:status": {
"f:currentReplicas": {}
}
},
"manager": "kube-controller-manager",
"operation": "Update",
"time": "2021-01-05T10:26:04Z"
}
],
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "598",
"selfLink": "/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/dice-roller",
"uid": "dd7c5329-567c-43c2-b159-756808d90a8e"
},
"spec": {
"maxReplicas": 15,
"minReplicas": 10,
"scaleTargetRef": {
"apiVersion": "apps/v1",
"kind": "Deployment",
"name": "dice-roller"
},
"targetCPUUtilizationPercentage": 50
},
"status": {
"currentReplicas": 10,
"desiredReplicas": 0,
"currentCPUUtilizationPercentage": 30
}
}
]
}
@@ -13,4 +13,4 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { DeploymentTables } from './DeploymentTables';
export { DeploymentsAccordions } from './DeploymentsAccordions';
@@ -0,0 +1,135 @@
/*
* Copyright 2020 Spotify AB
*
* 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 * as React from 'react';
import { Table, TableColumn, InfoCard } from '@backstage/core';
import { DetectedError, DetectedErrorsByCluster } from '../../error-detection';
import { Chip, Typography, Grid } from '@material-ui/core';
import EmptyStateImage from '../../../assets/emptystate.svg';
type ErrorReportingProps = {
detectedErrors: DetectedErrorsByCluster;
};
const columns: TableColumn<DetectedError>[] = [
{
title: 'cluster',
width: '15%',
render: (detectedError: DetectedError) => detectedError.cluster,
},
{
title: 'kind',
width: '15%',
render: (detectedError: DetectedError) => detectedError.kind,
},
{
title: 'name',
width: '30%',
render: (detectedError: DetectedError) => {
const errorCount = detectedError.names.length;
if (errorCount === 0) {
// This shouldn't happen
return null;
}
const displayName = detectedError.names[0];
const otherErrorCount = errorCount - 1;
return (
<>
{displayName}{' '}
{otherErrorCount > 0 && (
<Chip
label={`+ ${otherErrorCount} other${
otherErrorCount > 1 ? 's' : ''
}`}
size="small"
/>
)}
</>
);
},
},
{
title: 'messages',
width: '40%',
render: (detectedError: DetectedError) => (
<>
{detectedError.message.map((m, i) => (
<div key={i}>{m}</div>
))}
</>
),
},
];
const sortBySeverity = (a: DetectedError, b: DetectedError) => {
if (a.severity < b.severity) {
return 1;
} else if (b.severity < a.severity) {
return -1;
}
return 0;
};
export const ErrorReporting = ({ detectedErrors }: ErrorReportingProps) => {
const errors = Array.from(detectedErrors.values())
.flat()
.sort(sortBySeverity);
return (
<>
{errors.length === 0 ? (
<InfoCard title="Error Reporting">
<ErrorEmptyState />
</InfoCard>
) : (
<Table
title="Error Reporting"
data={errors}
columns={columns}
options={{ paging: true, search: false }}
/>
)}
</>
);
};
export const ErrorEmptyState = () => {
return (
<Grid
container
justify="center"
direction="column"
alignItems="center"
spacing={2}
>
<Grid item xs={12}>
<Typography variant="h5">
Nice! There are no errors to report!
</Typography>
</Grid>
<Grid item xs={12}>
<img
src={EmptyStateImage}
alt="EmptyState"
data-testid="emptyStateImg"
/>
</Grid>
</Grid>
);
};
@@ -13,4 +13,4 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Ingresses } from './Ingresses';
export { ErrorReporting } from './ErrorReporting';
@@ -16,37 +16,35 @@
import React from 'react';
import { render } from '@testing-library/react';
import * as hpaFixture from './__fixtures__/horizontalpodautoscalers.json';
import * as hpas from './__fixtures__/horizontalpodautoscalers.json';
import { wrapInTestApp } from '@backstage/test-utils';
import { HorizontalPodAutoscalers } from './HorizontalPodAutoscalers';
import { HorizontalPodAutoscalerDrawer } from './HorizontalPodAutoscalerDrawer';
describe('HorizontalPodAutoscalers', () => {
it('should render horizontalpodautoscaler', async () => {
const { getByText, getAllByText } = render(
describe('HorizontalPodAutoscalersDrawer', () => {
it('should render hpa drawer', async () => {
const { getByText } = render(
wrapInTestApp(
<HorizontalPodAutoscalers hpas={(hpaFixture as any).default} />,
<HorizontalPodAutoscalerDrawer hpa={hpas[0] as any} expanded>
<h1>CHILD</h1>
</HorizontalPodAutoscalerDrawer>,
),
);
// title
expect(getByText('dice-roller')).toBeInTheDocument();
expect(getByText('Horizontal Pod Autoscaler')).toBeInTheDocument();
expect(getByText('Scaling Target')).toBeInTheDocument();
expect(getByText('Api Version: apps/v1')).toBeInTheDocument();
expect(getByText('Kind: Deployment')).toBeInTheDocument();
expect(getByText('Name: dice-roller')).toBeInTheDocument();
expect(getByText('Min Replicas')).toBeInTheDocument();
expect(getByText('Max Replicas')).toBeInTheDocument();
expect(getByText('15')).toBeInTheDocument();
expect(getByText('Current Replicas')).toBeInTheDocument();
expect(getByText('Desired Replicas')).toBeInTheDocument();
expect(getByText('0')).toBeInTheDocument();
expect(getByText('CHILD')).toBeInTheDocument();
expect(getByText('HorizontalPodAutoscaler')).toBeInTheDocument();
expect(getByText('YAML')).toBeInTheDocument();
expect(getByText('Target CPU Utilization Percentage')).toBeInTheDocument();
expect(getByText('50')).toBeInTheDocument();
expect(getByText('Current CPU Utilization Percentage')).toBeInTheDocument();
expect(getByText('Last Scale Time')).toBeInTheDocument();
expect(getAllByText('unknown')).toHaveLength(2);
expect(getAllByText('10')).toHaveLength(2);
expect(getByText('30')).toBeInTheDocument();
expect(getByText('Min Replicas')).toBeInTheDocument();
expect(getByText('10')).toBeInTheDocument();
expect(getByText('Max Replicas')).toBeInTheDocument();
expect(getByText('15')).toBeInTheDocument();
expect(getByText('Current Replicas')).toBeInTheDocument();
expect(getByText('13')).toBeInTheDocument();
expect(getByText('Desired Replicas')).toBeInTheDocument();
expect(getByText('14')).toBeInTheDocument();
});
});
@@ -0,0 +1,51 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { V1HorizontalPodAutoscaler } from '@kubernetes/client-node';
import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer';
export const HorizontalPodAutoscalerDrawer = ({
hpa,
expanded,
children,
}: {
hpa: V1HorizontalPodAutoscaler;
expanded?: boolean;
children?: React.ReactNode;
}) => {
return (
<KubernetesDrawer
kind="HorizontalPodAutoscaler"
object={hpa}
expanded={expanded}
renderObject={(hpa: V1HorizontalPodAutoscaler) => {
return {
targetCPUUtilizationPercentage:
hpa.spec?.targetCPUUtilizationPercentage,
currentCPUUtilizationPercentage:
hpa.status?.currentCPUUtilizationPercentage,
minReplicas: hpa.spec?.minReplicas,
maxReplicas: hpa.spec?.maxReplicas,
currentReplicas: hpa.status?.currentReplicas,
desiredReplicas: hpa.status?.desiredReplicas,
};
}}
>
{children}
</KubernetesDrawer>
);
};
@@ -1,64 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { Grid } from '@material-ui/core';
import { V1HorizontalPodAutoscaler } from '@kubernetes/client-node';
import { InfoCard, StructuredMetadataTable } from '@backstage/core';
import { orUnknown } from '../../utils';
type HorizontalPodAutoscalersProps = {
hpas: V1HorizontalPodAutoscaler[];
children?: React.ReactNode;
};
export const HorizontalPodAutoscalers = ({
hpas,
}: HorizontalPodAutoscalersProps) => {
return (
<Grid container>
{hpas.map((hpa, i) => {
return (
<Grid item key={i}>
<InfoCard
title={hpa.metadata?.name ?? 'un-named service'}
subheader="Horizontal Pod Autoscaler"
>
<div>
<StructuredMetadataTable
metadata={{
scalingTarget: orUnknown(hpa.spec?.scaleTargetRef),
minReplicas: orUnknown(hpa.spec?.minReplicas),
maxReplicas: orUnknown(hpa.spec?.maxReplicas),
currentReplicas: orUnknown(hpa.status?.currentReplicas),
desiredReplicas: orUnknown(hpa.status?.desiredReplicas),
targetCPUUtilizationPercentage: orUnknown(
hpa.spec?.targetCPUUtilizationPercentage,
),
currentCPUUtilizationPercentage: orUnknown(
hpa.status?.currentCPUUtilizationPercentage,
),
lastScaleTime: orUnknown(hpa.status?.lastScaleTime),
}}
/>
</div>
</InfoCard>
</Grid>
);
})}
</Grid>
);
};
@@ -74,8 +74,9 @@
"targetCPUUtilizationPercentage": 50
},
"status": {
"currentReplicas": 10,
"desiredReplicas": 0
"currentReplicas": 13,
"desiredReplicas": 14,
"currentCPUUtilizationPercentage": 30
}
}
]
@@ -13,4 +13,4 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { HorizontalPodAutoscalers } from './HorizontalPodAutoscalers';
export { HorizontalPodAutoscalerDrawer } from './HorizontalPodAutoscalerDrawer';
@@ -1,47 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import * as ingressesFixture from './__fixtures__/ingress.json';
import { wrapInTestApp } from '@backstage/test-utils';
import { Ingresses } from './Ingresses';
describe('Ingresses', () => {
it('should render ingress', async () => {
const { getByText } = render(
wrapInTestApp(
<Ingresses ingresses={(ingressesFixture as any).default} />,
),
);
// title
expect(getByText('dice-roller')).toBeInTheDocument();
expect(getByText('Ingress')).toBeInTheDocument();
// values
expect(getByText('Backend')).toBeInTheDocument();
expect(getByText('Ip: 192.168.64.2')).toBeInTheDocument();
expect(getByText('Rules')).toBeInTheDocument();
expect(getByText('Host: nginx')).toBeInTheDocument();
expect(getByText('Http:')).toBeInTheDocument();
expect(getByText('Paths:')).toBeInTheDocument();
expect(getByText('Service Name: dice-roller')).toBeInTheDocument();
expect(getByText('Service Port: 80')).toBeInTheDocument();
expect(getByText('Path: /')).toBeInTheDocument();
expect(getByText('Path Type: ImplementationSpecific')).toBeInTheDocument();
});
});
@@ -1,51 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { Grid } from '@material-ui/core';
import { ExtensionsV1beta1Ingress } from '@kubernetes/client-node';
import { InfoCard, StructuredMetadataTable } from '@backstage/core';
type IngressesProps = {
ingresses: ExtensionsV1beta1Ingress[];
children?: React.ReactNode;
};
export const Ingresses = ({ ingresses }: IngressesProps) => {
return (
<Grid container>
{ingresses.map((ingress, i) => {
return (
<Grid item key={i}>
<InfoCard
title={ingress.metadata?.name ?? 'un-named ingress'}
subheader="Ingress"
>
<div>
<StructuredMetadataTable
metadata={{
backend: ingress.status?.loadBalancer?.ingress,
rules: ingress.spec?.rules,
}}
/>
</div>
</InfoCard>
</Grid>
);
})}
</Grid>
);
};
@@ -1,87 +0,0 @@
[
{
"metadata": {
"annotations": {
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"networking.k8s.io/v1beta1\",\"kind\":\"Ingress\",\"metadata\":{\"annotations\":{\"nginx.ingress.kubernetes.io/rewrite-target\":\"/$1\"},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"rules\":[{\"host\":\"nginx\",\"http\":{\"paths\":[{\"backend\":{\"serviceName\":\"dice-roller\",\"servicePort\":80},\"path\":\"/\"}]}}]}}\n",
"nginx.ingress.kubernetes.io/rewrite-target": "/$1"
},
"creationTimestamp": "2020-09-28T13:28:00.000Z",
"generation": 1,
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"managedFields": [
{
"apiVersion": "networking.k8s.io/v1beta1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {},
"f:nginx.ingress.kubernetes.io/rewrite-target": {}
},
"f:labels": {
".": {},
"f:backstage.io/kubernetes-id": {}
}
},
"f:spec": {
"f:rules": {}
}
},
"manager": "kubectl",
"operation": "Update",
"time": "2020-09-28T13:28:21.000Z"
},
{
"apiVersion": "networking.k8s.io/v1beta1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:status": {
"f:loadBalancer": {
"f:ingress": {}
}
}
},
"manager": "nginx-ingress-controller",
"operation": "Update",
"time": "2020-09-28T13:28:40.000Z"
}
],
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "699017",
"selfLink": "/apis/networking.k8s.io/v1beta1/namespaces/default/ingresses/dice-roller",
"uid": "e96994c0-49b9-4c1c-8ce0-72c5336fe960"
},
"spec": {
"rules": [
{
"host": "nginx",
"http": {
"paths": [
{
"backend": {
"serviceName": "dice-roller",
"servicePort": 80
},
"path": "/",
"pathType": "ImplementationSpecific"
}
]
}
}
]
},
"status": {
"loadBalancer": {
"ingress": [
{
"ip": "192.168.64.2"
}
]
}
}
}
]
@@ -17,7 +17,7 @@
import React from 'react';
import { WarningPanel } from '@backstage/core';
import { Typography } from '@material-ui/core';
import { ClusterObjects } from '../../../../kubernetes-backend/src';
import { ClusterObjects } from '@backstage/plugin-kubernetes-backend';
const clustersWithErrorsToErrorMessage = (
clustersWithErrors: ClusterObjects[],
@@ -14,89 +14,39 @@
* limitations under the License.
*/
import React, { ReactElement, useEffect, useState } from 'react';
import { Grid, TabProps } from '@material-ui/core';
import React, { useEffect, useState } from 'react';
import {
Accordion,
AccordionDetails,
AccordionSummary,
Divider,
Grid,
Typography,
} from '@material-ui/core';
import { Config } from '@backstage/config';
import {
CardTab,
configApiRef,
Content,
Page,
Progress,
TabbedCard,
StatusError,
StatusOK,
useApi,
} from '@backstage/core';
import { Entity } from '@backstage/catalog-model';
import { kubernetesApiRef } from '../../api/types';
import {
KubernetesRequestBody,
ClusterObjects,
FetchResponse,
KubernetesRequestBody,
ObjectsByEntityResponse,
} from '@backstage/plugin-kubernetes-backend';
import { kubernetesAuthProvidersApiRef } from '../../kubernetes-auth-provider/types';
import { DeploymentTables } from '../DeploymentTables';
import { DeploymentTriple } from '../../types/types';
import {
ExtensionsV1beta1Ingress,
V1ConfigMap,
V1HorizontalPodAutoscaler,
V1Service,
} from '@kubernetes/client-node';
import { Services } from '../Services';
import { ConfigMaps } from '../ConfigMaps';
import { Ingresses } from '../Ingresses';
import { HorizontalPodAutoscalers } from '../HorizontalPodAutoscalers';
import { ErrorPanel } from './ErrorPanel';
interface GroupedResponses extends DeploymentTriple {
services: V1Service[];
configMaps: V1ConfigMap[];
horizontalPodAutoscalers: V1HorizontalPodAutoscaler[];
ingresses: ExtensionsV1beta1Ingress[];
}
// TODO this could probably be a lodash groupBy
const groupResponses = (fetchResponse: FetchResponse[]) => {
return fetchResponse.reduce(
(prev, next) => {
switch (next.type) {
case 'deployments':
prev.deployments.push(...next.resources);
break;
case 'pods':
prev.pods.push(...next.resources);
break;
case 'replicasets':
prev.replicaSets.push(...next.resources);
break;
case 'services':
prev.services.push(...next.resources);
break;
case 'configmaps':
prev.configMaps.push(...next.resources);
break;
case 'horizontalpodautoscalers':
prev.horizontalPodAutoscalers.push(...next.resources);
break;
case 'ingresses':
prev.ingresses.push(...next.resources);
break;
default:
}
return prev;
},
{
pods: [],
replicaSets: [],
deployments: [],
services: [],
configMaps: [],
horizontalPodAutoscalers: [],
ingresses: [],
} as GroupedResponses,
);
};
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { DeploymentsAccordions } from '../DeploymentsAccordions';
import { ErrorReporting } from '../ErrorReporting';
import { groupResponses } from '../../utils/response';
import { DetectedError, detectErrors } from '../../error-detection';
type KubernetesContentProps = { entity: Entity; children?: React.ReactNode };
@@ -148,6 +98,11 @@ export const KubernetesContent = ({ entity }: KubernetesContentProps) => {
const clustersWithErrors =
kubernetesObjects?.items.filter(r => r.errors.length > 0) ?? [];
const detectedErrors =
kubernetesObjects !== undefined
? detectErrors(kubernetesObjects)
: new Map<string, DetectedError[]>();
return (
<Page themeId="tool">
<Content>
@@ -172,11 +127,29 @@ export const KubernetesContent = ({ entity }: KubernetesContentProps) => {
/>
)}
{kubernetesObjects?.items.map((item, i) => (
<Grid item key={i}>
<Cluster clusterObjects={item} />
</Grid>
))}
{kubernetesObjects && (
<>
<Grid item>
<ErrorReporting detectedErrors={detectedErrors} />
</Grid>
<Grid item>
<Divider />
</Grid>
<Grid item>
<Typography variant="h3">Your Clusters</Typography>
</Grid>
<Grid item container>
{kubernetesObjects?.items.map((item, i) => (
<Grid item key={i} xs={12}>
<Cluster
clusterObjects={item}
detectedErrors={detectedErrors.get(item.cluster.name)}
/>
</Grid>
))}
</Grid>
</>
)}
</Grid>
</Content>
</Page>
@@ -185,67 +158,97 @@ export const KubernetesContent = ({ entity }: KubernetesContentProps) => {
type ClusterProps = {
clusterObjects: ClusterObjects;
detectedErrors?: DetectedError[];
children?: React.ReactNode;
};
const Cluster = ({ clusterObjects }: ClusterProps) => {
const [selectedTab, setSelectedTab] = useState<string | number>('one');
const handleChange = (_ev: any, newSelectedTab: string | number) =>
setSelectedTab(newSelectedTab);
const Cluster = ({ clusterObjects, detectedErrors }: ClusterProps) => {
const groupedResponses = groupResponses(clusterObjects.resources);
const configMaps = groupedResponses.configMaps;
const hpas = groupedResponses.horizontalPodAutoscalers;
const ingresses = groupedResponses.ingresses;
const tabs: ReactElement<TabProps>[] = [
<CardTab key={1} value="one" label="Deployments">
<DeploymentTables
deploymentTriple={{
deployments: groupedResponses.deployments,
replicaSets: groupedResponses.replicaSets,
pods: groupedResponses.pods,
}}
/>
</CardTab>,
<CardTab key={2} value="two" label="Services">
<Services services={groupedResponses.services} />
</CardTab>,
];
if (configMaps.length > 0) {
tabs.push(
<CardTab key={3} value="three" label="Config Maps">
<ConfigMaps configMaps={configMaps} />
</CardTab>,
);
}
if (hpas.length > 0) {
tabs.push(
<CardTab key={4} value="four" label="Horizontal Pod Autoscalers">
<HorizontalPodAutoscalers hpas={hpas} />
</CardTab>,
);
}
if (ingresses.length > 0) {
tabs.push(
<CardTab key={5} value="five" label="Ingresses">
<Ingresses ingresses={ingresses} />
</CardTab>,
);
}
const podsWithErrors = new Set<string>(
detectedErrors
?.filter(de => de.kind === 'Pod')
.map(de => de.names)
.flat() ?? [],
);
return (
<>
<TabbedCard
value={selectedTab}
onChange={handleChange}
title={clusterObjects.cluster.name}
>
{tabs}
</TabbedCard>
<Accordion TransitionProps={{ unmountOnExit: true }}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<ClusterSummary
clusterName={clusterObjects.cluster.name}
totalNumberOfPods={groupedResponses.pods.length}
numberOfPodsWithErrors={podsWithErrors.size}
/>
</AccordionSummary>
<AccordionDetails>
<DeploymentsAccordions
deploymentResources={groupedResponses}
clusterPodNamesWithErrors={podsWithErrors}
/>
</AccordionDetails>
</Accordion>
</>
);
};
type ClusterSummaryProps = {
clusterName: string;
totalNumberOfPods: number;
numberOfPodsWithErrors: number;
children?: React.ReactNode;
};
const ClusterSummary = ({
clusterName,
totalNumberOfPods,
numberOfPodsWithErrors,
}: ClusterSummaryProps) => {
return (
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<Grid
xs={2}
item
direction="column"
justify="flex-start"
alignItems="flex-start"
spacing={0}
>
<Grid item xs>
<Typography variant="h3">{clusterName}</Typography>
<Typography color="textSecondary" variant="body1">
Cluster
</Typography>
</Grid>
</Grid>
<Grid item xs={1}>
<Divider style={{ height: '4em' }} orientation="vertical" />
</Grid>
<Grid
item
container
xs={3}
direction="column"
justify="flex-start"
alignItems="flex-start"
>
<Grid item>
<StatusOK>{totalNumberOfPods} pods</StatusOK>
</Grid>
<Grid item>
{numberOfPodsWithErrors > 0 ? (
<StatusError>{numberOfPodsWithErrors} pods with errors</StatusError>
) : (
<StatusOK>No pods with errors</StatusOK>
)}
</Grid>
</Grid>
</Grid>
);
};
@@ -0,0 +1,205 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React, { ChangeEvent, useState } from 'react';
import {
Button,
Typography,
makeStyles,
IconButton,
createStyles,
Theme,
Drawer,
Switch,
FormControlLabel,
Grid,
} from '@material-ui/core';
import Close from '@material-ui/icons/Close';
import { V1ObjectMeta } from '@kubernetes/client-node';
import { withStyles } from '@material-ui/core/styles';
import { CodeSnippet, StructuredMetadataTable } from '@backstage/core';
import jsYaml from 'js-yaml';
const useDrawerStyles = makeStyles((theme: Theme) =>
createStyles({
paper: {
width: '50%',
justifyContent: 'space-between',
padding: theme.spacing(2.5),
},
}),
);
const useDrawerContentStyles = makeStyles((_: Theme) =>
createStyles({
header: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
},
options: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-end',
},
icon: {
fontSize: 20,
},
content: {
height: '80%',
},
}),
);
const PodDrawerButton = withStyles({
root: {
padding: '6px 5px',
},
label: {
textTransform: 'none',
},
})(Button);
interface KubernetesDrawerable {
metadata?: V1ObjectMeta;
}
interface KubernetesDrawerProps<T extends KubernetesDrawerable> {
object: T;
renderObject: (obj: T) => object;
buttonVariant?: 'h5' | 'subtitle2';
kind: string;
expanded?: boolean;
children?: React.ReactNode;
}
export const KubernetesDrawer = <T extends KubernetesDrawerable>({
object,
renderObject,
kind,
buttonVariant = 'subtitle2',
expanded = false,
children,
}: KubernetesDrawerProps<T>) => {
const [isOpen, setIsOpen] = useState(expanded);
const classes = useDrawerStyles();
const toggleDrawer = (e: ChangeEvent<{}>, newValue: boolean) => {
e.stopPropagation();
setIsOpen(newValue);
};
return (
<>
<PodDrawerButton
onClick={e => toggleDrawer(e, true)}
onFocus={event => event.stopPropagation()}
>
{children === undefined ? (
<Typography variant={buttonVariant}>
{object.metadata?.name ?? 'unknown object'}
</Typography>
) : (
children
)}
</PodDrawerButton>
<Drawer
classes={{
paper: classes.paper,
}}
anchor="right"
open={isOpen}
onClose={(e: any) => toggleDrawer(e, false)}
onClick={event => event.stopPropagation()}
>
<KubernetesDrawerContent
kind={kind}
toggleDrawer={toggleDrawer}
object={object}
renderObject={renderObject}
/>
</Drawer>
</>
);
};
interface KubernetesDrawerContentProps<T extends KubernetesDrawerable> {
toggleDrawer: (e: ChangeEvent<{}>, isOpen: boolean) => void;
object: T;
renderObject: (obj: T) => object;
kind: string;
}
const KubernetesDrawerContent = <T extends KubernetesDrawerable>({
toggleDrawer,
object,
renderObject,
kind,
}: KubernetesDrawerContentProps<T>) => {
const [isYaml, setIsYaml] = useState<boolean>(false);
const classes = useDrawerContentStyles();
return (
<>
<div className={classes.header}>
<Grid
container
direction="column"
justify="flex-start"
alignItems="flex-start"
>
<Grid item>
<Typography variant="h5">
{object.metadata?.name ?? 'unknown name'}
</Typography>
</Grid>
<Grid item>
<Typography color="textSecondary" variant="body1">
{kind}
</Typography>
</Grid>
</Grid>
<IconButton
key="dismiss"
title="Close the drawer"
onClick={e => toggleDrawer(e, false)}
color="inherit"
>
<Close className={classes.icon} />
</IconButton>
</div>
<div className={classes.options}>
<FormControlLabel
control={
<Switch
checked={isYaml}
onChange={event => {
setIsYaml(event.target.checked);
}}
name="YAML"
/>
}
label="YAML"
/>
</div>
<div className={classes.content}>
{isYaml && <CodeSnippet language="yaml" text={jsYaml.dump(object)} />}
{!isYaml && <StructuredMetadataTable metadata={renderObject(object)} />}
</div>
</>
);
};
@@ -0,0 +1,91 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import * as pod from './__fixtures__/pod.json';
import * as crashingPod from './__fixtures__/crashing-pod.json';
import { wrapInTestApp } from '@backstage/test-utils';
import { PodDrawer } from './PodDrawer';
describe('PodDrawer', () => {
it('should render pod', async () => {
const { getByText, getAllByText } = render(
wrapInTestApp(<PodDrawer pod={pod as any} expanded />),
);
expect(getAllByText('dice-roller-6c8646bfd-2m5hv')).toHaveLength(2);
expect(getByText('Pod')).toBeInTheDocument();
expect(getByText('YAML')).toBeInTheDocument();
expect(getByText('Images')).toBeInTheDocument();
expect(getByText('nginx=nginx:1.14.2')).toBeInTheDocument();
expect(getByText('Phase')).toBeInTheDocument();
expect(getByText('Running')).toBeInTheDocument();
expect(getAllByText('Containers Ready')).toHaveLength(2);
expect(getByText('1/1')).toBeInTheDocument();
expect(getByText('Total Restarts')).toBeInTheDocument();
expect(getByText('0')).toBeInTheDocument();
expect(getByText('Container Statuses')).toBeInTheDocument();
expect(getByText('OK')).toBeInTheDocument();
expect(getByText('Initialized')).toBeInTheDocument();
expect(getByText('Ready')).toBeInTheDocument();
expect(getByText('Pod Scheduled')).toBeInTheDocument();
expect(getAllByText('True')).toHaveLength(4);
expect(getByText('Exposed Ports')).toBeInTheDocument();
expect(getByText('Nginx:')).toBeInTheDocument();
expect(getByText('Container Port: 80')).toBeInTheDocument();
expect(getByText('Protocol: TCP')).toBeInTheDocument();
});
it('should render crashing pod', async () => {
const { getByText, getAllByText } = render(
wrapInTestApp(<PodDrawer pod={crashingPod as any} expanded />),
);
expect(getAllByText('dice-roller-canary-7d64cd756c-55rfq')).toHaveLength(2);
expect(getByText('Pod')).toBeInTheDocument();
expect(getByText('YAML')).toBeInTheDocument();
expect(getByText('Images')).toBeInTheDocument();
expect(getByText('nginx=nginx:1.14.2')).toBeInTheDocument();
expect(getByText('other-side-car=nginx:1.14.2')).toBeInTheDocument();
expect(getByText('side-car=nginx:1.14.2')).toBeInTheDocument();
expect(getByText('Phase')).toBeInTheDocument();
expect(getByText('Running')).toBeInTheDocument();
expect(getAllByText('Containers Ready')).toHaveLength(2);
expect(getByText('1/3')).toBeInTheDocument();
expect(getByText('Total Restarts')).toBeInTheDocument();
expect(getByText('76')).toBeInTheDocument();
expect(getByText('Container Statuses')).toBeInTheDocument();
expect(getByText('Container: side-car')).toBeInTheDocument();
expect(getByText('Container: other-side-car')).toBeInTheDocument();
expect(getAllByText('CrashLoopBackOff')).toHaveLength(2);
expect(getByText('Initialized')).toBeInTheDocument();
expect(getByText('Ready')).toBeInTheDocument();
expect(getByText('Pod Scheduled')).toBeInTheDocument();
expect(getAllByText('True')).toHaveLength(2);
expect(getAllByText('False')).toHaveLength(2);
expect(
getAllByText('containers with unready status: [side-car other-side-car]'),
).toHaveLength(2);
expect(getByText('Exposed Ports')).toBeInTheDocument();
expect(getAllByText('Protocol: TCP')).toHaveLength(3);
expect(getByText('Nginx:')).toBeInTheDocument();
expect(getByText('Container Port: 80')).toBeInTheDocument();
expect(getByText('Side Car:')).toBeInTheDocument();
expect(getByText('Container Port: 81')).toBeInTheDocument();
expect(getByText('Other Side Car:')).toBeInTheDocument();
expect(getByText('Container Port: 82')).toBeInTheDocument();
});
});
+69
View File
@@ -0,0 +1,69 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { V1Pod } from '@kubernetes/client-node';
import {
containersReady,
containerStatuses,
totalRestarts,
imageChips,
renderCondition,
} from '../../utils/pod';
import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer';
export const PodDrawer = ({
pod,
expanded,
}: {
pod: V1Pod;
expanded?: boolean;
}) => {
return (
<KubernetesDrawer
object={pod}
expanded={expanded}
kind="Pod"
renderObject={(pod: V1Pod) => {
const phase = pod.status?.phase ?? 'unknown';
const ports =
pod.spec?.containers?.map(c => {
return {
[c.name]: c.ports,
};
}) ?? 'N/A';
const conditions = (pod.status?.conditions ?? [])
.map(renderCondition)
.reduce((accum, next) => {
accum[next[0]] = next[1];
return accum;
}, {} as { [key: string]: React.ReactNode });
return {
images: imageChips(pod),
phase: phase,
'Containers Ready': containersReady(pod),
'Total Restarts': totalRestarts(pod),
'Container Statuses': containerStatuses(pod),
...conditions,
'Exposed ports': ports,
};
}}
/>
);
};
@@ -0,0 +1,67 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import * as pod from './__fixtures__/pod.json';
import * as crashingPod from './__fixtures__/crashing-pod.json';
import { wrapInTestApp } from '@backstage/test-utils';
import { PodsTable } from './PodsTable';
describe('PodsTable', () => {
it('should render pod', async () => {
const { getByText } = render(
wrapInTestApp(<PodsTable pods={[pod as any]} />),
);
// titles
expect(getByText('name')).toBeInTheDocument();
expect(getByText('phase')).toBeInTheDocument();
expect(getByText('containers ready')).toBeInTheDocument();
expect(getByText('total restarts')).toBeInTheDocument();
expect(getByText('status')).toBeInTheDocument();
// values
expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument();
expect(getByText('Running')).toBeInTheDocument();
expect(getByText('1/1')).toBeInTheDocument();
expect(getByText('0')).toBeInTheDocument();
expect(getByText('OK')).toBeInTheDocument();
});
it('should render crashing pod', async () => {
const { getByText, getAllByText } = render(
wrapInTestApp(<PodsTable pods={[crashingPod as any]} />),
);
// titles
expect(getByText('name')).toBeInTheDocument();
expect(getByText('phase')).toBeInTheDocument();
expect(getByText('containers ready')).toBeInTheDocument();
expect(getByText('total restarts')).toBeInTheDocument();
expect(getByText('status')).toBeInTheDocument();
// values
expect(
getByText('dice-roller-canary-7d64cd756c-55rfq'),
).toBeInTheDocument();
expect(getByText('Running')).toBeInTheDocument();
expect(getByText('1/3')).toBeInTheDocument();
expect(getByText('76')).toBeInTheDocument();
expect(getByText('Container: side-car')).toBeInTheDocument();
expect(getByText('Container: other-side-car')).toBeInTheDocument();
expect(getAllByText('CrashLoopBackOff')).toHaveLength(2);
});
});
+74
View File
@@ -0,0 +1,74 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { Table, TableColumn } from '@backstage/core';
import { V1Pod } from '@kubernetes/client-node';
import { PodDrawer } from './PodDrawer';
import {
containersReady,
containerStatuses,
totalRestarts,
} from '../../utils/pod';
const columns: TableColumn<V1Pod>[] = [
{
title: 'name',
highlight: true,
render: (pod: V1Pod) => <PodDrawer pod={pod} />,
},
{
title: 'phase',
render: (pod: V1Pod) => pod.status?.phase ?? 'unknown',
},
{
title: 'containers ready',
align: 'center',
render: containersReady,
},
{
title: 'total restarts',
align: 'center',
render: totalRestarts,
type: 'numeric',
},
{
title: 'status',
render: containerStatuses,
},
];
type DeploymentTablesProps = {
pods: V1Pod[];
children?: React.ReactNode;
};
export const PodsTable = ({ pods }: DeploymentTablesProps) => {
const tableStyle: React.CSSProperties = {
minWidth: '0',
width: '100%',
};
return (
<div style={tableStyle}>
<Table
options={{ paging: true, search: false }}
data={pods}
columns={columns}
/>
</div>
);
};
@@ -0,0 +1,233 @@
{
"metadata": {
"creationTimestamp": "2020-09-25T10:34:01.000Z",
"generateName": "dice-roller-canary-7d64cd756c-",
"labels": {
"app": "dice-roller-canary",
"backstage.io/kubernetes-id": "dice-roller",
"pod-template-hash": "7d64cd756c"
},
"name": "dice-roller-canary-7d64cd756c-55rfq",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "dice-roller-canary-7d64cd756c",
"uid": "9208395b-a9a7-4e46-b881-6a189f7fbdb0"
}
],
"resourceVersion": "620452",
"selfLink": "/api/v1/namespaces/default/pods/dice-roller-canary-7d64cd756c-55rfq",
"uid": "65ad28e3-5d51-4b4b-9bf8-4cb069803034"
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "side-car",
"ports": [
{
"containerPort": 81,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "other-side-car",
"ports": [
{
"containerPort": 82,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "minikube",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-5gctn",
"secret": {
"defaultMode": 420,
"secretName": "default-token-5gctn"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T10:34:01.000Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T14:18:53.000Z",
"message": "containers with unready status: [side-car other-side-car]",
"reason": "ContainersNotReady",
"status": "False",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T14:18:53.000Z",
"message": "containers with unready status: [side-car other-side-car]",
"reason": "ContainersNotReady",
"status": "False",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T10:34:01.000Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://6ce15178d114a85f3d2e832de45c3355ab5b71ed5f4d4d225ee1c83bf07f69d9",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {},
"name": "nginx",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2020-09-25T10:34:01.000Z"
}
}
},
{
"containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {
"terminated": {
"containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4",
"exitCode": 1,
"finishedAt": "2020-09-25T14:18:52.000Z",
"reason": "Error",
"startedAt": "2020-09-25T14:18:50.000Z"
}
},
"name": "other-side-car",
"ready": false,
"restartCount": 38,
"started": false,
"state": {
"waiting": {
"message": "back-off 5m0s restarting failed container=other-side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)",
"reason": "CrashLoopBackOff"
}
}
},
{
"containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {
"terminated": {
"containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb",
"exitCode": 1,
"finishedAt": "2020-09-25T14:18:52.000Z",
"reason": "Error",
"startedAt": "2020-09-25T14:18:50.000Z"
}
},
"name": "side-car",
"ready": false,
"restartCount": 38,
"started": false,
"state": {
"waiting": {
"message": "back-off 5m0s restarting failed container=side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)",
"reason": "CrashLoopBackOff"
}
}
}
],
"hostIP": "192.168.64.2",
"phase": "Running",
"podIP": "172.17.0.16",
"podIPs": [
{
"ip": "172.17.0.16"
}
],
"qosClass": "BestEffort",
"startTime": "2020-09-25T10:34:01.000Z"
}
}
@@ -0,0 +1,139 @@
{
"metadata": {
"creationTimestamp": "2020-09-25T09:58:50.000Z",
"generateName": "dice-roller-6c8646bfd-",
"labels": {
"app": "dice-roller",
"backstage.io/kubernetes-id": "dice-roller",
"pod-template-hash": "6c8646bfd"
},
"name": "dice-roller-6c8646bfd-2m5hv",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "dice-roller-6c8646bfd",
"uid": "5126c354-4310-4e23-a9e4-c9b87cb69792"
}
],
"resourceVersion": "593216",
"selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-2m5hv",
"uid": "aadb71c0-36fa-43e3-b38a-162f134d4359"
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "minikube",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-5gctn",
"secret": {
"defaultMode": 420,
"secretName": "default-token-5gctn"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:50.000Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:55.000Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:55.000Z",
"status": "True",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:50.000Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://aa4489297c34c48bb33c18474a8d2b33854a82ed42155680b259f635f556ce70",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {},
"name": "nginx",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2020-09-25T09:58:53.000Z"
}
}
}
],
"hostIP": "192.168.64.2",
"phase": "Running",
"podIP": "172.17.0.11",
"podIPs": [
{
"ip": "172.17.0.11"
}
],
"qosClass": "BestEffort",
"startTime": "2020-09-25T09:58:50.000Z"
}
}
@@ -13,4 +13,5 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Services } from './Services';
export { PodDrawer } from './PodDrawer';
export { PodsTable } from './PodsTable';
@@ -1,54 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { render } from '@testing-library/react';
import { Services } from './Services';
import * as servicesFixture from './__fixtures__/services.json';
import { wrapInTestApp } from '@backstage/test-utils';
describe('Services', () => {
it('should render 2 services', async () => {
const { getByText, getAllByText } = render(
wrapInTestApp(<Services services={(servicesFixture as any).default} />),
);
// common elements
expect(getAllByText('Service')).toHaveLength(2);
expect(getAllByText('Ports')).toHaveLength(2);
expect(getAllByText('Type')).toHaveLength(2);
expect(getAllByText('Protocol: TCP')).toHaveLength(3);
// service 1
expect(getByText('dice-roller')).toBeInTheDocument();
expect(getByText('ClusterIP')).toBeInTheDocument();
expect(getByText('Name: port1')).toBeInTheDocument();
expect(getByText('Port: 80')).toBeInTheDocument();
expect(getByText('Target Port: 9376')).toBeInTheDocument();
expect(getByText('Name: port1')).toBeInTheDocument();
expect(getByText('Port: 81')).toBeInTheDocument();
expect(getByText('Target Port: 9377')).toBeInTheDocument();
expect(getByText('10.102.223.105')).toBeInTheDocument();
// service 2
expect(getByText('dice-roller-lb')).toBeInTheDocument();
expect(getByText('LoadBalancer')).toBeInTheDocument();
expect(getByText('Node Port: 32276')).toBeInTheDocument();
expect(getByText('Port: 8765')).toBeInTheDocument();
expect(getByText('Target Port: 9378')).toBeInTheDocument();
});
});
@@ -1,62 +0,0 @@
/*
* Copyright 2020 Spotify AB
*
* 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 React from 'react';
import { Grid } from '@material-ui/core';
import { V1Service } from '@kubernetes/client-node';
import { InfoCard, StructuredMetadataTable } from '@backstage/core';
type ServicesProps = {
services: V1Service[];
children?: React.ReactNode;
};
export const Services = ({ services }: ServicesProps) => {
return (
<Grid container>
{services.map((s, i) => {
const metadata: any = {};
if (s.status?.loadBalancer?.ingress?.length ?? -1 > 0) {
metadata.loadbalancer = s.status?.loadBalancer;
}
if (s.spec?.type === 'ClusterIP') {
metadata.clusterIP = s.spec.clusterIP;
}
return (
<Grid item key={i}>
<InfoCard
title={s.metadata?.name ?? 'un-named service'}
subheader="Service"
>
<div>
<StructuredMetadataTable
metadata={{
type: s.spec?.type,
ports: s.spec?.ports,
...metadata,
}}
/>
</div>
</InfoCard>
</Grid>
);
})}
</Grid>
);
};
@@ -1,164 +0,0 @@
[
{
"metadata": {
"annotations": {
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"name\":\"port1\",\"port\":80,\"protocol\":\"TCP\",\"targetPort\":9376},{\"name\":\"port2\",\"port\":81,\"protocol\":\"TCP\",\"targetPort\":9377}],\"selector\":{\"app\":\"dice-roller\"}}}\n"
},
"creationTimestamp": "2020-09-23T12:00:55.000Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {}
},
"f:labels": {
".": {},
"f:backstage.io/kubernetes-id": {}
}
},
"f:spec": {
"f:ports": {
".": {},
"k:{\"port\":80,\"protocol\":\"TCP\"}": {
".": {},
"f:name": {},
"f:port": {},
"f:protocol": {},
"f:targetPort": {}
},
"k:{\"port\":81,\"protocol\":\"TCP\"}": {
".": {},
"f:name": {},
"f:port": {},
"f:protocol": {},
"f:targetPort": {}
}
},
"f:selector": {
".": {},
"f:app": {}
},
"f:sessionAffinity": {},
"f:type": {}
}
},
"manager": "kubectl",
"operation": "Update",
"time": "2020-09-28T08:50:11.000Z"
}
],
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "665838",
"selfLink": "/api/v1/namespaces/default/services/dice-roller",
"uid": "ae9aff92-a525-4bc9-82dc-a0537bf8034c"
},
"spec": {
"clusterIP": "10.102.223.105",
"ports": [
{
"name": "port1",
"port": 80,
"protocol": "TCP",
"targetPort": 9376
},
{
"name": "port2",
"port": 81,
"protocol": "TCP",
"targetPort": 9377
}
],
"selector": {
"app": "dice-roller"
},
"sessionAffinity": "None",
"type": "ClusterIP"
},
"status": {
"loadBalancer": {}
}
},
{
"metadata": {
"annotations": {
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller-lb\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"port\":8765,\"targetPort\":9376}],\"selector\":{\"app\":\"dice-roller\"},\"type\":\"LoadBalancer\"}}\n"
},
"creationTimestamp": "2020-09-28T08:51:21.000Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:annotations": {
".": {},
"f:kubectl.kubernetes.io/last-applied-configuration": {}
},
"f:labels": {
".": {},
"f:backstage.io/kubernetes-id": {}
}
},
"f:spec": {
"f:externalTrafficPolicy": {},
"f:ports": {
".": {},
"k:{\"port\":8765,\"protocol\":\"TCP\"}": {
".": {},
"f:port": {},
"f:protocol": {},
"f:targetPort": {}
}
},
"f:selector": {
".": {},
"f:app": {}
},
"f:sessionAffinity": {},
"f:type": {}
}
},
"manager": "kubectl",
"operation": "Update",
"time": "2020-09-28T08:51:21.000Z"
}
],
"name": "dice-roller-lb",
"namespace": "default",
"resourceVersion": "665998",
"selfLink": "/api/v1/namespaces/default/services/dice-roller-lb",
"uid": "5554da3b-2041-4403-8cf4-cd2ccae760f8"
},
"spec": {
"clusterIP": "10.99.205.233",
"externalTrafficPolicy": "Cluster",
"ports": [
{
"nodePort": 32276,
"port": 8765,
"protocol": "TCP",
"targetPort": 9378
}
],
"selector": {
"app": "dice-roller"
},
"sessionAffinity": "None",
"type": "LoadBalancer"
},
"status": {
"loadBalancer": {}
}
}
]
@@ -0,0 +1,119 @@
{
"metadata": {
"annotations": {
"deployment.kubernetes.io/revision": "3",
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller-canary\",\"namespace\":\"default\"},\"spec\":{\"replicas\":2,\"selector\":{\"matchLabels\":{\"app\":\"dice-roller-canary\"}},\"template\":{\"metadata\":{\"labels\":{\"app\":\"dice-roller-canary\",\"backstage.io/kubernetes-id\":\"dice-roller\"}},\"spec\":{\"containers\":[{\"image\":\"nginx:1.14.2\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]},{\"image\":\"nginx:1.14.2\",\"name\":\"side-car\",\"ports\":[{\"containerPort\":81}]},{\"image\":\"nginx:1.14.2\",\"name\":\"other-side-car\",\"ports\":[{\"containerPort\":82}]}]}}}}\n"
},
"creationTimestamp": "2020-09-25T09:02:53.000Z",
"generation": 3,
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"name": "dice-roller-canary",
"namespace": "default",
"resourceVersion": "620480",
"selfLink": "/apis/apps/v1/namespaces/default/deployments/dice-roller-canary",
"uid": "0b6ae80f-999b-40e9-b116-ea925f0ed07b"
},
"spec": {
"progressDeadlineSeconds": 600,
"replicas": 2,
"revisionHistoryLimit": 10,
"selector": {
"matchLabels": {
"app": "dice-roller-canary"
}
},
"strategy": {
"rollingUpdate": {
"maxSurge": "25%",
"maxUnavailable": "25%"
},
"type": "RollingUpdate"
},
"template": {
"metadata": {
"creationTimestamp": null,
"labels": {
"app": "dice-roller-canary",
"backstage.io/kubernetes-id": "dice-roller"
}
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File"
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "side-car",
"ports": [
{
"containerPort": 81,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File"
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "other-side-car",
"ports": [
{
"containerPort": 82,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File"
}
],
"dnsPolicy": "ClusterFirst",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"terminationGracePeriodSeconds": 30
}
}
},
"status": {
"conditions": [
{
"lastTransitionTime": "2020-09-25T09:02:53.000Z",
"lastUpdateTime": "2020-09-25T10:34:04.000Z",
"message": "ReplicaSet \"dice-roller-canary-7d64cd756c\" has successfully progressed.",
"reason": "NewReplicaSetAvailable",
"status": "True",
"type": "Progressing"
},
{
"lastTransitionTime": "2020-09-25T13:48:06.000Z",
"lastUpdateTime": "2020-09-25T13:48:06.000Z",
"message": "Deployment does not have minimum availability.",
"reason": "MinimumReplicasUnavailable",
"status": "False",
"type": "Available"
}
],
"observedGeneration": 3,
"replicas": 2,
"unavailableReplicas": 2,
"updatedReplicas": 2
}
}
@@ -0,0 +1,92 @@
{
"metadata": {
"annotations": {
"deployment.kubernetes.io/revision": "2",
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"replicas\":10,\"selector\":{\"matchLabels\":{\"app\":\"dice-roller\"}},\"template\":{\"metadata\":{\"labels\":{\"app\":\"dice-roller\",\"backstage.io/kubernetes-id\":\"dice-roller\"}},\"spec\":{\"containers\":[{\"image\":\"nginx:1.14.2\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]}]}}}}\n"
},
"creationTimestamp": "2020-09-23T12:00:55.000Z",
"generation": 3,
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "593230",
"selfLink": "/apis/apps/v1/namespaces/default/deployments/dice-roller",
"uid": "7551e949-42d1-4061-83c5-9da107186e47"
},
"spec": {
"progressDeadlineSeconds": 600,
"replicas": 10,
"revisionHistoryLimit": 10,
"selector": {
"matchLabels": {
"app": "dice-roller"
}
},
"strategy": {
"rollingUpdate": {
"maxSurge": "25%",
"maxUnavailable": "25%"
},
"type": "RollingUpdate"
},
"template": {
"metadata": {
"creationTimestamp": null,
"labels": {
"app": "dice-roller",
"backstage.io/kubernetes-id": "dice-roller"
}
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File"
}
],
"dnsPolicy": "ClusterFirst",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"terminationGracePeriodSeconds": 30
}
}
},
"status": {
"availableReplicas": 10,
"conditions": [
{
"lastTransitionTime": "2020-09-23T12:00:55.000Z",
"lastUpdateTime": "2020-09-24T11:39:28.000Z",
"message": "ReplicaSet \"dice-roller-6c8646bfd\" has successfully progressed.",
"reason": "NewReplicaSetAvailable",
"status": "True",
"type": "Progressing"
},
{
"lastTransitionTime": "2020-09-25T09:58:55.000Z",
"lastUpdateTime": "2020-09-25T09:58:55.000Z",
"message": "Deployment has minimum availability.",
"reason": "MinimumReplicasAvailable",
"status": "True",
"type": "Available"
}
],
"observedGeneration": 3,
"readyReplicas": 10,
"replicas": 10,
"updatedReplicas": 10
}
}
@@ -0,0 +1,32 @@
{
"metadata": {
"annotations": {
"autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"True\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"SucceededGetScale\",\"message\":\"the HPA controller was able to get the target's current scale\"},{\"type\":\"ScalingActive\",\"status\":\"False\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"FailedGetResourceMetric\",\"message\":\"the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)\"}]",
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"autoscaling/v1\",\"kind\":\"HorizontalPodAutoscaler\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"maxReplicas\":15,\"minReplicas\":10,\"scaleTargetRef\":{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"name\":\"dice-roller\"},\"targetCPUUtilizationPercentage\":50}}\n"
},
"creationTimestamp": "2020-09-28T13:28:00.000Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "698957",
"selfLink": "/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/dice-roller",
"uid": "a70c8a90-5605-4d7d-adea-05cfb8d9d446"
},
"spec": {
"maxReplicas": 15,
"minReplicas": 10,
"scaleTargetRef": {
"apiVersion": "apps/v1",
"kind": "Deployment",
"name": "dice-roller"
},
"targetCPUUtilizationPercentage": 50
},
"status": {
"currentReplicas": 13,
"desiredReplicas": 14,
"currentCPUUtilizationPercentage": 30
}
}
@@ -0,0 +1,32 @@
{
"metadata": {
"annotations": {
"autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"True\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"SucceededGetScale\",\"message\":\"the HPA controller was able to get the target's current scale\"},{\"type\":\"ScalingActive\",\"status\":\"False\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"FailedGetResourceMetric\",\"message\":\"the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)\"}]",
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"autoscaling/v1\",\"kind\":\"HorizontalPodAutoscaler\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"maxReplicas\":15,\"minReplicas\":10,\"scaleTargetRef\":{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"name\":\"dice-roller\"},\"targetCPUUtilizationPercentage\":50}}\n"
},
"creationTimestamp": "2020-09-28T13:28:00.000Z",
"labels": {
"backstage.io/kubernetes-id": "dice-roller"
},
"name": "dice-roller",
"namespace": "default",
"resourceVersion": "698957",
"selfLink": "/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/dice-roller",
"uid": "a70c8a90-5605-4d7d-adea-05cfb8d9d446"
},
"spec": {
"maxReplicas": 10,
"minReplicas": 5,
"scaleTargetRef": {
"apiVersion": "apps/v1",
"kind": "Deployment",
"name": "dice-roller"
},
"targetCPUUtilizationPercentage": 70
},
"status": {
"currentReplicas": 10,
"desiredReplicas": 10,
"currentCPUUtilizationPercentage": 100
}
}
@@ -0,0 +1,233 @@
{
"metadata": {
"creationTimestamp": "2020-09-25T10:34:01.000Z",
"generateName": "dice-roller-canary-7d64cd756c-",
"labels": {
"app": "dice-roller-canary",
"backstage.io/kubernetes-id": "dice-roller",
"pod-template-hash": "7d64cd756c"
},
"name": "dice-roller-canary-7d64cd756c-55rfq",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "dice-roller-canary-7d64cd756c",
"uid": "9208395b-a9a7-4e46-b881-6a189f7fbdb0"
}
],
"resourceVersion": "620452",
"selfLink": "/api/v1/namespaces/default/pods/dice-roller-canary-7d64cd756c-55rfq",
"uid": "65ad28e3-5d51-4b4b-9bf8-4cb069803034"
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "side-car",
"ports": [
{
"containerPort": 81,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
},
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "other-side-car",
"ports": [
{
"containerPort": 82,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "minikube",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-5gctn",
"secret": {
"defaultMode": 420,
"secretName": "default-token-5gctn"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T10:34:01.000Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T14:18:53.000Z",
"message": "containers with unready status: [side-car other-side-car]",
"reason": "ContainersNotReady",
"status": "False",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T14:18:53.000Z",
"message": "containers with unready status: [side-car other-side-car]",
"reason": "ContainersNotReady",
"status": "False",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T10:34:01.000Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://6ce15178d114a85f3d2e832de45c3355ab5b71ed5f4d4d225ee1c83bf07f69d9",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {},
"name": "nginx",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2020-09-25T10:34:01.000Z"
}
}
},
{
"containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {
"terminated": {
"containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4",
"exitCode": 1,
"finishedAt": "2020-09-25T14:18:52.000Z",
"reason": "Error",
"startedAt": "2020-09-25T14:18:50.000Z"
}
},
"name": "other-side-car",
"ready": false,
"restartCount": 38,
"started": false,
"state": {
"waiting": {
"message": "back-off 5m0s restarting failed container=other-side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)",
"reason": "CrashLoopBackOff"
}
}
},
{
"containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {
"terminated": {
"containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb",
"exitCode": 1,
"finishedAt": "2020-09-25T14:18:52.000Z",
"reason": "Error",
"startedAt": "2020-09-25T14:18:50.000Z"
}
},
"name": "side-car",
"ready": false,
"restartCount": 38,
"started": false,
"state": {
"waiting": {
"message": "back-off 5m0s restarting failed container=side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)",
"reason": "CrashLoopBackOff"
}
}
}
],
"hostIP": "192.168.64.2",
"phase": "Running",
"podIP": "172.17.0.16",
"podIPs": [
{
"ip": "172.17.0.16"
}
],
"qosClass": "BestEffort",
"startTime": "2020-09-25T10:34:01.000Z"
}
}
@@ -0,0 +1,168 @@
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"creationTimestamp": "2021-01-06T14:33:54Z",
"generateName": "dice-roller-bad-cm-855bf85464-",
"labels": {
"app": "dice-roller-bad-cm",
"backstage.io/kubernetes-id": "dice-roller",
"pod-template-hash": "855bf85464"
},
"name": "dice-roller-bad-cm-855bf85464-mg6xb",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "dice-roller-bad-cm-855bf85464",
"uid": "9bc2a418-60eb-4dfc-9748-78cf49ea9863"
}
],
"resourceVersion": "2457755284",
"selfLink": "/api/v1/namespaces/default/pods/dice-roller-bad-cm-855bf85464-mg6xb",
"uid": "5f257d3c-a16d-4ef1-9dc9-d11e321a640a"
},
"spec": {
"containers": [
{
"env": [
{
"name": "SOME_ENV_VAR",
"valueFrom": {
"configMapKeyRef": {
"key": "some-key",
"name": "some-cm"
}
}
}
],
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {
"limits": {
"cpu": "500m",
"memory": "128Mi"
},
"requests": {
"cpu": "50m",
"memory": "64Mi"
}
},
"securityContext": {
"allowPrivilegeEscalation": false
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-dbkkb",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "node1",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-dbkkb",
"secret": {
"defaultMode": 420,
"secretName": "default-token-dbkkb"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2021-01-06T14:33:54Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-01-06T14:33:54Z",
"message": "containers with unready status: [nginx]",
"reason": "ContainersNotReady",
"status": "False",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-01-06T14:33:54Z",
"message": "containers with unready status: [nginx]",
"reason": "ContainersNotReady",
"status": "False",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-01-06T14:33:54Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"image": "nginx:1.14.2",
"imageID": "",
"lastState": {},
"name": "nginx",
"ready": false,
"restartCount": 0,
"started": false,
"state": {
"waiting": {
"message": "configmap \"some-cm\" not found",
"reason": "CreateContainerConfigError"
}
}
}
],
"hostIP": "10.1.33.73",
"phase": "Pending",
"podIP": "10.1.115.15",
"podIPs": [
{
"ip": "10.1.115.15"
}
],
"qosClass": "Burstable",
"startTime": "2021-01-06T14:33:54Z"
}
}
@@ -0,0 +1,139 @@
{
"metadata": {
"creationTimestamp": "2020-09-25T09:58:50.000Z",
"generateName": "dice-roller-6c8646bfd-",
"labels": {
"app": "dice-roller",
"backstage.io/kubernetes-id": "dice-roller",
"pod-template-hash": "6c8646bfd"
},
"name": "dice-roller-6c8646bfd-2m5hv",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "dice-roller-6c8646bfd",
"uid": "5126c354-4310-4e23-a9e4-c9b87cb69792"
}
],
"resourceVersion": "593216",
"selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-2m5hv",
"uid": "aadb71c0-36fa-43e3-b38a-162f134d4359"
},
"spec": {
"containers": [
{
"image": "nginx:1.14.2",
"imagePullPolicy": "IfNotPresent",
"name": "nginx",
"ports": [
{
"containerPort": 80,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-5gctn",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "minikube",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-5gctn",
"secret": {
"defaultMode": 420,
"secretName": "default-token-5gctn"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:50.000Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:55.000Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:55.000Z",
"status": "True",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2020-09-25T09:58:50.000Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://aa4489297c34c48bb33c18474a8d2b33854a82ed42155680b259f635f556ce70",
"image": "nginx:1.14.2",
"imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d",
"lastState": {},
"name": "nginx",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2020-09-25T09:58:53.000Z"
}
}
}
],
"hostIP": "192.168.64.2",
"phase": "Running",
"podIP": "172.17.0.11",
"podIPs": [
{
"ip": "172.17.0.11"
}
],
"qosClass": "BestEffort",
"startTime": "2020-09-25T09:58:50.000Z"
}
}
@@ -0,0 +1,70 @@
/*
* Copyright 2020 Spotify AB
*
* 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 {
DetectedError,
ErrorDetectable,
ErrorDetectableKind,
ErrorMapper,
} from './types';
// Run through the each error mapper for each object
// returning a deduplicated (mostly) result
export const detectErrorsInObjects = <T extends ErrorDetectable>(
objects: T[],
kind: ErrorDetectableKind,
clusterName: string,
errorMappers: ErrorMapper<T>[],
): DetectedError[] => {
// Build up a map of errors
// key: the joined message produced by an error
// value: the error
const errors = new Map<string, DetectedError>();
for (const object of objects) {
for (const errorMapper of errorMappers) {
if (errorMapper.errorExists(object)) {
const message = errorMapper.messageAccessor(object);
// TODO This is not perfect as errors with uuid/hashes/date/times will not be caught by this
const dedupKey = message.join('');
const value = errors.get(dedupKey);
const name = object.metadata?.name ?? 'unknown';
if (value !== undefined) {
// This gets translated into the Chip "+5 others"
// in the ErrorReporting component
// but we need to keep the names so we can easily
// find which objects owns the error later
value.names.push(name);
errors.set(dedupKey, value);
} else {
errors.set(dedupKey, {
cluster: clusterName,
kind: kind,
names: [name],
message: message,
severity: errorMapper.severity,
});
}
}
}
}
return Array.from(errors.values());
};
@@ -0,0 +1,49 @@
import { DetectedError, ErrorMapper } from './types';
import { V1Deployment } from '@kubernetes/client-node';
import { detectErrorsInObjects } from './common';
/*
* Copyright 2020 Spotify AB
*
* 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.
*/
const deploymentErrorMappers: ErrorMapper<V1Deployment>[] = [
{
// this is probably important
severity: 6,
errorExplanation: 'condition-message-present',
errorExists: deployment => {
return (deployment.status?.conditions ?? [])
.filter(c => c.status === 'False')
.some(c => c.message !== undefined);
},
messageAccessor: deployment => {
return (deployment.status?.conditions ?? [])
.filter(c => c.status === 'False')
.filter(c => c.message !== undefined)
.map(c => c.message ?? '');
},
},
];
export const detectErrorsInDeployments = (
deployments: V1Deployment[],
clusterName: string,
): DetectedError[] =>
detectErrorsInObjects(
deployments,
'Deployment',
clusterName,
deploymentErrorMappers,
);
@@ -0,0 +1,282 @@
/*
* Copyright 2020 Spotify AB
*
* 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 {
V1Pod,
V1Deployment,
V1HorizontalPodAutoscaler,
} from '@kubernetes/client-node';
import { detectErrors } from './error-detection';
import * as healthyPod from './__fixtures__/pod.json';
import * as podMissingCm from './__fixtures__/pod-missing-cm.json';
import * as crashingPod from './__fixtures__/pod-crashing.json';
import * as healthyDeploy from './__fixtures__/deploy-healthy.json';
import * as failingDeploy from './__fixtures__/deploy-bad.json';
import * as healthyHpa from './__fixtures__/hpa-healthy.json';
import * as maxedOutHpa from './__fixtures__/hpa-maxed-out.json';
import {
FetchResponse,
ObjectsByEntityResponse,
} from '@backstage/plugin-kubernetes-backend';
const CLUSTER_NAME = 'cluster-a';
const oneItem = (value: FetchResponse): ObjectsByEntityResponse => {
return {
items: [
{
cluster: { name: CLUSTER_NAME },
errors: [],
resources: [value],
},
],
};
};
const onePod = (pod: V1Pod): ObjectsByEntityResponse => {
return oneItem({
type: 'pods',
resources: [pod],
});
};
const oneDeployment = (deployment: V1Deployment): ObjectsByEntityResponse => {
return oneItem({
type: 'deployments',
resources: [deployment],
});
};
const oneHpa = (hpa: V1HorizontalPodAutoscaler): ObjectsByEntityResponse => {
return oneItem({
type: 'horizontalpodautoscalers',
resources: [hpa],
});
};
describe('detectErrors', () => {
it('should return errors from different clusters', () => {
const result = detectErrors({
items: [
{
cluster: { name: 'cluster-a' },
errors: [],
resources: [
{
type: 'pods',
resources: [crashingPod as any],
},
],
},
{
cluster: { name: 'cluster-b' },
errors: [],
resources: [
{
type: 'horizontalpodautoscalers',
resources: [maxedOutHpa as any],
},
],
},
{
cluster: { name: 'cluster-c' },
errors: [],
resources: [
{
type: 'deployments',
resources: [healthyDeploy as any],
},
],
},
],
});
expect(result.size).toBe(3);
const errorsFromClusterA = result.get('cluster-a');
const errorsFromClusterB = result.get('cluster-b');
const errorsFromClusterC = result.get('cluster-c');
expect(errorsFromClusterA).toBeDefined();
expect(errorsFromClusterA).toHaveLength(4);
expect(errorsFromClusterB).toBeDefined();
expect(errorsFromClusterB).toHaveLength(1);
expect(errorsFromClusterC).toBeDefined();
expect(errorsFromClusterC).toHaveLength(0);
});
it('should detect no errors in healthy pod', () => {
const result = detectErrors(onePod(healthyPod as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(0);
});
it('should detect errors in crashing pod', () => {
const result = detectErrors(onePod(crashingPod as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(4);
const [err1, err2, err3, err4] = errors ?? [];
expect(err1).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: [
'container=other-side-car restarted 38 times',
'container=side-car restarted 38 times',
],
names: ['dice-roller-canary-7d64cd756c-55rfq'],
severity: 4,
});
expect(err2).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: [
'containers with unready status: [side-car other-side-car]',
'containers with unready status: [side-car other-side-car]',
],
names: ['dice-roller-canary-7d64cd756c-55rfq'],
severity: 5,
});
expect(err3).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: [
'back-off 5m0s restarting failed container=other-side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)',
'back-off 5m0s restarting failed container=side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)',
],
names: ['dice-roller-canary-7d64cd756c-55rfq'],
severity: 6,
});
expect(err4).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: [
'container=other-side-car exited with error code (1)',
'container=side-car exited with error code (1)',
],
names: ['dice-roller-canary-7d64cd756c-55rfq'],
severity: 4,
});
});
it('should detect errors in pod with missing Config Map', () => {
const result = detectErrors(onePod(podMissingCm as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(2);
const [err1, err2] = errors ?? [];
expect(err1).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: [
'containers with unready status: [nginx]',
'containers with unready status: [nginx]',
],
names: ['dice-roller-bad-cm-855bf85464-mg6xb'],
severity: 5,
});
expect(err2).toStrictEqual({
cluster: 'cluster-a',
kind: 'Pod',
message: ['configmap "some-cm" not found'],
names: ['dice-roller-bad-cm-855bf85464-mg6xb'],
severity: 6,
});
});
it('should detect no errors in healthy deployment', () => {
const result = detectErrors(oneDeployment(healthyDeploy as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(0);
});
it('should detect in deployment which cant progress', () => {
const result = detectErrors(oneDeployment(failingDeploy as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(1);
const [err1] = errors ?? [];
expect(err1).toStrictEqual({
cluster: 'cluster-a',
kind: 'Deployment',
message: ['Deployment does not have minimum availability.'],
names: ['dice-roller-canary'],
severity: 6,
});
});
it('should detect no errors in healthy hpa', () => {
const result = detectErrors(oneHpa(healthyHpa as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(0);
});
it('should detect in maxed out hpa', () => {
const result = detectErrors(oneHpa(maxedOutHpa as any));
expect(result.size).toBe(1);
const errors = result.get(CLUSTER_NAME);
expect(errors).toBeDefined();
expect(errors).toHaveLength(1);
const [err1] = errors ?? [];
expect(err1).toStrictEqual({
cluster: 'cluster-a',
kind: 'HorizontalPodAutoscaler',
message: [
'Current number of replicas (10) is equal to the configured max number of replicas (10)',
],
names: ['dice-roller'],
severity: 8,
});
});
});
@@ -0,0 +1,58 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { DetectedError, DetectedErrorsByCluster } from './types';
import { ObjectsByEntityResponse } from '@backstage/plugin-kubernetes-backend';
import { groupResponses } from '../utils/response';
import { detectErrorsInPods } from './pods';
import { detectErrorsInDeployments } from './deployments';
import { detectErrorsInHpa } from './hpas';
// For each cluster try to find errors in each of the object types provided
// returning a map of cluster names to errors in that cluster
export const detectErrors = (
objects: ObjectsByEntityResponse,
): DetectedErrorsByCluster => {
const errors: DetectedErrorsByCluster = new Map<string, DetectedError[]>();
for (const clusterResponse of objects.items) {
let clusterErrors: DetectedError[] = [];
const groupedResponses = groupResponses(clusterResponse.resources);
clusterErrors = clusterErrors.concat(
detectErrorsInPods(groupedResponses.pods, clusterResponse.cluster.name),
);
clusterErrors = clusterErrors.concat(
detectErrorsInDeployments(
groupedResponses.deployments,
clusterResponse.cluster.name,
),
);
clusterErrors = clusterErrors.concat(
detectErrorsInHpa(
groupedResponses.horizontalPodAutoscalers,
clusterResponse.cluster.name,
),
);
errors.set(clusterResponse.cluster.name, clusterErrors);
}
return errors;
};
@@ -0,0 +1,50 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { V1HorizontalPodAutoscaler } from '@kubernetes/client-node';
import { DetectedError, ErrorMapper } from './types';
import { detectErrorsInObjects } from './common';
const hpaErrorMappers: ErrorMapper<V1HorizontalPodAutoscaler>[] = [
{
// this is probably important
severity: 8,
errorExplanation: 'hpa-max-current-replicas',
errorExists: hpa => {
return (hpa.spec?.maxReplicas ?? -1) === hpa.status?.currentReplicas;
},
messageAccessor: hpa => {
return [
`Current number of replicas (${
hpa.status?.currentReplicas
}) is equal to the configured max number of replicas (${
hpa.spec?.maxReplicas ?? -1
})`,
];
},
},
];
export const detectErrorsInHpa = (
hpas: V1HorizontalPodAutoscaler[],
clusterName: string,
): DetectedError[] =>
detectErrorsInObjects(
hpas,
'HorizontalPodAutoscaler',
clusterName,
hpaErrorMappers,
);
@@ -13,4 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { ConfigMaps } from './ConfigMaps';
export type { DetectedError, DetectedErrorsByCluster } from './types';
export { detectErrors } from './error-detection';
@@ -0,0 +1,95 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { V1Pod } from '@kubernetes/client-node';
import { totalRestarts } from '../utils/pod';
import { DetectedError, ErrorMapper } from './types';
import { detectErrorsInObjects } from './common';
const podErrorMappers: ErrorMapper<V1Pod>[] = [
{
severity: 5,
errorExplanation: 'status-message',
errorExists: pod => {
return pod.status?.message !== undefined;
},
messageAccessor: pod => {
return [pod.status?.message ?? ''];
},
},
{
severity: 4,
errorExplanation: 'containers-restarting',
errorExists: pod => {
// TODO magic number
return totalRestarts(pod) > 3;
},
messageAccessor: pod => {
return (pod.status?.containerStatuses ?? [])
.filter(cs => cs.restartCount > 0)
.map(cs => `container=${cs.name} restarted ${cs.restartCount} times`);
},
},
{
severity: 5,
errorExplanation: 'condition-message-present',
errorExists: pod => {
return (pod.status?.conditions ?? []).some(c => c.message !== undefined);
},
messageAccessor: pod => {
return (pod.status?.conditions ?? [])
.filter(c => c.message !== undefined)
.map(c => c.message ?? '');
},
},
{
severity: 6,
errorExplanation: 'container-waiting',
errorExists: pod => {
return (pod.status?.containerStatuses ?? []).some(
cs => cs.state?.waiting?.message !== undefined,
);
},
messageAccessor: pod => {
return (pod.status?.containerStatuses ?? [])
.filter(cs => cs.state?.waiting?.message !== undefined)
.map(cs => cs.state?.waiting?.message ?? '');
},
},
{
severity: 4,
errorExplanation: 'container-last-state-error',
errorExists: pod => {
return (pod.status?.containerStatuses ?? []).some(
cs => (cs.lastState?.terminated?.reason ?? '') === 'Error',
);
},
messageAccessor: pod => {
return (pod.status?.containerStatuses ?? [])
.filter(cs => (cs.lastState?.terminated?.reason ?? '') === 'Error')
.map(
cs =>
`container=${cs.name} exited with error code (${cs.lastState?.terminated?.exitCode})`,
);
},
},
];
export const detectErrorsInPods = (
pods: V1Pod[],
clusterName: string,
): DetectedError[] =>
detectErrorsInObjects(pods, 'Pod', clusterName, podErrorMappers);
@@ -0,0 +1,48 @@
/*
* Copyright 2020 Spotify AB
*
* 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.
*/
// Higher is more sever, but it's relative
import {
V1Deployment,
V1HorizontalPodAutoscaler,
V1Pod,
} from '@kubernetes/client-node';
export type ErrorSeverity = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
export type ErrorDetectable = V1Pod | V1Deployment | V1HorizontalPodAutoscaler;
export type ErrorDetectableKind =
| 'Pod'
| 'Deployment'
| 'HorizontalPodAutoscaler';
export type DetectedErrorsByCluster = Map<string, DetectedError[]>;
export interface DetectedError {
severity: ErrorSeverity;
cluster: string;
kind: ErrorDetectableKind;
names: string[];
message: string[];
}
export interface ErrorMapper<T extends ErrorDetectable> {
severity: ErrorSeverity;
errorExplanation: string;
errorExists: (object: T) => boolean;
messageAccessor: (object: T) => string[];
}
+17 -2
View File
@@ -14,10 +14,25 @@
* limitations under the License.
*/
import { V1Deployment, V1Pod, V1ReplicaSet } from '@kubernetes/client-node';
import {
V1Deployment,
V1Pod,
V1ReplicaSet,
V1HorizontalPodAutoscaler,
V1Service,
V1ConfigMap,
ExtensionsV1beta1Ingress,
} from '@kubernetes/client-node';
export interface DeploymentTriple {
export interface DeploymentResources {
pods: V1Pod[];
replicaSets: V1ReplicaSet[];
deployments: V1Deployment[];
horizontalPodAutoscalers: V1HorizontalPodAutoscaler[];
}
export interface GroupedResponses extends DeploymentResources {
services: V1Service[];
configMaps: V1ConfigMap[];
ingresses: ExtensionsV1beta1Ingress[];
}
+104
View File
@@ -0,0 +1,104 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { V1Pod, V1PodCondition } from '@kubernetes/client-node';
import React, { Fragment, ReactNode } from 'react';
import {
StatusAborted,
StatusError,
StatusOK,
SubvalueCell,
} from '@backstage/core';
import { Chip } from '@material-ui/core';
import { V1DeploymentCondition } from '@kubernetes/client-node/dist/gen/model/v1DeploymentCondition';
export const imageChips = (pod: V1Pod): ReactNode => {
const containerStatuses = pod.status?.containerStatuses ?? [];
const images = containerStatuses.map((cs, i) => {
return <Chip key={i} label={`${cs.name}=${cs.image}`} size="small" />;
});
return <div>{images}</div>;
};
export const containersReady = (pod: V1Pod): string => {
const containerStatuses = pod.status?.containerStatuses ?? [];
const containersReady = containerStatuses.filter(cs => cs.ready).length;
return `${containersReady}/${containerStatuses.length}`;
};
export const totalRestarts = (pod: V1Pod): number => {
const containerStatuses = pod.status?.containerStatuses ?? [];
return containerStatuses?.reduce((a, b) => a + b.restartCount, 0);
};
export const containerStatuses = (pod: V1Pod): ReactNode => {
const containerStatuses = pod.status?.containerStatuses ?? [];
const errors = containerStatuses.reduce((accum, next) => {
if (next.state === undefined) {
return accum;
}
const waiting = next.state.waiting;
const terminated = next.state.terminated;
const renderCell = (reason: string | undefined) => (
<Fragment key={`${pod.metadata?.name}-${next.name}`}>
<SubvalueCell
value={<StatusError>Container: {next.name}</StatusError>}
subvalue={reason}
/>
<br />
</Fragment>
);
if (waiting) {
accum.push(renderCell(waiting.reason));
}
if (terminated) {
accum.push(renderCell(terminated.reason));
}
return accum;
}, [] as React.ReactNode[]);
if (errors.length === 0) {
return <StatusOK>OK</StatusOK>;
}
return errors;
};
export const renderCondition = (
condition: V1PodCondition | V1DeploymentCondition,
): [string, ReactNode] => {
const status = condition.status;
if (status === 'True') {
return [condition.type, <StatusOK>True</StatusOK>];
} else if (status === 'False') {
return [
condition.type,
<SubvalueCell
value={<StatusError>False</StatusError>}
subvalue={condition.message ?? ''}
/>,
];
}
return [condition.type, <StatusAborted />];
};
+62
View File
@@ -0,0 +1,62 @@
/*
* Copyright 2020 Spotify AB
*
* 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 { FetchResponse } from '@backstage/plugin-kubernetes-backend';
import { GroupedResponses } from '../types/types';
// TODO this could probably be a lodash groupBy
export const groupResponses = (
fetchResponse: FetchResponse[],
): GroupedResponses => {
return fetchResponse.reduce(
(prev, next) => {
switch (next.type) {
case 'deployments':
prev.deployments.push(...next.resources);
break;
case 'pods':
prev.pods.push(...next.resources);
break;
case 'replicasets':
prev.replicaSets.push(...next.resources);
break;
case 'services':
prev.services.push(...next.resources);
break;
case 'configmaps':
prev.configMaps.push(...next.resources);
break;
case 'horizontalpodautoscalers':
prev.horizontalPodAutoscalers.push(...next.resources);
break;
case 'ingresses':
prev.ingresses.push(...next.resources);
break;
default:
}
return prev;
},
{
pods: [],
replicaSets: [],
deployments: [],
services: [],
configMaps: [],
horizontalPodAutoscalers: [],
ingresses: [],
} as GroupedResponses,
);
};