prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); }
await this.fillData( logGroupArn, credentials, region, {
resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8296456336975098 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });\n }\n await this.fillData(\n natGatewayArn,\n credentials,", "score": 0.8261855244636536 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.8125893473625183 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8082774877548218 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " nameSpace: string, metricName: string, dimensions: Dimension[]\n ){ \n if(resourceArn in this.utilization){\n const cloudWatchClient = new CloudWatch({ \n credentials: credentials, \n region: region\n }); \n const endTime = new Date(Date.now()); \n const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago\n const period = 43200; ", "score": 0.7998870015144348 } ]
typescript
await this.fillData( logGroupArn, credentials, region, {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) {
field.report(messages.confirmed, 'confirmed', field, { otherField }) return }
} ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 0.8516618013381958 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " field.report(messages.literal, 'literal', field, options)\n return\n }\n /**\n * Mutating input with normalized value\n */\n field.mutate(input, field)\n})", "score": 0.8490405678749084 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8478778004646301 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8451158404350281 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8430764675140381 } ]
typescript
field.report(messages.confirmed, 'confirmed', field, { otherField }) return }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field
.report(messages.creditCard, 'creditCard', field, {
providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 0.8234515190124512 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8199954032897949 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8179827332496643 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8167800903320312 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8166731595993042 } ]
typescript
.report(messages.creditCard, 'creditCard', field, {
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this
.fillData( instanceArn, credentials, region, {
resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8823322057723999 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8651454448699951 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " credentials: any, \n region: string, \n data: { [ key: keyof Data ]: Data[keyof Data] }\n ) {\n for (const key in data) {\n this.addData(resourceArn, key, data[key]);\n }\n await this.identifyCloudformationStack(\n credentials, \n region, ", "score": 0.8556691408157349 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8522407412528992 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.region = regions[0];\n this.rdsClient = new RDS({\n credentials,\n region: this.region\n });\n this.cwClient = new CloudWatch({ \n credentials, \n region: this.region", "score": 0.8392296433448792 } ]
typescript
.fillData( instanceArn, credentials, region, {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (
storedBytes / ONE_GB_IN_BYTES) * 0.03;
const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8390188813209534 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8335870504379272 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8242189288139343 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n return metricDataRes.MetricDataResults;\n }\n private async getRegionalUtilization (credentials: any, region: string) {\n const allNatGateways = await this.getAllNatGateways(credentials, region);\n const analyzeNatGateway = async (natGateway: NatGateway) => {\n const natGatewayId = natGateway.NatGatewayId;\n const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);\n const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId);\n const activeConnectionCount = get(results, '[0].Values[0]') as number;", "score": 0.8199864625930786 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": "import get from 'lodash.get';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { Bucket, S3 } from '@aws-sdk/client-s3';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns, ONE_GB_IN_BYTES } from '../types/constants.js';\ntype S3CostData = {\n monthlyCost: number,", "score": 0.8198869228363037 } ]
typescript
storedBytes / ONE_GB_IN_BYTES) * 0.03;
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) );
const cost = await getInstanceCost(pricingClient, instanceType.InstanceType);
if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " totalIops: number,\n totalThroughput: number\n ): StorageAndIOCosts {\n let storageCost = 0;\n let iopsCost = 0;\n let throughputCost = 0;\n if (dbInstance.StorageType === 'gp2') {\n if (dbInstance.MultiAZ) {\n storageCost = storageUsedInGB * 0.23;\n } else {", "score": 0.8737139105796814 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " const {\n totalIops,\n totalThroughput,\n freeStorageSpace,\n totalBackupStorageBilled\n } = metrics;\n const dbInstanceClass = dbInstance.DBInstanceClass;\n const storageUsedInGB = \n dbInstance.AllocatedStorage ? \n dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) :", "score": 0.8681480288505554 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " });\n const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand;\n const onDemandKeys = Object.keys(onDemandData);\n const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions;\n const priceDimensionsKeys = Object.keys(priceDimensionsData);\n const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD;\n const instanceCost = pricePerHour * 24 * 30;\n const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics);\n const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost;\n const rdsCosts = {", "score": 0.8677365779876709 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " iopsCost = (dbInstance.Iops || 0) * 0.10;\n }\n }\n return {\n totalStorageCost: storageCost,\n iopsCost,\n throughputCost\n };\n }\n private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) {", "score": 0.8634647130966187 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const lowCpuUtilization = (\n (avgCpuIsStable && maxCpuIsStable) ||\n maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html\n );\n const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values);\n const {\n max: maxMemory,\n isStable: maxMemoryIsStable\n } = getStabilityStats(maxMemoryMetrics.Values);\n const lowMemoryUtilization = (", "score": 0.8632538318634033 } ]
typescript
const cost = await getInstanceCost(pricingClient, instanceType.InstanceType);
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers
.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8332554697990417 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8284843564033508 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.8276029229164124 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 0.8250118494033813 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8242388963699341 } ]
typescript
.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials:
any, region: string, _overrides?: AwsServiceOverrides) {
const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.9016014337539673 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.8997715711593628 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " totalCost: 0,\n instanceCost: 0,\n totalStorageCost: 0,\n iopsCost: 0,\n throughputCost: 0\n } as RdsCosts;\n } \n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides", "score": 0.8936335444450378 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.8862521648406982 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8833203315734863 } ]
typescript
any, region: string, _overrides?: AwsServiceOverrides) {
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) {
const instanceArn = Arns.Ec2(region, this.accountId, instanceId);
const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const allTasks = [];\n const taskIdPartitions = chunk(taskIds, 100);\n for (const taskIdPartition of taskIdPartitions) {\n const describeTasksResponse = await this.ecsClient.describeTasks({\n cluster: service.clusterArn,\n tasks: taskIdPartition\n });\n const {\n tasks = []\n } = describeTasksResponse;", "score": 0.8403013348579407 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8283199667930603 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " cluster: service.clusterArn,\n containerInstances: tasks.map(task => task.containerInstanceArn)\n });\n containerInstance = containerInstanceResponse?.containerInstances?.at(0);\n }\n const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => {\n acc.add(instance.ec2InstanceId);\n return acc;\n }, new Set<string>());\n const numEc2Instances = uniqueEc2Instances.size;", "score": 0.8266223669052124 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " });\n this.pricingClient = new Pricing({\n credentials,\n region: this.region\n });\n let dbInstances: DBInstance[] = [];\n let describeDBInstancesRes: DescribeDBInstancesCommandOutput;\n do {\n describeDBInstancesRes = await this.rdsClient.describeDBInstances({});\n dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ];", "score": 0.8255550861358643 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " return instanceFamily;\n }\n private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> {\n const instanceTypes = [];\n let nextToken;\n do {\n const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({\n InstanceTypes: instanceTypeNames,\n NextToken: nextToken\n });", "score": 0.8241996765136719 } ]
typescript
const instanceArn = Arns.Ec2(region, this.accountId, instanceId);
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) {
field.report(messages.notIn, 'notIn', field, options) return }
} ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8832188248634338 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8613187670707703 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.8603731989860535 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8575438261032104 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8539277911186218 } ]
typescript
field.report(messages.notIn, 'notIn', field, options) return }
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.
addScenario(logGroupArn, 'hasRetentionPolicy', {
value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " Bucket: bucketName\n });\n if (!res.IntelligentTieringConfigurationList) {\n const { monthlySavings } = await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasIntelligentTiering', {\n value: 'false',\n optimize: { \n action: 'enableIntelligientTiering', \n isActionable: true,\n reason: 'Intelligient tiering is not enabled for this bucket',", "score": 0.8330762386322021 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " if (\n response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined)\n ) {\n await this.s3Client.getBucketLifecycleConfiguration({\n Bucket: bucketName\n }).catch(async (e) => { \n if(e.Code === 'NoSuchLifecycleConfiguration'){ \n await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasLifecyclePolicy', {\n value: 'false',", "score": 0.8275169134140015 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.8240256905555725 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.823137640953064 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.8223164677619934 } ]
typescript
addScenario(logGroupArn, 'hasRetentionPolicy', {
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.
addScenario(instanceArn, 'unused', {
value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " this.addScenario(dbInstanceArn, 'cpuUtilization', {\n value: metrics.cpuUtilization.toString(), \n scaleDown: {\n action: '', \n isActionable: false,\n reason: 'Max CPU Utilization is under 50%',\n monthlySavings: 0\n }\n });\n }", "score": 0.8746702671051025 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.8606352806091309 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " (avgMemoryIsStable && maxMemoryIsStable) ||\n maxMemory < 10\n );\n const requestCountMetricValues = [\n ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || [])\n ];\n const totalRequestCount = stats.sum(requestCountMetricValues);\n const noNetworkUtilization = totalRequestCount === 0;\n if (\n lowCpuUtilization &&", "score": 0.8576313853263855 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.8509173393249512 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " this.addScenario(service.serviceArn, 'unused', {\n value: 'true',\n delete: {\n action: 'deleteService',\n isActionable: true,\n reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and'\n + ' network traffic.',\n monthlySavings: monthlyCost\n }\n });", "score": 0.8487382531166077 } ]
typescript
addScenario(instanceArn, 'unused', {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost,
hourlyCost: getHourlyCost(totalMonthlyCost) }
); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8590026497840881 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8573230504989624 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8290532827377319 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8275779485702515 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.8267288208007812 } ]
typescript
hourlyCost: getHourlyCost(totalMonthlyCost) }
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await
rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.8961485028266907 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.8923095464706421 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8276022672653198 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8162610530853271 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": " });\n autoScalingGroups = [...autoScalingGroups, ...groups]; \n while(asgRes.NextToken){ \n asgRes = await autoScalingClient.describeAutoScalingGroups({\n NextToken: asgRes.NextToken\n });\n autoScalingGroups = [...autoScalingGroups, ...asgRes.AutoScalingGroups.map((group) => { \n return { \n name: group.AutoScalingGroupName, \n arn: group.AutoScalingGroupARN", "score": 0.8154251575469971 } ]
typescript
rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) {
if (!helpers.isCreditCard(value as string)) {
field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.834883451461792 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.829004168510437 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8284977674484253 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8225200176239014 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " if (!field.isValid) {\n return\n }\n callback(Object.keys(value as Record<string, any>), field)\n }\n)", "score": 0.8221504092216492 } ]
typescript
if (!helpers.isCreditCard(value as string)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) {
if (!helpers.isPostalCode(value as string, 'any')) {
field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8377808332443237 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.8376915454864502 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " if (!field.isValid) {\n return\n }\n callback(Object.keys(value as Record<string, any>), field)\n }\n)", "score": 0.8344526290893555 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8315814733505249 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8303504586219788 } ]
typescript
if (!helpers.isPostalCode(value as string, 'any')) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (
!helpers.isUUID(value as string)) {
field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8526732921600342 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8380786180496216 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8366385698318481 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8345992565155029 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.8345786929130554 } ]
typescript
!helpers.isUUID(value as string)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find(
(countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8341505527496338 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.8298438787460327 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8293226957321167 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 0.8246132731437683 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8240218162536621 } ]
typescript
(countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) }
}) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 0.8461912870407104 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8417338132858276 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8353629112243652 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8337782621383667 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8322491645812988 } ]
typescript
field.report(messages.passport, 'passport', field, { countryCodes }) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string,
refs: RefsStore, options: ParserOptions): TupleNode {
return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.9211332201957703 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.8973244428634644 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.8896081447601318 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8826784491539001 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 0.8823498487472534 } ]
typescript
refs: RefsStore, options: ParserOptions): TupleNode {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization (
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) {
const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.9367115497589111 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.9072700142860413 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.8990491628646851 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " {\n Name: 'ClusterName',\n Value: service.clusterArn?.split('/').pop()\n }]);\n });\n }\n console.info('this.utilization:\\n', JSON.stringify(this.utilization, null, 2));\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides", "score": 0.8805834054946899 }, { "filename": "src/service-utilizations/aws-account-utilization.tsx", "retrieved_chunk": " throw new Error('Method not implemented.');\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides: AwsServiceOverrides\n ): Promise<void> {\n const region = regions[0];\n await this.checkPermissionsForCostExplorer(awsCredentialsProvider, region);\n await this.checkPermissionsForPricing(awsCredentialsProvider, region);\n }\n async checkPermissionsForPricing (awsCredentialsProvider: AwsCredentialsProvider, region: string) {", "score": 0.8677895665168762 } ]
typescript
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) {
import cached from 'cached'; import dayjs from 'dayjs'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import HttpError from 'http-errors'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ContainerInstance, DesiredStatus, ECS, LaunchType, ListClustersCommandOutput, ListServicesCommandOutput, ListTasksCommandOutput, Service, Task, TaskDefinition, TaskDefinitionField, DescribeContainerInstancesCommandOutput } from '@aws-sdk/client-ecs'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { ElasticLoadBalancingV2 } from '@aws-sdk/client-elastic-load-balancing-v2'; import { Api, ApiGatewayV2, GetApisCommandOutput, Integration } from '@aws-sdk/client-apigatewayv2'; import { DescribeInstanceTypesCommandOutput, EC2, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, MAX_MEMORY, AVG_MEMORY, ALB_REQUEST_COUNT, APIG_REQUEST_COUNT } from '../types/constants.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getHourlyCost } from '../utils/utils.js'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; const cache = cached<string>('ecs-util-cache', { backend: { type: 'memory' } }); type AwsEcsUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEcsMetrics = ['CPUUtilization', 'MemoryUtilization']; type EcsService = { clusterArn: string; serviceArn: string; } type ClusterServices = { [clusterArn: string]: { serviceArns: string[]; } } type FargateScaleRange = { min: number; max: number; increment: number; }; type FargateScaleOption = { [cpu: number]: { discrete?: number[]; range?: FargateScaleRange; } } type FargateScale = { cpu: number, memory: number } type AwsEcsUtilizationOverrides = AwsServiceOverrides & { services: EcsService[]; } export class AwsEcsUtilization extends
AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
serviceArns: string[]; services: Service[]; ecsClient: ECS; ec2Client: EC2; cwClient: CloudWatch; elbV2Client: ElasticLoadBalancingV2; apigClient: ApiGatewayV2; pricingClient: Pricing; serviceCosts: { [ service: string ]: number }; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.serviceArns = []; this.services = []; this.serviceCosts = {}; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteService') { await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region); } } private async listAllClusters (): Promise<string[]> { const allClusterArns: string[] = []; let nextToken; do { const response: ListClustersCommandOutput = await this.ecsClient.listClusters({ nextToken }); const { clusterArns = [], nextToken: nextClusterToken } = response || {}; allClusterArns.push(...clusterArns); nextToken = nextClusterToken; } while (nextToken); return allClusterArns; } private async listServicesForClusters (clusterArn: string): Promise<ClusterServices> { const services: string[] = []; let nextToken; do { const response: ListServicesCommandOutput = await this.ecsClient.listServices({ cluster: clusterArn, nextToken }); const { serviceArns = [], nextToken: nextServicesToken } = response || {}; services.push(...serviceArns); nextToken = nextServicesToken; } while (nextToken); return { [clusterArn]: { serviceArns: services } }; } private async describeAllServices (): Promise<Service[]> { const clusterArns = await this.listAllClusters(); const allServices: EcsService[] = []; for (const clusterArn of clusterArns) { const servicesForCluster = await this.listServicesForClusters(clusterArn); allServices.push(...servicesForCluster[clusterArn].serviceArns.map(s => ({ clusterArn, serviceArn: s }))); } return this.describeTheseServices(allServices); } private async describeTheseServices (ecsServices: EcsService[]): Promise<Service[]> { const clusters = ecsServices.reduce<ClusterServices>((acc, ecsService) => { acc[ecsService.clusterArn] = acc[ecsService.clusterArn] || { serviceArns: [] }; acc[ecsService.clusterArn].serviceArns.push(ecsService.serviceArn); return acc; }, {}); const services: Service[] = []; for (const [clusterArn, clusterServices] of Object.entries(clusters)) { const serviceChunks = chunk(clusterServices.serviceArns, 10); for (const serviceChunk of serviceChunks) { const response = await this.ecsClient.describeServices({ cluster: clusterArn, services: serviceChunk }); services.push(...(response?.services || [])); } } return services; } private async getLoadBalacerArnForService (service: Service): Promise<string> { const response = await this.elbV2Client.describeTargetGroups({ TargetGroupArns: [service.loadBalancers?.at(0)?.targetGroupArn] }); return response?.TargetGroups?.at(0)?.LoadBalancerArns?.at(0); } private async findIntegration (apiId: string, registryArn: string): Promise<Integration | undefined> { let nextToken: string; let registeredIntegration: Integration; do { const response = await this.apigClient.getIntegrations({ ApiId: apiId, NextToken: nextToken }); const { Items = [], NextToken } = response || {}; registeredIntegration = Items.find(i => i.IntegrationUri === registryArn); if (!registeredIntegration) { nextToken = NextToken; } } while (nextToken); return registeredIntegration; } private async findRegisteredApi (service: Service, apis: Api[]): Promise<Api | undefined> { const registryArn = service.serviceRegistries?.at(0)?.registryArn; let registeredApi: Api; for (const api of apis) { const registeredIntegration = await this.findIntegration(api.ApiId, registryArn); if (registeredIntegration) { registeredApi = api; break; } } return registeredApi; } private async getApiIdForService (service: Service): Promise<string> { let nextToken: string; let registeredApi: Api; do { const apiResponse: GetApisCommandOutput = await this.apigClient.getApis({ NextToken: nextToken }); const { Items = [], NextToken } = apiResponse || {}; registeredApi = await this.findRegisteredApi(service, Items); if (!registeredApi) { nextToken = NextToken; } } while (nextToken); return registeredApi.ApiId; } private async getTask (service: Service): Promise<Task> { const taskListResponse = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, maxResults: 1, desiredStatus: DesiredStatus.RUNNING }); const { taskArns = [] } = taskListResponse || {}; const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: [taskArns.at(0)] }); const task = describeTasksResponse?.tasks?.at(0); return task; } private async getAllTasks (service: Service): Promise<Task[]> { const taskIds = []; let nextTaskToken; do { const taskListResponse: ListTasksCommandOutput = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, desiredStatus: DesiredStatus.RUNNING, nextToken: nextTaskToken }); const { taskArns = [], nextToken } = taskListResponse || {}; taskIds.push(...taskArns); nextTaskToken = nextToken; } while (nextTaskToken); const allTasks = []; const taskIdPartitions = chunk(taskIds, 100); for (const taskIdPartition of taskIdPartitions) { const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: taskIdPartition }); const { tasks = [] } = describeTasksResponse; allTasks.push(...tasks); } return allTasks; } private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> { const ec2InstanceResponse = await this.ec2Client.describeInstances({ InstanceIds: [containerInstance.ec2InstanceId] }); const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType; const instanceFamily = instanceType?.split('.')?.at(0); return instanceFamily; } private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private getEcsServiceDataQueries (serviceName: string, clusterName: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/ECS', MetricName: metricName, Dimensions: [ { Name: 'ServiceName', Value: serviceName }, { Name: 'ClusterName', Value: clusterName } ] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: AVG_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Average') }, { Id: MAX_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Maximum') } ]; } private getAlbRequestCountQuery (loadBalancerArn: string, period: number): MetricDataQuery { return { Id: ALB_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApplicationELB', MetricName: 'RequestCount', Dimensions: [ { Name: 'ServiceName', Value: loadBalancerArn } ] }, Period: period, Stat: 'Sum' } }; } private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery { return { Id: APIG_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApiGateway', MetricName: 'Count', Dimensions: [ { Name: 'ApiId', Value: apiId } ] }, Period: period, Stat: 'Sum' } }; } private async getMetrics (args: { service: Service, startTime: Date; endTime: Date; period: number; }): Promise<{[ key: string ]: MetricDataResult}> { const { service, startTime, endTime, period } = args; const { serviceName, clusterArn, loadBalancers, serviceRegistries } = service; const clusterName = clusterArn?.split('/').pop(); const queries: MetricDataQuery[] = this.getEcsServiceDataQueries(serviceName, clusterName, period); if (loadBalancers && loadBalancers.length > 0) { const loadBalancerArn = await this.getLoadBalacerArnForService(service); queries.push(this.getAlbRequestCountQuery(loadBalancerArn, period)); } else if (serviceRegistries && serviceRegistries.length > 0) { const apiId = await this.getApiIdForService(service); queries.push(this.getApigRequestCountQuery(apiId, period)); } const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await this.cwClient.getMetricData({ MetricDataQueries: queries, StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private createDiscreteValuesForRange (range: FargateScaleRange): number[] { const { min, max, increment } = range; const discreteVales: number[] = []; let i = min; do { i = i + increment; discreteVales.push(i); } while (i <= max); return discreteVales; } private async getEc2ContainerInfo (service: Service) { const tasks = await this.getAllTasks(service); const taskCpu = Number(tasks.at(0)?.cpu); const allocatedMemory = Number(tasks.at(0)?.memory); let allocatedCpu = taskCpu; let containerInstance: ContainerInstance; let containerInstanceResponse: DescribeContainerInstancesCommandOutput; if (!taskCpu || taskCpu === 0) { const containerInstanceTaskGroupObject = tasks.reduce<{ [containerInstanceArn: string]: { containerInstanceArn: string; tasks: Task[]; } }>((acc, task) => { const { containerInstanceArn } = task; acc[containerInstanceArn] = acc[containerInstanceArn] || { containerInstanceArn, tasks: [] }; acc[containerInstanceArn].tasks.push(task); return acc; }, {}); const containerInstanceTaskGroups = Object.values(containerInstanceTaskGroupObject); containerInstanceTaskGroups.sort((a, b) => { if (a.tasks.length > b.tasks.length) { return -1; } else if (a.tasks.length < b.tasks.length) { return 1; } return 0; }); const largestContainerInstance = containerInstanceTaskGroups.at(0); const maxTaskCount = get(largestContainerInstance, 'tasks.length') || 0; const filteredTaskGroups = containerInstanceTaskGroups .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn)); if (isEmpty(filteredTaskGroups)) { return undefined; } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn) }); // largest container instance containerInstance = containerInstanceResponse?.containerInstances?.at(0); const containerInstanceCpuResource = containerInstance.registeredResources?.find(r => r.name === 'CPU'); const containerInstanceCpu = Number( containerInstanceCpuResource?.doubleValue || containerInstanceCpuResource?.integerValue || containerInstanceCpuResource?.longValue ); allocatedCpu = containerInstanceCpu / maxTaskCount; } } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: tasks.map(task => task.containerInstanceArn) }); containerInstance = containerInstanceResponse?.containerInstances?.at(0); } const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => { acc.add(instance.ec2InstanceId); return acc; }, new Set<string>()); const numEc2Instances = uniqueEc2Instances.size; const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value; const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType); const monthlyCost = monthlyInstanceCost * numEc2Instances; this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances }; } private async checkForEc2ScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { const info = await this.getEc2ContainerInfo(service); if (!info) { return; } const { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances } = info; const maxConsumedVcpus = (maxCpuPercentage * allocatedCpu) / 1024; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const instanceVcpus = allocatedCpu / 1024; let instanceFamily = instanceType?.split('.')?.at(0); if (!instanceFamily) { instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance); } const allInstanceTypes = Object.values(_InstanceType); const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const betterFitCpu = ( it.VCpuInfo.DefaultVCpus >= maxConsumedVcpus && it.VCpuInfo.DefaultVCpus <= instanceVcpus ); const betterFitMemory = ( it.MemoryInfo.SizeInMiB >= maxConsumedMemory && it.MemoryInfo.SizeInMiB <= allocatedMemory ); return betterFitCpu && betterFitMemory; }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1; return memoryScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType); const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances; this.addScenario(service.serviceArn, 'overAllocated', { value: 'true', scaleDown: { action: 'scaleDownEc2Service', isActionable: false, reason: 'The EC2 instances used in this Service\'s cluster appears to be over allocated based on its CPU' + `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) { let monthlyCost = 0; if (platform.toLowerCase() === 'windows') { monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30; } else { if (cpuArch === 'x86_64') { monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; } else { monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30; } } return monthlyCost; } private async getFargateInfo (service: Service) { const tasks = await this.getAllTasks(service); const numTasks = tasks.length; const task = tasks.at(0); const allocatedCpu = Number(task?.cpu); const allocatedMemory = Number(task?.memory); const platform = task.platformFamily || ''; const cpuArch = (task.attributes.find(attr => attr.name === 'ecs.cpu-architecture'))?.value || 'x86_64'; const vcpu = allocatedCpu / 1024; const memory = allocatedMemory / 1024; const monthlyCost = this.calculateFargateCost(platform, cpuArch, vcpu, memory, numTasks); this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost }; } private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html const fargateScaleOptions: FargateScaleOption = { 256: { discrete: [0.5, 1, 2] }, 512: { range: { min: 1, max: 4, increment: 1 } }, 1024: { range: { min: 2, max: 8, increment: 1 } }, 2048: { range: { min: 4, max: 16, increment: 1 } }, 4096: { range: { min: 8, max: 30, increment: 1 } }, 8192: { range: { min: 16, max: 60, increment: 4 } }, 16384: { range: { min: 32, max: 120, increment: 4 } } }; const { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost } = await this.getFargateInfo(service); const maxConsumedCpu = maxCpuPercentage * allocatedCpu; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const lowerCpuOptions = Object.keys(fargateScaleOptions).filter((cpuString) => { const cpu = Number(cpuString); return cpu < allocatedCpu && cpu > maxConsumedCpu; }).sort(); let targetScaleOption: FargateScale; for (const cpuOption of lowerCpuOptions) { const scalingOption = fargateScaleOptions[Number(cpuOption)]; const memoryOptionValues = []; const discreteMemoryOptionValues = scalingOption.discrete || []; memoryOptionValues.push(...discreteMemoryOptionValues); const rangeMemoryOptionsValues = scalingOption.range ? this.createDiscreteValuesForRange(scalingOption.range) : []; memoryOptionValues.push(...rangeMemoryOptionsValues); const optimizedMemory = memoryOptionValues.filter(mem => (mem > maxConsumedMemory)).sort().at(0); if (optimizedMemory) { targetScaleOption = { cpu: Number(cpuOption), memory: (optimizedMemory * 1024) }; break; } } if (targetScaleOption) { const targetMonthlyCost = this.calculateFargateCost( platform, cpuArch, targetScaleOption.cpu / 1024, targetScaleOption.memory / 1024, numTasks ); this.addScenario(service.serviceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownFargateService', isActionable: false, reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' + `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` + `${targetScaleOption.memory} MiB.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) { this.ecsClient = new ECS({ credentials, region }); this.ec2Client = new EC2({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); this.elbV2Client = new ElasticLoadBalancingV2({ credentials, region }); this.apigClient = new ApiGatewayV2({ credentials, region }); this.pricingClient = new Pricing({ credentials, region }); if (overrides?.services) { this.services = await this.describeTheseServices(overrides?.services); } else { this.services = await this.describeAllServices(); } if (this.services.length === 0) return; for (const service of this.services) { const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ service, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [AVG_MEMORY]: avgMemoryMetrics, [MAX_MEMORY]: maxMemoryMetrics, [ALB_REQUEST_COUNT]: albRequestCountMetrics, [APIG_REQUEST_COUNT]: apigRequestCountMetrics } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values); const { max: maxMemory, isStable: maxMemoryIsStable } = getStabilityStats(maxMemoryMetrics.Values); const lowMemoryUtilization = ( (avgMemoryIsStable && maxMemoryIsStable) || maxMemory < 10 ); const requestCountMetricValues = [ ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || []) ]; const totalRequestCount = stats.sum(requestCountMetricValues); const noNetworkUtilization = totalRequestCount === 0; if ( lowCpuUtilization && lowMemoryUtilization && noNetworkUtilization ) { const info = service.launchType === LaunchType.FARGATE ? await this.getFargateInfo(service) : await this.getEc2ContainerInfo(service); if (!info) { return; } const { monthlyCost } = info; this.addScenario(service.serviceArn, 'unused', { value: 'true', delete: { action: 'deleteService', isActionable: true, reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and' + ' network traffic.', monthlySavings: monthlyCost } }); } else if (maxCpu < 0.8 && maxMemory < 0.8) { if (service.launchType === LaunchType.FARGATE) { await this.checkForFargateScaleDown(service, maxCpu, maxMemory); } else { await this.checkForEc2ScaleDown(service, maxCpu, maxMemory); } } const monthlyCost = this.serviceCosts[service.serviceName] || 0; await this.fillData( service.serviceArn, credentials, region, { resourceId: service.serviceName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); AwsEcsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, service.serviceArn, 'AWS/ECS', metricName, [{ Name: 'ServiceName', Value: service.serviceName }, { Name: 'ClusterName', Value: service.clusterArn?.split('/').pop() }]); }); } console.info('this.utilization:\n', JSON.stringify(this.utilization, null, 2)); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } async deleteService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); await ecsClient.deleteService({ service: serviceArn, cluster: clusterName }); } async scaleDownFargateService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string, cpu: number, memory: number ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); const serviceResponse = await ecsClient.describeServices({ cluster: clusterName, services: [serviceArn] }); const taskDefinitionArn = serviceResponse?.services?.at(0)?.taskDefinition; const taskDefResponse = await ecsClient.describeTaskDefinition( { taskDefinition: taskDefinitionArn, include: [TaskDefinitionField.TAGS] } ); const taskDefinition: TaskDefinition = taskDefResponse?.taskDefinition; const tags = taskDefResponse?.tags; const { containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes } = taskDefinition; // TODO: CPU and Memory validation? const revisionResponse = await ecsClient.registerTaskDefinition({ cpu: cpu.toString(), memory: memory.toString(), containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes, tags }); await ecsClient.updateService({ cluster: clusterName, service: serviceArn, taskDefinition: revisionResponse?.taskDefinition?.taskDefinitionArn, forceNewDeployment: true }); } async scaleDownEc2Service (_serviceArn: string, _cpu: number, _memory: number) { /* TODO: Update Asg/Capacity provider? Or update memory/cpu allocation on the tasks? Or both? */ throw HttpError.NotImplemented('Automatic scale down for EC2 backed ECS Clusters is not yet supported.'); } }
src/service-utilizations/aws-ecs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": "import { getInstanceCost } from '../utils/ec2-utils.js';\nimport { Arns } from '../types/constants.js';\nconst cache = cached<string>('ec2-util-cache', {\n backend: {\n type: 'memory'\n }\n});\ntype AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated';\nconst AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn'];\ntype AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & {", "score": 0.8598172664642334 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.859187126159668 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": "import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { Volume } from '@aws-sdk/client-ec2';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns } from '../types/constants.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nexport type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps';\nconst EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps'];", "score": 0.8483338356018066 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": "/*\nimport { AutoScaling } from '@aws-sdk/client-auto-scaling';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { AlertType } from '../types/types.js';\nexport type AutoScalingGroupsUtilizationProps = { \n hasScalingPolicy?: boolean; \n cpuUtilization?: number;\n networkIn?: number;", "score": 0.8481597900390625 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": "const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000);\nconst twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000);\ntype AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes';\nconst AwsCloudWatchLogsMetrics = ['IncomingBytes'];\nexport class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> {\n constructor () {\n super();\n }", "score": 0.847015380859375 } ]
typescript
AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
import cached from 'cached'; import dayjs from 'dayjs'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import HttpError from 'http-errors'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ContainerInstance, DesiredStatus, ECS, LaunchType, ListClustersCommandOutput, ListServicesCommandOutput, ListTasksCommandOutput, Service, Task, TaskDefinition, TaskDefinitionField, DescribeContainerInstancesCommandOutput } from '@aws-sdk/client-ecs'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { ElasticLoadBalancingV2 } from '@aws-sdk/client-elastic-load-balancing-v2'; import { Api, ApiGatewayV2, GetApisCommandOutput, Integration } from '@aws-sdk/client-apigatewayv2'; import { DescribeInstanceTypesCommandOutput, EC2, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, MAX_MEMORY, AVG_MEMORY, ALB_REQUEST_COUNT, APIG_REQUEST_COUNT } from '../types/constants.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getHourlyCost } from '../utils/utils.js'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; const cache = cached<string>('ecs-util-cache', { backend: { type: 'memory' } }); type AwsEcsUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEcsMetrics = ['CPUUtilization', 'MemoryUtilization']; type EcsService = { clusterArn: string; serviceArn: string; } type ClusterServices = { [clusterArn: string]: { serviceArns: string[]; } } type FargateScaleRange = { min: number; max: number; increment: number; }; type FargateScaleOption = { [cpu: number]: { discrete?: number[]; range?: FargateScaleRange; } } type FargateScale = { cpu: number, memory: number }
type AwsEcsUtilizationOverrides = AwsServiceOverrides & {
services: EcsService[]; } export class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> { serviceArns: string[]; services: Service[]; ecsClient: ECS; ec2Client: EC2; cwClient: CloudWatch; elbV2Client: ElasticLoadBalancingV2; apigClient: ApiGatewayV2; pricingClient: Pricing; serviceCosts: { [ service: string ]: number }; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.serviceArns = []; this.services = []; this.serviceCosts = {}; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteService') { await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region); } } private async listAllClusters (): Promise<string[]> { const allClusterArns: string[] = []; let nextToken; do { const response: ListClustersCommandOutput = await this.ecsClient.listClusters({ nextToken }); const { clusterArns = [], nextToken: nextClusterToken } = response || {}; allClusterArns.push(...clusterArns); nextToken = nextClusterToken; } while (nextToken); return allClusterArns; } private async listServicesForClusters (clusterArn: string): Promise<ClusterServices> { const services: string[] = []; let nextToken; do { const response: ListServicesCommandOutput = await this.ecsClient.listServices({ cluster: clusterArn, nextToken }); const { serviceArns = [], nextToken: nextServicesToken } = response || {}; services.push(...serviceArns); nextToken = nextServicesToken; } while (nextToken); return { [clusterArn]: { serviceArns: services } }; } private async describeAllServices (): Promise<Service[]> { const clusterArns = await this.listAllClusters(); const allServices: EcsService[] = []; for (const clusterArn of clusterArns) { const servicesForCluster = await this.listServicesForClusters(clusterArn); allServices.push(...servicesForCluster[clusterArn].serviceArns.map(s => ({ clusterArn, serviceArn: s }))); } return this.describeTheseServices(allServices); } private async describeTheseServices (ecsServices: EcsService[]): Promise<Service[]> { const clusters = ecsServices.reduce<ClusterServices>((acc, ecsService) => { acc[ecsService.clusterArn] = acc[ecsService.clusterArn] || { serviceArns: [] }; acc[ecsService.clusterArn].serviceArns.push(ecsService.serviceArn); return acc; }, {}); const services: Service[] = []; for (const [clusterArn, clusterServices] of Object.entries(clusters)) { const serviceChunks = chunk(clusterServices.serviceArns, 10); for (const serviceChunk of serviceChunks) { const response = await this.ecsClient.describeServices({ cluster: clusterArn, services: serviceChunk }); services.push(...(response?.services || [])); } } return services; } private async getLoadBalacerArnForService (service: Service): Promise<string> { const response = await this.elbV2Client.describeTargetGroups({ TargetGroupArns: [service.loadBalancers?.at(0)?.targetGroupArn] }); return response?.TargetGroups?.at(0)?.LoadBalancerArns?.at(0); } private async findIntegration (apiId: string, registryArn: string): Promise<Integration | undefined> { let nextToken: string; let registeredIntegration: Integration; do { const response = await this.apigClient.getIntegrations({ ApiId: apiId, NextToken: nextToken }); const { Items = [], NextToken } = response || {}; registeredIntegration = Items.find(i => i.IntegrationUri === registryArn); if (!registeredIntegration) { nextToken = NextToken; } } while (nextToken); return registeredIntegration; } private async findRegisteredApi (service: Service, apis: Api[]): Promise<Api | undefined> { const registryArn = service.serviceRegistries?.at(0)?.registryArn; let registeredApi: Api; for (const api of apis) { const registeredIntegration = await this.findIntegration(api.ApiId, registryArn); if (registeredIntegration) { registeredApi = api; break; } } return registeredApi; } private async getApiIdForService (service: Service): Promise<string> { let nextToken: string; let registeredApi: Api; do { const apiResponse: GetApisCommandOutput = await this.apigClient.getApis({ NextToken: nextToken }); const { Items = [], NextToken } = apiResponse || {}; registeredApi = await this.findRegisteredApi(service, Items); if (!registeredApi) { nextToken = NextToken; } } while (nextToken); return registeredApi.ApiId; } private async getTask (service: Service): Promise<Task> { const taskListResponse = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, maxResults: 1, desiredStatus: DesiredStatus.RUNNING }); const { taskArns = [] } = taskListResponse || {}; const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: [taskArns.at(0)] }); const task = describeTasksResponse?.tasks?.at(0); return task; } private async getAllTasks (service: Service): Promise<Task[]> { const taskIds = []; let nextTaskToken; do { const taskListResponse: ListTasksCommandOutput = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, desiredStatus: DesiredStatus.RUNNING, nextToken: nextTaskToken }); const { taskArns = [], nextToken } = taskListResponse || {}; taskIds.push(...taskArns); nextTaskToken = nextToken; } while (nextTaskToken); const allTasks = []; const taskIdPartitions = chunk(taskIds, 100); for (const taskIdPartition of taskIdPartitions) { const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: taskIdPartition }); const { tasks = [] } = describeTasksResponse; allTasks.push(...tasks); } return allTasks; } private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> { const ec2InstanceResponse = await this.ec2Client.describeInstances({ InstanceIds: [containerInstance.ec2InstanceId] }); const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType; const instanceFamily = instanceType?.split('.')?.at(0); return instanceFamily; } private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private getEcsServiceDataQueries (serviceName: string, clusterName: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/ECS', MetricName: metricName, Dimensions: [ { Name: 'ServiceName', Value: serviceName }, { Name: 'ClusterName', Value: clusterName } ] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: AVG_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Average') }, { Id: MAX_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Maximum') } ]; } private getAlbRequestCountQuery (loadBalancerArn: string, period: number): MetricDataQuery { return { Id: ALB_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApplicationELB', MetricName: 'RequestCount', Dimensions: [ { Name: 'ServiceName', Value: loadBalancerArn } ] }, Period: period, Stat: 'Sum' } }; } private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery { return { Id: APIG_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApiGateway', MetricName: 'Count', Dimensions: [ { Name: 'ApiId', Value: apiId } ] }, Period: period, Stat: 'Sum' } }; } private async getMetrics (args: { service: Service, startTime: Date; endTime: Date; period: number; }): Promise<{[ key: string ]: MetricDataResult}> { const { service, startTime, endTime, period } = args; const { serviceName, clusterArn, loadBalancers, serviceRegistries } = service; const clusterName = clusterArn?.split('/').pop(); const queries: MetricDataQuery[] = this.getEcsServiceDataQueries(serviceName, clusterName, period); if (loadBalancers && loadBalancers.length > 0) { const loadBalancerArn = await this.getLoadBalacerArnForService(service); queries.push(this.getAlbRequestCountQuery(loadBalancerArn, period)); } else if (serviceRegistries && serviceRegistries.length > 0) { const apiId = await this.getApiIdForService(service); queries.push(this.getApigRequestCountQuery(apiId, period)); } const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await this.cwClient.getMetricData({ MetricDataQueries: queries, StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private createDiscreteValuesForRange (range: FargateScaleRange): number[] { const { min, max, increment } = range; const discreteVales: number[] = []; let i = min; do { i = i + increment; discreteVales.push(i); } while (i <= max); return discreteVales; } private async getEc2ContainerInfo (service: Service) { const tasks = await this.getAllTasks(service); const taskCpu = Number(tasks.at(0)?.cpu); const allocatedMemory = Number(tasks.at(0)?.memory); let allocatedCpu = taskCpu; let containerInstance: ContainerInstance; let containerInstanceResponse: DescribeContainerInstancesCommandOutput; if (!taskCpu || taskCpu === 0) { const containerInstanceTaskGroupObject = tasks.reduce<{ [containerInstanceArn: string]: { containerInstanceArn: string; tasks: Task[]; } }>((acc, task) => { const { containerInstanceArn } = task; acc[containerInstanceArn] = acc[containerInstanceArn] || { containerInstanceArn, tasks: [] }; acc[containerInstanceArn].tasks.push(task); return acc; }, {}); const containerInstanceTaskGroups = Object.values(containerInstanceTaskGroupObject); containerInstanceTaskGroups.sort((a, b) => { if (a.tasks.length > b.tasks.length) { return -1; } else if (a.tasks.length < b.tasks.length) { return 1; } return 0; }); const largestContainerInstance = containerInstanceTaskGroups.at(0); const maxTaskCount = get(largestContainerInstance, 'tasks.length') || 0; const filteredTaskGroups = containerInstanceTaskGroups .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn)); if (isEmpty(filteredTaskGroups)) { return undefined; } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn) }); // largest container instance containerInstance = containerInstanceResponse?.containerInstances?.at(0); const containerInstanceCpuResource = containerInstance.registeredResources?.find(r => r.name === 'CPU'); const containerInstanceCpu = Number( containerInstanceCpuResource?.doubleValue || containerInstanceCpuResource?.integerValue || containerInstanceCpuResource?.longValue ); allocatedCpu = containerInstanceCpu / maxTaskCount; } } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: tasks.map(task => task.containerInstanceArn) }); containerInstance = containerInstanceResponse?.containerInstances?.at(0); } const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => { acc.add(instance.ec2InstanceId); return acc; }, new Set<string>()); const numEc2Instances = uniqueEc2Instances.size; const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value; const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType); const monthlyCost = monthlyInstanceCost * numEc2Instances; this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances }; } private async checkForEc2ScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { const info = await this.getEc2ContainerInfo(service); if (!info) { return; } const { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances } = info; const maxConsumedVcpus = (maxCpuPercentage * allocatedCpu) / 1024; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const instanceVcpus = allocatedCpu / 1024; let instanceFamily = instanceType?.split('.')?.at(0); if (!instanceFamily) { instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance); } const allInstanceTypes = Object.values(_InstanceType); const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const betterFitCpu = ( it.VCpuInfo.DefaultVCpus >= maxConsumedVcpus && it.VCpuInfo.DefaultVCpus <= instanceVcpus ); const betterFitMemory = ( it.MemoryInfo.SizeInMiB >= maxConsumedMemory && it.MemoryInfo.SizeInMiB <= allocatedMemory ); return betterFitCpu && betterFitMemory; }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1; return memoryScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType); const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances; this.addScenario(service.serviceArn, 'overAllocated', { value: 'true', scaleDown: { action: 'scaleDownEc2Service', isActionable: false, reason: 'The EC2 instances used in this Service\'s cluster appears to be over allocated based on its CPU' + `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) { let monthlyCost = 0; if (platform.toLowerCase() === 'windows') { monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30; } else { if (cpuArch === 'x86_64') { monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; } else { monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30; } } return monthlyCost; } private async getFargateInfo (service: Service) { const tasks = await this.getAllTasks(service); const numTasks = tasks.length; const task = tasks.at(0); const allocatedCpu = Number(task?.cpu); const allocatedMemory = Number(task?.memory); const platform = task.platformFamily || ''; const cpuArch = (task.attributes.find(attr => attr.name === 'ecs.cpu-architecture'))?.value || 'x86_64'; const vcpu = allocatedCpu / 1024; const memory = allocatedMemory / 1024; const monthlyCost = this.calculateFargateCost(platform, cpuArch, vcpu, memory, numTasks); this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost }; } private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html const fargateScaleOptions: FargateScaleOption = { 256: { discrete: [0.5, 1, 2] }, 512: { range: { min: 1, max: 4, increment: 1 } }, 1024: { range: { min: 2, max: 8, increment: 1 } }, 2048: { range: { min: 4, max: 16, increment: 1 } }, 4096: { range: { min: 8, max: 30, increment: 1 } }, 8192: { range: { min: 16, max: 60, increment: 4 } }, 16384: { range: { min: 32, max: 120, increment: 4 } } }; const { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost } = await this.getFargateInfo(service); const maxConsumedCpu = maxCpuPercentage * allocatedCpu; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const lowerCpuOptions = Object.keys(fargateScaleOptions).filter((cpuString) => { const cpu = Number(cpuString); return cpu < allocatedCpu && cpu > maxConsumedCpu; }).sort(); let targetScaleOption: FargateScale; for (const cpuOption of lowerCpuOptions) { const scalingOption = fargateScaleOptions[Number(cpuOption)]; const memoryOptionValues = []; const discreteMemoryOptionValues = scalingOption.discrete || []; memoryOptionValues.push(...discreteMemoryOptionValues); const rangeMemoryOptionsValues = scalingOption.range ? this.createDiscreteValuesForRange(scalingOption.range) : []; memoryOptionValues.push(...rangeMemoryOptionsValues); const optimizedMemory = memoryOptionValues.filter(mem => (mem > maxConsumedMemory)).sort().at(0); if (optimizedMemory) { targetScaleOption = { cpu: Number(cpuOption), memory: (optimizedMemory * 1024) }; break; } } if (targetScaleOption) { const targetMonthlyCost = this.calculateFargateCost( platform, cpuArch, targetScaleOption.cpu / 1024, targetScaleOption.memory / 1024, numTasks ); this.addScenario(service.serviceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownFargateService', isActionable: false, reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' + `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` + `${targetScaleOption.memory} MiB.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) { this.ecsClient = new ECS({ credentials, region }); this.ec2Client = new EC2({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); this.elbV2Client = new ElasticLoadBalancingV2({ credentials, region }); this.apigClient = new ApiGatewayV2({ credentials, region }); this.pricingClient = new Pricing({ credentials, region }); if (overrides?.services) { this.services = await this.describeTheseServices(overrides?.services); } else { this.services = await this.describeAllServices(); } if (this.services.length === 0) return; for (const service of this.services) { const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ service, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [AVG_MEMORY]: avgMemoryMetrics, [MAX_MEMORY]: maxMemoryMetrics, [ALB_REQUEST_COUNT]: albRequestCountMetrics, [APIG_REQUEST_COUNT]: apigRequestCountMetrics } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values); const { max: maxMemory, isStable: maxMemoryIsStable } = getStabilityStats(maxMemoryMetrics.Values); const lowMemoryUtilization = ( (avgMemoryIsStable && maxMemoryIsStable) || maxMemory < 10 ); const requestCountMetricValues = [ ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || []) ]; const totalRequestCount = stats.sum(requestCountMetricValues); const noNetworkUtilization = totalRequestCount === 0; if ( lowCpuUtilization && lowMemoryUtilization && noNetworkUtilization ) { const info = service.launchType === LaunchType.FARGATE ? await this.getFargateInfo(service) : await this.getEc2ContainerInfo(service); if (!info) { return; } const { monthlyCost } = info; this.addScenario(service.serviceArn, 'unused', { value: 'true', delete: { action: 'deleteService', isActionable: true, reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and' + ' network traffic.', monthlySavings: monthlyCost } }); } else if (maxCpu < 0.8 && maxMemory < 0.8) { if (service.launchType === LaunchType.FARGATE) { await this.checkForFargateScaleDown(service, maxCpu, maxMemory); } else { await this.checkForEc2ScaleDown(service, maxCpu, maxMemory); } } const monthlyCost = this.serviceCosts[service.serviceName] || 0; await this.fillData( service.serviceArn, credentials, region, { resourceId: service.serviceName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); AwsEcsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, service.serviceArn, 'AWS/ECS', metricName, [{ Name: 'ServiceName', Value: service.serviceName }, { Name: 'ClusterName', Value: service.clusterArn?.split('/').pop() }]); }); } console.info('this.utilization:\n', JSON.stringify(this.utilization, null, 2)); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } async deleteService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); await ecsClient.deleteService({ service: serviceArn, cluster: clusterName }); } async scaleDownFargateService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string, cpu: number, memory: number ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); const serviceResponse = await ecsClient.describeServices({ cluster: clusterName, services: [serviceArn] }); const taskDefinitionArn = serviceResponse?.services?.at(0)?.taskDefinition; const taskDefResponse = await ecsClient.describeTaskDefinition( { taskDefinition: taskDefinitionArn, include: [TaskDefinitionField.TAGS] } ); const taskDefinition: TaskDefinition = taskDefResponse?.taskDefinition; const tags = taskDefResponse?.tags; const { containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes } = taskDefinition; // TODO: CPU and Memory validation? const revisionResponse = await ecsClient.registerTaskDefinition({ cpu: cpu.toString(), memory: memory.toString(), containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes, tags }); await ecsClient.updateService({ cluster: clusterName, service: serviceArn, taskDefinition: revisionResponse?.taskDefinition?.taskDefinitionArn, forceNewDeployment: true }); } async scaleDownEc2Service (_serviceArn: string, _cpu: number, _memory: number) { /* TODO: Update Asg/Capacity provider? Or update memory/cpu allocation on the tasks? Or both? */ throw HttpError.NotImplemented('Automatic scale down for EC2 backed ECS Clusters is not yet supported.'); } }
src/service-utilizations/aws-ecs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/types/types.ts", "retrieved_chunk": " userInput?: UserInput\n}\nexport type AwsUtilizationOverrides = {\n [ serviceName: string ]: AwsServiceOverrides\n}\nexport type StabilityStats = {\n mean: number;\n max: number;\n maxZScore: number;\n standardDeviation: number;", "score": 0.8557658195495605 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": "import { getInstanceCost } from '../utils/ec2-utils.js';\nimport { Arns } from '../types/constants.js';\nconst cache = cached<string>('ec2-util-cache', {\n backend: {\n type: 'memory'\n }\n});\ntype AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated';\nconst AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn'];\ntype AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & {", "score": 0.8468706607818604 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " backend: {\n type: 'memory'\n }\n});\ntype AwsUtilizationProviderProps = AwsUtilizationProviderType & {\n utilization?: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region?: string;\n};", "score": 0.8442535400390625 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": "/*\nimport { AutoScaling } from '@aws-sdk/client-auto-scaling';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { AlertType } from '../types/types.js';\nexport type AutoScalingGroupsUtilizationProps = { \n hasScalingPolicy?: boolean; \n cpuUtilization?: number;\n networkIn?: number;", "score": 0.8414732217788696 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8395617008209229 } ]
typescript
type AwsEcsUtilizationOverrides = AwsServiceOverrides & {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report
(messages.postalCode, 'postalCode', field) }
} else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 0.8404714465141296 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8299767374992371 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8296841382980347 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8281754851341248 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8216772675514221 } ]
typescript
(messages.postalCode, 'postalCode', field) }
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost,
hourlyCost: getHourlyCost(this.cost) }
); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9183833003044128 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8708274364471436 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8506662845611572 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.838032603263855 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8375005722045898 } ]
typescript
hourlyCost: getHourlyCost(this.cost) }
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) {
this.addScenario(natGatewayArn, 'activeConnectionCount', {
value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8854503631591797 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.8704029321670532 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8674360513687134 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.865770697593689 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8637833595275879 } ]
typescript
this.addScenario(natGatewayArn, 'activeConnectionCount', {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId;
const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);
const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8797101974487305 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8773269653320312 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8695516586303711 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8658456206321716 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.8629006743431091 } ]
typescript
const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost,
hourlyCost: getHourlyCost(cost) }
); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9318330883979797 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8620548844337463 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8597872257232666 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8566248416900635 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8517817854881287 } ]
typescript
hourlyCost: getHourlyCost(cost) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map(
(schema, index) => schema[PARSE](String(index), refs, options)), }
} }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9452720880508423 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n allowUnknownProperties: this.#allowUnknownProperties,\n validations: this.compileValidations(refs),\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: this.#groups.map((group) => {\n return group[PARSE](refs, options)\n }),", "score": 0.9393197894096375 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.928848385810852 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.9199712872505188 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9174560308456421 } ]
typescript
(schema, index) => schema[PARSE](String(index), refs, options)), }
import cached from 'cached'; import dayjs from 'dayjs'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import HttpError from 'http-errors'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ContainerInstance, DesiredStatus, ECS, LaunchType, ListClustersCommandOutput, ListServicesCommandOutput, ListTasksCommandOutput, Service, Task, TaskDefinition, TaskDefinitionField, DescribeContainerInstancesCommandOutput } from '@aws-sdk/client-ecs'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { ElasticLoadBalancingV2 } from '@aws-sdk/client-elastic-load-balancing-v2'; import { Api, ApiGatewayV2, GetApisCommandOutput, Integration } from '@aws-sdk/client-apigatewayv2'; import { DescribeInstanceTypesCommandOutput, EC2, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, MAX_MEMORY, AVG_MEMORY, ALB_REQUEST_COUNT, APIG_REQUEST_COUNT } from '../types/constants.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getHourlyCost } from '../utils/utils.js'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; const cache = cached<string>('ecs-util-cache', { backend: { type: 'memory' } }); type AwsEcsUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEcsMetrics = ['CPUUtilization', 'MemoryUtilization']; type EcsService = { clusterArn: string; serviceArn: string; } type ClusterServices = { [clusterArn: string]: { serviceArns: string[]; } } type FargateScaleRange = { min: number; max: number; increment: number; }; type FargateScaleOption = { [cpu: number]: { discrete?: number[]; range?: FargateScaleRange; } } type FargateScale = { cpu: number, memory: number } type AwsEcsUtilizationOverrides = AwsServiceOverrides & { services: EcsService[]; }
export class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
serviceArns: string[]; services: Service[]; ecsClient: ECS; ec2Client: EC2; cwClient: CloudWatch; elbV2Client: ElasticLoadBalancingV2; apigClient: ApiGatewayV2; pricingClient: Pricing; serviceCosts: { [ service: string ]: number }; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.serviceArns = []; this.services = []; this.serviceCosts = {}; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteService') { await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region); } } private async listAllClusters (): Promise<string[]> { const allClusterArns: string[] = []; let nextToken; do { const response: ListClustersCommandOutput = await this.ecsClient.listClusters({ nextToken }); const { clusterArns = [], nextToken: nextClusterToken } = response || {}; allClusterArns.push(...clusterArns); nextToken = nextClusterToken; } while (nextToken); return allClusterArns; } private async listServicesForClusters (clusterArn: string): Promise<ClusterServices> { const services: string[] = []; let nextToken; do { const response: ListServicesCommandOutput = await this.ecsClient.listServices({ cluster: clusterArn, nextToken }); const { serviceArns = [], nextToken: nextServicesToken } = response || {}; services.push(...serviceArns); nextToken = nextServicesToken; } while (nextToken); return { [clusterArn]: { serviceArns: services } }; } private async describeAllServices (): Promise<Service[]> { const clusterArns = await this.listAllClusters(); const allServices: EcsService[] = []; for (const clusterArn of clusterArns) { const servicesForCluster = await this.listServicesForClusters(clusterArn); allServices.push(...servicesForCluster[clusterArn].serviceArns.map(s => ({ clusterArn, serviceArn: s }))); } return this.describeTheseServices(allServices); } private async describeTheseServices (ecsServices: EcsService[]): Promise<Service[]> { const clusters = ecsServices.reduce<ClusterServices>((acc, ecsService) => { acc[ecsService.clusterArn] = acc[ecsService.clusterArn] || { serviceArns: [] }; acc[ecsService.clusterArn].serviceArns.push(ecsService.serviceArn); return acc; }, {}); const services: Service[] = []; for (const [clusterArn, clusterServices] of Object.entries(clusters)) { const serviceChunks = chunk(clusterServices.serviceArns, 10); for (const serviceChunk of serviceChunks) { const response = await this.ecsClient.describeServices({ cluster: clusterArn, services: serviceChunk }); services.push(...(response?.services || [])); } } return services; } private async getLoadBalacerArnForService (service: Service): Promise<string> { const response = await this.elbV2Client.describeTargetGroups({ TargetGroupArns: [service.loadBalancers?.at(0)?.targetGroupArn] }); return response?.TargetGroups?.at(0)?.LoadBalancerArns?.at(0); } private async findIntegration (apiId: string, registryArn: string): Promise<Integration | undefined> { let nextToken: string; let registeredIntegration: Integration; do { const response = await this.apigClient.getIntegrations({ ApiId: apiId, NextToken: nextToken }); const { Items = [], NextToken } = response || {}; registeredIntegration = Items.find(i => i.IntegrationUri === registryArn); if (!registeredIntegration) { nextToken = NextToken; } } while (nextToken); return registeredIntegration; } private async findRegisteredApi (service: Service, apis: Api[]): Promise<Api | undefined> { const registryArn = service.serviceRegistries?.at(0)?.registryArn; let registeredApi: Api; for (const api of apis) { const registeredIntegration = await this.findIntegration(api.ApiId, registryArn); if (registeredIntegration) { registeredApi = api; break; } } return registeredApi; } private async getApiIdForService (service: Service): Promise<string> { let nextToken: string; let registeredApi: Api; do { const apiResponse: GetApisCommandOutput = await this.apigClient.getApis({ NextToken: nextToken }); const { Items = [], NextToken } = apiResponse || {}; registeredApi = await this.findRegisteredApi(service, Items); if (!registeredApi) { nextToken = NextToken; } } while (nextToken); return registeredApi.ApiId; } private async getTask (service: Service): Promise<Task> { const taskListResponse = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, maxResults: 1, desiredStatus: DesiredStatus.RUNNING }); const { taskArns = [] } = taskListResponse || {}; const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: [taskArns.at(0)] }); const task = describeTasksResponse?.tasks?.at(0); return task; } private async getAllTasks (service: Service): Promise<Task[]> { const taskIds = []; let nextTaskToken; do { const taskListResponse: ListTasksCommandOutput = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, desiredStatus: DesiredStatus.RUNNING, nextToken: nextTaskToken }); const { taskArns = [], nextToken } = taskListResponse || {}; taskIds.push(...taskArns); nextTaskToken = nextToken; } while (nextTaskToken); const allTasks = []; const taskIdPartitions = chunk(taskIds, 100); for (const taskIdPartition of taskIdPartitions) { const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: taskIdPartition }); const { tasks = [] } = describeTasksResponse; allTasks.push(...tasks); } return allTasks; } private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> { const ec2InstanceResponse = await this.ec2Client.describeInstances({ InstanceIds: [containerInstance.ec2InstanceId] }); const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType; const instanceFamily = instanceType?.split('.')?.at(0); return instanceFamily; } private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private getEcsServiceDataQueries (serviceName: string, clusterName: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/ECS', MetricName: metricName, Dimensions: [ { Name: 'ServiceName', Value: serviceName }, { Name: 'ClusterName', Value: clusterName } ] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: AVG_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Average') }, { Id: MAX_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Maximum') } ]; } private getAlbRequestCountQuery (loadBalancerArn: string, period: number): MetricDataQuery { return { Id: ALB_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApplicationELB', MetricName: 'RequestCount', Dimensions: [ { Name: 'ServiceName', Value: loadBalancerArn } ] }, Period: period, Stat: 'Sum' } }; } private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery { return { Id: APIG_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApiGateway', MetricName: 'Count', Dimensions: [ { Name: 'ApiId', Value: apiId } ] }, Period: period, Stat: 'Sum' } }; } private async getMetrics (args: { service: Service, startTime: Date; endTime: Date; period: number; }): Promise<{[ key: string ]: MetricDataResult}> { const { service, startTime, endTime, period } = args; const { serviceName, clusterArn, loadBalancers, serviceRegistries } = service; const clusterName = clusterArn?.split('/').pop(); const queries: MetricDataQuery[] = this.getEcsServiceDataQueries(serviceName, clusterName, period); if (loadBalancers && loadBalancers.length > 0) { const loadBalancerArn = await this.getLoadBalacerArnForService(service); queries.push(this.getAlbRequestCountQuery(loadBalancerArn, period)); } else if (serviceRegistries && serviceRegistries.length > 0) { const apiId = await this.getApiIdForService(service); queries.push(this.getApigRequestCountQuery(apiId, period)); } const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await this.cwClient.getMetricData({ MetricDataQueries: queries, StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private createDiscreteValuesForRange (range: FargateScaleRange): number[] { const { min, max, increment } = range; const discreteVales: number[] = []; let i = min; do { i = i + increment; discreteVales.push(i); } while (i <= max); return discreteVales; } private async getEc2ContainerInfo (service: Service) { const tasks = await this.getAllTasks(service); const taskCpu = Number(tasks.at(0)?.cpu); const allocatedMemory = Number(tasks.at(0)?.memory); let allocatedCpu = taskCpu; let containerInstance: ContainerInstance; let containerInstanceResponse: DescribeContainerInstancesCommandOutput; if (!taskCpu || taskCpu === 0) { const containerInstanceTaskGroupObject = tasks.reduce<{ [containerInstanceArn: string]: { containerInstanceArn: string; tasks: Task[]; } }>((acc, task) => { const { containerInstanceArn } = task; acc[containerInstanceArn] = acc[containerInstanceArn] || { containerInstanceArn, tasks: [] }; acc[containerInstanceArn].tasks.push(task); return acc; }, {}); const containerInstanceTaskGroups = Object.values(containerInstanceTaskGroupObject); containerInstanceTaskGroups.sort((a, b) => { if (a.tasks.length > b.tasks.length) { return -1; } else if (a.tasks.length < b.tasks.length) { return 1; } return 0; }); const largestContainerInstance = containerInstanceTaskGroups.at(0); const maxTaskCount = get(largestContainerInstance, 'tasks.length') || 0; const filteredTaskGroups = containerInstanceTaskGroups .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn)); if (isEmpty(filteredTaskGroups)) { return undefined; } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn) }); // largest container instance containerInstance = containerInstanceResponse?.containerInstances?.at(0); const containerInstanceCpuResource = containerInstance.registeredResources?.find(r => r.name === 'CPU'); const containerInstanceCpu = Number( containerInstanceCpuResource?.doubleValue || containerInstanceCpuResource?.integerValue || containerInstanceCpuResource?.longValue ); allocatedCpu = containerInstanceCpu / maxTaskCount; } } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: tasks.map(task => task.containerInstanceArn) }); containerInstance = containerInstanceResponse?.containerInstances?.at(0); } const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => { acc.add(instance.ec2InstanceId); return acc; }, new Set<string>()); const numEc2Instances = uniqueEc2Instances.size; const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value; const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType); const monthlyCost = monthlyInstanceCost * numEc2Instances; this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances }; } private async checkForEc2ScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { const info = await this.getEc2ContainerInfo(service); if (!info) { return; } const { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances } = info; const maxConsumedVcpus = (maxCpuPercentage * allocatedCpu) / 1024; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const instanceVcpus = allocatedCpu / 1024; let instanceFamily = instanceType?.split('.')?.at(0); if (!instanceFamily) { instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance); } const allInstanceTypes = Object.values(_InstanceType); const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const betterFitCpu = ( it.VCpuInfo.DefaultVCpus >= maxConsumedVcpus && it.VCpuInfo.DefaultVCpus <= instanceVcpus ); const betterFitMemory = ( it.MemoryInfo.SizeInMiB >= maxConsumedMemory && it.MemoryInfo.SizeInMiB <= allocatedMemory ); return betterFitCpu && betterFitMemory; }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1; return memoryScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType); const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances; this.addScenario(service.serviceArn, 'overAllocated', { value: 'true', scaleDown: { action: 'scaleDownEc2Service', isActionable: false, reason: 'The EC2 instances used in this Service\'s cluster appears to be over allocated based on its CPU' + `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) { let monthlyCost = 0; if (platform.toLowerCase() === 'windows') { monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30; } else { if (cpuArch === 'x86_64') { monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; } else { monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30; } } return monthlyCost; } private async getFargateInfo (service: Service) { const tasks = await this.getAllTasks(service); const numTasks = tasks.length; const task = tasks.at(0); const allocatedCpu = Number(task?.cpu); const allocatedMemory = Number(task?.memory); const platform = task.platformFamily || ''; const cpuArch = (task.attributes.find(attr => attr.name === 'ecs.cpu-architecture'))?.value || 'x86_64'; const vcpu = allocatedCpu / 1024; const memory = allocatedMemory / 1024; const monthlyCost = this.calculateFargateCost(platform, cpuArch, vcpu, memory, numTasks); this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost }; } private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html const fargateScaleOptions: FargateScaleOption = { 256: { discrete: [0.5, 1, 2] }, 512: { range: { min: 1, max: 4, increment: 1 } }, 1024: { range: { min: 2, max: 8, increment: 1 } }, 2048: { range: { min: 4, max: 16, increment: 1 } }, 4096: { range: { min: 8, max: 30, increment: 1 } }, 8192: { range: { min: 16, max: 60, increment: 4 } }, 16384: { range: { min: 32, max: 120, increment: 4 } } }; const { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost } = await this.getFargateInfo(service); const maxConsumedCpu = maxCpuPercentage * allocatedCpu; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const lowerCpuOptions = Object.keys(fargateScaleOptions).filter((cpuString) => { const cpu = Number(cpuString); return cpu < allocatedCpu && cpu > maxConsumedCpu; }).sort(); let targetScaleOption: FargateScale; for (const cpuOption of lowerCpuOptions) { const scalingOption = fargateScaleOptions[Number(cpuOption)]; const memoryOptionValues = []; const discreteMemoryOptionValues = scalingOption.discrete || []; memoryOptionValues.push(...discreteMemoryOptionValues); const rangeMemoryOptionsValues = scalingOption.range ? this.createDiscreteValuesForRange(scalingOption.range) : []; memoryOptionValues.push(...rangeMemoryOptionsValues); const optimizedMemory = memoryOptionValues.filter(mem => (mem > maxConsumedMemory)).sort().at(0); if (optimizedMemory) { targetScaleOption = { cpu: Number(cpuOption), memory: (optimizedMemory * 1024) }; break; } } if (targetScaleOption) { const targetMonthlyCost = this.calculateFargateCost( platform, cpuArch, targetScaleOption.cpu / 1024, targetScaleOption.memory / 1024, numTasks ); this.addScenario(service.serviceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownFargateService', isActionable: false, reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' + `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` + `${targetScaleOption.memory} MiB.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) { this.ecsClient = new ECS({ credentials, region }); this.ec2Client = new EC2({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); this.elbV2Client = new ElasticLoadBalancingV2({ credentials, region }); this.apigClient = new ApiGatewayV2({ credentials, region }); this.pricingClient = new Pricing({ credentials, region }); if (overrides?.services) { this.services = await this.describeTheseServices(overrides?.services); } else { this.services = await this.describeAllServices(); } if (this.services.length === 0) return; for (const service of this.services) { const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ service, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [AVG_MEMORY]: avgMemoryMetrics, [MAX_MEMORY]: maxMemoryMetrics, [ALB_REQUEST_COUNT]: albRequestCountMetrics, [APIG_REQUEST_COUNT]: apigRequestCountMetrics } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values); const { max: maxMemory, isStable: maxMemoryIsStable } = getStabilityStats(maxMemoryMetrics.Values); const lowMemoryUtilization = ( (avgMemoryIsStable && maxMemoryIsStable) || maxMemory < 10 ); const requestCountMetricValues = [ ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || []) ]; const totalRequestCount = stats.sum(requestCountMetricValues); const noNetworkUtilization = totalRequestCount === 0; if ( lowCpuUtilization && lowMemoryUtilization && noNetworkUtilization ) { const info = service.launchType === LaunchType.FARGATE ? await this.getFargateInfo(service) : await this.getEc2ContainerInfo(service); if (!info) { return; } const { monthlyCost } = info; this.addScenario(service.serviceArn, 'unused', { value: 'true', delete: { action: 'deleteService', isActionable: true, reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and' + ' network traffic.', monthlySavings: monthlyCost } }); } else if (maxCpu < 0.8 && maxMemory < 0.8) { if (service.launchType === LaunchType.FARGATE) { await this.checkForFargateScaleDown(service, maxCpu, maxMemory); } else { await this.checkForEc2ScaleDown(service, maxCpu, maxMemory); } } const monthlyCost = this.serviceCosts[service.serviceName] || 0; await this.fillData( service.serviceArn, credentials, region, { resourceId: service.serviceName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); AwsEcsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, service.serviceArn, 'AWS/ECS', metricName, [{ Name: 'ServiceName', Value: service.serviceName }, { Name: 'ClusterName', Value: service.clusterArn?.split('/').pop() }]); }); } console.info('this.utilization:\n', JSON.stringify(this.utilization, null, 2)); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } async deleteService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); await ecsClient.deleteService({ service: serviceArn, cluster: clusterName }); } async scaleDownFargateService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string, cpu: number, memory: number ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); const serviceResponse = await ecsClient.describeServices({ cluster: clusterName, services: [serviceArn] }); const taskDefinitionArn = serviceResponse?.services?.at(0)?.taskDefinition; const taskDefResponse = await ecsClient.describeTaskDefinition( { taskDefinition: taskDefinitionArn, include: [TaskDefinitionField.TAGS] } ); const taskDefinition: TaskDefinition = taskDefResponse?.taskDefinition; const tags = taskDefResponse?.tags; const { containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes } = taskDefinition; // TODO: CPU and Memory validation? const revisionResponse = await ecsClient.registerTaskDefinition({ cpu: cpu.toString(), memory: memory.toString(), containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes, tags }); await ecsClient.updateService({ cluster: clusterName, service: serviceArn, taskDefinition: revisionResponse?.taskDefinition?.taskDefinitionArn, forceNewDeployment: true }); } async scaleDownEc2Service (_serviceArn: string, _cpu: number, _memory: number) { /* TODO: Update Asg/Capacity provider? Or update memory/cpu allocation on the tasks? Or both? */ throw HttpError.NotImplemented('Automatic scale down for EC2 backed ECS Clusters is not yet supported.'); } }
src/service-utilizations/aws-ecs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.8639334440231323 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": "import { getInstanceCost } from '../utils/ec2-utils.js';\nimport { Arns } from '../types/constants.js';\nconst cache = cached<string>('ec2-util-cache', {\n backend: {\n type: 'memory'\n }\n});\ntype AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated';\nconst AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn'];\ntype AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & {", "score": 0.8615070581436157 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": "const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000);\nconst twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000);\ntype AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes';\nconst AwsCloudWatchLogsMetrics = ['IncomingBytes'];\nexport class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> {\n constructor () {\n super();\n }", "score": 0.8557949066162109 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": "import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { Volume } from '@aws-sdk/client-ec2';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns } from '../types/constants.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nexport type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps';\nconst EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps'];", "score": 0.8554685115814209 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": "/*\nimport { AutoScaling } from '@aws-sdk/client-auto-scaling';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { AlertType } from '../types/types.js';\nexport type AutoScalingGroupsUtilizationProps = { \n hasScalingPolicy?: boolean; \n cpuUtilization?: number;\n networkIn?: number;", "score": 0.8534048795700073 } ]
typescript
export class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode:
(typeof helpers)['passportCountryCodes'][number][] }
/** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 0.8262670040130615 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " PassportOptions | ((field: FieldContext) => PassportOptions)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const countryCodes =\n typeof options === 'function' ? options(field).countryCode : options.countryCode", "score": 0.8262425661087036 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],", "score": 0.8134168386459351 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " CreditCardOptions,\n PostalCodeOptions,\n NormalizeUrlOptions,\n AlphaNumericOptions,\n NormalizeEmailOptions,\n} from '../../types.js'\nimport camelcase from 'camelcase'\nimport normalizeUrl from 'normalize-url'\n/**\n * Validates the value to be a string", "score": 0.8122707009315491 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " postalCountryCodes: postalCodeLocales as PostalCodeLocale[],\n passportCountryCodes: [\n 'AM',\n 'AR',\n 'AT',\n 'AU',\n 'AZ',\n 'BE',\n 'BG',\n 'BR',", "score": 0.8108956813812256 } ]
typescript
(typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [
IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.9140989780426025 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.8894302845001221 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.8892481327056885 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8870241641998291 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8865163326263428 } ]
typescript
IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await
rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.8805810213088989 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.8718600273132324 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.861853837966919 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8522228002548218 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8498156666755676 } ]
typescript
rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); }
await this.fillData( natGatewayArn, credentials, region, {
resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8437323570251465 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8327042460441589 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " isActionable: true,\n reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' +\n 'and network traffic.', \n monthlySavings: cost\n }\n });\n } else {\n // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization\n const networkInMax = stats.max(maxNetworkBytesIn.Values);\n const networkOutMax = stats.max(maxNetworkBytesOut.Values);", "score": 0.8300308585166931 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " Bucket: bucketName\n });\n if (!res.IntelligentTieringConfigurationList) {\n const { monthlySavings } = await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasIntelligentTiering', {\n value: 'false',\n optimize: { \n action: 'enableIntelligientTiering', \n isActionable: true,\n reason: 'Intelligient tiering is not enabled for this bucket',", "score": 0.8292171359062195 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " action: 'deleteEBSVolume',\n isActionable: true,\n reason: 'No operations performed on this volume in the last week',\n monthlySavings: cost\n }\n });\n }\n }\n}", "score": 0.8216754198074341 } ]
typescript
await this.fillData( natGatewayArn, credentials, region, {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await
rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.8849720358848572 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8464103937149048 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8259279727935791 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8246303796768188 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8177758455276489 } ]
typescript
rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name;
const bucketArn = Arns.S3(bucketName);
await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " });\n this.ec2Client = new EC2({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({\n credentials,\n region\n });\n this.elbV2Client = new ElasticLoadBalancingV2({", "score": 0.8776229619979858 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.region = regions[0];\n this.rdsClient = new RDS({\n credentials,\n region: this.region\n });\n this.cwClient = new CloudWatch({ \n credentials, \n region: this.region", "score": 0.8770278692245483 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) {\n await cwLogsClient.createExportTask({\n logGroupName,\n destination: bucket,\n from: 0,\n to: Date.now()\n });\n }\n private async getAllLogGroups (credentials: any, region: string) {\n let allLogGroups: LogGroup[] = [];", "score": 0.8643139004707336 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const cwClient = new CloudWatch({\n credentials,\n region\n });\n const pricingClient = new Pricing({\n credentials,\n region\n });\n this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds);\n const instanceIds = this.instances.map(i => i.InstanceId);", "score": 0.8557496070861816 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8548626899719238 } ]
typescript
const bucketArn = Arns.S3(bucketName);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost =
(bucketBytes / ONE_GB_IN_BYTES) * 0.022;
/* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " Stat: 'Sum'\n }\n }\n ],\n StartTime: oneMonthAgo,\n EndTime: new Date()\n });\n const readIops = get(res, 'MetricDataResults[0].Values[0]', 0);\n const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0);\n const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0);", "score": 0.8819811344146729 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand;\n const onDemandKeys = Object.keys(onDemandData);\n const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions;\n const priceDimensionsKeys = Object.keys(priceDimensionsData);\n const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD;\n // monthly cost\n return pricePerHour * 24 * 30;\n }\n}", "score": 0.8701823353767395 }, { "filename": "src/utils/ec2-utils.ts", "retrieved_chunk": " ServiceCode: 'AmazonEC2'\n });\n const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand;\n const onDemandKeys = Object.keys(onDemandData);\n const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions;\n const priceDimensionsKeys = Object.keys(priceDimensionsData);\n const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD;\n return pricePerHour * 24 * 30;\n}", "score": 0.8592857122421265 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " Metric: {\n Namespace: 'AWS/RDS',\n MetricName: 'TotalBackupStorageBilled',\n Dimensions: [{\n Name: 'DBInstanceIdentifier',\n Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'", "score": 0.848591685295105 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0);\n const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0);\n const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0);\n const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0);\n const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0);\n return {\n totalIops: readIops + writeIops,\n totalThroughput: readThroughput + writeThroughput,\n freeStorageSpace,\n totalBackupStorageBilled,", "score": 0.8432997465133667 } ]
typescript
(bucketBytes / ONE_GB_IN_BYTES) * 0.022;
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export
interface ErrorReporterContract extends BaseReporter {
createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>", "score": 0.8272134065628052 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 0.825005054473877 }, { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": " */\nexport class SimpleErrorReporter implements ErrorReporterContract {\n /**\n * Boolean to know one or more errors have been reported\n */\n hasErrors: boolean = false\n /**\n * Collection of errors\n */\n errors: SimpleError[] = []", "score": 0.8241317272186279 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 0.804846465587616 }, { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": " /**\n * Report an error.\n */\n report(\n message: string,\n rule: string,\n field: FieldContext,\n meta?: Record<string, any> | undefined\n ) {\n const error: SimpleError = {", "score": 0.8004432916641235 } ]
typescript
interface ErrorReporterContract extends BaseReporter {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from './helpers.js' import { createRule } from './create_rule.js' import { SchemaBuilder } from '../schema/builder.js' import { SimpleMessagesProvider } from '../messages_provider/simple_messages_provider.js' import { VineValidator } from './validator.js' import { fields, messages } from '../defaults.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' import { SimpleErrorReporter } from '../reporters/simple_error_reporter.js' /** * Validate user input with type-safety using a pre-compiled schema. */ export class Vine extends SchemaBuilder { /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields) /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter() /** * Control whether or not to convert empty strings to null */ convertEmptyStringsToNull: boolean = false /** * Helpers to perform type-checking or cast types keeping * HTML forms serialization behavior in mind. */ helpers = helpers /** * Convert a validation function to a Vine schema rule */ createRule = createRule /** * Pre-compiles a schema into a validation function. * * ```ts * const validate = vine.compile(schema) * await validate({ data }) * ``` */ compile<Schema extends SchemaTypes>(schema: Schema) { return new VineValidator<Schema, Record<string, any> | undefined>(schema, { convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, }) } /** * Define a callback to validate the metadata given to the validator * at runtime */ withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) { return { compile: <Schema extends SchemaTypes>(schema: Schema) => { return new VineValidator<Schema, MetaData>(schema, { convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, metaDataValidator: callback, }) }, } } /** * Validate data against a schema. Optionally, you can define * error messages, fields, a custom messages provider, * or an error reporter. * * ```ts * await vine.validate({ schema, data }) * await vine.validate({ schema, data, messages, fields }) * * await vine.validate({ schema, data, messages, fields }, { * errorReporter * }) * ``` */ validate<Schema extends SchemaTypes>( options: { /** * Schema to use for validation */ schema: Schema /** * Data to validate */ data: any } & ValidationOptions<Record<string, any> | undefined> ): Promise<Infer<Schema>> { const validator = this.compile(options.schema) return validator
.validate(options.data, options) }
}
src/vine/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/vine/validator.ts", "retrieved_chunk": " : [options: ValidationOptions<MetaData>]\n ): Promise<Infer<Schema>> {\n if (options?.meta && this.#metaDataValidator) {\n this.#metaDataValidator(options.meta)\n }\n const errorReporter = options?.errorReporter || this.errorReporter\n const messagesProvider = options?.messagesProvider || this.messagesProvider\n return this.#validateFn(\n data,\n options?.meta || {},", "score": 0.9023621678352356 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": " implicit?: boolean\n isAsync?: boolean\n }\n) {\n const rule: ValidationRule<Options> = {\n validator,\n isAsync: metaData?.isAsync || validator.constructor.name === 'AsyncFunction',\n implicit: metaData?.implicit ?? false,\n }\n return function (...options: GetArgs<Options>): Validation<Options> {", "score": 0.8387491703033447 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " * meta: { userId: auth.user.id },\n * errorReporter,\n * messagesProvider\n * })\n * ```\n */\n validate(\n data: any,\n ...[options]: [undefined] extends MetaData\n ? [options?: ValidationOptions<MetaData> | undefined]", "score": 0.8368816375732422 }, { "filename": "src/types.ts", "retrieved_chunk": "export type Validation<Options extends any> = {\n /**\n * Options to pass to the validator function.\n */\n options?: Options\n /**\n * The rule to use\n */\n rule: ValidationRule<Options>\n}", "score": 0.8323618769645691 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8295367956161499 } ]
typescript
.validate(options.data, options) }
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this
.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
} else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.84409499168396 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " scaleDown: {\n action: 'scaleDownEc2Service',\n isActionable: false,\n reason: 'The EC2 instances used in this Service\\'s cluster appears to be over allocated based on its CPU' + \n `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }", "score": 0.8346188068389893 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const monthlySavings = cost - targetInstanceCost;\n this.addScenario(instanceArn, 'overAllocated', {\n value: 'overAllocated',\n scaleDown: {\n action: 'scaleDownInstance',\n isActionable: false,\n reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + \n `suggest scaling down to a ${targetInstanceType.InstanceType}`,\n monthlySavings\n }", "score": 0.8290229439735413 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": "import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Pricing } from '@aws-sdk/client-pricing';\nimport get from 'lodash.get';\nimport { ONE_GB_IN_BYTES } from '../types/constants.js';\nimport { getHourlyCost } from '../utils/utils.js';\nconst oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000));", "score": 0.8235836029052734 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.8234963417053223 } ]
typescript
.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { Compiler, refsBuilder } from '@vinejs/compiler' import type { MessagesProviderContact, Refs } from '@vinejs/compiler/types' import { messages } from '../defaults.js' import { OTYPE, PARSE } from '../symbols.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, } from '../types.js' /** * Error messages to share with the compiler */ const COMPILER_ERROR_MESSAGES = { required: messages.required, array: messages.array, object: messages.object, } /** * Vine Validator exposes the API to validate data using a pre-compiled * schema. */ export class VineValidator< Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>, > { /** * Reference to static types */ declare [OTYPE]: Schema[typeof OTYPE] /** * Validator to use to validate metadata */ #metaDataValidator?: MetaDataValidator /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract /** * Parses schema to compiler nodes. */ #parse(schema: Schema) { const refs = refsBuilder() return { compilerNode: { type: 'root' as const, schema:
schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
} /** * Refs computed from the compiled output */ #refs: Refs /** * Compiled validator function */ #validateFn: ReturnType<Compiler['compile']> constructor( schema: Schema, options: { convertEmptyStringsToNull: boolean metaDataValidator?: MetaDataValidator messagesProvider: MessagesProviderContact errorReporter: () => ErrorReporterContract } ) { const { compilerNode, refs } = this.#parse(schema) this.#refs = refs this.#validateFn = new Compiler(compilerNode, { convertEmptyStringsToNull: options.convertEmptyStringsToNull, messages: COMPILER_ERROR_MESSAGES, }).compile() this.errorReporter = options.errorReporter this.messagesProvider = options.messagesProvider this.#metaDataValidator = options.metaDataValidator } /** * Validate data against a schema. Optionally, you can share metaData with * the validator * * ```ts * await validator.validate(data) * await validator.validate(data, { meta: {} }) * * await validator.validate(data, { * meta: { userId: auth.user.id }, * errorReporter, * messagesProvider * }) * ``` */ validate( data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>] ): Promise<Infer<Schema>> { if (options?.meta && this.#metaDataValidator) { this.#metaDataValidator(options.meta) } const errorReporter = options?.errorReporter || this.errorReporter const messagesProvider = options?.messagesProvider || this.messagesProvider return this.#validateFn( data, options?.meta || {}, this.#refs, messagesProvider, errorReporter() ) } }
src/vine/validator.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8938246965408325 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8884037137031555 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8859077095985413 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return {\n conditionalFnRefId: refs.trackConditional((value, field) => {\n return schema[IS_OF_TYPE]!(value, field)\n }),\n schema: schema[PARSE](propertyName, refs, options),\n }\n }),\n }\n }\n}", "score": 0.8848187923431396 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8792262673377991 } ]
typescript
schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName);
this.addScenario(bucketArn, 'hasIntelligentTiering', {
value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " } = await this.getLogGroupData(credentials, region, logGroup);\n this.addScenario(logGroupArn, 'hasRetentionPolicy', {\n value: retentionInDays?.toString(),\n optimize: {\n action: 'setRetentionPolicy',\n isActionable: true,\n reason: 'this log group does not have a retention policy',\n monthlySavings: monthlyStorageCost\n }\n });", "score": 0.8487493991851807 }, { "filename": "src/service-utilizations/aws-account-utilization.tsx", "retrieved_chunk": " const pricingClient = new Pricing({ \n credentials: await awsCredentialsProvider.getCredentials(),\n region: region\n });\n await pricingClient.describeServices({}).catch((e) => { \n if(e.Code === 'AccessDeniedException'){ \n this.addScenario('PriceListAPIs', 'hasPermissionsForPriceList', {\n value: 'false',\n optimize: {\n action: '', ", "score": 0.844693124294281 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8276312351226807 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.8226885199546814 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8198282718658447 } ]
typescript
this.addScenario(bucketArn, 'hasIntelligentTiering', {
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); }
protected addData (resourceArn: string, dataType: keyof Data, value: any) {
// only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8345417380332947 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " }\n async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) {\n const s3Client = new S3({\n credentials: await awsCredentialsProvider.getCredentials()\n });\n const resourceId = resourceArn.split(':').at(-1);\n if (actionName === 'enableIntelligientTiering') { \n await this.enableIntelligientTiering(s3Client, resourceId);\n }\n }", "score": 0.8323009014129639 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8295414447784424 }, { "filename": "src/types/types.ts", "retrieved_chunk": "import { Tag } from '@aws-sdk/client-ec2';\nexport type Data = {\n region: string,\n resourceId: string,\n associatedResourceId?: string,\n stack?: string,\n hourlyCost?: number,\n monthlyCost?: number,\n maxMonthlySavings?: number,\n [ key: string ]: any;", "score": 0.8264979720115662 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.820966899394989 } ]
typescript
protected addData (resourceArn: string, dataType: keyof Data, value: any) {
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.
fillData( bucketArn, credentials, region, {
resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8756879568099976 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8514544367790222 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " } = await this.getLogGroupData(credentials, region, logGroup);\n this.addScenario(logGroupArn, 'hasRetentionPolicy', {\n value: retentionInDays?.toString(),\n optimize: {\n action: 'setRetentionPolicy',\n isActionable: true,\n reason: 'this log group does not have a retention policy',\n monthlySavings: monthlyStorageCost\n }\n });", "score": 0.8499218821525574 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8499075174331665 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.849265992641449 } ]
typescript
fillData( bucketArn, credentials, region, {
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max(
scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
}); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8447561264038086 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8445374965667725 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8400126099586487 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " if (!utilization[service] || isEmpty(utilization[service])) return;\n Object.keys(utilization[service]).forEach((resource) => { \n totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0;\n });\n });\n return usd.format(totalSavings);\n}\nexport function sentenceCase (name: string): string { \n const result = name.replace(/([A-Z])/g, ' $1');\n return result[0].toUpperCase() + result.substring(1).toLowerCase();", "score": 0.8343519568443298 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": "import get from 'lodash.get';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { Bucket, S3 } from '@aws-sdk/client-s3';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns, ONE_GB_IN_BYTES } from '../types/constants.js';\ntype S3CostData = {\n monthlyCost: number,", "score": 0.8290249109268188 } ]
typescript
scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } }
public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; }
public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " this.addScenario(dbInstanceArn, 'cpuUtilization', {\n value: metrics.cpuUtilization.toString(), \n scaleDown: {\n action: '', \n isActionable: false,\n reason: 'Max CPU Utilization is under 50%',\n monthlySavings: 0\n }\n });\n }", "score": 0.8548918962478638 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": "const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000);\nconst twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000);\ntype AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes';\nconst AwsCloudWatchLogsMetrics = ['IncomingBytes'];\nexport class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> {\n constructor () {\n super();\n }", "score": 0.8358525633811951 }, { "filename": "src/types/types.ts", "retrieved_chunk": "}\nexport type Scenarios<ScenarioTypes extends string> = {\n [ scenarioType in ScenarioTypes ]: Scenario\n}\nexport type Resource<ScenarioTypes extends string> = {\n scenarios: Scenarios<ScenarioTypes>,\n data: Data,\n metrics: Metrics\n}\nexport type Utilization<ScenarioTypes extends string> = {", "score": 0.8354834318161011 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8316739201545715 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.829958438873291 } ]
typescript
public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; }
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn
= Arns.Ebs(region, this.accountId, volumeId);
const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0; await this.fillData( volumeArn, credentials, region, { resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await rateLimitMap(volumes, 5, 5, analyzeEbsVolume); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'hasAttachedInstances', { value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8775252103805542 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n return metricDataRes.MetricDataResults;\n }\n private async getRegionalUtilization (credentials: any, region: string) {\n const allNatGateways = await this.getAllNatGateways(credentials, region);\n const analyzeNatGateway = async (natGateway: NatGateway) => {\n const natGatewayId = natGateway.NatGatewayId;\n const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);\n const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId);\n const activeConnectionCount = get(results, '[0].Values[0]') as number;", "score": 0.8686645030975342 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8684266805648804 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.855965256690979 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.8556910157203674 } ]
typescript
= Arns.Ebs(region, this.accountId, volumeId);
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0,
scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
}); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8447561264038086 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8445374965667725 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8400126099586487 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " if (!utilization[service] || isEmpty(utilization[service])) return;\n Object.keys(utilization[service]).forEach((resource) => { \n totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0;\n });\n });\n return usd.format(totalSavings);\n}\nexport function sentenceCase (name: string): string { \n const result = name.replace(/([A-Z])/g, ' $1');\n return result[0].toUpperCase() + result.substring(1).toLowerCase();", "score": 0.8343519568443298 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": "import get from 'lodash.get';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { Bucket, S3 } from '@aws-sdk/client-s3';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns, ONE_GB_IN_BYTES } from '../types/constants.js';\ntype S3CostData = {\n monthlyCost: number,", "score": 0.8290249109268188 } ]
typescript
scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0,
scenario.optimize?.monthlySavings || 0 );
}); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8447561264038086 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8445374965667725 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8400126099586487 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " if (!utilization[service] || isEmpty(utilization[service])) return;\n Object.keys(utilization[service]).forEach((resource) => { \n totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0;\n });\n });\n return usd.format(totalSavings);\n}\nexport function sentenceCase (name: string): string { \n const result = name.replace(/([A-Z])/g, ' $1');\n return result[0].toUpperCase() + result.substring(1).toLowerCase();", "score": 0.8343519568443298 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": "import get from 'lodash.get';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { Bucket, S3 } from '@aws-sdk/client-s3';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns, ONE_GB_IN_BYTES } from '../types/constants.js';\ntype S3CostData = {\n monthlyCost: number,", "score": 0.8290249109268188 } ]
typescript
scenario.optimize?.monthlySavings || 0 );
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn = Arns.Ebs(region, this.accountId, volumeId); const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0;
await this.fillData( volumeArn, credentials, region, {
resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await rateLimitMap(volumes, 5, 5, analyzeEbsVolume); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'hasAttachedInstances', { value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8894611597061157 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8653651475906372 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8586737513542175 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8528770208358765 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.851557731628418 } ]
typescript
await this.fillData( volumeArn, credentials, region, {
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn = Arns.Ebs(region, this.accountId, volumeId); const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0; await this.fillData( volumeArn, credentials, region, { resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await
rateLimitMap(volumes, 5, 5, analyzeEbsVolume);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'hasAttachedInstances', { value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.8878427147865295 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8522347211837769 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8500286340713501 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8384447693824768 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8339075446128845 } ]
typescript
rateLimitMap(volumes, 5, 5, analyzeEbsVolume);
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn = Arns.Ebs(region, this.accountId, volumeId); const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0; await this.fillData( volumeArn, credentials, region, { resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await rateLimitMap(volumes, 5, 5, analyzeEbsVolume); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.
addScenario(volumeArn, 'hasAttachedInstances', {
value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n}", "score": 0.8890198469161987 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8829860687255859 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.87601637840271 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.8760148286819458 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.87396240234375 } ]
typescript
addScenario(volumeArn, 'hasAttachedInstances', {
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021; const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;
await this.fillData(dbInstanceArn, credentials, this.region, {
resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) }); rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasDatabaseConnections', { value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8632716536521912 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const cwClient = new CloudWatch({\n credentials,\n region\n });\n const pricingClient = new Pricing({\n credentials,\n region\n });\n this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds);\n const instanceIds = this.instances.map(i => i.InstanceId);", "score": 0.8604248762130737 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8578610420227051 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8496315479278564 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.849416971206665 } ]
typescript
await this.fillData(dbInstanceArn, credentials, this.region, {
import React from 'react'; import get from 'lodash.get'; import { BaseProvider, BaseWidget } from '@tinystacks/ops-core'; import { AwsResourceType, Utilization, actionTypeToEnum, HistoryEvent } from '../types/types.js'; import { RecommendationsOverrides, HasActionType, HasUtilization, Regions } from '../types/utilization-recommendations-types.js'; import { UtilizationRecommendationsUi } from './utilization-recommendations-ui/utilization-recommendations-ui.js'; import { filterUtilizationForActionType } from '../utils/utilization.js'; import { AwsUtilizationRecommendations as AwsUtilizationRecommendationsType } from '../ops-types.js'; export type AwsUtilizationRecommendationsProps = AwsUtilizationRecommendationsType & HasActionType & HasUtilization & Regions; export class AwsUtilizationRecommendations extends BaseWidget { utilization?: { [key: AwsResourceType | string]: Utilization<string> }; sessionHistory: HistoryEvent[]; allRegions?: string[]; region?: string; constructor (props: AwsUtilizationRecommendationsProps) { super(props); this.utilization = props.utilization; this.region = props.region || 'us-east-1'; this.sessionHistory = props.sessionHistory || []; this.allRegions = props.allRegions; } static fromJson (props: AwsUtilizationRecommendationsProps) { return new AwsUtilizationRecommendations(props); } toJson () { return { ...super.toJson(), utilization: this.utilization, sessionHistory: this.sessionHistory, allRegions: this.allRegions, region: this.region }; } async getData (providers: BaseProvider[], overrides?: RecommendationsOverrides) { const depMap = { utils: '../utils/utils.js' }; const { getAwsCredentialsProvider, getAwsUtilizationProvider, listAllRegions } = await import(depMap.utils); const utilProvider = getAwsUtilizationProvider(providers); const awsCredsProvider = getAwsCredentialsProvider(providers); this.allRegions = await listAllRegions(awsCredsProvider); if (overrides?.refresh) { await utilProvider.hardRefresh(awsCredsProvider, this.region); } this.sessionHistory = await utilProvider.getSessionHistory(); if (overrides?.region) { this.region = overrides.region; await utilProvider.hardRefresh(awsCredsProvider, this.region); } this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region); if (overrides?.resourceActions) { const { actionType, resourceArns } = overrides.resourceActions; const resourceArnsSet = new Set<string>(resourceArns); const filteredServices =
filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);
for (const serviceUtil of Object.keys(filteredServices)) { const filteredServiceUtil = Object.keys(filteredServices[serviceUtil]) .filter(resArn => resourceArnsSet.has(resArn)); for (const resourceArn of filteredServiceUtil) { const resource = filteredServices[serviceUtil][resourceArn]; for (const scenario of Object.keys(resource.scenarios)) { await utilProvider.doAction( serviceUtil, awsCredsProvider, get(resource.scenarios[scenario], `${actionType}.action`), actionTypeToEnum[actionType], resourceArn, get(resource.data, 'region', 'us-east-1') ); } } } } } render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) { function onResourcesAction (resourceArns: string[], actionType: string) { overridesCallback({ resourceActions: { resourceArns, actionType } }); } function onRefresh () { overridesCallback({ refresh: true }); } function onRegionChange (region: string) { overridesCallback({ region }); } return ( <UtilizationRecommendationsUi utilization={this.utilization || {}} sessionHistory={this.sessionHistory} onResourcesAction={onResourcesAction} onRefresh={onRefresh} allRegions={this.allRegions || []} region={this.region} onRegionChange={onRegionChange} /> ); } }
src/widgets/aws-utilization-recommendations.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );\n await utilizationCache.set(service, this.utilization[service]);\n }\n return this.utilization;", "score": 0.9224101901054382 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n async getUtilization (\n credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n if (serviceOverrides?.forceRefesh) {\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );", "score": 0.9118947982788086 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.8948534727096558 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.891816258430481 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.8847800493240356 } ]
typescript
filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);
import isEmpty from 'lodash.isempty'; import { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js'; export function filterUtilizationForActionType ( utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[] ): { [service: string]: Utilization<string> } { const filtered: { [service: string]: Utilization<string> } = {}; if (!utilization) { return filtered; } Object.keys(utilization).forEach((service) => { filtered[service] = filterServiceForActionType(utilization, service, actionType, session); }); return filtered; } export function filterServiceForActionType ( utilization: { [service: string]: Utilization<string> }, service: string, actionType: ActionType, session: HistoryEvent[] ) { const resourcesInProgress = session.map((historyevent) => { return historyevent.resourceArn; }); const serviceUtil = utilization[service]; const actionFilteredServiceUtil = Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => { if(resourcesInProgress.includes(id)){ delete aggUtil[id]; return aggUtil; } const filteredScenarios: Scenarios<string> = {}; Object.entries(resource.scenarios).forEach(([sType, details]) => { if (Object.hasOwn(details, actionType)) { filteredScenarios[sType] = details; } }); if (!filteredScenarios || isEmpty(filteredScenarios)) { return aggUtil; } aggUtil[id] = { ...resource, scenarios: filteredScenarios }; return aggUtil; }, {}); return actionFilteredServiceUtil; } export function getNumberOfResourcesFromFilteredActions (filtered
: { [service: string]: Utilization<string> }): number {
let total = 0; Object.keys(filtered).forEach((s) => { if (!filtered[s] || isEmpty(filtered[s])) return; total += Object.keys(filtered[s]).length; }); return total; } export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } { const result: { [ key in ActionType ]: number } = { [ActionType.OPTIMIZE]: 0, [ActionType.DELETE]: 0, [ActionType.SCALE_DOWN]: 0 }; session.forEach((historyEvent) => { result[historyEvent.actionType] ++; }); return result; } export function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; total += Object.keys(utilization[service]).length; }); return total; } export function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); let totalSavings = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; Object.keys(utilization[service]).forEach((resource) => { totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0; }); }); return usd.format(totalSavings); } export function sentenceCase (name: string): string { const result = name.replace(/([A-Z])/g, ' $1'); return result[0].toUpperCase() + result.substring(1).toLowerCase(); } export function splitServiceName (name: string) { return name?.split(/(?=[A-Z])/).join(' '); }
src/utils/utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " </Box>\n </SimpleGrid>\n );\n}\nfunction getTotalRecommendationValues (\n utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[]\n) { \n const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);\n const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const totalResources = getTotalNumberOfResources(utilizations);", "score": 0.8230936527252197 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8168699145317078 }, { "filename": "src/types/types.ts", "retrieved_chunk": "}\nexport type Scenarios<ScenarioTypes extends string> = {\n [ scenarioType in ScenarioTypes ]: Scenario\n}\nexport type Resource<ScenarioTypes extends string> = {\n scenarios: Scenarios<ScenarioTypes>,\n data: Data,\n metrics: Metrics\n}\nexport type Utilization<ScenarioTypes extends string> = {", "score": 0.8057655692100525 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8046398758888245 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];\n const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th =>\n <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'>\n {sentenceCase(th)}\n </Th>\n ): undefined;\n const taskRows = Object.keys(serviceUtil).map(resArn => (", "score": 0.8004249334335327 } ]
typescript
: { [service: string]: Utilization<string> }): number {
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName:
string, serviceUtil: Utilization<string>) {
const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.8913697004318237 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { CHECKBOX_CELL_MAX_WIDTH } from './recommendations-table.js';\nimport { splitServiceName } from '../../utils/utilization.js';\nexport default function ServiceTableRow (props: ServiceTableRowProps) {\n const { serviceUtil, serviceName, children, isChecked, onServiceCheckChange } = props;\n const { isOpen, onToggle } = useDisclosure();\n return (\n <React.Fragment>\n <Tr key={serviceName}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox ", "score": 0.8715372681617737 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": " isChecked={isChecked}\n onChange={onServiceCheckChange}\n />\n </Td>\n <Td>{splitServiceName(serviceName)}</Td>\n <Td>{Object.keys(serviceUtil).length}</Td>\n <Td>\n <Button\n variant='link'\n onClick={onToggle}", "score": 0.8712677955627441 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " if (Object.hasOwn(serviceUtil, resourceArn)) {\n resourceFilteredServices.add(serviceName);\n break;\n }\n }\n });\n const resourceFilteredServiceTables = [...resourceFilteredServices].map((s) => {\n return (\n <Box borderRadius='6px' key={s} mb='3'>\n <HStack bgColor='gray.50' p='1'>", "score": 0.8490156531333923 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { ChevronDownIcon, ChevronUpIcon } from '@chakra-ui/icons';\nimport {\n Tr,\n Td,\n Button,\n useDisclosure,\n Checkbox\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { ServiceTableRowProps } from '../../types/utilization-recommendations-types.js';", "score": 0.840251088142395 } ]
typescript
string, serviceUtil: Utilization<string>) {
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const
backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021;
const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost; await this.fillData(dbInstanceArn, credentials, this.region, { resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) }); rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasDatabaseConnections', { value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n case 'sc1': {\n cost = 0.015 * storage;\n break;\n }\n default: {\n const iops = volume.Iops || 0;\n const throughput = volume.Throughput || 0;\n cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput);\n break;", "score": 0.863449215888977 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " break;\n }\n case 'gp2': {\n cost = 0.10 * storage;\n break;\n }\n case 'io2': {\n let iops = volume.Iops || 0;\n let iopsCost = 0;\n if (iops > 64000) {", "score": 0.8509418368339539 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " if (volume.VolumeId in this.volumeCosts) {\n return this.volumeCosts[volume.VolumeId];\n }\n let cost = 0;\n const storage = volume.Size || 0;\n switch (volume.VolumeType) {\n case 'gp3': {\n const iops = volume.Iops || 0;\n const throughput = volume.Throughput || 0;\n cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput);", "score": 0.8457753658294678 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0);\n const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022;\n /* TODO: improve estimate \n * Based on idea that lower tiers will contain less data\n * Uses arbitrary percentages to separate amount of data in tiers\n */\n const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES;\n const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES;\n const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES;\n const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES;", "score": 0.8374698162078857 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " cost = (0.125 * volume.Size) + iopsCost;\n break;\n }\n case 'io1': {\n cost = (0.125 * storage) + (0.065 * volume.Iops);\n break;\n }\n case 'st1': {\n cost = 0.045 * storage;\n break;", "score": 0.8358645439147949 } ]
typescript
backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021;
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021; const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost; await this.fillData(dbInstanceArn, credentials, this.region, { resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost
: getHourlyCost(monthlyCost) });
rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasDatabaseConnections', { value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8783060312271118 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8739380240440369 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.86568284034729 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8596615791320801 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8566158413887024 } ]
typescript
: getHourlyCost(monthlyCost) });
import React from 'react'; import { BaseProvider, BaseWidget } from '@tinystacks/ops-core'; import { Widget } from '@tinystacks/ops-model'; import { Stack } from '@chakra-ui/react'; import RecommendationOverview from '../components/recommendation-overview.js'; import { AwsUtilizationOverrides, HistoryEvent, Utilization } from '../types/types.js'; import { AwsUtilization as AwsUtilizationType } from '../ops-types.js'; export type AwsUtilizationProps = AwsUtilizationType & { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[] region: string } export class AwsUtilization extends BaseWidget { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[]; region: string; constructor (props: AwsUtilizationProps) { super(props); this.region = props.region || 'us-east-1'; this.utilization = props.utilization || {}; this.sessionHistory = props.sessionHistory || []; } async getData (providers?: BaseProvider[]): Promise<void> { const depMap = { utils: './utils/utils.js' }; const { getAwsCredentialsProvider, getAwsUtilizationProvider } = await import(depMap.utils); const utilProvider = getAwsUtilizationProvider(providers); const awsCredsProvider = getAwsCredentialsProvider(providers); this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region); } static fromJson (object: AwsUtilizationProps): AwsUtilization { return new AwsUtilization(object); } toJson (): AwsUtilizationProps { return { ...super.toJson(), utilization: this.utilization, region: this.region, sessionHistory: this.sessionHistory }; } render ( _children?: (Widget & { renderedElement: JSX.Element; })[], _overridesCallback
?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
return ( <Stack width='100%'> <RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/> </Stack> ); } }
src/widgets/aws-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8790571689605713 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8626716136932373 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.8503153920173645 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " backend: {\n type: 'memory'\n }\n});\ntype AwsUtilizationProviderProps = AwsUtilizationProviderType & {\n utilization?: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region?: string;\n};", "score": 0.8493553400039673 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " function onRegionChange (region: string) {\n overridesCallback({\n region\n });\n }\n return (\n <UtilizationRecommendationsUi\n utilization={this.utilization || {}}\n sessionHistory={this.sessionHistory}\n onResourcesAction={onResourcesAction}", "score": 0.8488050103187561 } ]
typescript
?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
import isEmpty from 'lodash.isempty'; import { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js'; export function filterUtilizationForActionType ( utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[] ): { [service: string]: Utilization<string> } { const filtered: { [service: string]: Utilization<string> } = {}; if (!utilization) { return filtered; } Object.keys(utilization).forEach((service) => { filtered[service] = filterServiceForActionType(utilization, service, actionType, session); }); return filtered; } export function filterServiceForActionType ( utilization: { [service: string]: Utilization<string> }, service: string, actionType: ActionType, session: HistoryEvent[] ) { const resourcesInProgress = session.map((historyevent) => { return historyevent.resourceArn; }); const serviceUtil = utilization[service]; const actionFilteredServiceUtil = Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => { if(resourcesInProgress.includes(id)){ delete aggUtil[id]; return aggUtil; } const filteredScenarios: Scenarios<string> = {}; Object.entries(resource.scenarios).forEach(([sType, details]) => { if (Object.hasOwn(details, actionType)) { filteredScenarios[sType] = details; } }); if (!filteredScenarios || isEmpty(filteredScenarios)) { return aggUtil; } aggUtil[id] = { ...resource, scenarios: filteredScenarios }; return aggUtil; }, {}); return actionFilteredServiceUtil; } export function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(filtered).forEach((s) => { if (!filtered[s] || isEmpty(filtered[s])) return; total += Object.keys(filtered[s]).length; }); return total; }
export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {
const result: { [ key in ActionType ]: number } = { [ActionType.OPTIMIZE]: 0, [ActionType.DELETE]: 0, [ActionType.SCALE_DOWN]: 0 }; session.forEach((historyEvent) => { result[historyEvent.actionType] ++; }); return result; } export function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; total += Object.keys(utilization[service]).length; }); return total; } export function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); let totalSavings = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; Object.keys(utilization[service]).forEach((resource) => { totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0; }); }); return usd.format(totalSavings); } export function sentenceCase (name: string): string { const result = name.replace(/([A-Z])/g, ' $1'); return result[0].toUpperCase() + result.substring(1).toLowerCase(); } export function splitServiceName (name: string) { return name?.split(/(?=[A-Z])/).join(' '); }
src/utils/utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " </Box>\n </SimpleGrid>\n );\n}\nfunction getTotalRecommendationValues (\n utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[]\n) { \n const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);\n const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const totalResources = getTotalNumberOfResources(utilizations);", "score": 0.8705934286117554 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " const numOptimizeChanges = getNumberOfResourcesFromFilteredActions(optimizeChanges);\n const inProgressActions = getNumberOfResourcesInProgress(sessionHistory);\n function actionSummaryStack (\n actionType: ActionType, icon: JSX.Element, actionLabel: string, \n numResources: number, description: string, numResourcesInProgress: number\n ) {\n return (\n <Stack w=\"100%\" p='2' pl='5' pr='5'>\n <Flex>\n <Box w='20px'>", "score": 0.8347117900848389 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 0.815804123878479 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "} from './types/types.js';\nimport { AwsServiceUtilization } from './service-utilizations/aws-service-utilization.js';\nimport { AwsServiceUtilizationFactory } from './service-utilizations/aws-service-utilization-factory.js';\nimport { AwsUtilizationProvider as AwsUtilizationProviderType } from './ops-types.js';\nconst utilizationCache = cached<Utilization<string>>('utilization', {\n backend: {\n type: 'memory'\n }\n});\nconst sessionHistoryCache = cached<Array<HistoryEvent>>('session-history', {", "score": 0.8088195323944092 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8051333427429199 } ]
typescript
export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {
import React from 'react'; import { BaseProvider, BaseWidget } from '@tinystacks/ops-core'; import { Widget } from '@tinystacks/ops-model'; import { Stack } from '@chakra-ui/react'; import RecommendationOverview from '../components/recommendation-overview.js'; import { AwsUtilizationOverrides, HistoryEvent, Utilization } from '../types/types.js'; import { AwsUtilization as AwsUtilizationType } from '../ops-types.js'; export type AwsUtilizationProps = AwsUtilizationType & { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[] region: string } export class AwsUtilization extends BaseWidget { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[]; region: string; constructor (props: AwsUtilizationProps) { super(props); this.region = props.region || 'us-east-1'; this.utilization = props.utilization || {}; this.sessionHistory = props.sessionHistory || []; } async getData (providers?: BaseProvider[]): Promise<void> { const depMap = { utils: './utils/utils.js' }; const { getAwsCredentialsProvider, getAwsUtilizationProvider } = await import(depMap.utils); const utilProvider = getAwsUtilizationProvider(providers); const awsCredsProvider = getAwsCredentialsProvider(providers); this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region); } static fromJson (object: AwsUtilizationProps): AwsUtilization { return new AwsUtilization(object); } toJson (): AwsUtilizationProps { return { ...super.toJson(), utilization: this.utilization, region: this.region, sessionHistory: this.sessionHistory }; } render ( _children?: (Widget & { renderedElement: JSX.Element; })[], _overridesCallback?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element { return ( <Stack width='100%'> <
RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/> </Stack> );
} }
src/widgets/aws-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": "import React from 'react';\nimport { Box, Heading, Text, SimpleGrid } from '@chakra-ui/react';\nimport { ActionType, HistoryEvent, Utilization } from '../types/types.js';\nimport { filterUtilizationForActionType, \n getNumberOfResourcesFromFilteredActions, \n getTotalMonthlySavings, \n getTotalNumberOfResources } from '../utils/utilization.js';\nexport default function RecommendationOverview (\n props: { utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] }\n) {", "score": 0.8613496422767639 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8547661304473877 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " function onRegionChange (region: string) {\n overridesCallback({\n region\n });\n }\n return (\n <UtilizationRecommendationsUi\n utilization={this.utilization || {}}\n sessionHistory={this.sessionHistory}\n onResourcesAction={onResourcesAction}", "score": 0.8538237810134888 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": "}\nexport function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) {\n const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props;\n const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY);\n const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]);\n const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE);\n if (wizardStep === WizardSteps.SUMMARY) {\n return (\n <RecommendationsActionSummary\n utilization={utilization}", "score": 0.8473110795021057 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "import React from 'react';\nimport get from 'lodash.get';\nimport { BaseProvider, BaseWidget } from '@tinystacks/ops-core';\nimport { AwsResourceType, Utilization, actionTypeToEnum, HistoryEvent } from '../types/types.js';\nimport { \n RecommendationsOverrides,\n HasActionType,\n HasUtilization,\n Regions\n} from '../types/utilization-recommendations-types.js';", "score": 0.8409739136695862 } ]
typescript
RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/> </Stack> );
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021; const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost; await this.fillData(dbInstanceArn, credentials, this.region, { resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) }); rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this
.addScenario(dbInstanceArn, 'hasDatabaseConnections', {
value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8430442214012146 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8255319595336914 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.824607789516449 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8196700811386108 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }\n }\n protected addMetric (resourceArn: string, metricName: string, metric: Metric){ \n if(resourceArn in this.utilization){ \n this.utilization[resourceArn].metrics[metricName] = metric;\n }\n }\n protected async identifyCloudformationStack (\n credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string\n ) {", "score": 0.8153366446495056 } ]
typescript
.addScenario(dbInstanceArn, 'hasDatabaseConnections', {
import { Widget } from '@tinystacks/ops-model'; import { ActionType, AwsResourceType, HistoryEvent, Utilization } from './types.js'; export type HasActionType = { actionType: ActionType; } export type HasUtilization = { utilization: { [key: AwsResourceType | string]: Utilization<string> }; sessionHistory: HistoryEvent[]; } interface RemovableResource { onRemoveResource: (resourceArn: string) => void; } interface HasResourcesAction { onResourcesAction: (resourceArns: string[], actionType: string) => void; } interface Refresh { onRefresh: () => void; } export type UtilizationRecommendationsWidget = Widget & HasActionType & HasUtilization & { region: string }; export interface Regions { onRegionChange: (region: string) => void; allRegions: string[]; region: string; } export type UtilizationRecommendationsUiProps = HasUtilization & HasResourcesAction & Refresh & Regions; export type RecommendationsCallback = (props: RecommendationsOverrides) => void; export type RecommendationsOverrides = { refresh?: boolean; resourceActions?: { actionType: string, resourceArns: string[] }; region?: string; }; export type RecommendationsTableProps = HasActionType & HasUtilization & { onContinue: (resourceArns: string[]) => void; onBack: () => void; onRefresh: () => void; }; export type RecommendationsActionsSummaryProps = Widget & HasUtilization; export type RecommendationsActionSummaryProps = HasUtilization & Regions & { onContinue: (selectedActionType:
ActionType) => void;
onRefresh: () => void; }; export type ConfirmSingleRecommendationProps = RemovableResource & HasActionType & HasResourcesAction & { resourceArn: string; }; export type ConfirmRecommendationsProps = RemovableResource & HasActionType & HasResourcesAction & HasUtilization & { resourceArns: string[]; onBack: () => void; }; export type ServiceTableRowProps = { serviceUtil: Utilization<string>; serviceName: string; children?: React.ReactNode; onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void; isChecked: boolean; };
src/types/utilization-recommendations-types.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 0.905830979347229 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": " <RecommendationsActionSummary\n utilization={utilization}\n sessionHistory={sessionHistory}\n onRefresh={onRefresh}\n onContinue={(selectedActionType: ActionType) => {\n setActionType(selectedActionType);\n setWizardStep(WizardSteps.TABLE);\n }}\n allRegions={allRegions}\n region={region}", "score": 0.9049766659736633 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "import {\n UtilizationRecommendationsUi\n} from './utilization-recommendations-ui/utilization-recommendations-ui.js';\nimport { filterUtilizationForActionType } from '../utils/utilization.js';\nimport { AwsUtilizationRecommendations as AwsUtilizationRecommendationsType } from '../ops-types.js';\nexport type AwsUtilizationRecommendationsProps = \n AwsUtilizationRecommendationsType & \n HasActionType & \n HasUtilization & \n Regions;", "score": 0.8998566269874573 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.8980477452278137 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": "}\nexport function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) {\n const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props;\n const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY);\n const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]);\n const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE);\n if (wizardStep === WizardSteps.SUMMARY) {\n return (\n <RecommendationsActionSummary\n utilization={utilization}", "score": 0.8929044604301453 } ]
typescript
ActionType) => void;
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'>
{ splitServiceName(sidePanelService)}
</Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.833448588848114 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " <Menu>\n <MenuButton as={Button} rightIcon={<ChevronDownIcon />}>\n {regionLabel}\n </MenuButton>\n <MenuList minW=\"0\" w={150} h={40} sx={{ overflow:'scroll' }}>\n {allRegions.map(region => \n <MenuItem onClick={() => onRegionChange(region)}>{region}</MenuItem>\n )}\n </MenuList>\n </Menu>", "score": 0.831866979598999 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import React from 'react';\nimport { \n Box, \n Button, \n Flex, \n Heading, \n Icon, \n Menu, \n MenuButton,\n MenuItem, ", "score": 0.8245382905006409 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " {icon}\n </Box>\n <Stack w='450px' pl='1'>\n <Box>\n <Heading as='h5' size='sm'>{actionLabel}</Heading>\n </Box>\n <Box>\n <Text fontSize='sm' color='gray.500'>{description}</Text>\n </Box>\n </Stack>", "score": 0.8240138292312622 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": " isChecked={isChecked}\n onChange={onServiceCheckChange}\n />\n </Td>\n <Td>{splitServiceName(serviceName)}</Td>\n <Td>{Object.keys(serviceUtil).length}</Td>\n <Td>\n <Button\n variant='link'\n onClick={onToggle}", "score": 0.8221926689147949 } ]
typescript
{ splitServiceName(sidePanelService)}
import React from 'react'; import { Box, Button, Flex, Heading, Icon, Menu, MenuButton, MenuItem, MenuList, Spacer, Stack, Text } from '@chakra-ui/react'; import { DeleteIcon, ArrowForwardIcon, ArrowDownIcon, ChevronDownIcon } from '@chakra-ui/icons'; import { TbVectorBezier2 } from 'react-icons/tb/index.js'; import { filterUtilizationForActionType, getNumberOfResourcesFromFilteredActions, getNumberOfResourcesInProgress } from '../../utils/utilization.js'; import { ActionType } from '../../types/types.js'; import { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js'; import { TbRefresh } from 'react-icons/tb/index.js'; export function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) { const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props; const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory); const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory); const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory); const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges); const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges); const numOptimizeChanges = getNumberOfResourcesFromFilteredActions(optimizeChanges); const inProgressActions = getNumberOfResourcesInProgress(sessionHistory); function actionSummaryStack ( actionType: ActionType, icon: JSX.Element, actionLabel: string, numResources: number, description: string, numResourcesInProgress: number ) { return ( <Stack w="100%" p='2' pl='5' pr='5'> <Flex> <Box w='20px'> {icon} </Box> <Stack w='450px' pl='1'> <Box> <Heading as='h5' size='sm'>{actionLabel}</Heading> </Box> <Box> <Text fontSize='sm' color='gray.500'>{description}</Text> </Box> </Stack> <Spacer /> <Box w='150px'> <Text fontSize='sm' color='gray.500'>{numResources} available</Text> {numResourcesInProgress ? <Text fontSize='sm' color='gray.500'>{numResourcesInProgress} in progress</Text> : null } </Box> <Button colorScheme="purple" variant="outline" marginRight={'8px'} size='sm' border="0px" onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Button colorScheme='purple' size='sm' onClick={() => onContinue(actionType)} > {<>Review <ArrowForwardIcon /></>} </Button> </Flex> </Stack> ); } return ( <Stack pt="20px" pb="20px" w="100%"> <Stack width="20%" pb={3} px={4} align='baseline'> <Menu> <MenuButton as={Button} rightIcon={<ChevronDownIcon />}> {regionLabel} </MenuButton> <MenuList minW="0" w={150} h={40} sx={{ overflow:'scroll' }}>
{allRegions.map(region => <MenuItem onClick={() => onRegionChange(region)}>{region}</MenuItem> )}
</MenuList> </Menu> </Stack> <hr /> {actionSummaryStack( ActionType.DELETE, <DeleteIcon color='gray' />, 'Delete', numDeleteChanges, 'Resources that have had no recent activity.', inProgressActions['delete'] )} <hr /> {actionSummaryStack( ActionType.SCALE_DOWN, <ArrowDownIcon color='gray' />, 'Scale Down', numScaleDownChanges, 'Resources are recently underutilized.', inProgressActions['scaleDown'] )} <hr /> {actionSummaryStack( ActionType.OPTIMIZE, <Icon as={TbVectorBezier2} color='gray' />, 'Optimize', numOptimizeChanges, 'Resources that would be more cost effective using an AWS optimization tool.', inProgressActions['optimize'] )} </Stack> ); }
src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " onRefresh={onRefresh}\n allRegions={this.allRegions || []}\n region={this.region}\n onRegionChange={onRegionChange}\n />\n );\n }\n}", "score": 0.8551762104034424 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.8501024842262268 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " onResourcesAction={onResourcesAction}\n />\n ))}\n </Stack>\n </Box>\n );\n });\n return (\n <Stack p=\"20px\" w=\"100%\">\n <Flex>", "score": 0.8468152284622192 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " size='xl'\n >\n <DrawerOverlay />\n <DrawerContent marginTop='50px'>\n <DrawerCloseButton />\n <DrawerHeader> \n <Flex>\n <Box>\n <Heading fontSize='xl'> \n { splitServiceName(sidePanelService)}", "score": 0.8424379825592041 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": " onRegionChange={onRegionChange}\n />\n );\n // #endregion\n}", "score": 0.841947615146637 } ]
typescript
{allRegions.map(region => <MenuItem onClick={() => onRegionChange(region)}>{region}</MenuItem> )}
import React from 'react'; import { BaseProvider, BaseWidget } from '@tinystacks/ops-core'; import { Widget } from '@tinystacks/ops-model'; import { Stack } from '@chakra-ui/react'; import RecommendationOverview from '../components/recommendation-overview.js'; import { AwsUtilizationOverrides, HistoryEvent, Utilization } from '../types/types.js'; import { AwsUtilization as AwsUtilizationType } from '../ops-types.js'; export type AwsUtilizationProps = AwsUtilizationType & { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[] region: string } export class AwsUtilization extends BaseWidget { utilization: { [ serviceName: string ] : Utilization<string> }; sessionHistory: HistoryEvent[]; region: string; constructor (props: AwsUtilizationProps) { super(props); this.region = props.region || 'us-east-1'; this.utilization = props.utilization || {}; this.sessionHistory = props.sessionHistory || []; } async getData (providers?: BaseProvider[]): Promise<void> { const depMap = { utils: './utils/utils.js' }; const { getAwsCredentialsProvider, getAwsUtilizationProvider } = await import(depMap.utils); const utilProvider = getAwsUtilizationProvider(providers); const awsCredsProvider = getAwsCredentialsProvider(providers); this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region); } static fromJson (object: AwsUtilizationProps): AwsUtilization { return new AwsUtilization(object); } toJson (): AwsUtilizationProps { return { ...super.toJson(), utilization: this.utilization, region: this.region, sessionHistory: this.sessionHistory }; } render ( _children?: (Widget & { renderedElement: JSX.Element; })[],
_overridesCallback?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
return ( <Stack width='100%'> <RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/> </Stack> ); } }
src/widgets/aws-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8724769353866577 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.858642578125 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n toJson (): AwsUtilizationProviderProps {\n return {\n ...super.toJson(),\n services: this.services,\n utilization: this.utilization\n };\n }\n initServices (services: AwsResourceType[]) {\n this.services = services;", "score": 0.8529475331306458 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8525148034095764 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " backend: {\n type: 'memory'\n }\n});\ntype AwsUtilizationProviderProps = AwsUtilizationProviderType & {\n utilization?: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region?: string;\n};", "score": 0.8459459543228149 } ]
typescript
_overridesCallback?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
import React, { useState } from 'react'; import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalBody, ModalCloseButton, Button, HStack, Heading, Stack, Text, Box, useDisclosure, Input, AlertTitle, AlertIcon, Alert, Spacer, Flex } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { ConfirmSingleRecommendation } from './confirm-single-recommendation.js'; import { ConfirmRecommendationsProps } from '../../types/utilization-recommendations-types.js'; import { actionTypeText } from '../../types/types.js'; import { filterUtilizationForActionType } from '../../utils/utilization.js'; export function ConfirmRecommendations (props: ConfirmRecommendationsProps) { const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props; const { isOpen, onOpen, onClose } = useDisclosure(); const [confirmationText, setConfirmationText] = useState<string>(''); const [error, setError] = useState<string | undefined>(undefined); const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const resourceFilteredServices = new Set<string>(); Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => { for (const resourceArn of resourceArns) { if (Object.hasOwn(serviceUtil, resourceArn)) { resourceFilteredServices.add(serviceName); break; } } }); const resourceFilteredServiceTables = [...resourceFilteredServices].map((s) => { return ( <Box borderRadius='6px' key={s} mb='3'> <HStack bgColor='gray.50' p='1'> <Text fontSize='sm'>{s}</Text> </HStack> <Stack pl='5' pr='5'> {resourceArns .filter(r => Object.hasOwn(filteredServices[s], r)) .map(rarn => ( <
ConfirmSingleRecommendation resourceArn={rarn}
actionType={actionType} onRemoveResource={onRemoveResource} onResourcesAction={onResourcesAction} /> ))} </Stack> </Box> ); }); return ( <Stack p="20px" w="100%"> <Flex> <Stack> <Heading as='h4' size='md'>Delete Unused Resources</Heading> <Text color='gray.500'> These resources are underutilized and can likely be safely deleted. Remove any resources you would like to save and continue to delete all remaining resources. Deleting resources may take a while after the button is clicked, and you may see the same recommendation for a while as AWS takes some time to delete resources. </Text> </Stack> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button> </Box> </Flex> <hr /> <Box> {resourceFilteredServiceTables} </Box> <Modal isOpen={isOpen} onClose={() => { setError(undefined); setConfirmationText(undefined); onClose(); }}> <ModalOverlay /> <ModalContent> <ModalHeader>Confirm {actionType}</ModalHeader> <ModalCloseButton /> <ModalBody> <Text fontSize='xl'>You are about to {actionType} {resourceArns.length} resources.</Text> <Text fontSize='xl'>To confirm, type '{actionType} resources' in the input below.</Text> <Text fontSize='xs'> Please note, as we are cleaning up your resources they may still appear as recommendations until the process completes in the background. </Text> <Text pt='1'>Confirm {actionType}</Text> <HStack> <Input value={confirmationText} onChange={event => setConfirmationText(event.target.value)} /> </HStack> <Flex pt='1'> <Spacer/> <Box> <Button colorScheme='red' size='sm' onClick={() => { if (confirmationText !== actionType + ' resources') { setError(`Type '${actionType} resources' in the box to continue`); } else { setError(undefined); onResourcesAction(resourceArns, actionType); } }} > {actionLabel} </Button> </Box> </Flex> <Alert status='error' hidden={!error}> <AlertIcon /> <AlertTitle>{error}</AlertTitle> </Alert> </ModalBody> </ModalContent> </Modal> </Stack> ); }
src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn]?.data?.resourceId || resArn} \n aria-label='A tooltip'\n bg='purple.400'\n color='white'\n >\n { serviceUtil[resArn]?.data?.resourceId || resArn }", "score": 0.8496794700622559 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": " />\n );\n }\n if (wizardStep === WizardSteps.CONFIRM) {\n return (\n <ConfirmRecommendations\n resourceArns={selectedResourceArns}\n actionType={actionType}\n sessionHistory={sessionHistory}\n onRemoveResource={(resourceArn: string) => {", "score": 0.8479543328285217 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": "import {\n Stack, Button, Spacer, Flex, Text, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader,\n ModalOverlay, useDisclosure\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { ConfirmSingleRecommendationProps } from '../../types/utilization-recommendations-types.js';\nimport { actionTypeText } from '../../types/types.js';\nexport function ConfirmSingleRecommendation (props: ConfirmSingleRecommendationProps) {\n const { resourceArn, actionType, onRemoveResource, onResourcesAction } = props;\n // TODO: const { isOpen, onOpen, onClose } = useDisclosure();", "score": 0.8462694883346558 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " <Tr key={resArn}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox\n isChecked={checkedResources.includes(resArn)}\n onChange={onResourceCheckChange(resArn, serviceName)}\n />\n </Td>\n <Td\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'", "score": 0.8417957425117493 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " return Object.keys(serviceUtil).map(resArn => (\n <>\n <Tr key={resArn}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox\n isChecked={checkedResources.includes(resArn)}\n onChange={onResourceCheckChange(resArn, serviceName)} />\n </Td>\n <Td\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}", "score": 0.8415554761886597 } ]
typescript
ConfirmSingleRecommendation resourceArn={rarn}
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'>
{sentenceCase(th)}
</Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8817883729934692 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " if (Object.hasOwn(serviceUtil, resourceArn)) {\n resourceFilteredServices.add(serviceName);\n break;\n }\n }\n });\n const resourceFilteredServiceTables = [...resourceFilteredServices].map((s) => {\n return (\n <Box borderRadius='6px' key={s} mb='3'>\n <HStack bgColor='gray.50' p='1'>", "score": 0.8650960922241211 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.8420348167419434 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": " setSelectedResourceArns(selectedResourceArns.filter((r: string) => r !== resourceArn));\n }}\n onResourcesAction={onResourcesAction}\n utilization={utilization}\n onBack={() => { \n setWizardStep(WizardSteps.TABLE);\n }}\n />);\n }\n return (", "score": 0.8333923816680908 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8330878615379333 } ]
typescript
{sentenceCase(th)}
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021; const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider
, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> {
const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost; await this.fillData(dbInstanceArn, credentials, this.region, { resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) }); rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasDatabaseConnections', { value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.9234465956687927 }, { "filename": "src/service-utilizations/aws-account-utilization.tsx", "retrieved_chunk": " throw new Error('Method not implemented.');\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides: AwsServiceOverrides\n ): Promise<void> {\n const region = regions[0];\n await this.checkPermissionsForCostExplorer(awsCredentialsProvider, region);\n await this.checkPermissionsForPricing(awsCredentialsProvider, region);\n }\n async checkPermissionsForPricing (awsCredentialsProvider: AwsCredentialsProvider, region: string) {", "score": 0.9176921844482422 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.9010710120201111 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }\n checkForUnusedVolume (volume: Volume, volumeArn: string) { \n if(!volume.Attachments || volume.Attachments.length === 0){", "score": 0.8992592096328735 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8975591063499451 } ]
typescript
, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> {
import React, { useState } from 'react'; import { ActionType } from '../../types/types.js'; import { RecommendationsActionSummary } from './recommendations-action-summary.js'; import { RecommendationsTable } from './recommendations-table.js'; import { ConfirmRecommendations } from './confirm-recommendations.js'; import { UtilizationRecommendationsUiProps } from '../../types/utilization-recommendations-types.js'; enum WizardSteps { SUMMARY='summary', TABLE='table', CONFIRM='confirm' } export function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) { const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props; const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY); const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]); const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE); if (wizardStep === WizardSteps.SUMMARY) { return ( <RecommendationsActionSummary utilization={utilization} sessionHistory={sessionHistory} onRefresh={onRefresh} onContinue={(selectedActionType: ActionType) => { setActionType(selectedActionType); setWizardStep(WizardSteps.TABLE); }} allRegions={allRegions} onRegionChange={onRegionChange} region={region} /> ); } if (wizardStep === WizardSteps.TABLE) { return ( <RecommendationsTable utilization={utilization} actionType={actionType} sessionHistory={sessionHistory} onRefresh={() => { onRefresh(); setWizardStep(WizardSteps.TABLE); //this does nothing }} onContinue
={(checkedResources) => {
setWizardStep(WizardSteps.CONFIRM); setSelectedResourceArns(checkedResources); }} onBack={() => { setWizardStep(WizardSteps.SUMMARY); setSelectedResourceArns([]); }} /> ); } if (wizardStep === WizardSteps.CONFIRM) { return ( <ConfirmRecommendations resourceArns={selectedResourceArns} actionType={actionType} sessionHistory={sessionHistory} onRemoveResource={(resourceArn: string) => { setSelectedResourceArns(selectedResourceArns.filter((r: string) => r !== resourceArn)); }} onResourcesAction={onResourcesAction} utilization={utilization} onBack={() => { setWizardStep(WizardSteps.TABLE); }} />); } return ( <RecommendationsActionSummary utilization={utilization} sessionHistory={sessionHistory} onRefresh={onRefresh} onContinue={(selectedActionType: ActionType) => { setActionType(selectedActionType); setWizardStep(WizardSteps.TABLE); }} allRegions={allRegions} region={region} onRegionChange={onRegionChange} /> ); // #endregion }
src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.9057468175888062 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 0.867750883102417 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceActions?: {\n actionType: string,\n resourceArns: string[]\n };\n region?: string;\n};\nexport type RecommendationsTableProps = HasActionType & HasUtilization & {\n onContinue: (resourceArns: string[]) => void;\n onBack: () => void;\n onRefresh: () => void;", "score": 0.8674194812774658 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": "export function ConfirmRecommendations (props: ConfirmRecommendationsProps) {\n const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props;\n const { isOpen, onOpen, onClose } = useDisclosure();\n const [confirmationText, setConfirmationText] = useState<string>('');\n const [error, setError] = useState<string | undefined>(undefined);\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const resourceFilteredServices = new Set<string>();\n Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => {\n for (const resourceArn of resourceArns) {", "score": 0.856364369392395 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </>\n ));\n }\n function table () {\n if (!utilization || isEmpty(utilization)) {\n return <>No recommendations available!</>;\n }\n return (\n <TableContainer border=\"1px\" borderColor=\"gray.100\">\n <Table variant=\"simple\">", "score": 0.8495089411735535 } ]
typescript
={(checkedResources) => {
import isEmpty from 'lodash.isempty'; import { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js'; export function filterUtilizationForActionType ( utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[] ): { [service: string]: Utilization<string> } { const filtered: { [service: string]: Utilization<string> } = {}; if (!utilization) { return filtered; } Object.keys(utilization).forEach((service) => { filtered[service] = filterServiceForActionType(utilization, service, actionType, session); }); return filtered; } export function filterServiceForActionType ( utilization: { [service: string]: Utilization<string> }, service: string, actionType: ActionType, session: HistoryEvent[] ) { const resourcesInProgress = session.map((historyevent) => { return historyevent.resourceArn; }); const serviceUtil = utilization[service]; const actionFilteredServiceUtil = Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => { if(resourcesInProgress.includes(id)){ delete aggUtil[id]; return aggUtil; } const filteredScenarios: Scenarios<string> = {}; Object.entries(resource.scenarios).forEach(([sType, details]) => { if (Object
.hasOwn(details, actionType)) {
filteredScenarios[sType] = details; } }); if (!filteredScenarios || isEmpty(filteredScenarios)) { return aggUtil; } aggUtil[id] = { ...resource, scenarios: filteredScenarios }; return aggUtil; }, {}); return actionFilteredServiceUtil; } export function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(filtered).forEach((s) => { if (!filtered[s] || isEmpty(filtered[s])) return; total += Object.keys(filtered[s]).length; }); return total; } export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } { const result: { [ key in ActionType ]: number } = { [ActionType.OPTIMIZE]: 0, [ActionType.DELETE]: 0, [ActionType.SCALE_DOWN]: 0 }; session.forEach((historyEvent) => { result[historyEvent.actionType] ++; }); return result; } export function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; total += Object.keys(utilization[service]).length; }); return total; } export function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); let totalSavings = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; Object.keys(utilization[service]).forEach((resource) => { totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0; }); }); return usd.format(totalSavings); } export function sentenceCase (name: string): string { const result = name.replace(/([A-Z])/g, ' $1'); return result[0].toUpperCase() + result.substring(1).toLowerCase(); } export function splitServiceName (name: string) { return name?.split(/(?=[A-Z])/).join(' '); }
src/utils/utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8684964179992676 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];\n const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th =>\n <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'>\n {sentenceCase(th)}\n </Th>\n ): undefined;\n const taskRows = Object.keys(serviceUtil).map(resArn => (", "score": 0.8570977449417114 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.841284453868866 }, { "filename": "src/types/types.ts", "retrieved_chunk": "}\nexport type Scenarios<ScenarioTypes extends string> = {\n [ scenarioType in ScenarioTypes ]: Scenario\n}\nexport type Resource<ScenarioTypes extends string> = {\n scenarios: Scenarios<ScenarioTypes>,\n data: Data,\n metrics: Metrics\n}\nexport type Utilization<ScenarioTypes extends string> = {", "score": 0.8332036733627319 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " serviceUtil={serviceUtil}\n children={resourcesTable(service, serviceUtil)}\n key={service + 'table'}\n onServiceCheckChange={onServiceCheckChange(service)}\n isChecked={checkedServices.includes(service)}\n />\n );\n }\n function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) {\n const tableHeadersSet = new Set<string>();", "score": 0.8305890560150146 } ]
typescript
.hasOwn(details, actionType)) {
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {
SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })}
</Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " const { isOpen, onClose } = useDisclosure();\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1) + ' now';\n return (\n <Stack w=\"100%\" pb='2' pt='2'>\n <Flex>\n <Stack>\n <Text>{resourceArn}</Text>\n </Stack>\n {/* TODO */}\n {/* <Stack>", "score": 0.8465410470962524 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " <Heading style={labelStyles}>{totalResources}</Heading>\n <Text style={textStyles}>{'resources'}</Text>\n </Box>\n <Box p={5}>\n <Heading style={labelStyles}>{totalUnusedResources}</Heading>\n <Text style={textStyles}>{'unused resources'}</Text>\n </Box>\n <Box p={5}>\n <Heading style={labelStyles}>{ totalMonthlySavings }</Heading>\n <Text style={textStyles}>{'potential monthly savings'}</Text>", "score": 0.844690203666687 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " };\n }\n render (\n _children?: (Widget & { renderedElement: JSX.Element; })[],\n _overridesCallback?: (overrides: AwsUtilizationOverrides) => void\n ): JSX.Element {\n return (\n <Stack width='100%'>\n <RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/>\n </Stack>", "score": 0.8399661183357239 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " </Stack>\n <hr />\n {actionSummaryStack(\n ActionType.DELETE, <DeleteIcon color='gray' />, 'Delete', numDeleteChanges,\n 'Resources that have had no recent activity.', inProgressActions['delete']\n )}\n <hr />\n {actionSummaryStack(\n ActionType.SCALE_DOWN, <ArrowDownIcon color='gray' />, 'Scale Down', numScaleDownChanges,\n 'Resources are recently underutilized.', inProgressActions['scaleDown']", "score": 0.8380584716796875 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " <Text fontSize='sm' color='gray.500'>$19625</Text>\n <br />\n </Stack> */}\n <Spacer />\n <Stack>\n {/* TODO */}\n {/* <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel}</Button> */}\n <Button variant='link' size='sm' onClick={() => onRemoveResource(resourceArn)}>\n {'Don\\'t ' + actionTypeText[actionType]}\n </Button>", "score": 0.8339048624038696 } ]
typescript
SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })}
import { Widget } from '@tinystacks/ops-model'; import { ActionType, AwsResourceType, HistoryEvent, Utilization } from './types.js'; export type HasActionType = { actionType: ActionType; } export type HasUtilization = { utilization: { [key: AwsResourceType | string]: Utilization<string> }; sessionHistory: HistoryEvent[]; } interface RemovableResource { onRemoveResource: (resourceArn: string) => void; } interface HasResourcesAction { onResourcesAction: (resourceArns: string[], actionType: string) => void; } interface Refresh { onRefresh: () => void; } export type UtilizationRecommendationsWidget = Widget & HasActionType & HasUtilization & { region: string }; export interface Regions { onRegionChange: (region: string) => void; allRegions: string[]; region: string; } export type UtilizationRecommendationsUiProps = HasUtilization & HasResourcesAction & Refresh & Regions; export type RecommendationsCallback = (props: RecommendationsOverrides) => void; export type RecommendationsOverrides = { refresh?: boolean; resourceActions?: { actionType: string, resourceArns: string[] }; region?: string; }; export type RecommendationsTableProps = HasActionType & HasUtilization & { onContinue: (resourceArns: string[]) => void; onBack: () => void; onRefresh: () => void; }; export type RecommendationsActionsSummaryProps = Widget & HasUtilization; export type RecommendationsActionSummaryProps = HasUtilization & Regions & { onContinue: (selectedActionType: ActionType) => void; onRefresh: () => void; }; export type ConfirmSingleRecommendationProps = RemovableResource & HasActionType & HasResourcesAction & { resourceArn: string; }; export type ConfirmRecommendationsProps = RemovableResource & HasActionType & HasResourcesAction & HasUtilization & { resourceArns: string[]; onBack: () => void; }; export type ServiceTableRowProps = {
serviceUtil: Utilization<string>;
serviceName: string; children?: React.ReactNode; onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void; isChecked: boolean; };
src/types/utilization-recommendations-types.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": "export function ConfirmRecommendations (props: ConfirmRecommendationsProps) {\n const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props;\n const { isOpen, onOpen, onClose } = useDisclosure();\n const [confirmationText, setConfirmationText] = useState<string>('');\n const [error, setError] = useState<string | undefined>(undefined);\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const resourceFilteredServices = new Set<string>();\n Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => {\n for (const resourceArn of resourceArns) {", "score": 0.8913856744766235 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.8748319745063782 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": "import {\n Stack, Button, Spacer, Flex, Text, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader,\n ModalOverlay, useDisclosure\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { ConfirmSingleRecommendationProps } from '../../types/utilization-recommendations-types.js';\nimport { actionTypeText } from '../../types/types.js';\nexport function ConfirmSingleRecommendation (props: ConfirmSingleRecommendationProps) {\n const { resourceArn, actionType, onRemoveResource, onResourcesAction } = props;\n // TODO: const { isOpen, onOpen, onClose } = useDisclosure();", "score": 0.871588408946991 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "import {\n UtilizationRecommendationsUi\n} from './utilization-recommendations-ui/utilization-recommendations-ui.js';\nimport { filterUtilizationForActionType } from '../utils/utilization.js';\nimport { AwsUtilizationRecommendations as AwsUtilizationRecommendationsType } from '../ops-types.js';\nexport type AwsUtilizationRecommendationsProps = \n AwsUtilizationRecommendationsType & \n HasActionType & \n HasUtilization & \n Regions;", "score": 0.8645452260971069 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 0.8556315898895264 } ]
typescript
serviceUtil: Utilization<string>;
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {
SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })}
</Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx", "retrieved_chunk": " aria-label={'downCaret'}\n leftIcon={<ChevronDownIcon/>}\n size='lg'\n colorScheme='black'\n >\n Related Resources\n </Button>\n <Spacer/>\n <Table size='sm' marginTop='12px'>\n <Thead>", "score": 0.8431425094604492 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " const { isOpen, onClose } = useDisclosure();\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1) + ' now';\n return (\n <Stack w=\"100%\" pb='2' pt='2'>\n <Flex>\n <Stack>\n <Text>{resourceArn}</Text>\n </Stack>\n {/* TODO */}\n {/* <Stack>", "score": 0.8361722826957703 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": " aria-label={isOpen ? 'upCaret' : 'downCaret'}\n rightIcon={isOpen ? <ChevronUpIcon />: <ChevronDownIcon/>}\n size='sm'\n colorScheme='purple'\n fontWeight='1px'\n >\n {isOpen ? 'Hide resources' : 'Show resources'}\n </Button>\n </Td>\n </Tr>", "score": 0.834247350692749 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " MenuList, \n Spacer, \n Stack, \n Text \n} from '@chakra-ui/react';\nimport { DeleteIcon, ArrowForwardIcon, ArrowDownIcon, ChevronDownIcon } from '@chakra-ui/icons';\nimport { TbVectorBezier2 } from 'react-icons/tb/index.js';\nimport { filterUtilizationForActionType, \n getNumberOfResourcesFromFilteredActions, \n getNumberOfResourcesInProgress } from '../../utils/utilization.js';", "score": 0.8342412710189819 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " </Stack>\n <hr />\n {actionSummaryStack(\n ActionType.DELETE, <DeleteIcon color='gray' />, 'Delete', numDeleteChanges,\n 'Resources that have had no recent activity.', inProgressActions['delete']\n )}\n <hr />\n {actionSummaryStack(\n ActionType.SCALE_DOWN, <ArrowDownIcon color='gray' />, 'Scale Down', numScaleDownChanges,\n 'Resources are recently underutilized.', inProgressActions['scaleDown']", "score": 0.8319634795188904 } ]
typescript
SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })}
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <
ServiceTableRow serviceName={service}
serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { CHECKBOX_CELL_MAX_WIDTH } from './recommendations-table.js';\nimport { splitServiceName } from '../../utils/utilization.js';\nexport default function ServiceTableRow (props: ServiceTableRowProps) {\n const { serviceUtil, serviceName, children, isChecked, onServiceCheckChange } = props;\n const { isOpen, onToggle } = useDisclosure();\n return (\n <React.Fragment>\n <Tr key={serviceName}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox ", "score": 0.8598857522010803 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": " isChecked={isChecked}\n onChange={onServiceCheckChange}\n />\n </Td>\n <Td>{splitServiceName(serviceName)}</Td>\n <Td>{Object.keys(serviceUtil).length}</Td>\n <Td>\n <Button\n variant='link'\n onClick={onToggle}", "score": 0.8477095365524292 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.8304202556610107 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " if (Object.hasOwn(serviceUtil, resourceArn)) {\n resourceFilteredServices.add(serviceName);\n break;\n }\n }\n });\n const resourceFilteredServiceTables = [...resourceFilteredServices].map((s) => {\n return (\n <Box borderRadius='6px' key={s} mb='3'>\n <HStack bgColor='gray.50' p='1'>", "score": 0.8299475312232971 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { ChevronDownIcon, ChevronUpIcon } from '@chakra-ui/icons';\nimport {\n Tr,\n Td,\n Button,\n useDisclosure,\n Checkbox\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { ServiceTableRowProps } from '../../types/utilization-recommendations-types.js';", "score": 0.8151419758796692 } ]
typescript
ServiceTableRow serviceName={service}
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } };
await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.9021685123443604 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.8986702561378479 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8331718444824219 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8218549489974976 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8194347023963928 } ]
typescript
await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);
import React, { useState } from 'react'; import { ActionType } from '../../types/types.js'; import { RecommendationsActionSummary } from './recommendations-action-summary.js'; import { RecommendationsTable } from './recommendations-table.js'; import { ConfirmRecommendations } from './confirm-recommendations.js'; import { UtilizationRecommendationsUiProps } from '../../types/utilization-recommendations-types.js'; enum WizardSteps { SUMMARY='summary', TABLE='table', CONFIRM='confirm' } export function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) { const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props; const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY); const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]); const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE); if (wizardStep === WizardSteps.SUMMARY) { return ( <RecommendationsActionSummary utilization={utilization} sessionHistory={sessionHistory} onRefresh={onRefresh} onContinue={(selectedActionType: ActionType) => { setActionType(selectedActionType); setWizardStep(WizardSteps.TABLE); }} allRegions={allRegions} onRegionChange={onRegionChange} region={region} /> ); } if (wizardStep === WizardSteps.TABLE) { return ( <RecommendationsTable utilization={utilization} actionType={actionType} sessionHistory={sessionHistory} onRefresh={() => { onRefresh(); setWizardStep(WizardSteps.TABLE); //this does nothing }} onContinue={(checkedResources) => { setWizardStep(WizardSteps.CONFIRM); setSelectedResourceArns(checkedResources); }} onBack={() => { setWizardStep(WizardSteps.SUMMARY); setSelectedResourceArns([]); }} /> ); } if (wizardStep === WizardSteps.CONFIRM) { return ( <
ConfirmRecommendations resourceArns={selectedResourceArns}
actionType={actionType} sessionHistory={sessionHistory} onRemoveResource={(resourceArn: string) => { setSelectedResourceArns(selectedResourceArns.filter((r: string) => r !== resourceArn)); }} onResourcesAction={onResourcesAction} utilization={utilization} onBack={() => { setWizardStep(WizardSteps.TABLE); }} />); } return ( <RecommendationsActionSummary utilization={utilization} sessionHistory={sessionHistory} onRefresh={onRefresh} onContinue={(selectedActionType: ActionType) => { setActionType(selectedActionType); setWizardStep(WizardSteps.TABLE); }} allRegions={allRegions} region={region} onRegionChange={onRegionChange} /> ); // #endregion }
src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": "export function ConfirmRecommendations (props: ConfirmRecommendationsProps) {\n const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props;\n const { isOpen, onOpen, onClose } = useDisclosure();\n const [confirmationText, setConfirmationText] = useState<string>('');\n const [error, setError] = useState<string | undefined>(undefined);\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const resourceFilteredServices = new Set<string>();\n Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => {\n for (const resourceArn of resourceArns) {", "score": 0.850560188293457 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Text fontSize='sm'>{s}</Text>\n </HStack>\n <Stack pl='5' pr='5'>\n {resourceArns\n .filter(r => Object.hasOwn(filteredServices[s], r))\n .map(rarn => (\n <ConfirmSingleRecommendation\n resourceArn={rarn}\n actionType={actionType}\n onRemoveResource={onRemoveResource}", "score": 0.8461410403251648 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": "import {\n Stack, Button, Spacer, Flex, Text, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader,\n ModalOverlay, useDisclosure\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { ConfirmSingleRecommendationProps } from '../../types/utilization-recommendations-types.js';\nimport { actionTypeText } from '../../types/types.js';\nexport function ConfirmSingleRecommendation (props: ConfirmSingleRecommendationProps) {\n const { resourceArn, actionType, onRemoveResource, onResourcesAction } = props;\n // TODO: const { isOpen, onOpen, onClose } = useDisclosure();", "score": 0.8328465819358826 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": "};\nexport type RecommendationsActionsSummaryProps = Widget & HasUtilization;\nexport type RecommendationsActionSummaryProps = HasUtilization & Regions & {\n onContinue: (selectedActionType: ActionType) => void;\n onRefresh: () => void;\n};\nexport type ConfirmSingleRecommendationProps = RemovableResource & HasActionType & HasResourcesAction & {\n resourceArn: string;\n};\nexport type ConfirmRecommendationsProps = RemovableResource & HasActionType & HasResourcesAction & HasUtilization & {", "score": 0.8193246126174927 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " actionTypeToEnum[actionType],\n resourceArn,\n get(resource.data, 'region', 'us-east-1')\n );\n }\n }\n }\n }\n }\n render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) {", "score": 0.8165831565856934 } ]
typescript
ConfirmRecommendations resourceArns={selectedResourceArns}
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } }
await this.fillData( instanceArn, credentials, region, {
resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8646902441978455 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.8569475412368774 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8514988422393799 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.843783438205719 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8375041484832764 } ]
typescript
await this.fillData( instanceArn, credentials, region, {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this
.fillData( logGroupArn, credentials, region, {
resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8258999586105347 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8086421489715576 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });\n }\n await this.fillData(\n natGatewayArn,\n credentials,", "score": 0.8063833713531494 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " nameSpace: string, metricName: string, dimensions: Dimension[]\n ){ \n if(resourceArn in this.utilization){\n const cloudWatchClient = new CloudWatch({ \n credentials: credentials, \n region: region\n }); \n const endTime = new Date(Date.now()); \n const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago\n const period = 43200; ", "score": 0.7901506423950195 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.7872828841209412 } ]
typescript
.fillData( logGroupArn, credentials, region, {
import cached from 'cached'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { BaseProvider } from '@tinystacks/ops-core'; import { ActionType, AwsResourceType, AwsServiceOverrides, AwsUtilizationOverrides, HistoryEvent, Utilization } from './types/types.js'; import { AwsServiceUtilization } from './service-utilizations/aws-service-utilization.js'; import { AwsServiceUtilizationFactory } from './service-utilizations/aws-service-utilization-factory.js'; import { AwsUtilizationProvider as AwsUtilizationProviderType } from './ops-types.js'; const utilizationCache = cached<Utilization<string>>('utilization', { backend: { type: 'memory' } }); const sessionHistoryCache = cached<Array<HistoryEvent>>('session-history', { backend: { type: 'memory' } }); type AwsUtilizationProviderProps = AwsUtilizationProviderType & { utilization?: { [key: AwsResourceType | string]: Utilization<string> }; region?: string; }; class AwsUtilizationProvider extends BaseProvider { static type = 'AwsUtilizationProvider'; services: AwsResourceType[]; utilizationClasses: { [key: AwsResourceType | string]: AwsServiceUtilization<string> }; utilization: { [key: AwsResourceType | string]: Utilization<string> }; region: string; constructor (props: AwsUtilizationProviderProps) { super(props); const { services } = props; this.utilizationClasses = {}; this.utilization = {}; this.initServices(services || [ 'Account', 'CloudwatchLogs', 'Ec2Instance', 'EcsService', 'NatGateway', 'S3Bucket', 'EbsVolume', 'RdsInstance' ]); } static fromJson (props: AwsUtilizationProviderProps) { return new AwsUtilizationProvider(props); } toJson (): AwsUtilizationProviderProps { return { ...super.toJson(), services: this.services, utilization: this.utilization }; } initServices (services: AwsResourceType[]) { this.services = services; for (const service of this.services) { this.utilizationClasses[service] = AwsServiceUtilizationFactory.
createObject(service);
} } async refreshUtilizationData ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, region: string, overrides?: AwsServiceOverrides ): Promise<Utilization<string>> { try { await this.utilizationClasses[service]?.getUtilization(credentialsProvider, [ region ], overrides); return this.utilizationClasses[service]?.utilization; } catch (e) { console.error(e); return {}; } } async doAction ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, actionName: string, actionType: ActionType, resourceArn: string, region: string ) { const event: HistoryEvent = { service, actionType, actionName, resourceArn, region, timestamp: new Date().toISOString() }; const history: HistoryEvent[] = await this.getSessionHistory(); history.push(event); await this.utilizationClasses[service].doAction(credentialsProvider, actionName, resourceArn, region); await sessionHistoryCache.set('history', history); } async hardRefresh ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } return this.utilization; } async getUtilization ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; if (serviceOverrides?.forceRefesh) { this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } else { this.utilization[service] = await utilizationCache.getOrElse( service, async () => await this.refreshUtilizationData(service, credentialsProvider, region, serviceOverrides) ); } } return this.utilization; } async getSessionHistory (): Promise<HistoryEvent[]> { return sessionHistoryCache.getOrElse('history', []); } } export { AwsUtilizationProvider };
src/aws-utilization-provider.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.864013135433197 }, { "filename": "src/service-utilizations/aws-service-utilization-factory.ts", "retrieved_chunk": "import { AwsEcsUtilization } from './aws-ecs-utilization.js';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nexport class AwsServiceUtilizationFactory {\n static createObject (awsService: AwsResourceType): AwsServiceUtilization<string> {\n switch (awsService) {\n case AwsResourceTypes.CloudwatchLogs:\n return new AwsCloudwatchLogsUtilization();\n case AwsResourceTypes.S3Bucket: \n return new s3Utilization(); \n case AwsResourceTypes.RdsInstance: ", "score": 0.8512552380561829 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " }\n static fromJson (object: AwsUtilizationProps): AwsUtilization {\n return new AwsUtilization(object);\n }\n toJson (): AwsUtilizationProps {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n region: this.region, \n sessionHistory: this.sessionHistory", "score": 0.8476453423500061 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " region: string\n}\nexport class AwsUtilization extends BaseWidget {\n utilization: { [ serviceName: string ] : Utilization<string> };\n sessionHistory: HistoryEvent[];\n region: string;\n constructor (props: AwsUtilizationProps) {\n super(props);\n this.region = props.region || 'us-east-1';\n this.utilization = props.utilization || {};", "score": 0.8447633981704712 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings: number\n}\nexport type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy';\nexport class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> {\n s3Client: S3;\n cwClient: CloudWatch;\n bucketCostData: { [ bucketName: string ]: S3CostData };\n constructor () {\n super();\n this.bucketCostData = {};", "score": 0.8443397283554077 } ]
typescript
createObject(service);
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn
= Arns.Ec2(region, this.accountId, instanceId);
const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " return instanceFamily;\n }\n private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> {\n const instanceTypes = [];\n let nextToken;\n do {\n const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({\n InstanceTypes: instanceTypeNames,\n NextToken: nextToken\n });", "score": 0.8603893518447876 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " });\n this.pricingClient = new Pricing({\n credentials,\n region: this.region\n });\n let dbInstances: DBInstance[] = [];\n let describeDBInstancesRes: DescribeDBInstancesCommandOutput;\n do {\n describeDBInstancesRes = await this.rdsClient.describeDBInstances({});\n dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ];", "score": 0.8432640433311462 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region);\n }\n }\n private async listAllClusters (): Promise<string[]> {\n const allClusterArns: string[] = [];\n let nextToken;\n do {\n const response: ListClustersCommandOutput = await this.ecsClient.listClusters({\n nextToken\n });", "score": 0.8422713279724121 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.841776967048645 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " const resourceId = resourceArn.split('/')[1];\n await this.deleteNatGateway(ec2Client, resourceId);\n }\n }\n async deleteNatGateway (ec2Client: EC2, natGatewayId: string) {\n await ec2Client.deleteNatGateway({\n NatGatewayId: natGatewayId\n });\n }\n private async getAllNatGateways (credentials: any, region: string) {", "score": 0.8407062888145447 } ]
typescript
= Arns.Ec2(region, this.accountId, instanceId);
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) {
this.addScenario(instanceArn, 'unused', {
value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " this.addScenario(dbInstanceArn, 'cpuUtilization', {\n value: metrics.cpuUtilization.toString(), \n scaleDown: {\n action: '', \n isActionable: false,\n reason: 'Max CPU Utilization is under 50%',\n monthlySavings: 0\n }\n });\n }", "score": 0.8637792468070984 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.862006664276123 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " isActionable: false,\n reason: 'This instance has more than half of its allocated storage still available',\n monthlySavings: 0\n }\n });\n }\n }\n async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){\n if (metrics.cpuUtilization < 50) {\n await this.getRdsInstanceCosts(dbInstance, metrics);", "score": 0.8573424816131592 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.8495857119560242 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " (avgMemoryIsStable && maxMemoryIsStable) ||\n maxMemory < 10\n );\n const requestCountMetricValues = [\n ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || [])\n ];\n const totalRequestCount = stats.sum(requestCountMetricValues);\n const noNetworkUtilization = totalRequestCount === 0;\n if (\n lowCpuUtilization &&", "score": 0.8478655815124512 } ]
typescript
this.addScenario(instanceArn, 'unused', {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this
.fillData( natGatewayArn, credentials, region, {
resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8743516802787781 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8425520658493042 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " Bucket: bucketName\n });\n if (!res.IntelligentTieringConfigurationList) {\n const { monthlySavings } = await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasIntelligentTiering', {\n value: 'false',\n optimize: { \n action: 'enableIntelligientTiering', \n isActionable: true,\n reason: 'Intelligient tiering is not enabled for this bucket',", "score": 0.8383185267448425 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8359665870666504 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8358549475669861 } ]
typescript
.fillData( natGatewayArn, credentials, region, {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn =
Arns.NatGateway(region, this.accountId, natGatewayId);
const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.881787896156311 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8756498694419861 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.871798574924469 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) {\n const ec2Client = new EC2({\n credentials,\n region\n });\n const autoScalingClient = new AutoScaling({\n credentials,\n region\n });", "score": 0.864590048789978 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.862886905670166 } ]
typescript
Arns.NatGateway(region, this.accountId, natGatewayId);
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost:
getHourlyCost(cost) }
); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8824575543403625 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8803347945213318 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8593020439147949 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8536945581436157 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8462426066398621 } ]
typescript
getHourlyCost(cost) }
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0;
const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03;
const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8408254384994507 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8357250690460205 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8280075788497925 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": "import get from 'lodash.get';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { Bucket, S3 } from '@aws-sdk/client-s3';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns, ONE_GB_IN_BYTES } from '../types/constants.js';\ntype S3CostData = {\n monthlyCost: number,", "score": 0.8229526877403259 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " }\n async setAndGetBucketCostData (bucketName: string) {\n if (!(bucketName in this.bucketCostData)) {\n const res = await this.cwClient.getMetricData({\n StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)),\n EndTime: new Date(),\n MetricDataQueries: [\n {\n Id: 'incomingBytes',\n MetricStat: {", "score": 0.8222730159759521 } ]
typescript
const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03;
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(
_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
} else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.84443199634552 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " scaleDown: {\n action: 'scaleDownEc2Service',\n isActionable: false,\n reason: 'The EC2 instances used in this Service\\'s cluster appears to be over allocated based on its CPU' + \n `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }", "score": 0.8311524391174316 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const monthlySavings = cost - targetInstanceCost;\n this.addScenario(instanceArn, 'overAllocated', {\n value: 'overAllocated',\n scaleDown: {\n action: 'scaleDownInstance',\n isActionable: false,\n reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + \n `suggest scaling down to a ${targetInstanceType.InstanceType}`,\n monthlySavings\n }", "score": 0.8294782638549805 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.8277294635772705 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8270894289016724 } ]
typescript
_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost
: getHourlyCost(this.cost) }
); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8729342222213745 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8544517755508423 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region\n });\n this.apigClient = new ApiGatewayV2({\n credentials,\n region\n });\n this.pricingClient = new Pricing({\n credentials,\n region", "score": 0.8442922234535217 }, { "filename": "src/types/constants.ts", "retrieved_chunk": "import { AwsResourceType } from './types.js';\nexport const Arns = {\n NatGateway (region: string, accountId: string, natGatewayId: string) {\n return `arn:aws:ec2:${region}:${accountId}:natgateway/${natGatewayId}`;\n },\n Ec2 (region: string, accountId: string, instanceId: string) {\n return `arn:aws:ec2:${region}:${accountId}:instance/${instanceId}`;\n },\n S3 (bucketName: string) {\n return `arn:aws:s3:::${bucketName}`;", "score": 0.8324456810951233 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8312786221504211 } ]
typescript
: getHourlyCost(this.cost) }
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup);
this.addScenario(logGroupArn, 'hasRetentionPolicy', {
value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " Bucket: bucketName\n });\n if (!res.IntelligentTieringConfigurationList) {\n const { monthlySavings } = await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasIntelligentTiering', {\n value: 'false',\n optimize: { \n action: 'enableIntelligientTiering', \n isActionable: true,\n reason: 'Intelligient tiering is not enabled for this bucket',", "score": 0.8370524644851685 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " if (\n response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined)\n ) {\n await this.s3Client.getBucketLifecycleConfiguration({\n Bucket: bucketName\n }).catch(async (e) => { \n if(e.Code === 'NoSuchLifecycleConfiguration'){ \n await this.setAndGetBucketCostData(bucketName);\n this.addScenario(bucketArn, 'hasLifecyclePolicy', {\n value: 'false',", "score": 0.8333311676979065 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.8315464854240417 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8292661905288696 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.8266257047653198 } ]
typescript
this.addScenario(logGroupArn, 'hasRetentionPolicy', {
import cached from 'cached'; import dayjs from 'dayjs'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import HttpError from 'http-errors'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ContainerInstance, DesiredStatus, ECS, LaunchType, ListClustersCommandOutput, ListServicesCommandOutput, ListTasksCommandOutput, Service, Task, TaskDefinition, TaskDefinitionField, DescribeContainerInstancesCommandOutput } from '@aws-sdk/client-ecs'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { ElasticLoadBalancingV2 } from '@aws-sdk/client-elastic-load-balancing-v2'; import { Api, ApiGatewayV2, GetApisCommandOutput, Integration } from '@aws-sdk/client-apigatewayv2'; import { DescribeInstanceTypesCommandOutput, EC2, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, MAX_MEMORY, AVG_MEMORY, ALB_REQUEST_COUNT, APIG_REQUEST_COUNT } from '../types/constants.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getHourlyCost } from '../utils/utils.js'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; const cache = cached<string>('ecs-util-cache', { backend: { type: 'memory' } }); type AwsEcsUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEcsMetrics = ['CPUUtilization', 'MemoryUtilization']; type EcsService = { clusterArn: string; serviceArn: string; } type ClusterServices = { [clusterArn: string]: { serviceArns: string[]; } } type FargateScaleRange = { min: number; max: number; increment: number; }; type FargateScaleOption = { [cpu: number]: { discrete?: number[]; range?: FargateScaleRange; } } type FargateScale = { cpu: number, memory: number } type AwsEcsUtilizationOverrides = AwsServiceOverrides & { services: EcsService[]; } export
class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
serviceArns: string[]; services: Service[]; ecsClient: ECS; ec2Client: EC2; cwClient: CloudWatch; elbV2Client: ElasticLoadBalancingV2; apigClient: ApiGatewayV2; pricingClient: Pricing; serviceCosts: { [ service: string ]: number }; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.serviceArns = []; this.services = []; this.serviceCosts = {}; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteService') { await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region); } } private async listAllClusters (): Promise<string[]> { const allClusterArns: string[] = []; let nextToken; do { const response: ListClustersCommandOutput = await this.ecsClient.listClusters({ nextToken }); const { clusterArns = [], nextToken: nextClusterToken } = response || {}; allClusterArns.push(...clusterArns); nextToken = nextClusterToken; } while (nextToken); return allClusterArns; } private async listServicesForClusters (clusterArn: string): Promise<ClusterServices> { const services: string[] = []; let nextToken; do { const response: ListServicesCommandOutput = await this.ecsClient.listServices({ cluster: clusterArn, nextToken }); const { serviceArns = [], nextToken: nextServicesToken } = response || {}; services.push(...serviceArns); nextToken = nextServicesToken; } while (nextToken); return { [clusterArn]: { serviceArns: services } }; } private async describeAllServices (): Promise<Service[]> { const clusterArns = await this.listAllClusters(); const allServices: EcsService[] = []; for (const clusterArn of clusterArns) { const servicesForCluster = await this.listServicesForClusters(clusterArn); allServices.push(...servicesForCluster[clusterArn].serviceArns.map(s => ({ clusterArn, serviceArn: s }))); } return this.describeTheseServices(allServices); } private async describeTheseServices (ecsServices: EcsService[]): Promise<Service[]> { const clusters = ecsServices.reduce<ClusterServices>((acc, ecsService) => { acc[ecsService.clusterArn] = acc[ecsService.clusterArn] || { serviceArns: [] }; acc[ecsService.clusterArn].serviceArns.push(ecsService.serviceArn); return acc; }, {}); const services: Service[] = []; for (const [clusterArn, clusterServices] of Object.entries(clusters)) { const serviceChunks = chunk(clusterServices.serviceArns, 10); for (const serviceChunk of serviceChunks) { const response = await this.ecsClient.describeServices({ cluster: clusterArn, services: serviceChunk }); services.push(...(response?.services || [])); } } return services; } private async getLoadBalacerArnForService (service: Service): Promise<string> { const response = await this.elbV2Client.describeTargetGroups({ TargetGroupArns: [service.loadBalancers?.at(0)?.targetGroupArn] }); return response?.TargetGroups?.at(0)?.LoadBalancerArns?.at(0); } private async findIntegration (apiId: string, registryArn: string): Promise<Integration | undefined> { let nextToken: string; let registeredIntegration: Integration; do { const response = await this.apigClient.getIntegrations({ ApiId: apiId, NextToken: nextToken }); const { Items = [], NextToken } = response || {}; registeredIntegration = Items.find(i => i.IntegrationUri === registryArn); if (!registeredIntegration) { nextToken = NextToken; } } while (nextToken); return registeredIntegration; } private async findRegisteredApi (service: Service, apis: Api[]): Promise<Api | undefined> { const registryArn = service.serviceRegistries?.at(0)?.registryArn; let registeredApi: Api; for (const api of apis) { const registeredIntegration = await this.findIntegration(api.ApiId, registryArn); if (registeredIntegration) { registeredApi = api; break; } } return registeredApi; } private async getApiIdForService (service: Service): Promise<string> { let nextToken: string; let registeredApi: Api; do { const apiResponse: GetApisCommandOutput = await this.apigClient.getApis({ NextToken: nextToken }); const { Items = [], NextToken } = apiResponse || {}; registeredApi = await this.findRegisteredApi(service, Items); if (!registeredApi) { nextToken = NextToken; } } while (nextToken); return registeredApi.ApiId; } private async getTask (service: Service): Promise<Task> { const taskListResponse = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, maxResults: 1, desiredStatus: DesiredStatus.RUNNING }); const { taskArns = [] } = taskListResponse || {}; const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: [taskArns.at(0)] }); const task = describeTasksResponse?.tasks?.at(0); return task; } private async getAllTasks (service: Service): Promise<Task[]> { const taskIds = []; let nextTaskToken; do { const taskListResponse: ListTasksCommandOutput = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, desiredStatus: DesiredStatus.RUNNING, nextToken: nextTaskToken }); const { taskArns = [], nextToken } = taskListResponse || {}; taskIds.push(...taskArns); nextTaskToken = nextToken; } while (nextTaskToken); const allTasks = []; const taskIdPartitions = chunk(taskIds, 100); for (const taskIdPartition of taskIdPartitions) { const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: taskIdPartition }); const { tasks = [] } = describeTasksResponse; allTasks.push(...tasks); } return allTasks; } private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> { const ec2InstanceResponse = await this.ec2Client.describeInstances({ InstanceIds: [containerInstance.ec2InstanceId] }); const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType; const instanceFamily = instanceType?.split('.')?.at(0); return instanceFamily; } private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private getEcsServiceDataQueries (serviceName: string, clusterName: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/ECS', MetricName: metricName, Dimensions: [ { Name: 'ServiceName', Value: serviceName }, { Name: 'ClusterName', Value: clusterName } ] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: AVG_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Average') }, { Id: MAX_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Maximum') } ]; } private getAlbRequestCountQuery (loadBalancerArn: string, period: number): MetricDataQuery { return { Id: ALB_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApplicationELB', MetricName: 'RequestCount', Dimensions: [ { Name: 'ServiceName', Value: loadBalancerArn } ] }, Period: period, Stat: 'Sum' } }; } private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery { return { Id: APIG_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApiGateway', MetricName: 'Count', Dimensions: [ { Name: 'ApiId', Value: apiId } ] }, Period: period, Stat: 'Sum' } }; } private async getMetrics (args: { service: Service, startTime: Date; endTime: Date; period: number; }): Promise<{[ key: string ]: MetricDataResult}> { const { service, startTime, endTime, period } = args; const { serviceName, clusterArn, loadBalancers, serviceRegistries } = service; const clusterName = clusterArn?.split('/').pop(); const queries: MetricDataQuery[] = this.getEcsServiceDataQueries(serviceName, clusterName, period); if (loadBalancers && loadBalancers.length > 0) { const loadBalancerArn = await this.getLoadBalacerArnForService(service); queries.push(this.getAlbRequestCountQuery(loadBalancerArn, period)); } else if (serviceRegistries && serviceRegistries.length > 0) { const apiId = await this.getApiIdForService(service); queries.push(this.getApigRequestCountQuery(apiId, period)); } const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await this.cwClient.getMetricData({ MetricDataQueries: queries, StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private createDiscreteValuesForRange (range: FargateScaleRange): number[] { const { min, max, increment } = range; const discreteVales: number[] = []; let i = min; do { i = i + increment; discreteVales.push(i); } while (i <= max); return discreteVales; } private async getEc2ContainerInfo (service: Service) { const tasks = await this.getAllTasks(service); const taskCpu = Number(tasks.at(0)?.cpu); const allocatedMemory = Number(tasks.at(0)?.memory); let allocatedCpu = taskCpu; let containerInstance: ContainerInstance; let containerInstanceResponse: DescribeContainerInstancesCommandOutput; if (!taskCpu || taskCpu === 0) { const containerInstanceTaskGroupObject = tasks.reduce<{ [containerInstanceArn: string]: { containerInstanceArn: string; tasks: Task[]; } }>((acc, task) => { const { containerInstanceArn } = task; acc[containerInstanceArn] = acc[containerInstanceArn] || { containerInstanceArn, tasks: [] }; acc[containerInstanceArn].tasks.push(task); return acc; }, {}); const containerInstanceTaskGroups = Object.values(containerInstanceTaskGroupObject); containerInstanceTaskGroups.sort((a, b) => { if (a.tasks.length > b.tasks.length) { return -1; } else if (a.tasks.length < b.tasks.length) { return 1; } return 0; }); const largestContainerInstance = containerInstanceTaskGroups.at(0); const maxTaskCount = get(largestContainerInstance, 'tasks.length') || 0; const filteredTaskGroups = containerInstanceTaskGroups .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn)); if (isEmpty(filteredTaskGroups)) { return undefined; } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn) }); // largest container instance containerInstance = containerInstanceResponse?.containerInstances?.at(0); const containerInstanceCpuResource = containerInstance.registeredResources?.find(r => r.name === 'CPU'); const containerInstanceCpu = Number( containerInstanceCpuResource?.doubleValue || containerInstanceCpuResource?.integerValue || containerInstanceCpuResource?.longValue ); allocatedCpu = containerInstanceCpu / maxTaskCount; } } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: tasks.map(task => task.containerInstanceArn) }); containerInstance = containerInstanceResponse?.containerInstances?.at(0); } const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => { acc.add(instance.ec2InstanceId); return acc; }, new Set<string>()); const numEc2Instances = uniqueEc2Instances.size; const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value; const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType); const monthlyCost = monthlyInstanceCost * numEc2Instances; this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances }; } private async checkForEc2ScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { const info = await this.getEc2ContainerInfo(service); if (!info) { return; } const { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances } = info; const maxConsumedVcpus = (maxCpuPercentage * allocatedCpu) / 1024; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const instanceVcpus = allocatedCpu / 1024; let instanceFamily = instanceType?.split('.')?.at(0); if (!instanceFamily) { instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance); } const allInstanceTypes = Object.values(_InstanceType); const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const betterFitCpu = ( it.VCpuInfo.DefaultVCpus >= maxConsumedVcpus && it.VCpuInfo.DefaultVCpus <= instanceVcpus ); const betterFitMemory = ( it.MemoryInfo.SizeInMiB >= maxConsumedMemory && it.MemoryInfo.SizeInMiB <= allocatedMemory ); return betterFitCpu && betterFitMemory; }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1; return memoryScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType); const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances; this.addScenario(service.serviceArn, 'overAllocated', { value: 'true', scaleDown: { action: 'scaleDownEc2Service', isActionable: false, reason: 'The EC2 instances used in this Service\'s cluster appears to be over allocated based on its CPU' + `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) { let monthlyCost = 0; if (platform.toLowerCase() === 'windows') { monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30; } else { if (cpuArch === 'x86_64') { monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; } else { monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30; } } return monthlyCost; } private async getFargateInfo (service: Service) { const tasks = await this.getAllTasks(service); const numTasks = tasks.length; const task = tasks.at(0); const allocatedCpu = Number(task?.cpu); const allocatedMemory = Number(task?.memory); const platform = task.platformFamily || ''; const cpuArch = (task.attributes.find(attr => attr.name === 'ecs.cpu-architecture'))?.value || 'x86_64'; const vcpu = allocatedCpu / 1024; const memory = allocatedMemory / 1024; const monthlyCost = this.calculateFargateCost(platform, cpuArch, vcpu, memory, numTasks); this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost }; } private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html const fargateScaleOptions: FargateScaleOption = { 256: { discrete: [0.5, 1, 2] }, 512: { range: { min: 1, max: 4, increment: 1 } }, 1024: { range: { min: 2, max: 8, increment: 1 } }, 2048: { range: { min: 4, max: 16, increment: 1 } }, 4096: { range: { min: 8, max: 30, increment: 1 } }, 8192: { range: { min: 16, max: 60, increment: 4 } }, 16384: { range: { min: 32, max: 120, increment: 4 } } }; const { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost } = await this.getFargateInfo(service); const maxConsumedCpu = maxCpuPercentage * allocatedCpu; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const lowerCpuOptions = Object.keys(fargateScaleOptions).filter((cpuString) => { const cpu = Number(cpuString); return cpu < allocatedCpu && cpu > maxConsumedCpu; }).sort(); let targetScaleOption: FargateScale; for (const cpuOption of lowerCpuOptions) { const scalingOption = fargateScaleOptions[Number(cpuOption)]; const memoryOptionValues = []; const discreteMemoryOptionValues = scalingOption.discrete || []; memoryOptionValues.push(...discreteMemoryOptionValues); const rangeMemoryOptionsValues = scalingOption.range ? this.createDiscreteValuesForRange(scalingOption.range) : []; memoryOptionValues.push(...rangeMemoryOptionsValues); const optimizedMemory = memoryOptionValues.filter(mem => (mem > maxConsumedMemory)).sort().at(0); if (optimizedMemory) { targetScaleOption = { cpu: Number(cpuOption), memory: (optimizedMemory * 1024) }; break; } } if (targetScaleOption) { const targetMonthlyCost = this.calculateFargateCost( platform, cpuArch, targetScaleOption.cpu / 1024, targetScaleOption.memory / 1024, numTasks ); this.addScenario(service.serviceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownFargateService', isActionable: false, reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' + `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` + `${targetScaleOption.memory} MiB.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) { this.ecsClient = new ECS({ credentials, region }); this.ec2Client = new EC2({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); this.elbV2Client = new ElasticLoadBalancingV2({ credentials, region }); this.apigClient = new ApiGatewayV2({ credentials, region }); this.pricingClient = new Pricing({ credentials, region }); if (overrides?.services) { this.services = await this.describeTheseServices(overrides?.services); } else { this.services = await this.describeAllServices(); } if (this.services.length === 0) return; for (const service of this.services) { const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ service, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [AVG_MEMORY]: avgMemoryMetrics, [MAX_MEMORY]: maxMemoryMetrics, [ALB_REQUEST_COUNT]: albRequestCountMetrics, [APIG_REQUEST_COUNT]: apigRequestCountMetrics } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values); const { max: maxMemory, isStable: maxMemoryIsStable } = getStabilityStats(maxMemoryMetrics.Values); const lowMemoryUtilization = ( (avgMemoryIsStable && maxMemoryIsStable) || maxMemory < 10 ); const requestCountMetricValues = [ ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || []) ]; const totalRequestCount = stats.sum(requestCountMetricValues); const noNetworkUtilization = totalRequestCount === 0; if ( lowCpuUtilization && lowMemoryUtilization && noNetworkUtilization ) { const info = service.launchType === LaunchType.FARGATE ? await this.getFargateInfo(service) : await this.getEc2ContainerInfo(service); if (!info) { return; } const { monthlyCost } = info; this.addScenario(service.serviceArn, 'unused', { value: 'true', delete: { action: 'deleteService', isActionable: true, reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and' + ' network traffic.', monthlySavings: monthlyCost } }); } else if (maxCpu < 0.8 && maxMemory < 0.8) { if (service.launchType === LaunchType.FARGATE) { await this.checkForFargateScaleDown(service, maxCpu, maxMemory); } else { await this.checkForEc2ScaleDown(service, maxCpu, maxMemory); } } const monthlyCost = this.serviceCosts[service.serviceName] || 0; await this.fillData( service.serviceArn, credentials, region, { resourceId: service.serviceName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); AwsEcsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, service.serviceArn, 'AWS/ECS', metricName, [{ Name: 'ServiceName', Value: service.serviceName }, { Name: 'ClusterName', Value: service.clusterArn?.split('/').pop() }]); }); } console.info('this.utilization:\n', JSON.stringify(this.utilization, null, 2)); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } async deleteService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); await ecsClient.deleteService({ service: serviceArn, cluster: clusterName }); } async scaleDownFargateService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string, cpu: number, memory: number ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); const serviceResponse = await ecsClient.describeServices({ cluster: clusterName, services: [serviceArn] }); const taskDefinitionArn = serviceResponse?.services?.at(0)?.taskDefinition; const taskDefResponse = await ecsClient.describeTaskDefinition( { taskDefinition: taskDefinitionArn, include: [TaskDefinitionField.TAGS] } ); const taskDefinition: TaskDefinition = taskDefResponse?.taskDefinition; const tags = taskDefResponse?.tags; const { containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes } = taskDefinition; // TODO: CPU and Memory validation? const revisionResponse = await ecsClient.registerTaskDefinition({ cpu: cpu.toString(), memory: memory.toString(), containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes, tags }); await ecsClient.updateService({ cluster: clusterName, service: serviceArn, taskDefinition: revisionResponse?.taskDefinition?.taskDefinitionArn, forceNewDeployment: true }); } async scaleDownEc2Service (_serviceArn: string, _cpu: number, _memory: number) { /* TODO: Update Asg/Capacity provider? Or update memory/cpu allocation on the tasks? Or both? */ throw HttpError.NotImplemented('Automatic scale down for EC2 backed ECS Clusters is not yet supported.'); } }
src/service-utilizations/aws-ecs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": "import { getInstanceCost } from '../utils/ec2-utils.js';\nimport { Arns } from '../types/constants.js';\nconst cache = cached<string>('ec2-util-cache', {\n backend: {\n type: 'memory'\n }\n});\ntype AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated';\nconst AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn'];\ntype AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & {", "score": 0.8594262599945068 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.8571183085441589 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": "/*\nimport { AutoScaling } from '@aws-sdk/client-auto-scaling';\nimport { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { AlertType } from '../types/types.js';\nexport type AutoScalingGroupsUtilizationProps = { \n hasScalingPolicy?: boolean; \n cpuUtilization?: number;\n networkIn?: number;", "score": 0.8513593673706055 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": "import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nimport { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { Volume } from '@aws-sdk/client-ec2';\nimport { CloudWatch } from '@aws-sdk/client-cloudwatch';\nimport { Arns } from '../types/constants.js';\nimport { getHourlyCost, rateLimitMap } from '../utils/utils.js';\nexport type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps';\nconst EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps'];", "score": 0.8489943742752075 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": "const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000);\nconst sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000);\nconst twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000);\ntype AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes';\nconst AwsCloudWatchLogsMetrics = ['IncomingBytes'];\nexport class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> {\n constructor () {\n super();\n }", "score": 0.8474042415618896 } ]
typescript
class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await
this.fillData( bucketArn, credentials, region, {
resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8757076859474182 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8514614105224609 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8499088287353516 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8487908244132996 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " } = await this.getLogGroupData(credentials, region, logGroup);\n this.addScenario(logGroupArn, 'hasRetentionPolicy', {\n value: retentionInDays?.toString(),\n optimize: {\n action: 'setRetentionPolicy',\n isActionable: true,\n reason: 'this log group does not have a retention policy',\n monthlySavings: monthlyStorageCost\n }\n });", "score": 0.8462960720062256 } ]
typescript
this.fillData( bucketArn, credentials, region, {
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.
resourceId, data.associatedResourceId );
this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8458046317100525 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8392409086227417 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8289678692817688 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " }\n async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) {\n const s3Client = new S3({\n credentials: await awsCredentialsProvider.getCredentials()\n });\n const resourceId = resourceArn.split(':').at(-1);\n if (actionName === 'enableIntelligientTiering') { \n await this.enableIntelligientTiering(s3Client, resourceId);\n }\n }", "score": 0.8268260955810547 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8210936188697815 } ]
typescript
resourceId, data.associatedResourceId );
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (
bucketBytes / ONE_GB_IN_BYTES) * 0.022;
/* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " Stat: 'Sum'\n }\n }\n ],\n StartTime: oneMonthAgo,\n EndTime: new Date()\n });\n const readIops = get(res, 'MetricDataResults[0].Values[0]', 0);\n const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0);\n const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0);", "score": 0.8831435441970825 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand;\n const onDemandKeys = Object.keys(onDemandData);\n const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions;\n const priceDimensionsKeys = Object.keys(priceDimensionsData);\n const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD;\n // monthly cost\n return pricePerHour * 24 * 30;\n }\n}", "score": 0.8730455636978149 }, { "filename": "src/utils/ec2-utils.ts", "retrieved_chunk": " ServiceCode: 'AmazonEC2'\n });\n const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand;\n const onDemandKeys = Object.keys(onDemandData);\n const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions;\n const priceDimensionsKeys = Object.keys(priceDimensionsData);\n const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD;\n return pricePerHour * 24 * 30;\n}", "score": 0.861981987953186 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " Metric: {\n Namespace: 'AWS/RDS',\n MetricName: 'TotalBackupStorageBilled',\n Dimensions: [{\n Name: 'DBInstanceIdentifier',\n Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'", "score": 0.8509016633033752 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0);\n const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0);\n const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0);\n const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0);\n const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0);\n return {\n totalIops: readIops + writeIops,\n totalThroughput: readThroughput + writeThroughput,\n freeStorageSpace,\n totalBackupStorageBilled,", "score": 0.8426089882850647 } ]
typescript
bucketBytes / ONE_GB_IN_BYTES) * 0.022;
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) {
this.addData(resourceArn, key, data[key]);
} await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8459241986274719 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.835179328918457 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8346657156944275 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8343950510025024 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": "export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> {\n accountId: string;\n volumeCosts: { [ volumeId: string ]: number };\n constructor () {\n super();\n this.volumeCosts = {};\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {", "score": 0.8289788961410522 } ]
typescript
this.addData(resourceArn, key, data[key]);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){
return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
} else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8336427211761475 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " scaleDown: {\n action: 'scaleDownEc2Service',\n isActionable: false,\n reason: 'The EC2 instances used in this Service\\'s cluster appears to be over allocated based on its CPU' + \n `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }", "score": 0.8319380283355713 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const monthlySavings = cost - targetInstanceCost;\n this.addScenario(instanceArn, 'overAllocated', {\n value: 'overAllocated',\n scaleDown: {\n action: 'scaleDownInstance',\n isActionable: false,\n reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + \n `suggest scaling down to a ${targetInstanceType.InstanceType}`,\n monthlySavings\n }", "score": 0.8306772708892822 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " DISK_READ_OPS,\n DISK_WRITE_OPS,\n MAX_NETWORK_BYTES_IN,\n MAX_NETWORK_BYTES_OUT,\n AVG_NETWORK_BYTES_IN,\n AVG_NETWORK_BYTES_OUT\n} from '../types/constants.js';\nimport { AwsServiceOverrides } from '../types/types.js';\nimport { Pricing } from '@aws-sdk/client-pricing';\nimport { getAccountId, getHourlyCost } from '../utils/utils.js';", "score": 0.8215606212615967 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.8191233277320862 } ]
typescript
return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.
addData(resourceArn, key, data[key]);
} await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8686826229095459 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8516464829444885 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8451470136642456 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " }\n async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) {\n const s3Client = new S3({\n credentials: await awsCredentialsProvider.getCredentials()\n });\n const resourceId = resourceArn.split(':').at(-1);\n if (actionName === 'enableIntelligientTiering') { \n await this.enableIntelligientTiering(s3Client, resourceId);\n }\n }", "score": 0.8276610374450684 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8261182308197021 } ]
typescript
addData(resourceArn, key, data[key]);
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario
.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
}); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.8791053295135498 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8503495454788208 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8480948805809021 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " if (!utilization[service] || isEmpty(utilization[service])) return;\n Object.keys(utilization[service]).forEach((resource) => { \n totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0;\n });\n });\n return usd.format(totalSavings);\n}\nexport function sentenceCase (name: string): string { \n const result = name.replace(/([A-Z])/g, ' $1');\n return result[0].toUpperCase() + result.substring(1).toLowerCase();", "score": 0.846818208694458 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " scenarios: filteredScenarios \n };\n return aggUtil;\n }, {});\n return actionFilteredServiceUtil;\n}\nexport function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number {\n let total = 0;\n Object.keys(filtered).forEach((s) => {\n if (!filtered[s] || isEmpty(filtered[s])) return;", "score": 0.8395538330078125 } ]
typescript
.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId,
data.associatedResourceId );
this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8532611727714539 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8470268845558167 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8248264789581299 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " }\n async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) {\n const s3Client = new S3({\n credentials: await awsCredentialsProvider.getCredentials()\n });\n const resourceId = resourceArn.split(':').at(-1);\n if (actionName === 'enableIntelligientTiering') { \n await this.enableIntelligientTiering(s3Client, resourceId);\n }\n }", "score": 0.8226639628410339 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8213257193565369 } ]
typescript
data.associatedResourceId );
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string
, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric;
} } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const {\n Id,\n Timestamps = [],\n Values = []\n } = metricData;\n if (!metrics[Id]) {\n metrics[Id] = metricData;\n } else {\n metrics[Id].Timestamps.push(...Timestamps);\n metrics[Id].Values.push(...Values);", "score": 0.8188858032226562 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " this.addScenario(dbInstanceArn, 'cpuUtilization', {\n value: metrics.cpuUtilization.toString(), \n scaleDown: {\n action: '', \n isActionable: false,\n reason: 'Max CPU Utilization is under 50%',\n monthlySavings: 0\n }\n });\n }", "score": 0.8057750463485718 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " Values = []\n } = metricData;\n if (!metrics[Id]) {\n metrics[Id] = metricData;\n } else {\n metrics[Id].Timestamps.push(...Timestamps);\n metrics[Id].Values.push(...Values);\n }\n });\n nextToken = NextToken;", "score": 0.79815673828125 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " actionTypeToEnum[actionType],\n resourceArn,\n get(resource.data, 'region', 'us-east-1')\n );\n }\n }\n }\n }\n }\n render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) {", "score": 0.7953130006790161 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7915286421775818 } ]
typescript
, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric;
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario
.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
}); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.879004716873169 }, { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " const totalMonthlySavings = getTotalMonthlySavings(utilizations);\n return { \n totalUnusedResources, \n totalMonthlySavings, \n totalResources\n };\n}", "score": 0.8541314601898193 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8483189344406128 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " if (!utilization[service] || isEmpty(utilization[service])) return;\n Object.keys(utilization[service]).forEach((resource) => { \n totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0;\n });\n });\n return usd.format(totalSavings);\n}\nexport function sentenceCase (name: string): string { \n const result = name.replace(/([A-Z])/g, ' $1');\n return result[0].toUpperCase() + result.substring(1).toLowerCase();", "score": 0.8473066091537476 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": "import { getInstanceCost } from '../utils/ec2-utils.js';\nimport { Arns } from '../types/constants.js';\nconst cache = cached<string>('ec2-util-cache', {\n backend: {\n type: 'memory'\n }\n});\ntype AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated';\nconst AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn'];\ntype AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & {", "score": 0.8397862315177917 } ]
typescript
.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );