Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added kubernetes.v2 endpoint #350

Merged
merged 6 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/api.v2/routes/kubernetes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const AWSXRay = require('aws-xray-sdk');
const k8s = require('@kubernetes/client-node');
const getLogger = require('../../utils/getLogger');

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

const logger = getLogger();

module.exports = {
'kubernetes#event': async (req, res, next) => {
logger.log('received kubernetes event');
try {
const {
reason, message, type, involvedObject: { name, namespace },
} = req.body;
logger.log(`[${reason}] received ${type} kubernetes event: ${message} ${name} in ${namespace}`);

// remove only pods in your namespace and due to backoff errors
if ((namespace.match('^pipeline-.*') || namespace.match('^worker-.*'))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This string includes regex characters ^ and .*. Instead of a string, would it be clearer to change this string as a Regex? e.g. /^pipeline-.*/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the difference? I think they do the same

Copy link
Contributor

@aerlaut aerlaut May 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it just makes it clearer that you're matching against a regex, not a string. It wouldn't affect the functionality, but it's fine if it's kept this way.

&& reason === 'BackOff' && type !== 'Normal' && message.includes('restarting')) {
kafkasl marked this conversation as resolved.
Show resolved Hide resolved
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
logger.log(`removing pod ${name} in ${namespace}`);
await k8sApi.deleteNamespacedPod(name, namespace);
}
res.status(200).send('ok');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have the OK() helper in the API (src/utis/responses/OK). Can you use that instead of hard-coding this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer not to, they are not equivalent and the OK() should still be included so it would be res.json(OK()) because we are in routes instead of route-services where the naked OK() is used. I had a lot of issues with the event-exporter due to the responses we were sending to it, so I'd rather leave it as it is considering it's an isolated and exceptional endpoint.

Copy link
Contributor Author

@kafkasl kafkasl May 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I modified it in the end, we'll need to verify it works correctly with the event-exporter because unfortunately it can't be tested until it's merged.

} catch (e) {
logger.error('error processing k8s event', e);
AWSXRay.getSegment().addError(e);
next(e);
}
},
};
39 changes: 31 additions & 8 deletions src/specs/api.v2.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,26 @@ paths:
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'
$ref: '#/components/schemas/HTTPError'
'401':
description: The request lacks authentication credentials.
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'
$ref: '#/components/schemas/HTTPError'
'403':
description: Forbidden request for this user.
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'
$ref: '#/components/schemas/HTTPError'
'404':
description: Not found error.
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'

put:
summary: Update processing configuration for an experiment
description: Update processing configuration for an experiment
Expand Down Expand Up @@ -130,14 +130,14 @@ paths:
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'
$ref: '#/components/schemas/HTTPError'
'404':
description: Not found error.
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'

'/experiments':
get:
summary: Get all experiments
Expand Down Expand Up @@ -532,7 +532,7 @@ paths:
schema:
type: object
properties:
oldPosition:
oldPosition:
type: integer
newPosition:
type: integer
Expand Down Expand Up @@ -828,7 +828,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPError'

'/access/{experimentId}':
get:
summary: Get the users with access to an experiment
Expand Down Expand Up @@ -861,6 +861,29 @@ paths:
application/json:
schema:
$ref: ./models/HTTPError.v1.yaml
/kubernetesEvents:
post:
summary: Monitoring of kubernetes cluster events
description: Events from Kubernetes Event Exporter relayed to the API.
operationId: receiveKubernetesEvent
x-eov-operation-id: kubernetes#event
x-eov-operation-handler: routes/kubernetes
responses:
'200':
description: 'A JSON-parseable was received by the server, *irrespective of whether it was correct/acceptable or not*.'
content:
text/plain:
schema:
type: string
pattern: ok
'500':
description: The data sent by the server could not be parsed as JSON.
content:
text/plain:
schema:
type: string
pattern: nok

components:
schemas:
CreateExperiment:
Expand Down
107 changes: 107 additions & 0 deletions tests/api.v2/routes/kubernetes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const k8s = require('@kubernetes/client-node');


jest.mock('@kubernetes/client-node');


const deleteNamespacedPod = jest.fn();
const patchNamespacedPod = jest.fn();
const listNamespacedPod = jest.fn();
const mockApi = {
deleteNamespacedPod,
patchNamespacedPod,
listNamespacedPod,
};

k8s.KubeConfig.mockImplementation(() => ({
loadFromDefault: jest.fn(),
makeApiClient: (() => mockApi),
}));


const removeRequest = {
metadata: {
name: 'pipeline-6f87dbcb55-wzvnk.16b31901b952f1ec',
namespace: 'pipeline-default',
uid: 'cf831e5f-29bf-4750-ae9a-8bbe4d1f93fd',
resourceVersion: '226149137',
creationTimestamp: '2021-10-31T11:09:44Z',
managedFields: [[Object]],
},
reason: 'BackOff',
message: 'Back-off restarting failed container',
source: {
component: 'kubelet',
host: 'fargate-ip-192-168-180-35.eu-west-1.compute.internal',
},
firstTimestamp: '2021-10-31T11:09:44Z',
lastTimestamp: '2021-10-31T11:13:28Z',
count: 16,
type: 'Warning',
eventTime: null,
reportingComponent: '',
reportingInstance: '',
involvedObject: {
kind: 'Pod',
namespace: 'pipeline-default',
name: 'pipeline-6f87dbcb55-wzvnk',
uid: 'd204be1b-6626-4320-8bae-3b203aff9562',
apiVersion: 'v1',
resourceVersion: '226145375',
fieldPath: 'spec.containers{pipeline}',
labels: {
activityId: 'wrong',
'eks.amazonaws.com/fargate-profile': 'pipeline-default',
'pod-template-hash': '6f87dbcb55',
sandboxId: 'default',
type: 'pipeline',
},
annotations: {
CapacityProvisioned: '1vCPU 5GB',
Logging: 'LoggingDisabled: LOGGING_CONFIGMAP_NOT_FOUND',
},
},
};

const express = require('express');
const request = require('supertest');
const expressLoader = require('../../../src/loaders/express');

describe('tests for experiment route', () => {
kafkasl marked this conversation as resolved.
Show resolved Hide resolved
let app = null;

beforeEach(async () => {
const mockApp = await expressLoader(express());
app = mockApp.app;
});

afterEach(() => {
/**
* Most important since b'coz of caching, the mocked implementations sometimes does not reset
*/
jest.resetModules();
jest.restoreAllMocks();
kafkasl marked this conversation as resolved.
Show resolved Hide resolved
});

it('sending a remove request works', async (done) => {
request(app)
.post('/v2/kubernetesEvents')
.send(removeRequest)
.expect(200)
.end((err) => {
if (err) {
return done(err);
}

return done();
});
});

it('sending an empty request works', async (done) => {
request(app)
.post('/v2/kubernetesEvents')
.send(undefined)
.expect(500)
.end((err) => done(err));
});
});