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

feat(server): Server should periodically delete old builds #471

Merged
merged 2 commits into from
Oct 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 13 additions & 0 deletions packages/server/src/api/storage/sql/sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,19 @@ class SqlStorageMethod {
}
}

/**
* @param {Date} runAt
* @return {Promise<LHCI.ServerCommand.Build[]>}
*/
async findBuildsBeforeTimestamp(runAt) {
const {buildModel} = this._sql();
const oldBuilds = await buildModel.findAll({
where: {runAt: {[Sequelize.Op.lte]: runAt}},
order: [['runAt', 'ASC']],
});
return oldBuilds;
}

/**
* @param {string} projectId
* @param {string} buildId
Expand Down
9 changes: 9 additions & 0 deletions packages/server/src/api/storage/storage-method.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,15 @@ class StorageMethod {
throw new Error('Unimplemented');
}

/**
* @param {Date} runAt
* @return {Promise<LHCI.ServerCommand.Build[]>}
*/
// eslint-disable-next-line no-unused-vars
async findBuildsBeforeTimestamp(runAt) {
throw new Error('Unimplemented');
}

/**
* @param {string} projectId
* @param {string} buildId
Expand Down
74 changes: 74 additions & 0 deletions packages/server/src/cron/delete-old-builds.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/

'use strict';
patrickhulce marked this conversation as resolved.
Show resolved Hide resolved

const {CronJob} = require('cron');
const {normalizeCronSchedule} = require('./utils');

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
* @param {number} maxAgeInDays
* @param {Date} now
* @return {Promise<void>}
*/
async function deleteOldBuilds(storageMethod, maxAgeInDays, now = new Date()) {
if (!maxAgeInDays || !Number.isInteger(maxAgeInDays) || maxAgeInDays <= 0) {
throw new Error('Invalid range');
}

const DAY_IN_MS = 24 * 60 * 60 * 1000;
const cutoffTime = new Date(Date.now() - maxAgeInDays * DAY_IN_MS);
const oldBuilds = await storageMethod.findBuildsBeforeTimestamp(cutoffTime);
for (const {projectId, id} of oldBuilds) {
await storageMethod.deleteBuild(projectId, id);
}
}

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
* @param {LHCI.ServerCommand.Options} options
* @return {void}
*/
function startDeleteOldBuildsCron(storageMethod, options) {
if (options.storage.storageMethod !== 'sql' || !options.deleteOldBuildsCron) {
return;
}

if (!options.deleteOldBuildsCron.schedule || !options.deleteOldBuildsCron.maxAgeInDays) {
throw new Error('Cannot configure schedule');
}

const log =
options.logLevel === 'silent'
? () => {}
: msg => process.stdout.write(`${new Date().toISOString()} - ${msg}\n`);

let inProgress = false;

const {schedule, maxAgeInDays} = options.deleteOldBuildsCron;

const cron = new CronJob(normalizeCronSchedule(schedule), () => {
if (inProgress) {
log(`Deleting old builds still in progress. Skipping...`);
return;
}
inProgress = true;
log(`Starting delete old builds`);
deleteOldBuilds(storageMethod, maxAgeInDays, new Date())
.then(() => {
log(`Successfully delete old builds`);
})
.catch(err => {
log(`Delete old builds failure: ${err.message}`);
})
.finally(() => {
inProgress = false;
});
});
cron.start();
}
module.exports = {startDeleteOldBuildsCron, deleteOldBuilds};
26 changes: 1 addition & 25 deletions packages/server/src/cron/psi-collect.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,7 @@
const {CronJob} = require('cron');
const {getGravatarUrlFromEmail} = require('@lhci/utils/src/build-context');
const PsiRunner = require('@lhci/utils/src/psi-runner.js');

/**
* @param {string} schedule
* @return {string}
*/
function normalizeCronSchedule(schedule) {
if (typeof schedule !== 'string') {
throw new Error(`Schedule must be provided`);
}

if (process.env.OVERRIDE_SCHEDULE_FOR_TEST) {
return process.env.OVERRIDE_SCHEDULE_FOR_TEST;
}

const parts = schedule.split(/\s+/).filter(Boolean);
if (parts.length !== 5) {
throw new Error(`Invalid cron format, expected <minutes> <hours> <day> <month> <day of week>`);
}

if (parts[0] === '*') {
throw new Error(`Cron schedule "${schedule}" is too frequent`);
}

return ['0', ...parts].join(' ');
}
const {normalizeCronSchedule} = require('./utils');

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
Expand Down
33 changes: 33 additions & 0 deletions packages/server/src/cron/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/

'use strict';
patrickhulce marked this conversation as resolved.
Show resolved Hide resolved

/**
* @param {string} schedule
* @return {string}
*/
function normalizeCronSchedule(schedule) {
if (typeof schedule !== 'string') {
throw new Error(`Schedule must be provided`);
}

if (process.env.OVERRIDE_SCHEDULE_FOR_TEST) {
return process.env.OVERRIDE_SCHEDULE_FOR_TEST;
}

const parts = schedule.split(/\s+/).filter(Boolean);
if (parts.length !== 5) {
throw new Error(`Invalid cron format, expected <minutes> <hours> <day> <month> <day of week>`);
}

if (parts[0] === '*') {
throw new Error(`Cron schedule "${schedule}" is too frequent`);
}

return ['0', ...parts].join(' ');
}
module.exports = {normalizeCronSchedule};
2 changes: 2 additions & 0 deletions packages/server/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const createProjectsRouter = require('./api/routes/projects.js');
const StorageMethod = require('./api/storage/storage-method.js');
const {errorMiddleware, createBasicAuthMiddleware} = require('./api/express-utils.js');
const {startPsiCollectCron} = require('./cron/psi-collect.js');
const {startDeleteOldBuildsCron} = require('./cron/delete-old-builds');
const version = require('../package.json').version;

