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(3209): Skip execution of virtual job and mark it as SUCCESS #76

Merged
merged 2 commits into from
Oct 4, 2024
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
96 changes: 67 additions & 29 deletions plugins/queue/scheduler.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ const TEMPORAL_TOKEN_TIMEOUT = 12 * 60; // 12 hours in minutes
const TEMPORAL_UNZIP_TOKEN_TIMEOUT = 2 * 60; // 2 hours in minutes
const BLOCKED_BY_SAME_JOB_WAIT_TIME = 5;

/**
* Checks whether the job associated with the build is virtual or not
* @method isVirtualJob
* @param {Object} annotations Job Annotations
* @return {Boolean}
*/
function isVirtualJob(annotations) {
return annotations && annotations['screwdriver.cd/virtualJob'];
Copy link
Member

Choose a reason for hiding this comment

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

is this annotation treated as a boolean or string ? If string you might have to check explicitly the expected value

Copy link
Member Author

Choose a reason for hiding this comment

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

Boolean

}

/**
* Posts a new build event to the API
* @method postBuildEvent
Expand Down Expand Up @@ -300,7 +310,8 @@ async function start(executor, config) {
apiUri,
pipeline,
isPR,
prParentJobId
prParentJobId,
annotations
} = config;
const forceStart = /\[(force start)\]/.test(causeMessage);

Expand Down Expand Up @@ -411,48 +422,75 @@ async function start(executor, config) {
throw value.error;
}

const token = executor.tokenGen(Object.assign(tokenConfig, { scope: ['temporal'] }), TEMPORAL_TOKEN_TIMEOUT);

// set the start time in the queue
Object.assign(config, { token });
// Store the config in redis
await executor.redisBreaker.runCommand('hset', executor.buildConfigTable, buildId, JSON.stringify(config));

const blockedBySameJob = reach(config, 'annotations>screwdriver.cd/blockedBySameJob', {
separator: '>',
default: true
});
const blockedBySameJobWaitTime = reach(config, 'annotations>screwdriver.cd/blockedBySameJobWaitTime', {
separator: '>',
default: BLOCKED_BY_SAME_JOB_WAIT_TIME
});
if (isVirtualJob(annotations)) {
// Bypass execution of the build if the job is virtual
const payload = {
status: 'SUCCESS',
statusMessage: 'Skipped execution of the virtual job'
};

// Note: arguments to enqueue are [queue name, job name, array of args]
enq = await executor.queueBreaker.runCommand('enqueue', executor.buildQueue, 'start', [
{
buildId,
jobId,
blockedBy: blockedBy.toString(),
blockedBySameJob,
blockedBySameJobWaitTime
}
]);
if (buildStats) {
await helper
.updateBuild(
{
buildId,
token: buildToken,
apiUri,
payload: { stats: build.stats, status: 'QUEUED' }
payload
},
helper.requestRetryStrategy
)
.catch(err => {
logger.error(`Failed to update build status for build ${buildId}: ${err}`);
logger.error(`virtualBuilds: failed to update build status for build ${buildId}: ${err}`);

throw err;
});
Copy link
Member

Choose a reason for hiding this comment

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

Can we abstract this section out, the same helper.updateBuild is called in either conditions just with different payload. Prefer this to be cleaner.

let payload;

if (isVirtualJob(annotations)) {
    // Bypass execution of the build if the job is virtual
    payload = {
        status: 'SUCCESS',
        statusMessage: 'Skipped execution of the virtual job'
    };
} else {
    const token = executor.tokenGen(
        Object.assign(tokenConfig, { scope: ['temporal'] }),
        TEMPORAL_TOKEN_TIMEOUT
    );

    // set the start time in the queue
    Object.assign(config, { token });
    // Store the config in redis
    await executor.redisBreaker.runCommand('hset', executor.buildConfigTable, buildId, JSON.stringify(config));

    const blockedBySameJob = reach(config, 'annotations>screwdriver.cd/blockedBySameJob', {
        separator: '>',
        default: true
    });
    const blockedBySameJobWaitTime = reach(config, 'annotations>screwdriver.cd/blockedBySameJobWaitTime', {
        separator: '>',
        default: BLOCKED_BY_SAME_JOB_WAIT_TIME
    });

    // Note: arguments to enqueue are [queue name, job name, array of args]
    enq = await executor.queueBreaker.runCommand('enqueue', executor.buildQueue, 'start', [
        {
            buildId,
            jobId,
            blockedBy: blockedBy.toString(),
            blockedBySameJob,
            blockedBySameJobWaitTime
        }
    ]);

    if (buildStats) {
        payload = { stats: build.stats, status: 'QUEUED' };
    }
}

await helper
    .updateBuild(
        {
            buildId,
            token: buildToken,
            apiUri,
            payload
        },
        helper.requestRetryStrategy
    )
    .catch(err => {
        if (isVirtualJob(annotations)) {
            logger.error(`virtualBuilds: failed to update build status for build ${buildId}: ${err}`);
        } else {
            logger.error(`Failed to update build status for build ${buildId}: ${err}`);
        }
        throw err;
    });

Copy link
Member Author

Choose a reason for hiding this comment

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

Done

} else {
const token = executor.tokenGen(
Object.assign(tokenConfig, { scope: ['temporal'] }),
TEMPORAL_TOKEN_TIMEOUT
);

// set the start time in the queue
Object.assign(config, { token });
// Store the config in redis
await executor.redisBreaker.runCommand('hset', executor.buildConfigTable, buildId, JSON.stringify(config));

const blockedBySameJob = reach(config, 'annotations>screwdriver.cd/blockedBySameJob', {
separator: '>',
default: true
});
const blockedBySameJobWaitTime = reach(config, 'annotations>screwdriver.cd/blockedBySameJobWaitTime', {
separator: '>',
default: BLOCKED_BY_SAME_JOB_WAIT_TIME
});

// Note: arguments to enqueue are [queue name, job name, array of args]
enq = await executor.queueBreaker.runCommand('enqueue', executor.buildQueue, 'start', [
{
buildId,
jobId,
blockedBy: blockedBy.toString(),
blockedBySameJob,
blockedBySameJobWaitTime
}
]);
if (buildStats) {
await helper
.updateBuild(
{
buildId,
token: buildToken,
apiUri,
payload: { stats: build.stats, status: 'QUEUED' }
},
helper.requestRetryStrategy
)
.catch(err => {
logger.error(`Failed to update build status for build ${buildId}: ${err}`);

throw err;
});
}
}
}

Expand Down
30 changes: 30 additions & 0 deletions test/plugins/queue/scheduler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,36 @@ describe('scheduler test', () => {
assert.calledWith(queueMock.enqueue, 'builds', 'start', [partialTestDefaultConfig]);
});
});

it('skip execution of the build and update the status to SUCCESS for virtual job', () => {
const dateNow = Date.now();
const sandbox = sinon.createSandbox({
useFakeTimers: false
});

sandbox.useFakeTimers(dateNow);
buildMock.stats = {};
testConfig.build = buildMock;
testConfig.annotations['screwdriver.cd/virtualJob'] = true;

return scheduler.start(executor, testConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.notCalled(redisMock.hset);
assert.notCalled(queueMock.enqueue);
assert.calledOnce(executor.tokenGen);
assert.calledWith(
helperMock.updateBuild,
{
buildId,
token: 'buildToken',
apiUri: 'http://api.com',
payload: { status: 'SUCCESS', statusMessage: 'Skipped execution of the virtual job' }
},
helperMock.requestRetryStrategy
);
sandbox.restore();
});
});
});

describe('startFrozen', () => {
Expand Down