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

fix: correcting teardown for integ test and code cleanup #188

Merged
merged 1 commit into from
Feb 8, 2024
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
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"editor.codeActionsOnSave": {
"source.organizeImports": true
"source.organizeImports": "explicit"
pcozzi marked this conversation as resolved.
Show resolved Hide resolved
},
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
Expand Down
3 changes: 3 additions & 0 deletions source/common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion source/common/config/rush/repo-state.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush.
{
"pnpmShrinkwrapHash": "a91e3cdfb0f70338c98919f90c62b3eb5bfe08c0",
"pnpmShrinkwrapHash": "def9633ab3e27f220d855c6f5ccdf1e7bdf6dfb9",
"preferredVersionsHash": "14c05a7722342014cec64c4bef7d9bed0d0b7b7f"
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,27 +39,27 @@ Feature: Device Patching
| $.patches[?(@.deviceId=="IntegrationTestCore1")].statusMessage | DEVICE_ACTIVATION_NOT_FOUND |
| $.patches[?(@.deviceId=="IntegrationTestCore1")].associationId | null |

# This test disabled because it is flaky. To-be investigated
# Scenario: Create a patch task for an EC2 Simulated edge device
# Given patch template "integration_test_template" exists
# And I create an activation for "ec2_edge_device_01" edge device
# When I launch an EC2 Instance "ec2_edge_device_01" emulating as an edge device
# And I pause for 180000ms
# When I create a patch Task for "ec2_edge_device_01" edge device with attributes
# | patchTemplateName | integration_test_template |
# | extraVars | { "uniqueVar1": "uniqueVarVal1", "uniqueVar2": "uniqueVarVal2"} |
# And I pause for 360000ms
# And last patch for device exists with following attributes
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].deviceId | ec2_edge_device_01 |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].patchId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].taskId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].createdAt | ___regex___:^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z$ |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].updatedAt | ___regex___:^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z$ |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].extraVars.uniqueVar1 | uniqueVarVal1 |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].extraVars.uniqueVar2 | uniqueVarVal2 |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].patchType | agentbased |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].patchStatus | success |
# | $.patches[?(@.deviceId=="ec2_edge_device_01")].associationId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |
# TODO: validate this test is no longer flaky with teardown cleanup
pcozzi marked this conversation as resolved.
Show resolved Hide resolved
Scenario: Create a patch task for an EC2 Simulated edge device
Given patch template "integration_test_template" exists
And I create an activation for "ec2_edge_device_01" edge device
When I launch an EC2 Instance "ec2_edge_device_01" emulating as an edge device
And I pause for 90000ms
When I create a patch Task for "ec2_edge_device_01" edge device with attributes
| patchTemplateName | integration_test_template |
| extraVars | { "uniqueVar1": "uniqueVarVal1", "uniqueVar2": "uniqueVarVal2"} |
And I pause for 120000ms
And last patch for device exists with following attributes
| $.patches[?(@.deviceId=="ec2_edge_device_01")].deviceId | ec2_edge_device_01 |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].patchId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].taskId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].createdAt | ___regex___:^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z$ |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].updatedAt | ___regex___:^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z$ |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].extraVars.uniqueVar1 | uniqueVarVal1 |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].extraVars.uniqueVar2 | uniqueVarVal2 |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].patchType | agentbased |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].patchStatus | success |
| $.patches[?(@.deviceId=="ec2_edge_device_01")].associationId | ___regex___:^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$ |

@teardown_patch_features
Scenario: Teardown
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@
*********************************************************************************************************************/
import 'reflect-metadata';

import { DataTable, Then, When, setDefaultTimeout } from '@cucumber/cucumber';
import { expect, use } from 'chai';
import { setDefaultTimeout, DataTable, Then, When } from '@cucumber/cucumber';