const DIST_FOLDER = path.join(__dirname, '../dist');
Expand Down Expand Up @@ -55,6 +56,7 @@ async function createApp(options) {
app.use(errorMiddleware);

startPsiCollectCron(storageMethod, options);
startDeleteOldBuildsCron(storageMethod, options);

return {app, storageMethod};
}
Expand Down
138 changes: 138 additions & 0 deletions packages/server/test/cron/delete-old-builds.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/
'use strict';
patrickhulce marked this conversation as resolved.
Show resolved Hide resolved

/* eslint-env jest */

/** @type {jest.MockInstance} */
let cronJob = jest.fn().mockReturnValue({start: () => {}});
jest.mock('cron', () => ({
CronJob: function(...args) {
// use this indirection because we have to invoke it with `new` and it's harder to mock assertions
return cronJob(...args);
},
}));

const {
startDeleteOldBuildsCron,
deleteOldBuilds,
} = require('../../src/cron/delete-old-builds.js');

describe('cron/delete-old-builds', () => {
/** @type {{ findBuildsBeforeTimestamp: jest.MockInstance, deleteBuild: jest.MockInstance}} */
let storageMethod;
beforeEach(() => {
storageMethod = {
findBuildsBeforeTimestamp: jest.fn().mockResolvedValue([]),
deleteBuild: jest.fn().mockResolvedValue({}),
};

cronJob = jest.fn().mockReturnValue({
start: () => {},
});
});
describe('.deleteOldBuilds', () => {
it.each([undefined, null, -1, new Date()])(
'should throw for invalid range (%s)',
async range => {
await expect(deleteOldBuilds(storageMethod, range)).rejects.toMatchObject({
message: 'Invalid range',
});
}
);

it('should collect', async () => {
storageMethod.deleteBuild.mockClear();
const deleteObjects = [{id: 'id-1', projectId: 'pid-1'}, {id: 'id-2', projectId: 'pid-2'}];
storageMethod.findBuildsBeforeTimestamp.mockResolvedValue(deleteObjects);
await deleteOldBuilds(storageMethod, 30, new Date('2019-01-01'));
expect(storageMethod.deleteBuild).toHaveBeenCalledTimes(deleteObjects.length);

expect(storageMethod.deleteBuild.mock.calls).toMatchObject([
['pid-1', 'id-1'],
['pid-2', 'id-2'],
]);
});
});

describe('.startDeleteOldBuildsCron', () => {
it.each([
[
'storageMethod is not sql',
{
storage: {
storageMethod: 'notsql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
maxAgeInDays: 30,
},
},
],
[
'no deleteOldBuilds options',
{
storage: {storageMethod: 'sql'},
},
],
])('should not schedule a cron job (%s)', (_, options) => {
startDeleteOldBuildsCron(storageMethod, options);
expect(cronJob).toHaveBeenCalledTimes(0);
});
it.each([
[
'no schedule',
{
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
maxAgeInDays: 30,
},
},
],
[
'no dateRagne',
{
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
},
},
],
])('should throw for invalid options (%s)', (_, options) => {
expect(() => startDeleteOldBuildsCron(storageMethod, options)).toThrow(/Cannot configure/);
});
it('should throw for invalid schedule', () => {
const options = {
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '* * *',
maxAgeInDays: 30,
},
};
expect(() => startDeleteOldBuildsCron(storageMethod, options)).toThrow(
/Invalid cron format/
);
});
it('should schedule a cron job', () => {
startDeleteOldBuildsCron(storageMethod, {
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
maxAgeInDays: 30,
},
});
expect(cronJob).toHaveBeenCalledTimes(1);
});
});
});
26 changes: 26 additions & 0 deletions packages/server/test/cron/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/
'use strict';
Copy link
Collaborator

Choose a reason for hiding this comment

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

add license comment


/* eslint-env jest */

const {normalizeCronSchedule} = require('../../src/cron/utils.js');

describe('cron/utils', () => {
describe('.normalizeCronSchedule()', () => {
it('should validate string', () => {
expect(() => normalizeCronSchedule(1)).toThrow(/Schedule must be provided/);
});

it('should validate cron job', () => {
expect(() => normalizeCronSchedule('* * * * *')).toThrow(/too frequent/);
});

it('should validate invalid format', () => {
expect(() => normalizeCronSchedule('* * *')).toThrow(/Invalid cron format/);
});
});
});
4 changes: 4 additions & 0 deletions types/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ declare global {
psiApiEndpoint?: string;
sites: Array<PsiCollectEntry>;
};
deleteOldBuildsCron?: {
schedule: string;
maxAgeInDays: number;
}
basicAuth?: {
username?: string;
password?: string;
Expand Down