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 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/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " });\n if (overrides?.services) {\n this.services = await this.describeTheseServices(overrides?.services);\n } else {\n this.services = await this.describeAllServices();\n }\n if (this.services.length === 0) return;\n for (const service of this.services) {\n const now = dayjs();\n const startTime = now.subtract(2, 'weeks');",
"score": 62.66929248452888
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " const services: Service[] = [];\n for (const [clusterArn, clusterServices] of Object.entries(clusters)) {\n const serviceChunks = chunk(clusterServices.serviceArns, 10);\n for (const serviceChunk of serviceChunks) {\n const response = await this.ecsClient.describeServices({\n cluster: clusterArn,\n services: serviceChunk\n });\n services.push(...(response?.services || []));\n }",
"score": 50.08638289301174
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " } = response || {};\n services.push(...serviceArns);\n nextToken = nextServicesToken;\n } while (nextToken);\n return {\n [clusterArn]: {\n serviceArns: services\n }\n };\n }",
"score": 40.94730087243083
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " super();\n this.serviceArns = [];\n this.services = [];\n this.serviceCosts = {};\n this.DEBUG_MODE = enableDebugMode || false;\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {\n if (actionName === 'deleteService') {",
"score": 34.58874418208803
},
{
"filename": "src/ops-types.ts",
"retrieved_chunk": " * ```yaml\n * UtilizationProvider:\n type: AwsUtilizationProvider\n * ```\n */\nexport interface AwsUtilizationProvider extends Provider {\n services?: AwsResourceType[];\n regions?: string[];\n}\nexport type AwsResourceType = 'Account' |",
"score": 33.41802967246186
}
] | typescript | this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service); |
/*
* @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 if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**",
"score": 27.64702772690855
},
{
"filename": "src/schema/record/rules.ts",
"retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**",
"score": 27.596155374004592
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 26.152935592104175
},
{
"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": 25.87783534934113
},
{
"filename": "src/schema/record/rules.ts",
"retrieved_chunk": " }\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.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field",
"score": 25.71052180016132
}
] | typescript | .report(messages.creditCard, 'creditCard', field, { |
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": " 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": 28.35932111405929
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " if (activeConnectionCount === 0) {\n this.addScenario(natGatewayArn, 'activeConnectionCount', {\n value: activeConnectionCount.toString(),\n delete: {\n action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });",
"score": 19.46552771994472
},
{
"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": 17.541161584372276
},
{
"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": 15.4839416663435
},
{
"filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx",
"retrieved_chunk": " });\n autoScalingGroups.forEach(async (group) => { \n const cpuUtilPercent = await this.getGroupCPUUTilization(cloudWatchClient, group.name); \n if(cpuUtilPercent < 50){ \n this.addScenario(group.name, 'cpuUtilization', {\n value: cpuUtilPercent, \n alertType: AlertType.Warning, \n reason: 'Max CPU Utilization has been under 50% for the last week', \n recommendation: 'scale down instance', \n actions: ['scaleDownInstance']",
"score": 15.413379435614868
}
] | typescript | await this.fillData(
logGroupArn,
credentials,
region,
{ |
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": 13.253874350606598
},
{
"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": 12.71657929640935
},
{
"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": 11.386082650841075
},
{
"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": 8.468849000611478
},
{
"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": 8.463749059211871
}
] | typescript | .fillData(
instanceArn,
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/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": 41.22171094246856
},
{
"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": 23.479195971327442
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 22.932963564599447
},
{
"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": 21.080124647724062
},
{
"filename": "src/schema/array/rules.ts",
"retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**",
"score": 20.96175547458267
}
] | 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-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": 24.244118569898006
},
{
"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": 23.285528188175686
},
{
"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": 22.95824668485252
},
{
"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": 22.170258908369995
},
{
"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": 21.441289783053584
}
] | 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/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": 56.85599862983355
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " [AVG_MEMORY]: avgMemoryMetrics,\n [MAX_MEMORY]: maxMemoryMetrics,\n [ALB_REQUEST_COUNT]: albRequestCountMetrics,\n [APIG_REQUEST_COUNT]: apigRequestCountMetrics\n } = metrics;\n const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values);\n const {\n max: maxCpu,\n isStable: maxCpuIsStable\n } = getStabilityStats(maxCpuMetrics.Values);",
"score": 41.18067171458022
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " numTasks,\n monthlyCost\n }; \n }\n private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) {\n // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html\n const fargateScaleOptions: FargateScaleOption = {\n 256: {\n discrete: [0.5, 1, 2]\n },",
"score": 26.562194078447632
},
{
"filename": "src/utils/stats.ts",
"retrieved_chunk": " }\n }\n const filteredMean = stats.mean(filteredDataSet);\n const filteredStdev = stats.standardDeviation(filteredDataSet);\n const max = stats.max(filteredDataSet);\n const maxZScore = stats.zScore(max, filteredMean, filteredStdev);\n const isStable = maxZScore < stabilityZScore;\n const anomalyPercentageString = anomalyPercentage ? `${Math.round(anomalyPercentage * 10000) / 10000}%` : undefined;\n return {\n mean: filteredMean,",
"score": 25.333609427761726
},
{
"filename": "src/utils/stats.ts",
"retrieved_chunk": " maxZScore: 0,\n standardDeviation: 0,\n wasFiltered: false,\n isStable: false\n };\n }\n let wasFiltered = removeOutliers;\n const mean = stats.mean(dataSet);\n const stdev = stats.standardDeviation(dataSet);\n let filteredDataSet = dataSet;",
"score": 24.583566975350195
}
] | 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/string/main.ts",
"retrieved_chunk": " return this.use(inRule({ choices }))\n }\n /**\n * Ensure the field's value under validation is not inside the pre-defined list.\n */\n notIn(list: string[] | ((field: FieldContext) => string[])) {\n return this.use(notInRule({ list }))\n }\n /**\n * Validates the value to be a valid credit card number",
"score": 52.4071431328429
},
{
"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": 30.705854471104686
},
{
"filename": "src/schema/string/main.ts",
"retrieved_chunk": " /**\n * Ensure the value ends with the pre-defined substring\n */\n notSameAs(otherField: string) {\n return this.use(notSameAsRule({ otherField }))\n }\n /**\n * Ensure the field's value under validation is a subset of the pre-defined list.\n */\n in(choices: string[] | ((field: FieldContext) => string[])) {",
"score": 30.014835662374104
},
{
"filename": "src/schema/enum/native_enum.ts",
"retrieved_chunk": "import type { EnumLike, FieldOptions, Validation } from '../../types.js'\n/**\n * VineNativeEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n *\n * The choices list is derived from TypeScript enum data type or an\n * object\n */\nexport class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<\n Values[keyof Values],",
"score": 28.64073715356509
},
{
"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": 25.604703614852607
}
] | 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-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": 17.909911918380203
},
{
"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": 17.774374549144213
},
{
"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": 17.04910306818869
},
{
"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": 16.751054892046895
},
{
"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": 16.686881083165876
}
] | 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/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": 43.595718960463074
},
{
"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": 43.38812175643359
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " if (!instanceFamily) {\n instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance);\n }\n const allInstanceTypes = Object.values(_InstanceType);\n const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`));\n const cachedInstanceTypes = await cache.getOrElse(\n instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily))\n );\n const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]');\n const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => {",
"score": 42.96241551660838
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " let i = min;\n do {\n i = i + increment;\n discreteVales.push(i);\n } while (i <= max);\n return discreteVales;\n }\n private async getEc2ContainerInfo (service: Service) {\n const tasks = await this.getAllTasks(service);\n const taskCpu = Number(tasks.at(0)?.cpu);",
"score": 42.46485943053094
},
{
"filename": "src/utils/utils.ts",
"retrieved_chunk": " const launchTimes: number[] = [];\n const results = new Array(array.length);\n // calculate num requests in last second\n function calcRequestsInLastSecond () {\n const now = Date.now();\n // look backwards in launchTimes to see how many were launched within the last second\n let cnt = 0;\n for (let i = launchTimes.length - 1; i >= 0; i--) {\n if (now - launchTimes[i] < 1000) {\n ++cnt;",
"score": 35.63835509677177
}
] | typescript | const instanceArn = Arns.Ec2(region, this.accountId, instanceId); |
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-service-utilization.ts",
"retrieved_chunk": " if (resourceArn in this.utilization) {\n const cfnClient = new CloudFormation({\n credentials,\n region\n });\n await cfnClient.describeStackResources({\n PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId\n }).then((res) => {\n const stack = res.StackResources[0].StackId;\n this.addData(resourceArn, 'stack', stack);",
"score": 14.301147965154515
},
{
"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": 12.259744228957448
},
{
"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": 10.9242559502232
},
{
"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": 10.765045583935093
},
{
"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": 10.684602033099273
}
] | 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/utils/ec2-utils.ts",
"retrieved_chunk": "import { Pricing } from '@aws-sdk/client-pricing';\nexport async function getInstanceCost (pricingClient: Pricing, instanceType: string) {\n const res = await pricingClient.getProducts({\n Filters: [\n {\n Type: 'TERM_MATCH',\n Field: 'instanceType',\n Value: instanceType\n },\n {",
"score": 18.584361576904154
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value;\n const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType);\n const monthlyCost = monthlyInstanceCost * numEc2Instances;\n this.serviceCosts[service.serviceName] = monthlyCost;\n return {\n allocatedCpu,\n allocatedMemory,\n containerInstance,\n instanceType,\n monthlyCost,",
"score": 16.86669566210063
},
{
"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": 16.136228624573874
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " allTasks.push(...tasks);\n }\n return allTasks;\n }\n private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> {\n const ec2InstanceResponse = await this.ec2Client.describeInstances({\n InstanceIds: [containerInstance.ec2InstanceId]\n });\n const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType;\n const instanceFamily = instanceType?.split('.')?.at(0);",
"score": 14.315928450336253
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " if (activeConnectionCount === 0) {\n this.addScenario(natGatewayArn, 'activeConnectionCount', {\n value: activeConnectionCount.toString(),\n delete: {\n action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });",
"score": 13.492040961116913
}
] | typescript | addScenario(instanceArn, 'unused', { |
/*
* @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": 25.399837404624016
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 25.378955232261127
},
{
"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": 25.194057375996326
},
{
"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": 25.014789763945096
},
{
"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": 24.890314474374147
}
] | typescript | if (!helpers.isCreditCard(value as string)) { |
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": 26.017992043702797
},
{
"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": 25.538696055070737
},
{
"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": 23.605521771116894
},
{
"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": 22.393898478685067
},
{
"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": 21.25542712719176
}
] | typescript | hourlyCost: getHourlyCost(totalMonthlyCost)
} |
/*
* @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": 26.145655540634028
},
{
"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": 25.399837404624016
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 25.378955232261127
},
{
"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": 25.194057375996326
},
{
"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": 24.890314474374147
}
] | typescript | if (!helpers.isPostalCode(value as string, 'any')) { |
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/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": 31.924450401177456
},
{
"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": 31.924450401177456
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesOutToDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.127663221291733
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesInFromDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.127663221291733
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " await this.getSidePanelMetrics(\n credentials, \n region, \n service.serviceArn, \n 'AWS/ECS', \n metricName, \n [{\n Name: 'ServiceName',\n Value: service.serviceName\n },",
"score": 17.06340373580078
}
] | 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/string/main.ts",
"retrieved_chunk": " */\n mobile(...args: Parameters<typeof mobileRule>) {\n return this.use(mobileRule(...args))\n }\n /**\n * Validates the value to be a valid IP address.\n */\n ipAddress(version?: 4 | 6) {\n return this.use(ipAddressRule(version ? { version } : undefined))\n }",
"score": 39.042563267234925
},
{
"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": 34.61244789323089
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 33.13545504726214
},
{
"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": 32.415680123307645
},
{
"filename": "src/schema/array/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 array if the field is valid.",
"score": 32.415680123307645
}
] | 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/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": 41.22171094246856
},
{
"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": 23.479195971327442
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 22.932963564599447
},
{
"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": 21.080124647724062
},
{
"filename": "src/schema/array/rules.ts",
"retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**",
"score": 20.96175547458267
}
] | 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": 41.22171094246856
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 24.056657321284153
},
{
"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": 23.720500000011132
},
{
"filename": "src/schema/record/rules.ts",
"retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**",
"score": 22.44023380116919
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {",
"score": 22.401015545852125
}
] | 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/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": 30.084607923005816
},
{
"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": 30.04180391673991
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " cloned.allowUnknownProperties()\n }\n return cloned as this\n }\n /**\n * Applies camelcase transform\n */\n toCamelCase() {\n return new VineCamelCaseObject(this)\n }",
"score": 29.645186314908432
},
{
"filename": "src/schema/union/main.ts",
"retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),",
"score": 25.32150953084436
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " * Clone object\n */\n clone(): this {\n const cloned = new VineObject<Properties, Output, CamelCaseOutput>(\n this.getProperties(),\n this.cloneOptions(),\n this.cloneValidations()\n )\n this.#groups.forEach((group) => cloned.merge(group))\n if (this.#allowUnknownProperties) {",
"score": 24.47420395321967
}
] | typescript | refs: RefsStore, options: ParserOptions): TupleNode { |
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": 22.35440113848673
},
{
"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": 22.158169361037647
},
{
"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": 19.584468690387787
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": "}\ntype RdsMetrics = {\n totalIops: number;\n totalThroughput: number;\n freeStorageSpace: number;\n totalBackupStorageBilled: number;\n cpuUtilization: number;\n databaseConnections: number;\n};\nexport type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' |",
"score": 18.71797189216763
},
{
"filename": "src/ops-types.ts",
"retrieved_chunk": " * ```yaml\n * UtilizationProvider:\n type: AwsUtilizationProvider\n * ```\n */\nexport interface AwsUtilizationProvider extends Provider {\n services?: AwsResourceType[];\n regions?: string[];\n}\nexport type AwsResourceType = 'Account' |",
"score": 18.660793604389358
}
] | typescript | AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> { |
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": 47.121070775643865
},
{
"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": 38.078833149635386
},
{
"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": 31.44201933532532
},
{
"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": 27.930730896499096
},
{
"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": 26.529265145272344
}
] | 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/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": 28.84483812348324
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": "}\ntype RdsMetrics = {\n totalIops: number;\n totalThroughput: number;\n freeStorageSpace: number;\n totalBackupStorageBilled: number;\n cpuUtilization: number;\n databaseConnections: number;\n};\nexport type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' |",
"score": 26.60523961058632
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": "// monthly costs\ntype StorageAndIOCosts = {\n totalStorageCost: number,\n iopsCost: number,\n throughputCost?: number\n};\n// monthly costs\ntype RdsCosts = StorageAndIOCosts & {\n totalCost: number,\n instanceCost: number",
"score": 26.199197420215384
},
{
"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": 20.29160693209427
},
{
"filename": "src/types/types.ts",
"retrieved_chunk": "export type MetricData = { \n timestamp?: number | Date;\n value: number\n}\nexport enum ActionType {\n OPTIMIZE='optimize',\n DELETE='delete',\n SCALE_DOWN='scaleDown'\n}\nexport const actionTypeText = {",
"score": 19.866995911433676
}
] | 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/schema/record/rules.ts",
"retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**",
"score": 28.803423904458494
},
{
"filename": "src/schema/array/rules.ts",
"retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**",
"score": 27.64702772690855
},
{
"filename": "src/schema/record/rules.ts",
"retrieved_chunk": " }\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.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field",
"score": 26.886022978923197
},
{
"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": 26.6071765602736
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)",
"score": 26.152935592104175
}
] | 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": 35.73571000728713
},
{
"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": 32.040329803624424
},
{
"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": 28.845106509864532
},
{
"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": 26.56026199535293
},
{
"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": 25.21009276878671
}
] | 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/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": 47.998991474996004
},
{
"filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts",
"retrieved_chunk": " ]\n });\n const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0);\n return monthlyIncomingBytes;\n }\n private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) {\n const cwLogsClient = new CloudWatchLogs({\n credentials,\n region\n });",
"score": 43.56653808424525
},
{
"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": 42.74033118110499
},
{
"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": 37.79196406540121
},
{
"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": 37.249527122689194
}
] | 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/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": 40.34324875802908
},
{
"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": 34.90657116519886
},
{
"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": 32.20775981423829
},
{
"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": 30.883377722866758
},
{
"filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts",
"retrieved_chunk": " ]\n });\n const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0);\n return monthlyIncomingBytes;\n }\n private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) {\n const cwLogsClient = new CloudWatchLogs({\n credentials,\n region\n });",
"score": 30.20749008371115
}
] | 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": 33.18522548534981
},
{
"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": 31.75741941634683
},
{
"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": 25.600862510329577
},
{
"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": 24.770773530949395
},
{
"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": 24.23320618556002
}
] | 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": 93.47742835281211
},
{
"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": 82.16241621091083
},
{
"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": 77.62824749777887
},
{
"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": 74.32168610179643
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,",
"score": 69.30254885934907
}
] | 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/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": 22.35440113848673
},
{
"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": 22.158169361037647
},
{
"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": 19.584468690387787
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": "}\ntype RdsMetrics = {\n totalIops: number;\n totalThroughput: number;\n freeStorageSpace: number;\n totalBackupStorageBilled: number;\n cpuUtilization: number;\n databaseConnections: number;\n};\nexport type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' |",
"score": 18.71797189216763
},
{
"filename": "src/ops-types.ts",
"retrieved_chunk": " * ```yaml\n * UtilizationProvider:\n type: AwsUtilizationProvider\n * ```\n */\nexport interface AwsUtilizationProvider extends Provider {\n services?: AwsResourceType[];\n regions?: string[];\n}\nexport type AwsResourceType = 'Account' |",
"score": 18.660793604389358
}
] | 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/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": 17.35036123672407
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " const matchesAnyCountryCode = countryCodes.find((countryCode) =>\n helpers.isPassportNumber(value as string, countryCode)\n )\n if (!matchesAnyCountryCode) {\n field.report(messages.passport, 'passport', field, { countryCodes })\n }\n})\n/**\n * Validates the value to be a valid postal code\n */",
"score": 16.27808907904371
},
{
"filename": "src/vine/create_rule.ts",
"retrieved_chunk": " * Returns args for the validation function.\n */\ntype GetArgs<T> = undefined extends T ? [options?: T] : [options: T]\n/**\n * Convert a validator function to a rule that you can apply\n * to any schema type using the `schema.use` method.\n */\nexport function createRule<Options = undefined>(\n validator: Validator<Options>,\n metaData?: {",
"score": 14.16159141241315
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": ")\n/**\n * Validates the value to be a valid credit card number\n */\nexport const creditCardRule = createRule<\n CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */",
"score": 13.11153896792159
},
{
"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": 12.146287351236683
}
] | 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": " */\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": 27.322314886506906
},
{
"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": 27.322314886506906
},
{
"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": 26.571074584523647
},
{
"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": 25.160018114190308
},
{
"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": 22.975720640040045
}
] | 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": " 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": 26.507283075183498
},
{
"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": 25.61563544525204
},
{
"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": 24.670803151581122
},
{
"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": 22.717464130968676
},
{
"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": 18.865103622791754
}
] | 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-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": 27.256999483711333
},
{
"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": 26.90815615081379
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " targetScaleOption.memory / 1024,\n numTasks\n );\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'overAllocated',\n scaleDown: {\n action: 'scaleDownFargateService',\n isActionable: false,\n reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' +\n `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` +",
"score": 24.049126926111477
},
{
"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": 22.77141622912042
},
{
"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": 21.900221291265424
}
] | 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": 35.56872680224067
},
{
"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": 26.50411285734487
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " await this.getSidePanelMetrics(\n credentials, \n region, \n service.serviceArn, \n 'AWS/ECS', \n metricName, \n [{\n Name: 'ServiceName',\n Value: service.serviceName\n },",
"score": 20.090893011742523
},
{
"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": 19.178729691060827
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " function metricStat (metricName: string, statistic: string) {\n return {\n Metric: {\n Namespace: 'AWS/ECS',\n MetricName: metricName,\n Dimensions: [\n {\n Name: 'ServiceName',\n Value: serviceName\n },",
"score": 15.087183638426312
}
] | 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/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": 26.10072168952434
},
{
"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": 24.00457522625124
},
{
"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": 22.918480549660035
},
{
"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": 22.34061820124382
},
{
"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": 21.057884267743166
}
] | typescript | const bucketArn = Arns.S3(bucketName); |
/*
* @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/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": 17.906348252480804
},
{
"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": 15.535918372639602
},
{
"filename": "src/vine/main.ts",
"retrieved_chunk": " messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields)\n /**\n * Error reporter to use on the validator\n */\n errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter()\n /**\n * Control whether or not to convert empty strings to null\n */\n convertEmptyStringsToNull: boolean = false\n /**",
"score": 14.991969260414821
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " }\n}\n/**\n * The base type for creating a custom literal type. Literal type\n * is a schema type that has no children elements.\n */\nexport abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType<\n Output,\n CamelCaseOutput\n> {",
"score": 14.377347905629628
},
{
"filename": "src/schema/union/main.ts",
"retrieved_chunk": " * Vine union represents a union data type. A union is a collection\n * of conditionals and each condition has an associated schema\n */\nexport class VineUnion<Conditional extends UnionConditional<SchemaTypes>>\n implements ConstructableSchema<Conditional[typeof OTYPE], Conditional[typeof COTYPE]>\n{\n declare [OTYPE]: Conditional[typeof OTYPE];\n declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {",
"score": 13.977930094735557
}
] | typescript | interface ErrorReporterContract extends BaseReporter { |
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": 41.766241460423906
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'writeThroughput',\n MetricStat: {",
"score": 37.757911856507015
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'writeIops',\n MetricStat: {",
"score": 37.757911856507015
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'totalBackupStorageBilled',\n MetricStat: {",
"score": 37.757911856507015
},
{
"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": 37.51017372218848
}
] | 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 { 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": " }\n /**\n * Validate data against a schema. Optionally, you can share metaData with\n * the validator\n *\n * ```ts\n * await validator.validate(data)\n * await validator.validate(data, { meta: {} })\n *\n * await validator.validate(data, {",
"score": 38.88912174178512
},
{
"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": 33.70905544303001
},
{
"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": 28.767640616076022
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface ErrorReporterContract extends BaseReporter {\n createError(): ValidationError\n}\n/**\n * The validator function to validate metadata given to a validation\n * pipeline\n */\nexport type MetaDataValidator = (meta: Record<string, any>) => void\n/**\n * Options accepted during the validate call.",
"score": 24.20962340904564
},
{
"filename": "src/vine/validator.ts",
"retrieved_chunk": " * Validator to use to validate metadata\n */\n #metaDataValidator?: MetaDataValidator\n /**\n * Messages provider to use on the validator\n */\n messagesProvider: MessagesProviderContact\n /**\n * Error reporter to use on the validator\n */",
"score": 19.658522833766536
}
] | typescript | .validate(options.data, options)
} |
/*
* @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": 32.12783416216442
},
{
"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": 30.8710561223458
},
{
"filename": "src/schema/tuple/main.ts",
"retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}",
"score": 28.748466912503904
},
{
"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": 28.232472593216883
},
{
"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": 28.23055955821951
}
] | 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-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": 21.16488005901111
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " this.utilization[resourceArn] = {\n scenarios: {},\n data: {}, \n metrics: {}\n } as Resource<ScenarioTypes>;\n }\n this.utilization[resourceArn].scenarios[scenarioType] = scenario;\n }\n protected async fillData (\n resourceArn: string, ",
"score": 20.679840439043105
},
{
"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": 19.044175175282064
},
{
"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": 18.301754661535284
},
{
"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": 18.12538540225549
}
] | typescript | .utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; |
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-nat-gateway-utilization.ts",
"retrieved_chunk": " private async getNatGatewayPrice (credentials: any) {\n const pricingClient = new Pricing({\n credentials,\n // global but have to specify region\n region: 'us-east-1'\n });\n const res = await pricingClient.getProducts({\n ServiceCode: 'AmazonEC2',\n Filters: [\n {",
"score": 23.311462901644482
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " if (resourceArn in this.utilization) {\n const cfnClient = new CloudFormation({\n credentials,\n region\n });\n await cfnClient.describeStackResources({\n PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId\n }).then((res) => {\n const stack = res.StackResources[0].StackId;\n this.addData(resourceArn, 'stack', stack);",
"score": 20.865700931207815
},
{
"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": 19.789418343135182
},
{
"filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx",
"retrieved_chunk": " res = await autoScalingClient.describePolicies({\n NextToken: res.NextToken\n }); \n policies.push(...res.ScalingPolicies.map((policy) => {\n return policy.AutoScalingGroupName;\n }));\n }\n const cloudWatchClient = new CloudWatch({ \n credentials: await awsCredentialsProvider.getCredentials(), \n region: region",
"score": 18.909943974980678
},
{
"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": 18.087958310823623
}
] | 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-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": 23.407509964387966
},
{
"filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts",
"retrieved_chunk": " async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {\n const resourceId = resourceArn.split(':').at(-2);\n if (actionName === 'deleteLogGroup') {\n const cwLogsClient = new CloudWatchLogs({\n credentials: await awsCredentialsProvider.getCredentials(),\n region\n });\n await this.deleteLogGroup(cwLogsClient, resourceId);",
"score": 22.744086511559154
},
{
"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": 22.07600999086915
},
{
"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": 21.829386404635695
},
{
"filename": "src/service-utilizations/aws-ec2-instance-utilization.ts",
"retrieved_chunk": " this.instances = [];\n this.DEBUG_MODE = enableDebugMode || false;\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {\n const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1);\n if (actionName === 'terminateInstance') {\n await this.terminateInstance(awsCredentialsProvider, resourceId, region);\n }",
"score": 21.495187228264403
}
] | 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/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": 41.45849860365352
},
{
"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": 30.10674493241604
},
{
"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": 28.172295975673286
},
{
"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": 25.432391948047343
},
{
"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": 24.613550484535907
}
] | 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/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": 54.046152117757586
},
{
"filename": "src/service-utilizations/aws-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 41.29400834876461
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} \n </Box>\n ));\n return ( \n <Drawer \n isOpen={showSideModal} \n onClose={() => {\n setShowSideModal(false);\n }}\n placement='right'",
"score": 35.776446036163385
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Td>\n {tableHeaders.map(th => \n <Td\n key={resArn + 'scenario' + th}\n maxW={RESOURCE_VALUE_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } ",
"score": 35.008592070421926
},
{
"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": 30.908663058036144
}
] | 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/types/types.ts",
"retrieved_chunk": " tags?: Tag[];\n}\nexport type Metrics = { \n [ metricName: string ]: Metric\n}\nexport type Metric = { \n yAxisLabel: string, \n yLimits?: number, \n values: MetricData[]\n}",
"score": 29.270350578086447
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-usage.tsx",
"retrieved_chunk": " if(isEmpty(metricData)){ \n return null;\n }\n const dataSet = { \n label: metricData.yAxisLabel, \n data: metricData.values.map(d => ({ \n x: d.timestamp, \n y: d.value\n })),\n borderColor: '#ED8936'",
"score": 27.828689457611972
},
{
"filename": "src/aws-utilization-provider.ts",
"retrieved_chunk": " resourceArn,\n region,\n timestamp: new Date().toISOString()\n };\n const history: HistoryEvent[] = await this.getSessionHistory();\n history.push(event);\n await this.utilizationClasses[service].doAction(credentialsProvider, actionName, resourceArn, region);\n await sessionHistoryCache.set('history', history);\n }\n async hardRefresh (",
"score": 19.71459209816239
},
{
"filename": "src/aws-utilization-provider.ts",
"retrieved_chunk": " await utilizationCache.set(service, this.utilization[service]);\n } else {\n this.utilization[service] = await utilizationCache.getOrElse(\n service,\n async () => await this.refreshUtilizationData(service, credentialsProvider, region, serviceOverrides)\n );\n }\n }\n return this.utilization;\n }",
"score": 17.731724300982883
},
{
"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": 16.49442033879442
}
] | 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/types/constants.ts",
"retrieved_chunk": " },\n Ebs (region: string, accountId: string, volumeId: string) {\n return `arn:aws:ec2:${region}:${accountId}:volume/${volumeId}`;\n }\n};\n// Because typescript enums transpile strangely and are even discouraged by typescript themselves:\n// Source: https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums\nexport const AwsResourceTypes: {\n [key: AwsResourceType | string]: AwsResourceType\n} = {",
"score": 43.85316041368078
},
{
"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": 36.0051553843117
},
{
"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": 33.659392881413055
},
{
"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": 30.284740959085017
},
{
"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": 28.09505100614931
}
] | 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/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": 54.046152117757586
},
{
"filename": "src/service-utilizations/aws-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 41.29400834876461
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} \n </Box>\n ));\n return ( \n <Drawer \n isOpen={showSideModal} \n onClose={() => {\n setShowSideModal(false);\n }}\n placement='right'",
"score": 35.776446036163385
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Td>\n {tableHeaders.map(th => \n <Td\n key={resArn + 'scenario' + th}\n maxW={RESOURCE_VALUE_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } ",
"score": 35.008592070421926
},
{
"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": 30.908663058036144
}
] | 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/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": 54.046152117757586
},
{
"filename": "src/service-utilizations/aws-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 41.29400834876461
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} \n </Box>\n ));\n return ( \n <Drawer \n isOpen={showSideModal} \n onClose={() => {\n setShowSideModal(false);\n }}\n placement='right'",
"score": 35.776446036163385
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Td>\n {tableHeaders.map(th => \n <Td\n key={resArn + 'scenario' + th}\n maxW={RESOURCE_VALUE_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } ",
"score": 35.008592070421926
},
{
"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": 30.908663058036144
}
] | 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": 24.550226047989085
},
{
"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": 21.428846333677804
},
{
"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": 20.542369389574308
},
{
"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": 19.71098261109352
},
{
"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": 19.308704378995774
}
] | 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": 34.294311299701114
},
{
"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": 25.480993725840737
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " await this.getSidePanelMetrics(\n credentials, \n region, \n service.serviceArn, \n 'AWS/ECS', \n metricName, \n [{\n Name: 'ServiceName',\n Value: service.serviceName\n },",
"score": 19.61406262367025
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesOutToDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.13123733338106
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesInFromDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.13123733338106
}
] | 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-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": 42.52304404007809
},
{
"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": 41.6561871096583
},
{
"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": 39.97173335474666
},
{
"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": 38.216981736766606
},
{
"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": 36.97677992966408
}
] | 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/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": 30.160865058119445
},
{
"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": 30.045892003077718
},
{
"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": 29.125897278741526
},
{
"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": 28.96365273679875
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " this.utilization[resourceArn] = {\n scenarios: {},\n data: {}, \n metrics: {}\n } as Resource<ScenarioTypes>;\n }\n this.utilization[resourceArn].scenarios[scenarioType] = scenario;\n }\n protected async fillData (\n resourceArn: string, ",
"score": 28.29313613818269
}
] | 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/widgets/aws-utilization.tsx",
"retrieved_chunk": " this.sessionHistory = props.sessionHistory || [];\n }\n async getData (providers?: BaseProvider[]): Promise<void> {\n const depMap = {\n utils: './utils/utils.js'\n };\n const { getAwsCredentialsProvider, getAwsUtilizationProvider } = await import(depMap.utils);\n const utilProvider = getAwsUtilizationProvider(providers);\n const awsCredsProvider = getAwsCredentialsProvider(providers);\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);",
"score": 56.348302657436335
},
{
"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": 49.003798452109365
},
{
"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": 45.35065715641926
},
{
"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": 41.41818199789858
},
{
"filename": "src/aws-utilization-provider.ts",
"retrieved_chunk": " try {\n await this.utilizationClasses[service]?.getUtilization(credentialsProvider, [ region ], overrides);\n return this.utilizationClasses[service]?.utilization;\n } catch (e) {\n console.error(e);\n return {};\n }\n }\n async doAction (\n service: AwsResourceType,",
"score": 38.76929607584585
}
] | 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/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " function onResourceCheckChange (resArn: string, serviceName: string) {\n return (e: React.ChangeEvent<HTMLInputElement>) => {\n if (e.target.checked) {\n setCheckedResources([...checkedResources, resArn]);\n } else {\n setCheckedServices(checkedServices.filter(s => s !== serviceName));\n setCheckedResources(checkedResources.filter(id => id !== resArn));\n }\n };\n }",
"score": 14.148684396670655
},
{
"filename": "src/utils/utils.ts",
"retrieved_chunk": " }\n runMore();\n });\n}\nexport function round (val: number, decimalPlace: number) {\n const factor = 10 ** decimalPlace;\n return Math.round(val * factor) / factor;\n}\nexport function getHourlyCost (monthlyCost: number) {\n return (monthlyCost / 30) / 24;",
"score": 13.815786430447334
},
{
"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": 13.591767733522738
},
{
"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": 13.323884170036257
},
{
"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": 13.191395044409143
}
] | 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": 48.38569542464639
},
{
"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": 43.82857376900819
},
{
"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": 40.60459984471412
},
{
"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": 39.45042316220518
},
{
"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": 26.2889727427205
}
] | 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/aws-ecs-utilization.ts",
"retrieved_chunk": " private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) {\n let monthlyCost = 0;\n if (platform.toLowerCase() === 'windows') {\n monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30;\n } else {\n if (cpuArch === 'x86_64') {\n monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; \n } else {\n monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30;\n }",
"score": 17.226847095703587
},
{
"filename": "src/utils/utils.ts",
"retrieved_chunk": " }\n runMore();\n });\n}\nexport function round (val: number, decimalPlace: number) {\n const factor = 10 ** decimalPlace;\n return Math.round(val * factor) / factor;\n}\nexport function getHourlyCost (monthlyCost: number) {\n return (monthlyCost / 30) / 24;",
"score": 15.914417550425494
},
{
"filename": "src/utils/utilization.ts",
"retrieved_chunk": " total += Object.keys(filtered[s]).length;\n });\n return total;\n}\nexport function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {\n const result: { [ key in ActionType ]: number } = {\n [ActionType.OPTIMIZE]: 0,\n [ActionType.DELETE]: 0,\n [ActionType.SCALE_DOWN]: 0\n }; ",
"score": 15.078875979819351
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " numTasks,\n monthlyCost\n }; \n }\n private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) {\n // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html\n const fargateScaleOptions: FargateScaleOption = {\n 256: {\n discrete: [0.5, 1, 2]\n },",
"score": 14.698786420297797
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " } while (nextToken);\n return metrics;\n }\n private createDiscreteValuesForRange (range: FargateScaleRange): number[] {\n const {\n min,\n max,\n increment\n } = range;\n const discreteVales: number[] = [];",
"score": 14.526880099374145
}
] | 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": 52.57230761011674
},
{
"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": 43.086584850854635
},
{
"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": 40.69923622040196
},
{
"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": 35.92474822610223
},
{
"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": 35.29481848334434
}
] | 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/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": 25.885439428382558
},
{
"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": 25.35383380618669
},
{
"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": 24.295161808852995
},
{
"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": 23.906969989437897
},
{
"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": 23.566230268757863
}
] | 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/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": 53.14237230728235
},
{
"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": 45.6833997004287
},
{
"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": 33.426402434716024
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " function onResourceCheckChange (resArn: string, serviceName: string) {\n return (e: React.ChangeEvent<HTMLInputElement>) => {\n if (e.target.checked) {\n setCheckedResources([...checkedResources, resArn]);\n } else {\n setCheckedServices(checkedServices.filter(s => s !== serviceName));\n setCheckedResources(checkedResources.filter(id => id !== resArn));\n }\n };\n }",
"score": 30.92909281773045
},
{
"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": 26.66575996340945
}
] | 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/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": 34.91051010375081
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx",
"retrieved_chunk": " >\n {<>Review <ArrowForwardIcon /></>}\n </Button>\n </Flex>\n </Stack>\n );\n }\n return (\n <Stack pt=\"20px\" pb=\"20px\" w=\"100%\">\n <Stack width=\"20%\" pb={3} px={4} align='baseline'>",
"score": 21.59142301640115
},
{
"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": 21.21762946779453
},
{
"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": 18.09358582471367
},
{
"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": 17.556832360245178
}
] | 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/widgets/utilization-recommendations-ui/side-panel-usage.tsx",
"retrieved_chunk": " const { metrics } = props; \n console.log('metrics: ', metrics);\n if(isEmpty(metrics)){ \n return null;\n }\n const tabListDom = Object.keys(metrics).map( metric => ( \n <Tab>{metrics[metric]?.yAxisLabel}</Tab>\n ));\n const tabPanelsDom = Object.keys(metrics).map( (metric) => { \n const metricData: Metric = metrics[metric];",
"score": 20.728953603854478
},
{
"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": 19.822108370958954
},
{
"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": 19.671522630595103
},
{
"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": 19.657050633280164
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " const metrics = await cloudWatchClient.getMetricStatistics({ \n Namespace: nameSpace, \n MetricName: metricName, \n StartTime: startTime,\n EndTime: endTime,\n Period: period,\n Statistics: ['Average'],\n Dimensions: dimensions\n });\n const values: MetricData[] = metrics.Datapoints.map(dp => ({ ",
"score": 18.320727319396504
}
] | typescript | .addScenario(dbInstanceArn, 'hasDatabaseConnections', { |
/* 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/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": 19.687470287436962
},
{
"filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx",
"retrieved_chunk": " <ModalHeader>Confirm {actionType}</ModalHeader>\n <ModalCloseButton />\n <ModalBody>\n <Text fontSize='xl'>You are about to {actionType} {resourceArns.length} resources.</Text>\n <Text fontSize='xl'>To confirm, type '{actionType} resources' in the input below.</Text>\n <Text fontSize='xs'> \n Please note, as we are cleaning up your resources they \n may still appear as recommendations until the process completes in the background.\n </Text>\n <Text pt='1'>Confirm {actionType}</Text>",
"score": 16.88465293622395
},
{
"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": 14.346983542179954
},
{
"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": 14.012173754076374
},
{
"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": 12.86259046373744
}
] | typescript | { splitServiceName(sidePanelService)} |
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/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": 37.44679023297652
},
{
"filename": "src/service-utilizations/aws-account-utilization.tsx",
"retrieved_chunk": " * https://docs.aws.amazon.com/cost-management/latest/userguide/billing-example-policies.html#example-policy-ce-api\n */\nexport type awsAccountUtilizationScenarios = 'hasPermissionsForPriceList' | 'hasPermissionsForCostExplorer';\nexport class awsAccountUtilization extends AwsServiceUtilization<awsAccountUtilizationScenarios> {\n constructor () {\n super();\n }\n doAction (\n _awsCredentialsProvider: AwsCredentialsProvider, _actionName: string, _resourceArn: string, _region: string\n ): void | Promise<void> {",
"score": 30.901585430258795
},
{
"filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx",
"retrieved_chunk": " sessionHistory={sessionHistory}\n onRefresh={onRefresh}\n onContinue={(selectedActionType: ActionType) => {\n setActionType(selectedActionType);\n setWizardStep(WizardSteps.TABLE);\n }}\n allRegions={allRegions}\n onRegionChange={onRegionChange}\n region={region}\n />",
"score": 28.816641015009893
},
{
"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": 28.358723174484254
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " * since calls are now region specific\n */\n abstract getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any\n ): void | Promise<void>;\n abstract doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string\n ): void | Promise<void>;\n protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) {\n if (!(resourceArn in this.utilization)) {",
"score": 23.474912273328687
}
] | typescript | ActionType) => void; |
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/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Drawer>\n );\n }\n return (\n <Stack pt=\"3\" pb=\"3\" w=\"100%\">\n <Flex pl='4' pr='4'>\n <Box>\n <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading>\n </Box>\n <Button ",
"score": 48.17563559823658
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " >\n Continue\n </Button>\n </Box>\n </Flex>\n <Stack pb='2' w=\"100%\">\n {table()}\n </Stack>\n {sidePanel()}\n </Stack>",
"score": 42.804874971676625
},
{
"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": 38.297447437273654
},
{
"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": 35.92365406177504
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-usage.tsx",
"retrieved_chunk": " </TabPanel>\n );\n });\n return (\n <Stack w='100%'>\n <Box>\n <Tabs size='md' variant='enclosed'>\n <TabList>\n {tabListDom}\n </TabList>",
"score": 22.052958283839992
}
] | 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": " 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": 32.22317637989139
},
{
"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": 26.69340233251036
},
{
"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": 25.885439428382558
},
{
"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": 25.35383380618669
},
{
"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": 24.295161808852995
}
] | 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-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": 35.74756364856622
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx",
"retrieved_chunk": " <Spacer />\n <Box w='150px'>\n <Text fontSize='sm' color='gray.500'>{numResources} available</Text>\n {numResourcesInProgress ? \n <Text fontSize='sm' color='gray.500'>{numResourcesInProgress} in progress</Text> : null }\n </Box>\n <Button \n colorScheme=\"purple\"\n variant=\"outline\" \n marginRight={'8px'} ",
"score": 28.9998682781748
},
{
"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": 28.840791672935197
},
{
"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": 27.362250822813827
},
{
"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": 23.892897646493502
}
] | 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/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": 58.910179286771566
},
{
"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": 43.279780794378894
},
{
"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": 43.14249771199833
},
{
"filename": "src/utils/utilization.ts",
"retrieved_chunk": " Object.keys(utilization).forEach((service) => {\n filtered[service] = filterServiceForActionType(utilization, service, actionType, session);\n });\n return filtered;\n}\nexport function filterServiceForActionType (\n utilization: { [service: string]: Utilization<string> }, service: string, \n actionType: ActionType, session: HistoryEvent[]\n) {\n const resourcesInProgress = session.map((historyevent) => {",
"score": 36.22937247537408
},
{
"filename": "src/utils/utilization.ts",
"retrieved_chunk": " total += Object.keys(filtered[s]).length;\n });\n return total;\n}\nexport function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {\n const result: { [ key in ActionType ]: number } = {\n [ActionType.OPTIMIZE]: 0,\n [ActionType.DELETE]: 0,\n [ActionType.SCALE_DOWN]: 0\n }; ",
"score": 35.921138260128146
}
] | 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-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": 34.65120310280961
},
{
"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": 31.44718157941975
},
{
"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": 28.77387420407501
},
{
"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": 22.372909097711265
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " * since calls are now region specific\n */\n abstract getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any\n ): void | Promise<void>;\n abstract doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string\n ): void | Promise<void>;\n protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) {\n if (!(resourceArn in this.utilization)) {",
"score": 21.556361614179114
}
] | 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": 28.77510093461286
},
{
"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": 22.755124722451473
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx",
"retrieved_chunk": " size='sm'\n border=\"0px\"\n onClick={() => onRefresh()}\n >\n <Icon as={TbRefresh} />\n </Button>\n <Button\n colorScheme='purple'\n size='sm'\n onClick={() => onContinue(actionType)}",
"score": 21.158032103557183
},
{
"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": 20.371634648172083
},
{
"filename": "src/widgets/aws-utilization-recommendations.tsx",
"retrieved_chunk": " function onResourcesAction (resourceArns: string[], actionType: string) {\n overridesCallback({\n resourceActions: { resourceArns, actionType }\n });\n }\n function onRefresh () {\n overridesCallback({\n refresh: true\n });\n }",
"score": 19.000267940307065
}
] | typescript | ={(checkedResources) => { |
/* 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": " 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": 28.19719749646195
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " if(isEmpty(data)){ \n return null;\n }\n if(isEmpty(data.associatedResourceId) && isEmpty(data.tags)){\n return null;\n }\n const relatedResourcesSection = data.associatedResourceId ? \n <Box marginTop='20px'>\n <Button\n variant='ghost'",
"score": 27.378643703776966
},
{
"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": 26.74921716064099
},
{
"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": 26.2889727427205
},
{
"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": 22.80596240295276
}
] | typescript | SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} |
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": 37.14468272166337
},
{
"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": 31.830161427763116
},
{
"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": 27.520184064389078
},
{
"filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx",
"retrieved_chunk": " </Stack>\n </Flex>\n <Modal isOpen={isOpen} onClose={onClose}>\n <ModalOverlay />\n <ModalContent>\n <ModalHeader>Confirm {actionType}</ModalHeader>\n <ModalCloseButton />\n <ModalBody>\n <Text>You are about to {actionType} the resource with id {resourceArn}.</Text>\n <Button",
"score": 27.283876018815587
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " function onResourceCheckChange (resArn: string, serviceName: string) {\n return (e: React.ChangeEvent<HTMLInputElement>) => {\n if (e.target.checked) {\n setCheckedResources([...checkedResources, resArn]);\n } else {\n setCheckedServices(checkedServices.filter(s => s !== serviceName));\n setCheckedResources(checkedResources.filter(id => id !== resArn));\n }\n };\n }",
"score": 27.025194324393496
}
] | 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/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": 36.927322769588145
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " size='lg'\n colorScheme='black'\n >\n Tags\n </Button>\n <Spacer/>\n <Table size='sm' marginTop='12px'>\n <Thead>\n <Tr>\n <Th ",
"score": 27.985511201094862
},
{
"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": 26.668280515391793
},
{
"filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx",
"retrieved_chunk": " <HStack>\n <Input value={confirmationText} onChange={event => setConfirmationText(event.target.value)} />\n </HStack>\n <Flex pt='1'>\n <Spacer/>\n <Box>\n <Button\n colorScheme='red'\n size='sm'\n onClick={() => {",
"score": 18.128266493735993
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " <Td color='gray.500'> {tag.Key}</Td>\n <Td color='gray.500'> {tag.Value}</Td>\n </Tr>\n ));\n const tagsSection = data.tags ? \n <Box marginTop='20px'>\n <Button\n variant='ghost'\n aria-label={'downCaret'}\n leftIcon={<ChevronDownIcon/>}",
"score": 17.664069491862243
}
] | typescript | SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} |
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/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": 29.293015903518615
},
{
"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": 28.440044299098272
},
{
"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": 27.690830502355237
},
{
"filename": "src/types/types.ts",
"retrieved_chunk": " tags?: Tag[];\n}\nexport type Metrics = { \n [ metricName: string ]: Metric\n}\nexport type Metric = { \n yAxisLabel: string, \n yLimits?: number, \n values: MetricData[]\n}",
"score": 26.22907455456021
},
{
"filename": "src/types/types.ts",
"retrieved_chunk": "export type HistoryEvent = {\n service: AwsResourceType;\n actionType: ActionType;\n actionName: string;\n resourceArn: string;\n region: string;\n timestamp: string;\n}",
"score": 25.484193901360122
}
] | 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/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": 28.18979141776459
},
{
"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": 26.502716902052217
},
{
"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": 23.333688635505037
},
{
"filename": "src/utils/utilization.ts",
"retrieved_chunk": " session.forEach((historyEvent) => { \n result[historyEvent.actionType] ++;\n });\n return result;\n}\nexport function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { \n let total = 0; \n Object.keys(utilization).forEach((service) => {\n if (!utilization[service] || isEmpty(utilization[service])) return;\n total += Object.keys(utilization[service]).length;",
"score": 20.446507212645376
},
{
"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": 19.06076368113424
}
] | 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/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": 34.553815854972704
},
{
"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": 34.553815854972704
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " await this.getSidePanelMetrics(\n credentials, \n region, \n service.serviceArn, \n 'AWS/ECS', \n metricName, \n [{\n Name: 'ServiceName',\n Value: service.serviceName\n },",
"score": 19.746821928481715
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesOutToDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.127663221291733
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " Metric: {\n Namespace: 'AWS/NATGateway',\n MetricName: 'BytesInFromDestination',\n Dimensions: [{\n Name: 'NatGatewayId',\n Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'",
"score": 19.127663221291733
}
] | 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": 7.717496920677453
},
{
"filename": "src/widgets/aws-utilization-recommendations.tsx",
"retrieved_chunk": " function onResourcesAction (resourceArns: string[], actionType: string) {\n overridesCallback({\n resourceActions: { resourceArns, actionType }\n });\n }\n function onRefresh () {\n overridesCallback({\n refresh: true\n });\n }",
"score": 6.643680001720007
},
{
"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": 6.496858621793804
},
{
"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": 6.2199712102182945
},
{
"filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx",
"retrieved_chunk": " if (confirmationText !== actionType + ' resources') {\n setError(`Type '${actionType} resources' in the box to continue`);\n } else {\n setError(undefined);\n onResourcesAction(resourceArns, actionType);\n }\n }}\n >\n {actionLabel}\n </Button>",
"score": 6.068896156552937
}
] | 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-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": 13.253874350606598
},
{
"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": 12.71657929640935
},
{
"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": 11.386082650841075
},
{
"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": 10.981452125727708
},
{
"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": 9.471340576215372
}
] | 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-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": 25.516970669310965
},
{
"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": 17.541161584372276
},
{
"filename": "src/service-utilizations/aws-nat-gateway-utilization.ts",
"retrieved_chunk": " if (activeConnectionCount === 0) {\n this.addScenario(natGatewayArn, 'activeConnectionCount', {\n value: activeConnectionCount.toString(),\n delete: {\n action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });",
"score": 16.868051116958377
},
{
"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": 15.4839416663435
},
{
"filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx",
"retrieved_chunk": " });\n autoScalingGroups.forEach(async (group) => { \n const cpuUtilPercent = await this.getGroupCPUUTilization(cloudWatchClient, group.name); \n if(cpuUtilPercent < 50){ \n this.addScenario(group.name, 'cpuUtilization', {\n value: cpuUtilPercent, \n alertType: AlertType.Warning, \n reason: 'Max CPU Utilization has been under 50% for the last week', \n recommendation: 'scale down instance', \n actions: ['scaleDownInstance']",
"score": 15.413379435614868
}
] | 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/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " });\n if (overrides?.services) {\n this.services = await this.describeTheseServices(overrides?.services);\n } else {\n this.services = await this.describeAllServices();\n }\n if (this.services.length === 0) return;\n for (const service of this.services) {\n const now = dayjs();\n const startTime = now.subtract(2, 'weeks');",
"score": 61.661999729986704
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " const services: Service[] = [];\n for (const [clusterArn, clusterServices] of Object.entries(clusters)) {\n const serviceChunks = chunk(clusterServices.serviceArns, 10);\n for (const serviceChunk of serviceChunks) {\n const response = await this.ecsClient.describeServices({\n cluster: clusterArn,\n services: serviceChunk\n });\n services.push(...(response?.services || []));\n }",
"score": 50.08638289301174
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " } = response || {};\n services.push(...serviceArns);\n nextToken = nextServicesToken;\n } while (nextToken);\n return {\n [clusterArn]: {\n serviceArns: services\n }\n };\n }",
"score": 39.39029542952863
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " super();\n this.serviceArns = [];\n this.services = [];\n this.serviceCosts = {};\n this.DEBUG_MODE = enableDebugMode || false;\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {\n if (actionName === 'deleteService') {",
"score": 34.58874418208803
},
{
"filename": "src/ops-types.ts",
"retrieved_chunk": " * ```yaml\n * UtilizationProvider:\n type: AwsUtilizationProvider\n * ```\n */\nexport interface AwsUtilizationProvider extends Provider {\n services?: AwsResourceType[];\n regions?: string[];\n}\nexport type AwsResourceType = 'Account' |",
"score": 33.41802967246186
}
] | 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": 43.38812175643359
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " let i = min;\n do {\n i = i + increment;\n discreteVales.push(i);\n } while (i <= max);\n return discreteVales;\n }\n private async getEc2ContainerInfo (service: Service) {\n const tasks = await this.getAllTasks(service);\n const taskCpu = Number(tasks.at(0)?.cpu);",
"score": 42.46485943053094
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " if (!instanceFamily) {\n instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance);\n }\n const allInstanceTypes = Object.values(_InstanceType);\n const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`));\n const cachedInstanceTypes = await cache.getOrElse(\n instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily))\n );\n const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]');\n const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => {",
"score": 38.417957526180615
},
{
"filename": "src/utils/utils.ts",
"retrieved_chunk": " const launchTimes: number[] = [];\n const results = new Array(array.length);\n // calculate num requests in last second\n function calcRequestsInLastSecond () {\n const now = Date.now();\n // look backwards in launchTimes to see how many were launched within the last second\n let cnt = 0;\n for (let i = launchTimes.length - 1; i >= 0; i--) {\n if (now - launchTimes[i] < 1000) {\n ++cnt;",
"score": 35.63835509677177
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-usage.tsx",
"retrieved_chunk": " tooltip: {\n callbacks: {\n title: function (this: TooltipModel<'line'>, items: TooltipItem<'line'>[]) {\n return items.map(i => new Date(get(i.raw, 'x')).toLocaleString());\n },\n label: function (this: TooltipModel<'line'>, item: TooltipItem<'line'>) {\n const datasetLabel = item.dataset.label || '';\n const dataPoint = item.formattedValue;\n return datasetLabel + ': ' + dataPoint;\n }",
"score": 34.26045851654879
}
] | 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/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": 24.808894942526948
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " numTasks,\n monthlyCost\n }; \n }\n private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) {\n // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html\n const fargateScaleOptions: FargateScaleOption = {\n 256: {\n discrete: [0.5, 1, 2]\n },",
"score": 23.60172391360527
},
{
"filename": "src/utils/ec2-utils.ts",
"retrieved_chunk": "import { Pricing } from '@aws-sdk/client-pricing';\nexport async function getInstanceCost (pricingClient: Pricing, instanceType: string) {\n const res = await pricingClient.getProducts({\n Filters: [\n {\n Type: 'TERM_MATCH',\n Field: 'instanceType',\n Value: instanceType\n },\n {",
"score": 21.36552877905149
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value;\n const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType);\n const monthlyCost = monthlyInstanceCost * numEc2Instances;\n this.serviceCosts[service.serviceName] = monthlyCost;\n return {\n allocatedCpu,\n allocatedMemory,\n containerInstance,\n instanceType,\n monthlyCost,",
"score": 20.134490139002292
},
{
"filename": "src/types/constants.ts",
"retrieved_chunk": " },\n Ebs (region: string, accountId: string, volumeId: string) {\n return `arn:aws:ec2:${region}:${accountId}:volume/${volumeId}`;\n }\n};\n// Because typescript enums transpile strangely and are even discouraged by typescript themselves:\n// Source: https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums\nexport const AwsResourceTypes: {\n [key: AwsResourceType | string]: AwsResourceType\n} = {",
"score": 17.361915465756194
}
] | 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-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": 15.137017363859743
},
{
"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": 14.496829053680358
},
{
"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": 13.909489120476383
},
{
"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": 12.948255744074261
},
{
"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": 12.24039041145783
}
] | 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/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": 40.34324875802908
},
{
"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": 34.90657116519886
},
{
"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": 32.20775981423829
},
{
"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": 30.883377722866758
},
{
"filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts",
"retrieved_chunk": " ]\n });\n const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0);\n return monthlyIncomingBytes;\n }\n private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) {\n const cwLogsClient = new CloudWatchLogs({\n credentials,\n region\n });",
"score": 30.20749008371115
}
] | 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-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": 28.94212862811464
},
{
"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": 25.23791338473747
},
{
"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": 24.770773530949395
},
{
"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": 22.863460516224595
},
{
"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": 21.816599406805853
}
] | 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-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": 24.244118569898006
},
{
"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": 23.285528188175686
},
{
"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": 22.95824668485252
},
{
"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": 22.170258908369995
},
{
"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": 21.441289783053584
}
] | 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/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": 21.16488005901111
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " this.utilization[resourceArn] = {\n scenarios: {},\n data: {}, \n metrics: {}\n } as Resource<ScenarioTypes>;\n }\n this.utilization[resourceArn].scenarios[scenarioType] = scenario;\n }\n protected async fillData (\n resourceArn: string, ",
"score": 20.679840439043105
},
{
"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": 19.044175175282064
},
{
"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": 18.301754661535284
},
{
"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": 18.12538540225549
}
] | 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-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": 29.789631271120296
},
{
"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": 27.81360648275301
},
{
"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": 26.193545608991545
},
{
"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": 25.21009276878671
},
{
"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": 24.21708307877087
}
] | typescript | : getHourlyCost(this.cost)
} |
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": 22.35440113848673
},
{
"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": 22.158169361037647
},
{
"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": 19.584468690387787
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": "}\ntype RdsMetrics = {\n totalIops: number;\n totalThroughput: number;\n freeStorageSpace: number;\n totalBackupStorageBilled: number;\n cpuUtilization: number;\n databaseConnections: number;\n};\nexport type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' |",
"score": 18.71797189216763
},
{
"filename": "src/ops-types.ts",
"retrieved_chunk": " * ```yaml\n * UtilizationProvider:\n type: AwsUtilizationProvider\n * ```\n */\nexport interface AwsUtilizationProvider extends Provider {\n services?: AwsResourceType[];\n regions?: string[];\n}\nexport type AwsResourceType = 'Account' |",
"score": 18.660793604389358
}
] | typescript | class AwsEcsUtilization extends AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> { |
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-service-utilization.ts",
"retrieved_chunk": " if (resourceArn in this.utilization) {\n const cfnClient = new CloudFormation({\n credentials,\n region\n });\n await cfnClient.describeStackResources({\n PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId\n }).then((res) => {\n const stack = res.StackResources[0].StackId;\n this.addData(resourceArn, 'stack', stack);",
"score": 14.640555262365316
},
{
"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": 12.509112883597268
},
{
"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": 11.014414238574915
},
{
"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": 10.958064811012408
},
{
"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": 10.9242559502232
}
] | typescript | this.addScenario(logGroupArn, 'hasRetentionPolicy', { |
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/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": 41.45849860365352
},
{
"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": 30.10674493241604
},
{
"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": 28.172295975673286
},
{
"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": 25.432391948047343
},
{
"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": 24.613550484535907
}
] | 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/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " if(isEmpty(data)){ \n return null;\n }\n if(isEmpty(data.associatedResourceId) && isEmpty(data.tags)){\n return null;\n }\n const relatedResourcesSection = data.associatedResourceId ? \n <Box marginTop='20px'>\n <Button\n variant='ghost'",
"score": 22.036187921412342
},
{
"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": 20.643520083530774
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " }\n </Td>\n <Td\n key={resArn + 'cost/hr'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.hourlyCost ?\n usd.format(serviceUtil[resArn].data.hourlyCost) :",
"score": 19.26877420088841
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " )}\n <Td\n key={resArn + 'cost/mo'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.monthlyCost ?\n usd.format(serviceUtil[resArn].data.monthlyCost) :\n 'Coming soon!'",
"score": 18.99659465456042
},
{
"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": 18.31014388512981
}
] | 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": 41.766241460423906
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'writeThroughput',\n MetricStat: {",
"score": 37.757911856507015
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'writeIops',\n MetricStat: {",
"score": 37.757911856507015
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month\n Stat: 'Average'\n }\n },\n {\n Id: 'totalBackupStorageBilled',\n MetricStat: {",
"score": 37.757911856507015
},
{
"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": 37.51017372218848
}
] | 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/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": 37.16366922401982
},
{
"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": 35.87717235519801
},
{
"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": 34.68025964197912
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " Tr\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { Data } from '../../types/types';\nimport isEmpty from 'lodash.isempty';\nimport { ChevronDownIcon } from '@chakra-ui/icons';\nexport default function SidePanelRelatedResources (props: { \n data: Data\n}) {\n const { data } = props; ",
"score": 30.861018418967525
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " }\n </Td>\n <Td\n key={resArn + 'cost/hr'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.hourlyCost ?\n usd.format(serviceUtil[resArn].data.hourlyCost) :",
"score": 25.629325359289233
}
] | 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/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": 22.46916896004275
},
{
"filename": "src/service-utilizations/aws-service-utilization.ts",
"retrieved_chunk": " this.utilization[resourceArn] = {\n scenarios: {},\n data: {}, \n metrics: {}\n } as Resource<ScenarioTypes>;\n }\n this.utilization[resourceArn].scenarios[scenarioType] = scenario;\n }\n protected async fillData (\n resourceArn: string, ",
"score": 22.04437579493934
},
{
"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": 19.636732590811633
},
{
"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": 19.166292923137167
},
{
"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": 19.044175175282064
}
] | 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/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": 34.68025964197912
},
{
"filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " Tr\n} from '@chakra-ui/react';\nimport React from 'react';\nimport { Data } from '../../types/types';\nimport isEmpty from 'lodash.isempty';\nimport { ChevronDownIcon } from '@chakra-ui/icons';\nexport default function SidePanelRelatedResources (props: { \n data: Data\n}) {\n const { data } = props; ",
"score": 30.861018418967525
},
{
"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": 28.885163967873886
},
{
"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": 26.71281748245185
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " }\n </Td>\n <Td\n key={resArn + 'cost/hr'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.hourlyCost ?\n usd.format(serviceUtil[resArn].data.hourlyCost) :",
"score": 25.629325359289233
}
] | 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/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": 50.892703152707014
},
{
"filename": "src/service-utilizations/aws-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 38.31491235425656
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} \n </Box>\n ));\n return ( \n <Drawer \n isOpen={showSideModal} \n onClose={() => {\n setShowSideModal(false);\n }}\n placement='right'",
"score": 35.776446036163385
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Td>\n {tableHeaders.map(th => \n <Td\n key={resArn + 'scenario' + th}\n maxW={RESOURCE_VALUE_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } ",
"score": 35.008592070421926
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " <Tr>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox\n isChecked={checkedResources.includes(resArn)}\n onChange={onResourceCheckChange(resArn, serviceName)} /> }\n </Td>\n <Td\n key={resArn + 'scenario' + th}\n >\n { serviceUtil[resArn].scenarios[th][actionType]?.reason }",
"score": 30.211596997586845
}
] | 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/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx",
"retrieved_chunk": " if(isEmpty(data)){ \n return null;\n }\n if(isEmpty(data.associatedResourceId) && isEmpty(data.tags)){\n return null;\n }\n const relatedResourcesSection = data.associatedResourceId ? \n <Box marginTop='20px'>\n <Button\n variant='ghost'",
"score": 27.54229351841147
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " }\n </Td>\n <Td\n key={resArn + 'cost/hr'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.hourlyCost ?\n usd.format(serviceUtil[resArn].data.hourlyCost) :",
"score": 26.75179079425135
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " )}\n <Td\n key={resArn + 'cost/mo'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n { serviceUtil[resArn]?.data?.monthlyCost ?\n usd.format(serviceUtil[resArn].data.monthlyCost) :\n 'Coming soon!'",
"score": 26.370123648826198
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Tooltip>\n </Td>\n <Td\n key={resArn + 'cost/mo'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n {usd.format(serviceUtil[resArn].data.monthlyCost)}\n </Td>",
"score": 22.743719553697957
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " <Td\n key={resArn + 'cost/hr'}\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n {usd.format(serviceUtil[resArn].data.hourlyCost)}\n </Td>\n <Td\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}",
"score": 22.32644058648187
}
] | 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-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 36.481056181047435
},
{
"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": 36.13238122710412
},
{
"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": 35.00738226044567
},
{
"filename": "src/service-utilizations/aws-ec2-instance-utilization.ts",
"retrieved_chunk": " this.instances = [];\n this.DEBUG_MODE = enableDebugMode || false;\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {\n const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1);\n if (actionName === 'terminateInstance') {\n await this.terminateInstance(awsCredentialsProvider, resourceId, region);\n }",
"score": 34.86172727147661
},
{
"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": 34.51177592372694
}
] | 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/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": 50.892703152707014
},
{
"filename": "src/service-utilizations/aws-s3-utilization.tsx",
"retrieved_chunk": " };\n }\n return this.bucketCostData[bucketName];\n }\n findActionFromOverrides (_overrides: AwsServiceOverrides){ \n if(_overrides.scenarioType === 'hasIntelligentTiering'){ \n return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;\n }\n else{ \n return '';",
"score": 38.31491235425656
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} \n </Box>\n ));\n return ( \n <Drawer \n isOpen={showSideModal} \n onClose={() => {\n setShowSideModal(false);\n }}\n placement='right'",
"score": 35.776446036163385
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " </Td>\n {tableHeaders.map(th => \n <Td\n key={resArn + 'scenario' + th}\n maxW={RESOURCE_VALUE_MAX_WIDTH}\n overflow='hidden'\n textOverflow='ellipsis'\n >\n <Tooltip \n label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } ",
"score": 35.008592070421926
},
{
"filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx",
"retrieved_chunk": " <Tr>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox\n isChecked={checkedResources.includes(resArn)}\n onChange={onResourceCheckChange(resArn, serviceName)} /> }\n </Td>\n <Td\n key={resArn + 'scenario' + th}\n >\n { serviceUtil[resArn].scenarios[th][actionType]?.reason }",
"score": 30.211596997586845
}
] | typescript | .scaleDown?.monthlySavings || 0,
scenario.optimize?.monthlySavings || 0
); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.