import { container } from '../../di/inversify.config';
import { buildModel, validateExpectedAttributes } from '../common/common.steps';
import { getAdditionalHeaders } from '../notifications/notifications.utils';
import { world } from './commandandcontrol.world';
import {
COMMANDANDCONTROL_CLIENT_TYPES,
MessageResource,
MessagesService,
} from '@awssolutions/cdf-commandandcontrol-client';
import { container } from '../../di/inversify.config';
import { buildModel, validateExpectedAttributes } from '../common/common.steps';
import { getAdditionalHeaders } from '../notifications/notifications.utils';
import { world } from './commandandcontrol.world';

import chai_string = require('chai-string');
use(chai_string);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from '@awssolutions/cdf-device-patcher-client';

import { EC2Client, RunInstancesCommand, RunInstancesCommandInput } from '@aws-sdk/client-ec2';
import { logger } from '@awssolutions/simple-cdf-logger';
import { fail } from 'assert';
import fs from 'fs';
import { container } from '../../di/inversify.config';
Expand Down Expand Up @@ -102,7 +103,7 @@ When(
options.to = activation.activationRegion;
await replaceInFile(options);
} catch (err) {
console.log(`preparing bootstrap script failed: ${err}`);
logger.error(`preparing bootstrap script failed: ${err}`);
throw err;
}

Expand Down Expand Up @@ -136,7 +137,7 @@ When(
};
await ec2.send(new RunInstancesCommand(params));
} catch (err) {
console.log(`launching ec2 failed: ${err}`);
logger.error(`launching ec2 failed: ${err}`);
throw err;
}
} catch (err) {
Expand Down Expand Up @@ -267,7 +268,6 @@ Then(
const artifacts_certs_key = this['core']?.artifacts?.certs?.key;
const artifacts_config_bucket = this['core']?.artifacts?.config?.bucket;
const artifacts_config_key = this['core']?.artifacts?.config?.key;

const patch: CreatePatchRequest = {
deviceId,
patchTemplateName: template,
Expand Down Expand Up @@ -295,6 +295,7 @@ Then(
patchTask,
getAdditionalHeaders(world.authToken)
);
logger.debug('patchTaskId: ' + this['patchTaskId']);
} catch (e) {
this[RESPONSE_STATUS] = e.status;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,33 @@
import { Before, setDefaultTimeout } from '@cucumber/cucumber';
import { resolve } from 'path';

import { Dictionary } from '@awssolutions/cdf-lambda-invoke';
import {
TemplatesService,
PatchType,
CreatePatchTemplateParams,
DEVICE_PATCHER_CLIENT_TYPES,
ListPatchResponse,
PatchResponse,
PatchService,
PatchType,
TemplatesService,
} from '@awssolutions/cdf-device-patcher-client';
import { DEVICE_PATCHER_CLIENT_TYPES } from '@awssolutions/cdf-device-patcher-client';
import { Dictionary } from '@awssolutions/cdf-lambda-invoke';

import { container } from '../di/inversify.config';
import { AUTHORIZATION_TOKEN } from '../step_definitions/common/common.steps';
import { logger } from '@awssolutions/simple-cdf-logger';
import {
DescribeInstancesCommand,
EC2Client,
TerminateInstancesCommand,
} from '@aws-sdk/client-ec2';
import { logger } from '@awssolutions/simple-cdf-logger';
import { container } from '../di/inversify.config';
import { AUTHORIZATION_TOKEN } from '../step_definitions/common/common.steps';

setDefaultTimeout(30 * 1000);

const INTEGRATION_TEST_PATCH_TEMPLATE = 'integration_test_template';
const GGV2_CORE_INSTALLATION_TEMPLATE = 'ggv2_ec2_amazonlinux2_template';
const PATCH_ENHANCED_DEVICE_ID = 'DevicePatcherIntegrationTestCore';
const PATCH_DEVICE_ID_1 = 'IntegrationTestCore1';
const PATCH_DEVICE_ID_2 = 'ec2_edge_device_01';
pcozzi marked this conversation as resolved.
Show resolved Hide resolved

const ec2 = new EC2Client({ region: process.env.AWS_REGION });

Expand All @@ -45,12 +51,33 @@ function getAdditionalHeaders(world: unknown): Dictionary {
}

const templatesSvc: TemplatesService = container.get(DEVICE_PATCHER_CLIENT_TYPES.TemplatesService);
const patchSvc: PatchService = container.get(DEVICE_PATCHER_CLIENT_TYPES.PatchService);

async function deletePatchTemplate(world: unknown, name: string) {
try {
await templatesSvc.deleteTemplate(name, getAdditionalHeaders(world));
} catch (e) {
logger.error(e);
logger.error(`deletePatchTemplate: ${JSON.stringify(e)}`);
}
}

async function deletePatchesForDevice(world: unknown, deviceId: string) {
try {
// get all patches for the given device
const patchList: ListPatchResponse = await patchSvc.listPatchesByDeviceId(
deviceId,
undefined,
getAdditionalHeaders(world)
);
const patches: PatchResponse[] = patchList.patches;

// delete all patches for the given device
const deletionPromises = patches.map((patch): Promise<void> => {
return patchSvc.deletePatch(patch.patchId, getAdditionalHeaders(world));
});
await Promise.all(deletionPromises);
} catch (e) {
logger.error(`deletePatchesForDevice: ${JSON.stringify(e)}`);
}
}

Expand All @@ -71,7 +98,7 @@ async function createIntegrationTestPatchTemplate(world: unknown, name: string)
};
await templatesSvc.createTemplate(template, getAdditionalHeaders(world));
} catch (e) {
logger.error(e);
logger.error(`createIntegrationTestPatchTemplate: ${JSON.stringify(e)}`);
}
}

Expand All @@ -88,7 +115,7 @@ async function createGGV2CorePatchTemplate(world: unknown, name: string) {
};
await templatesSvc.createTemplate(template, getAdditionalHeaders(world));
} catch (e) {
logger.error(e);
logger.error(`createGGV2CorePatchTemplate: ${JSON.stringify(e)}`);
}
}

Expand All @@ -111,15 +138,19 @@ async function cleanupEC2Instances() {
}
}

async function teardown_patches_feature() {
async function teardown_patches_feature(world: unknown) {
await deletePatchesForDevice(world, PATCH_DEVICE_ID_1);
await deletePatchesForDevice(world, PATCH_DEVICE_ID_2);
await deletePatchTemplate(world, INTEGRATION_TEST_PATCH_TEMPLATE);
await cleanupEC2Instances();
}

async function teardown_activation_features() {
console.log('teardown_activation_features');
logger.debug('teardown_activation_features');
}

async function teardown_enhanced_patch_templates_features(world: unknown) {
await deletePatchesForDevice(world, PATCH_ENHANCED_DEVICE_ID);
await deletePatchTemplate(world, GGV2_CORE_INSTALLATION_TEMPLATE);
await cleanupEC2Instances();
}
Expand All @@ -130,7 +161,7 @@ Before({ tags: '@setup_patch_features' }, async function () {
});

Before({ tags: '@teardown_patch_features' }, async function () {
await teardown_patches_feature();
await teardown_patches_feature(this);
});

Before({ tags: '@setup_activation_features' }, async function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,13 @@ const templateBucket = process.env.PROVISIONING_TEMPLATES_BUCKET;
const templatePrefix = process.env.PROVISIONING_TEMPLATES_PREFIX;

async function teardown(world: unknown) {
// logger.debug(`\ngreengrass_provisioning_hooks: teardown: in:`);

logger.debug(`\ngreengrass_provisioning_hooks: teardown: in: ${JSON.stringify(world)}`);

// service cleanup
const templates = ['IntegrationTest'];
for (const t of templates) {
try {
await templatesSvc.deleteTemplate(t, getAdditionalHeaders(world[AUTHORIZATION_TOKEN]));
} catch (err) {
logger.silly(`teardown: deleteTemplate: ${JSON.stringify(err)}`);
// swallow the error
}
}
Expand All @@ -75,6 +72,7 @@ async function teardown(world: unknown) {
try {
await deviceSvc.deleteDevice(clientDevice);
} catch (err) {
logger.silly(`teardown: deleteDevice: ${JSON.stringify(err)}`);
// swallow the error
}
}
Expand All @@ -95,6 +93,7 @@ async function teardown(world: unknown) {
}),
});
} catch (err) {
logger.silly(`teardown: createCoreTask: ${JSON.stringify(err)}`);
// swallow the error
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"winston-transport": "4.4.0"
},
"devDependencies": {
"@awssolutions/cdf-config-inject": "workspace:^2.5.2",
"@awssolutions/eslint-config-custom": "workspace:~0.0.0",
"@typescript-eslint/eslint-plugin": "6.2.0",
"eslint": "8.46.0",
Expand Down
34 changes: 21 additions & 13 deletions source/packages/libraries/core/simple-cdf-logger/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import '@awssolutions/cdf-config-inject';

import { format } from 'logform';
import { LoggerOptions, createLogger, transports } from 'winston';
const { combine, timestamp, printf } = format;
Expand All @@ -19,19 +21,25 @@ export function setRequestId(newRequestId: string) {
}
}

export const logger = createLogger(<LoggerOptions>{
level,
exitOnError: false,
transports: [new transports.Console()],
format: combine(
timestamp(),
printf((nfo) => {
return `${nfo.timestamp} ${nfo.level}: rid-${requestId ? requestId : 'not-set-yet'}: ${
nfo.message
}`;
})
),
});
export const logger = (function () {
if (typeof level == 'undefined') {
// this indicates that no log level was set through .env (see: cdf-config-inject)
console.error('LOGGING_LEVEL not set');
}
return createLogger(<LoggerOptions>{
level,
exitOnError: false,
transports: [new transports.Console()],
format: combine(
timestamp(),
printf((nfo) => {
return `${nfo.timestamp} ${nfo.level}: rid-${
requestId ? requestId : 'not-set-yet'
}: ${nfo.message}`;
})
),
});
})();

export function getRequestIdFromContext(context: any) {
let requestId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
*********************************************************************************************************************/
import 'reflect-metadata';

import { logger } from '@awssolutions/simple-cdf-logger';
import { container } from './di/inversify.config';
import { logger } from '@awssolutions/simple-cdf-logger';
import { TYPES } from './di/types';
import { EventModel } from './events/events.models';
import { EventsService } from './events/events.service';
Expand Down
3 changes: 2 additions & 1 deletion source/packages/services/bulkcerts/src/lambda_sns_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
* and limitations under the License. *
*********************************************************************************************************************/
import { container } from './di/inversify.config';

import { logger } from '@awssolutions/simple-cdf-logger';
import { Context, SNSEvent } from 'aws-lambda';
import ow from 'ow';
import { CertificateChunkRequest } from './certificates/certificates.models';
import { CertificatesService } from './certificates/certificates.service';
import { container } from './di/inversify.config';
import { TYPES } from './di/types';

let service: CertificatesService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

import ow from 'ow';

import { logger } from '@awssolutions/simple-cdf-logger';
import { container } from './di/inversify.config';
import { logger } from '@awssolutions/simple-cdf-logger';
import { TYPES } from './di/types';
import { Response } from './responses/responses.models';
import { ResponsesService } from './responses/responses.service';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

import ow from 'ow';

import { logger } from '@awssolutions/simple-cdf-logger';
import { container } from './di/inversify.config';
import { logger } from '@awssolutions/simple-cdf-logger';
import { TYPES } from './di/types';
import { Response } from './responses/responses.models';
import { ResponsesService } from './responses/responses.service';
Expand Down
Loading
Loading