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/widgets/aws-utilization.tsx", "retrieved_chunk": " }\n static fromJson (object: AwsUtilizationProps): AwsUtilization {\n return new AwsUtilization(object);\n }\n toJson (): AwsUtilizationProps {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n region: this.region, \n sessionHistory: this.sessionHistory", "score": 0.8470925688743591 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8422011137008667 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.8373163342475891 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " region: string\n}\nexport class AwsUtilization extends BaseWidget {\n utilization: { [ serviceName: string ] : Utilization<string> };\n sessionHistory: HistoryEvent[];\n region: string;\n constructor (props: AwsUtilizationProps) {\n super(props);\n this.region = props.region || 'us-east-1';\n this.utilization = props.utilization || {};", "score": 0.835340142250061 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8337624073028564 } ]
typescript
this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); }
await this.fillData( logGroupArn, credentials, region, {
resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8916019797325134 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });\n }\n await this.fillData(\n natGatewayArn,\n credentials,", "score": 0.881247878074646 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " optimize: { \n action: '', \n isActionable: false,\n reason: 'This bucket does not have a lifecycle policy',\n monthlySavings: 0\n }\n });\n }\n });\n }", "score": 0.8555570840835571 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " Value: dbInstance.DBInstanceIdentifier\n }]\n },\n Period: 30 * 24 * 12 * 300, // 1 month,\n Stat: 'Maximum',\n Unit: 'Percent'\n }\n },\n {\n Id: 'databaseConnections',", "score": 0.8382670283317566 }, { "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": 0.8353735208511353 } ]
typescript
await this.fillData( logGroupArn, credentials, region, {
import React from 'react'; import { Box, Heading, Text, SimpleGrid } from '@chakra-ui/react'; import { ActionType, HistoryEvent, Utilization } from '../types/types.js'; import { filterUtilizationForActionType, getNumberOfResourcesFromFilteredActions, getTotalMonthlySavings, getTotalNumberOfResources } from '../utils/utilization.js'; export default function RecommendationOverview ( props: { utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] } ) { const { utilizations, sessionHistory } = props; const { totalUnusedResources, totalMonthlySavings, totalResources } = getTotalRecommendationValues(utilizations, sessionHistory); const labelStyles = { fontFamily: 'Inter', fontSize: '42px', fontWeight: '400', lineHeight: '150%', color: '#000000' }; const textStyles = { fontFamily: 'Inter', fontSize: '14px', fontWeight: '500', lineHeight: '150%', color: 'rgba(0, 0, 0, 0.48)' }; return ( <SimpleGrid columns={3} spacing={2}> <Box p={5}> <Heading style={labelStyles}>{totalResources}</Heading> <Text style={textStyles}>{'resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{totalUnusedResources}</Heading> <Text style={textStyles}>{'unused resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{ totalMonthlySavings }</Heading> <Text style={textStyles}>{'potential monthly savings'}</Text> </Box> </SimpleGrid> ); } function getTotalRecommendationValues ( utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] ) {
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges); const totalResources = getTotalNumberOfResources(utilizations); const totalMonthlySavings = getTotalMonthlySavings(utilizations); return { totalUnusedResources, totalMonthlySavings, totalResources }; }
src/components/recommendation-overview.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "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": 0.8199363350868225 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": "import isEmpty from 'lodash.isempty';\nimport { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js';\nexport function filterUtilizationForActionType (\n utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[]\n):\n{ [service: string]: Utilization<string> } {\n const filtered: { [service: string]: Utilization<string> } = {};\n if (!utilization) {\n return filtered;\n }", "score": 0.8169841170310974 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " serviceUtil={serviceUtil}\n children={resourcesTable(service, serviceUtil)}\n key={service + 'table'}\n onServiceCheckChange={onServiceCheckChange(service)}\n isChecked={checkedServices.includes(service)}\n />\n );\n }\n function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) {\n const tableHeadersSet = new Set<string>();", "score": 0.8081422448158264 }, { "filename": "src/types/types.ts", "retrieved_chunk": " action: string,\n isActionable: boolean,\n reason: string\n monthlySavings?: number\n}\nexport type Scenario = {\n value: string,\n delete?: Action,\n scaleDown?: Action,\n optimize?: Action", "score": 0.8066089153289795 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " const numOptimizeChanges = getNumberOfResourcesFromFilteredActions(optimizeChanges);\n const inProgressActions = getNumberOfResourcesInProgress(sessionHistory);\n function actionSummaryStack (\n actionType: ActionType, icon: JSX.Element, actionLabel: string, \n numResources: number, description: string, numResourcesInProgress: number\n ) {\n return (\n <Stack w=\"100%\" p='2' pl='5' pr='5'>\n <Flex>\n <Box w='20px'>", "score": 0.8041418194770813 } ]
typescript
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this
.fillData( instanceArn, credentials, region, {
resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8821909427642822 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8484064340591431 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const ecsClient = new ECS({\n credentials,\n region\n });\n await ecsClient.deleteService({\n service: serviceArn,\n cluster: clusterName\n });\n }\n async scaleDownFargateService (", "score": 0.845320463180542 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings\n }\n });\n }\n }\n }\n async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) {\n const response = await this.s3Client.getBucketLocation({\n Bucket: bucketName\n });", "score": 0.8412972688674927 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8395437002182007 } ]
typescript
.fillData( instanceArn, credentials, region, {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (
storedBytes / ONE_GB_IN_BYTES) * 0.03;
const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8652005195617676 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []];\n } while (describeNatGatewaysRes?.NextToken);\n return allNatGateways;\n }\n private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) {\n const cwClient = new CloudWatch({\n credentials,\n region\n });\n const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000));", "score": 0.8576112389564514 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.854012668132782 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.85393226146698 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " nameSpace: string, metricName: string, dimensions: Dimension[]\n ){ \n if(resourceArn in this.utilization){\n const cloudWatchClient = new CloudWatch({ \n credentials: credentials, \n region: region\n }); \n const endTime = new Date(Date.now()); \n const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago\n const period = 43200; ", "score": 0.8512214422225952 } ]
typescript
storedBytes / ONE_GB_IN_BYTES) * 0.03;
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers
.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8391166925430298 }, { "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": 0.82701176404953 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8236967325210571 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 0.8218854665756226 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8199377059936523 } ]
typescript
.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
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": 0.8609497547149658 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.8214986324310303 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " (avgMemoryIsStable && maxMemoryIsStable) ||\n maxMemory < 10\n );\n const requestCountMetricValues = [\n ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || [])\n ];\n const totalRequestCount = stats.sum(requestCountMetricValues);\n const noNetworkUtilization = totalRequestCount === 0;\n if (\n lowCpuUtilization &&", "score": 0.8092802166938782 }, { "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": 0.8079617023468018 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " storageCost = storageUsedInGB * 0.115;\n }\n } else if (dbInstance.StorageType === 'gp3') {\n if (dbInstance.MultiAZ) {\n storageCost = storageUsedInGB * 0.23;\n iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0;\n // verify throughput metrics are in MB/s\n throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0;\n } else {\n storageCost = storageUsedInGB * 0.115;", "score": 0.7962023019790649 } ]
typescript
const cost = await getInstanceCost(pricingClient, instanceType.InstanceType);
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) {
field.report(messages.notIn, 'notIn', field, options) return }
} ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\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": 0.8832728862762451 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.8826781511306763 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8717669248580933 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8673655986785889 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 0.8629944324493408 } ]
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/rds-utilization.tsx", "retrieved_chunk": " totalCost: 0,\n instanceCost: 0,\n totalStorageCost: 0,\n iopsCost: 0,\n throughputCost: 0\n } as RdsCosts;\n } \n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides", "score": 0.887376606464386 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.885048508644104 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " cpuUtilization,\n databaseConnections\n };\n }\n private getAuroraCosts (\n storageUsedInGB: number, \n totalBackupStorageBilled: number,\n totalIops: number \n ): StorageAndIOCosts {\n const storageCost = storageUsedInGB * 0.10;", "score": 0.8805842399597168 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " isActionable: false,\n reason: 'This instance has more than half of its allocated storage still available',\n monthlySavings: 0\n }\n });\n }\n }\n async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){\n if (metrics.cpuUtilization < 50) {\n await this.getRdsInstanceCosts(dbInstance, metrics);", "score": 0.8635568618774414 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " iopsCost = (dbInstance.Iops || 0) * 0.10;\n }\n }\n return {\n totalStorageCost: storageCost,\n iopsCost,\n throughputCost\n };\n }\n private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) {", "score": 0.8617551326751709 } ]
typescript
any, region: string, _overrides?: AwsServiceOverrides) {
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) {
const instanceArn = Arns.Ec2(region, this.accountId, instanceId);
const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " 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": 0.8752607107162476 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " cluster: service.clusterArn,\n containerInstances: tasks.map(task => task.containerInstanceArn)\n });\n containerInstance = containerInstanceResponse?.containerInstances?.at(0);\n }\n const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => {\n acc.add(instance.ec2InstanceId);\n return acc;\n }, new Set<string>());\n const numEc2Instances = uniqueEc2Instances.size;", "score": 0.8549023270606995 }, { "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": 0.838422417640686 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " return instanceFamily;\n }\n private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> {\n const instanceTypes = [];\n let nextToken;\n do {\n const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({\n InstanceTypes: instanceTypeNames,\n NextToken: nextToken\n });", "score": 0.8270098567008972 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const filteredTaskGroups = containerInstanceTaskGroups\n .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn));\n if (isEmpty(filteredTaskGroups)) {\n return undefined;\n } else {\n containerInstanceResponse = await this.ecsClient.describeContainerInstances({\n cluster: service.clusterArn,\n containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn)\n });\n // largest container instance", "score": 0.825364351272583 } ]
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-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8527439832687378 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8474926948547363 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8396543264389038 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8338669538497925 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8283064365386963 } ]
typescript
addScenario(logGroupArn, 'hasRetentionPolicy', {
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.
addScenario(instanceArn, 'unused', {
value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost, hourlyCost: getHourlyCost(cost) } ); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " isActionable: false,\n reason: 'This instance has more than half of its allocated storage still available',\n monthlySavings: 0\n }\n });\n }\n }\n async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){\n if (metrics.cpuUtilization < 50) {\n await this.getRdsInstanceCosts(dbInstance, metrics);", "score": 0.8704768419265747 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " totalIops: number,\n totalThroughput: number\n ): StorageAndIOCosts {\n let storageCost = 0;\n let iopsCost = 0;\n let throughputCost = 0;\n if (dbInstance.StorageType === 'gp2') {\n if (dbInstance.MultiAZ) {\n storageCost = storageUsedInGB * 0.23;\n } else {", "score": 0.8651885986328125 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.8623712062835693 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.8521685004234314 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8437641263008118 } ]
typescript
addScenario(instanceArn, 'unused', {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost,
hourlyCost: getHourlyCost(totalMonthlyCost) }
); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.9111267924308777 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9079802632331848 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8787165284156799 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8744021058082581 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8676290512084961 } ]
typescript
hourlyCost: getHourlyCost(totalMonthlyCost) }
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await
rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.9128174781799316 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.9079487323760986 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " Namespace: 'AWS/EC2',\n MetricName: metricName,\n Dimensions: [{\n Name: 'InstanceId',\n Value: instanceId\n }]\n },\n Period: period,\n Stat: statistic\n };", "score": 0.8475509881973267 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'\n }\n },\n {\n Id: 'bytesOutToDestination',\n MetricStat: {", "score": 0.8437322378158569 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Maximum'\n }\n },\n {\n Id: 'bytesInFromDestination',\n MetricStat: {", "score": 0.8403217792510986 } ]
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 * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8375705480575562 }, { "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": 0.8243792057037354 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8240293264389038 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8208413124084473 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8207915425300598 } ]
typescript
if (!helpers.isCreditCard(value as string)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) {
if (!helpers.isPostalCode(value as string, 'any')) {
field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8478701114654541 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8451928496360779 }, { "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": 0.8399645686149597 }, { "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": 0.8384436368942261 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8366014957427979 } ]
typescript
if (!helpers.isPostalCode(value as string, 'any')) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (
!helpers.isUUID(value as string)) {
field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.9167618751525879 }, { "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": 0.9057445526123047 }, { "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": 0.8941425681114197 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8864296674728394 }, { "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": 0.8848052024841309 } ]
typescript
!helpers.isUUID(value as string)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find(
(countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8370692729949951 }, { "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": 0.8231576681137085 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 0.8192041516304016 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "import { messages } from '../../defaults.js'\n/**\n * Enforce the value to be a number or a string representation\n * of a number\n */\nexport const numberRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsNumber = options.strict ? value : helpers.asNumber(value)\n if (\n typeof valueAsNumber !== 'number' ||\n Number.isNaN(valueAsNumber) ||", "score": 0.8188464045524597 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8184254169464111 } ]
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/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": 0.8253370523452759 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 0.8229595422744751 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8142038583755493 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8064714074134827 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 0.8050554990768433 } ]
typescript
field.report(messages.passport, 'passport', field, { countryCodes }) }
import cached from 'cached'; import dayjs from 'dayjs'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import HttpError from 'http-errors'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ContainerInstance, DesiredStatus, ECS, LaunchType, ListClustersCommandOutput, ListServicesCommandOutput, ListTasksCommandOutput, Service, Task, TaskDefinition, TaskDefinitionField, DescribeContainerInstancesCommandOutput } from '@aws-sdk/client-ecs'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { ElasticLoadBalancingV2 } from '@aws-sdk/client-elastic-load-balancing-v2'; import { Api, ApiGatewayV2, GetApisCommandOutput, Integration } from '@aws-sdk/client-apigatewayv2'; import { DescribeInstanceTypesCommandOutput, EC2, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, MAX_MEMORY, AVG_MEMORY, ALB_REQUEST_COUNT, APIG_REQUEST_COUNT } from '../types/constants.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getHourlyCost } from '../utils/utils.js'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; const cache = cached<string>('ecs-util-cache', { backend: { type: 'memory' } }); type AwsEcsUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEcsMetrics = ['CPUUtilization', 'MemoryUtilization']; type EcsService = { clusterArn: string; serviceArn: string; } type ClusterServices = { [clusterArn: string]: { serviceArns: string[]; } } type FargateScaleRange = { min: number; max: number; increment: number; }; type FargateScaleOption = { [cpu: number]: { discrete?: number[]; range?: FargateScaleRange; } } type FargateScale = { cpu: number, memory: number } type AwsEcsUtilizationOverrides = AwsServiceOverrides & { services: EcsService[]; } export class AwsEcsUtilization extends
AwsServiceUtilization<AwsEcsUtilizationScenarioTypes> {
serviceArns: string[]; services: Service[]; ecsClient: ECS; ec2Client: EC2; cwClient: CloudWatch; elbV2Client: ElasticLoadBalancingV2; apigClient: ApiGatewayV2; pricingClient: Pricing; serviceCosts: { [ service: string ]: number }; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.serviceArns = []; this.services = []; this.serviceCosts = {}; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteService') { await this.deleteService(awsCredentialsProvider, resourceArn.split('/')[1], resourceArn, region); } } private async listAllClusters (): Promise<string[]> { const allClusterArns: string[] = []; let nextToken; do { const response: ListClustersCommandOutput = await this.ecsClient.listClusters({ nextToken }); const { clusterArns = [], nextToken: nextClusterToken } = response || {}; allClusterArns.push(...clusterArns); nextToken = nextClusterToken; } while (nextToken); return allClusterArns; } private async listServicesForClusters (clusterArn: string): Promise<ClusterServices> { const services: string[] = []; let nextToken; do { const response: ListServicesCommandOutput = await this.ecsClient.listServices({ cluster: clusterArn, nextToken }); const { serviceArns = [], nextToken: nextServicesToken } = response || {}; services.push(...serviceArns); nextToken = nextServicesToken; } while (nextToken); return { [clusterArn]: { serviceArns: services } }; } private async describeAllServices (): Promise<Service[]> { const clusterArns = await this.listAllClusters(); const allServices: EcsService[] = []; for (const clusterArn of clusterArns) { const servicesForCluster = await this.listServicesForClusters(clusterArn); allServices.push(...servicesForCluster[clusterArn].serviceArns.map(s => ({ clusterArn, serviceArn: s }))); } return this.describeTheseServices(allServices); } private async describeTheseServices (ecsServices: EcsService[]): Promise<Service[]> { const clusters = ecsServices.reduce<ClusterServices>((acc, ecsService) => { acc[ecsService.clusterArn] = acc[ecsService.clusterArn] || { serviceArns: [] }; acc[ecsService.clusterArn].serviceArns.push(ecsService.serviceArn); return acc; }, {}); const services: Service[] = []; for (const [clusterArn, clusterServices] of Object.entries(clusters)) { const serviceChunks = chunk(clusterServices.serviceArns, 10); for (const serviceChunk of serviceChunks) { const response = await this.ecsClient.describeServices({ cluster: clusterArn, services: serviceChunk }); services.push(...(response?.services || [])); } } return services; } private async getLoadBalacerArnForService (service: Service): Promise<string> { const response = await this.elbV2Client.describeTargetGroups({ TargetGroupArns: [service.loadBalancers?.at(0)?.targetGroupArn] }); return response?.TargetGroups?.at(0)?.LoadBalancerArns?.at(0); } private async findIntegration (apiId: string, registryArn: string): Promise<Integration | undefined> { let nextToken: string; let registeredIntegration: Integration; do { const response = await this.apigClient.getIntegrations({ ApiId: apiId, NextToken: nextToken }); const { Items = [], NextToken } = response || {}; registeredIntegration = Items.find(i => i.IntegrationUri === registryArn); if (!registeredIntegration) { nextToken = NextToken; } } while (nextToken); return registeredIntegration; } private async findRegisteredApi (service: Service, apis: Api[]): Promise<Api | undefined> { const registryArn = service.serviceRegistries?.at(0)?.registryArn; let registeredApi: Api; for (const api of apis) { const registeredIntegration = await this.findIntegration(api.ApiId, registryArn); if (registeredIntegration) { registeredApi = api; break; } } return registeredApi; } private async getApiIdForService (service: Service): Promise<string> { let nextToken: string; let registeredApi: Api; do { const apiResponse: GetApisCommandOutput = await this.apigClient.getApis({ NextToken: nextToken }); const { Items = [], NextToken } = apiResponse || {}; registeredApi = await this.findRegisteredApi(service, Items); if (!registeredApi) { nextToken = NextToken; } } while (nextToken); return registeredApi.ApiId; } private async getTask (service: Service): Promise<Task> { const taskListResponse = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, maxResults: 1, desiredStatus: DesiredStatus.RUNNING }); const { taskArns = [] } = taskListResponse || {}; const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: [taskArns.at(0)] }); const task = describeTasksResponse?.tasks?.at(0); return task; } private async getAllTasks (service: Service): Promise<Task[]> { const taskIds = []; let nextTaskToken; do { const taskListResponse: ListTasksCommandOutput = await this.ecsClient.listTasks({ cluster: service.clusterArn, serviceName: service.serviceName, desiredStatus: DesiredStatus.RUNNING, nextToken: nextTaskToken }); const { taskArns = [], nextToken } = taskListResponse || {}; taskIds.push(...taskArns); nextTaskToken = nextToken; } while (nextTaskToken); const allTasks = []; const taskIdPartitions = chunk(taskIds, 100); for (const taskIdPartition of taskIdPartitions) { const describeTasksResponse = await this.ecsClient.describeTasks({ cluster: service.clusterArn, tasks: taskIdPartition }); const { tasks = [] } = describeTasksResponse; allTasks.push(...tasks); } return allTasks; } private async getInstanceFamilyForContainerInstance (containerInstance: ContainerInstance): Promise<string> { const ec2InstanceResponse = await this.ec2Client.describeInstances({ InstanceIds: [containerInstance.ec2InstanceId] }); const instanceType = ec2InstanceResponse?.Reservations?.at(0)?.Instances?.at(0)?.InstanceType; const instanceFamily = instanceType?.split('.')?.at(0); return instanceFamily; } private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private getEcsServiceDataQueries (serviceName: string, clusterName: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/ECS', MetricName: metricName, Dimensions: [ { Name: 'ServiceName', Value: serviceName }, { Name: 'ClusterName', Value: clusterName } ] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: AVG_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Average') }, { Id: MAX_MEMORY, MetricStat: metricStat('MemoryUtilization', 'Maximum') } ]; } private getAlbRequestCountQuery (loadBalancerArn: string, period: number): MetricDataQuery { return { Id: ALB_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApplicationELB', MetricName: 'RequestCount', Dimensions: [ { Name: 'ServiceName', Value: loadBalancerArn } ] }, Period: period, Stat: 'Sum' } }; } private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery { return { Id: APIG_REQUEST_COUNT, MetricStat: { Metric: { Namespace: 'AWS/ApiGateway', MetricName: 'Count', Dimensions: [ { Name: 'ApiId', Value: apiId } ] }, Period: period, Stat: 'Sum' } }; } private async getMetrics (args: { service: Service, startTime: Date; endTime: Date; period: number; }): Promise<{[ key: string ]: MetricDataResult}> { const { service, startTime, endTime, period } = args; const { serviceName, clusterArn, loadBalancers, serviceRegistries } = service; const clusterName = clusterArn?.split('/').pop(); const queries: MetricDataQuery[] = this.getEcsServiceDataQueries(serviceName, clusterName, period); if (loadBalancers && loadBalancers.length > 0) { const loadBalancerArn = await this.getLoadBalacerArnForService(service); queries.push(this.getAlbRequestCountQuery(loadBalancerArn, period)); } else if (serviceRegistries && serviceRegistries.length > 0) { const apiId = await this.getApiIdForService(service); queries.push(this.getApigRequestCountQuery(apiId, period)); } const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await this.cwClient.getMetricData({ MetricDataQueries: queries, StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private createDiscreteValuesForRange (range: FargateScaleRange): number[] { const { min, max, increment } = range; const discreteVales: number[] = []; let i = min; do { i = i + increment; discreteVales.push(i); } while (i <= max); return discreteVales; } private async getEc2ContainerInfo (service: Service) { const tasks = await this.getAllTasks(service); const taskCpu = Number(tasks.at(0)?.cpu); const allocatedMemory = Number(tasks.at(0)?.memory); let allocatedCpu = taskCpu; let containerInstance: ContainerInstance; let containerInstanceResponse: DescribeContainerInstancesCommandOutput; if (!taskCpu || taskCpu === 0) { const containerInstanceTaskGroupObject = tasks.reduce<{ [containerInstanceArn: string]: { containerInstanceArn: string; tasks: Task[]; } }>((acc, task) => { const { containerInstanceArn } = task; acc[containerInstanceArn] = acc[containerInstanceArn] || { containerInstanceArn, tasks: [] }; acc[containerInstanceArn].tasks.push(task); return acc; }, {}); const containerInstanceTaskGroups = Object.values(containerInstanceTaskGroupObject); containerInstanceTaskGroups.sort((a, b) => { if (a.tasks.length > b.tasks.length) { return -1; } else if (a.tasks.length < b.tasks.length) { return 1; } return 0; }); const largestContainerInstance = containerInstanceTaskGroups.at(0); const maxTaskCount = get(largestContainerInstance, 'tasks.length') || 0; const filteredTaskGroups = containerInstanceTaskGroups .filter(taskGroup => !isEmpty(taskGroup.containerInstanceArn)); if (isEmpty(filteredTaskGroups)) { return undefined; } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: containerInstanceTaskGroups.map(taskGroup => taskGroup.containerInstanceArn) }); // largest container instance containerInstance = containerInstanceResponse?.containerInstances?.at(0); const containerInstanceCpuResource = containerInstance.registeredResources?.find(r => r.name === 'CPU'); const containerInstanceCpu = Number( containerInstanceCpuResource?.doubleValue || containerInstanceCpuResource?.integerValue || containerInstanceCpuResource?.longValue ); allocatedCpu = containerInstanceCpu / maxTaskCount; } } else { containerInstanceResponse = await this.ecsClient.describeContainerInstances({ cluster: service.clusterArn, containerInstances: tasks.map(task => task.containerInstanceArn) }); containerInstance = containerInstanceResponse?.containerInstances?.at(0); } const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => { acc.add(instance.ec2InstanceId); return acc; }, new Set<string>()); const numEc2Instances = uniqueEc2Instances.size; const instanceType = containerInstance.attributes.find(attr => attr.name === 'ecs.instance-type')?.value; const monthlyInstanceCost = await getInstanceCost(this.pricingClient, instanceType); const monthlyCost = monthlyInstanceCost * numEc2Instances; this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances }; } private async checkForEc2ScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { const info = await this.getEc2ContainerInfo(service); if (!info) { return; } const { allocatedCpu, allocatedMemory, containerInstance, instanceType, monthlyCost, numEc2Instances } = info; const maxConsumedVcpus = (maxCpuPercentage * allocatedCpu) / 1024; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const instanceVcpus = allocatedCpu / 1024; let instanceFamily = instanceType?.split('.')?.at(0); if (!instanceFamily) { instanceFamily = await this.getInstanceFamilyForContainerInstance(containerInstance); } const allInstanceTypes = Object.values(_InstanceType); const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const betterFitCpu = ( it.VCpuInfo.DefaultVCpus >= maxConsumedVcpus && it.VCpuInfo.DefaultVCpus <= instanceVcpus ); const betterFitMemory = ( it.MemoryInfo.SizeInMiB >= maxConsumedMemory && it.MemoryInfo.SizeInMiB <= allocatedMemory ); return betterFitCpu && betterFitMemory; }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1; return memoryScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType); const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances; this.addScenario(service.serviceArn, 'overAllocated', { value: 'true', scaleDown: { action: 'scaleDownEc2Service', isActionable: false, reason: 'The EC2 instances used in this Service\'s cluster appears to be over allocated based on its CPU' + `and Memory utilization. We suggest scaling down to a ${targetInstanceType.InstanceType}.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } private calculateFargateCost (platform: string, cpuArch: string, vcpu: number, memory: number, numTasks: number) { let monthlyCost = 0; if (platform.toLowerCase() === 'windows') { monthlyCost = (((0.09148 + 0.046) * vcpu) + (0.01005 * memory)) * numTasks * 24 * 30; } else { if (cpuArch === 'x86_64') { monthlyCost = ((0.04048 * vcpu) + (0.004445 * memory)) * numTasks * 24 * 30; } else { monthlyCost = ((0.03238 * vcpu) + (0.00356 * memory)) * numTasks * 24 * 30; } } return monthlyCost; } private async getFargateInfo (service: Service) { const tasks = await this.getAllTasks(service); const numTasks = tasks.length; const task = tasks.at(0); const allocatedCpu = Number(task?.cpu); const allocatedMemory = Number(task?.memory); const platform = task.platformFamily || ''; const cpuArch = (task.attributes.find(attr => attr.name === 'ecs.cpu-architecture'))?.value || 'x86_64'; const vcpu = allocatedCpu / 1024; const memory = allocatedMemory / 1024; const monthlyCost = this.calculateFargateCost(platform, cpuArch, vcpu, memory, numTasks); this.serviceCosts[service.serviceName] = monthlyCost; return { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost }; } private async checkForFargateScaleDown (service: Service, maxCpuPercentage: number, maxMemoryPercentage: number) { // Source: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html const fargateScaleOptions: FargateScaleOption = { 256: { discrete: [0.5, 1, 2] }, 512: { range: { min: 1, max: 4, increment: 1 } }, 1024: { range: { min: 2, max: 8, increment: 1 } }, 2048: { range: { min: 4, max: 16, increment: 1 } }, 4096: { range: { min: 8, max: 30, increment: 1 } }, 8192: { range: { min: 16, max: 60, increment: 4 } }, 16384: { range: { min: 32, max: 120, increment: 4 } } }; const { allocatedCpu, allocatedMemory, platform, cpuArch, numTasks, monthlyCost } = await this.getFargateInfo(service); const maxConsumedCpu = maxCpuPercentage * allocatedCpu; const maxConsumedMemory = maxMemoryPercentage * allocatedMemory; const lowerCpuOptions = Object.keys(fargateScaleOptions).filter((cpuString) => { const cpu = Number(cpuString); return cpu < allocatedCpu && cpu > maxConsumedCpu; }).sort(); let targetScaleOption: FargateScale; for (const cpuOption of lowerCpuOptions) { const scalingOption = fargateScaleOptions[Number(cpuOption)]; const memoryOptionValues = []; const discreteMemoryOptionValues = scalingOption.discrete || []; memoryOptionValues.push(...discreteMemoryOptionValues); const rangeMemoryOptionsValues = scalingOption.range ? this.createDiscreteValuesForRange(scalingOption.range) : []; memoryOptionValues.push(...rangeMemoryOptionsValues); const optimizedMemory = memoryOptionValues.filter(mem => (mem > maxConsumedMemory)).sort().at(0); if (optimizedMemory) { targetScaleOption = { cpu: Number(cpuOption), memory: (optimizedMemory * 1024) }; break; } } if (targetScaleOption) { const targetMonthlyCost = this.calculateFargateCost( platform, cpuArch, targetScaleOption.cpu / 1024, targetScaleOption.memory / 1024, numTasks ); this.addScenario(service.serviceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownFargateService', isActionable: false, reason: 'This ECS service appears to be over allocated based on its CPU, Memory, and network utilization. ' + `We suggest scaling the CPU down to ${targetScaleOption.cpu} and the Memory to ` + `${targetScaleOption.memory} MiB.`, monthlySavings: monthlyCost - targetMonthlyCost } }); } } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) { this.ecsClient = new ECS({ credentials, region }); this.ec2Client = new EC2({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); this.elbV2Client = new ElasticLoadBalancingV2({ credentials, region }); this.apigClient = new ApiGatewayV2({ credentials, region }); this.pricingClient = new Pricing({ credentials, region }); if (overrides?.services) { this.services = await this.describeTheseServices(overrides?.services); } else { this.services = await this.describeAllServices(); } if (this.services.length === 0) return; for (const service of this.services) { const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ service, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [AVG_MEMORY]: avgMemoryMetrics, [MAX_MEMORY]: maxMemoryMetrics, [ALB_REQUEST_COUNT]: albRequestCountMetrics, [APIG_REQUEST_COUNT]: apigRequestCountMetrics } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values); const { max: maxMemory, isStable: maxMemoryIsStable } = getStabilityStats(maxMemoryMetrics.Values); const lowMemoryUtilization = ( (avgMemoryIsStable && maxMemoryIsStable) || maxMemory < 10 ); const requestCountMetricValues = [ ...(albRequestCountMetrics?.Values || []), ...(apigRequestCountMetrics?.Values || []) ]; const totalRequestCount = stats.sum(requestCountMetricValues); const noNetworkUtilization = totalRequestCount === 0; if ( lowCpuUtilization && lowMemoryUtilization && noNetworkUtilization ) { const info = service.launchType === LaunchType.FARGATE ? await this.getFargateInfo(service) : await this.getEc2ContainerInfo(service); if (!info) { return; } const { monthlyCost } = info; this.addScenario(service.serviceArn, 'unused', { value: 'true', delete: { action: 'deleteService', isActionable: true, reason: 'This ECS service appears to be unused based on its CPU utilizaiton, Memory utilizaiton, and' + ' network traffic.', monthlySavings: monthlyCost } }); } else if (maxCpu < 0.8 && maxMemory < 0.8) { if (service.launchType === LaunchType.FARGATE) { await this.checkForFargateScaleDown(service, maxCpu, maxMemory); } else { await this.checkForEc2ScaleDown(service, maxCpu, maxMemory); } } const monthlyCost = this.serviceCosts[service.serviceName] || 0; await this.fillData( service.serviceArn, credentials, region, { resourceId: service.serviceName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); AwsEcsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, service.serviceArn, 'AWS/ECS', metricName, [{ Name: 'ServiceName', Value: service.serviceName }, { Name: 'ClusterName', Value: service.clusterArn?.split('/').pop() }]); }); } console.info('this.utilization:\n', JSON.stringify(this.utilization, null, 2)); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } async deleteService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); await ecsClient.deleteService({ service: serviceArn, cluster: clusterName }); } async scaleDownFargateService ( awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string, cpu: number, memory: number ) { const credentials = await awsCredentialsProvider.getCredentials(); const ecsClient = new ECS({ credentials, region }); const serviceResponse = await ecsClient.describeServices({ cluster: clusterName, services: [serviceArn] }); const taskDefinitionArn = serviceResponse?.services?.at(0)?.taskDefinition; const taskDefResponse = await ecsClient.describeTaskDefinition( { taskDefinition: taskDefinitionArn, include: [TaskDefinitionField.TAGS] } ); const taskDefinition: TaskDefinition = taskDefResponse?.taskDefinition; const tags = taskDefResponse?.tags; const { containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes } = taskDefinition; // TODO: CPU and Memory validation? const revisionResponse = await ecsClient.registerTaskDefinition({ cpu: cpu.toString(), memory: memory.toString(), containerDefinitions, family, ephemeralStorage, executionRoleArn, inferenceAccelerators, ipcMode, networkMode, pidMode, placementConstraints, proxyConfiguration, requiresCompatibilities, runtimePlatform, taskRoleArn, volumes, tags }); await ecsClient.updateService({ cluster: clusterName, service: serviceArn, taskDefinition: revisionResponse?.taskDefinition?.taskDefinitionArn, forceNewDeployment: true }); } async scaleDownEc2Service (_serviceArn: string, _cpu: number, _memory: number) { /* TODO: Update Asg/Capacity provider? Or update memory/cpu allocation on the tasks? Or both? */ throw HttpError.NotImplemented('Automatic scale down for EC2 backed ECS Clusters is not yet supported.'); } }
src/service-utilizations/aws-ecs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " instanceIds: string[];\n}\nexport class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> {\n instanceIds: string[];\n instances: Instance[];\n accountId: string;\n DEBUG_MODE: boolean;\n constructor (enableDebugMode?: boolean) {\n super();\n this.instanceIds = [];", "score": 0.8408599495887756 }, { "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": 0.8404488563537598 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.83793705701828 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings: number\n}\nexport type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy';\nexport class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> {\n s3Client: S3;\n cwClient: CloudWatch;\n bucketCostData: { [ bucketName: string ]: S3CostData };\n constructor () {\n super();\n this.bucketCostData = {};", "score": 0.8313683271408081 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " 'hasAutoScalingEnabled';\nconst rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization'];\nexport class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> {\n private instanceCosts: { [instanceId: string]: RdsCosts };\n private rdsClient: RDS;\n private cwClient: CloudWatch;\n private pricingClient: Pricing;\n private region: string;\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string", "score": 0.8293346762657166 } ]
typescript
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 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/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 0.9288947582244873 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.isOptional = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow custom transformed values\n */\nclass TransformModifier<", "score": 0.9277572631835938 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.9180031418800354 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback\n return this\n }\n /**\n * Compiles the group\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {\n return {\n type: 'group',", "score": 0.9118171334266663 }, { "filename": "src/types.ts", "retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**", "score": 0.9085661172866821 } ]
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/aws-utilization-provider.ts", "retrieved_chunk": " backend: {\n type: 'memory'\n }\n});\ntype AwsUtilizationProviderProps = AwsUtilizationProviderType & {\n utilization?: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region?: string;\n};", "score": 0.8615378141403198 }, { "filename": "src/types/types.ts", "retrieved_chunk": " userInput?: UserInput\n}\nexport type AwsUtilizationOverrides = {\n [ serviceName: string ]: AwsServiceOverrides\n}\nexport type StabilityStats = {\n mean: number;\n max: number;\n maxZScore: number;\n standardDeviation: number;", "score": 0.8566474914550781 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8498718738555908 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.848190188407898 }, { "filename": "src/types/types.ts", "retrieved_chunk": "import { Tag } from '@aws-sdk/client-ec2';\nexport type Data = {\n region: string,\n resourceId: string,\n associatedResourceId?: string,\n stack?: string,\n hourlyCost?: number,\n monthlyCost?: number,\n maxMonthlySavings?: number,\n [ key: string ]: any;", "score": 0.8238211870193481 } ]
typescript
type AwsEcsUtilizationOverrides = AwsServiceOverrides & {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization (
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) {
const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.9546022415161133 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.9141789674758911 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8856862783432007 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " totalCost: 0,\n instanceCost: 0,\n totalStorageCost: 0,\n iopsCost: 0,\n throughputCost: 0\n } as RdsCosts;\n } \n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides", "score": 0.882937490940094 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8760871887207031 } ]
typescript
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: 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/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": 0.8369688987731934 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 0.8308865427970886 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 0.8289320468902588 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.825018048286438 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8223251104354858 } ]
typescript
(messages.postalCode, 'postalCode', field) }
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost,
hourlyCost: getHourlyCost(this.cost) }
); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9554011821746826 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8963587880134583 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8731868267059326 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8693689107894897 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8408812284469604 } ]
typescript
hourlyCost: getHourlyCost(this.cost) }
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId;
const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);
const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8931306600570679 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8776034116744995 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8662229776382446 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8639752268791199 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.863578200340271 } ]
typescript
const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);
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": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8740866184234619 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8323809504508972 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8290829658508301 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8265448808670044 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8217860460281372 } ]
typescript
this.addScenario(natGatewayArn, 'activeConnectionCount', {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map(
(schema, index) => schema[PARSE](String(index), refs, options)), }
} }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9312459230422974 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n allowUnknownProperties: this.#allowUnknownProperties,\n validations: this.compileValidations(refs),\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: this.#groups.map((group) => {\n return group[PARSE](refs, options)\n }),", "score": 0.9136145114898682 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8667306900024414 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.8583215475082397 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8559181094169617 } ]
typescript
(schema, index) => schema[PARSE](String(index), refs, options)), }
import cached from 'cached'; import dayjs from 'dayjs'; import isNil from 'lodash.isnil'; import chunk from 'lodash.chunk'; import * as stats from 'simple-statistics'; import { DescribeInstanceTypesCommandOutput, DescribeInstancesCommandOutput, EC2, Instance, InstanceTypeInfo, _InstanceType } from '@aws-sdk/client-ec2'; import { AutoScaling } from '@aws-sdk/client-auto-scaling'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { CloudWatch, MetricDataQuery, MetricDataResult } from '@aws-sdk/client-cloudwatch'; import { getStabilityStats } from '../utils/stats.js'; import { AVG_CPU, MAX_CPU, DISK_READ_OPS, DISK_WRITE_OPS, MAX_NETWORK_BYTES_IN, MAX_NETWORK_BYTES_OUT, AVG_NETWORK_BYTES_IN, AVG_NETWORK_BYTES_OUT } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { Pricing } from '@aws-sdk/client-pricing'; import { getAccountId, getHourlyCost } from '../utils/utils.js'; import { getInstanceCost } from '../utils/ec2-utils.js'; import { Arns } from '../types/constants.js'; const cache = cached<string>('ec2-util-cache', { backend: { type: 'memory' } }); type AwsEc2InstanceUtilizationScenarioTypes = 'unused' | 'overAllocated'; const AwsEc2InstanceMetrics = ['CPUUtilization', 'NetworkIn']; type AwsEc2InstanceUtilizationOverrides = AwsServiceOverrides & { instanceIds: string[]; } export class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> { instanceIds: string[]; instances: Instance[]; accountId: string; DEBUG_MODE: boolean; constructor (enableDebugMode?: boolean) { super(); this.instanceIds = []; this.instances = []; this.DEBUG_MODE = enableDebugMode || false; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'terminateInstance') { await this.terminateInstance(awsCredentialsProvider, resourceId, region); } } private async describeAllInstances (ec2Client: EC2, instanceIds?: string[]): Promise<Instance[]> { const instances: Instance[] = []; let nextToken; do { const response: DescribeInstancesCommandOutput = await ec2Client.describeInstances({ InstanceIds: instanceIds, NextToken: nextToken }); response?.Reservations.forEach((reservation) => { instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []); }); nextToken = response?.NextToken; } while (nextToken); return instances; } private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] { function metricStat (metricName: string, statistic: string) { return { Metric: { Namespace: 'AWS/EC2', MetricName: metricName, Dimensions: [{ Name: 'InstanceId', Value: instanceId }] }, Period: period, Stat: statistic }; } return [ { Id: AVG_CPU, MetricStat: metricStat('CPUUtilization', 'Average') }, { Id: MAX_CPU, MetricStat: metricStat('CPUUtilization', 'Maximum') }, { Id: DISK_READ_OPS, MetricStat: metricStat('DiskReadOps', 'Sum') }, { Id: DISK_WRITE_OPS, MetricStat: metricStat('DiskWriteOps', 'Sum') }, { Id: MAX_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Maximum') }, { Id: MAX_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Maximum') }, { Id: AVG_NETWORK_BYTES_IN, MetricStat: metricStat('NetworkIn', 'Average') }, { Id: AVG_NETWORK_BYTES_OUT, MetricStat: metricStat('NetworkOut', 'Average') } ]; } private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> { const instanceTypes = []; let nextToken; do { const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await ec2Client.describeInstanceTypes({ InstanceTypes: instanceTypeNames, NextToken: nextToken }); const { InstanceTypes = [], NextToken } = instanceTypeResponse; instanceTypes.push(...InstanceTypes); nextToken = NextToken; } while (nextToken); return instanceTypes; } private async getMetrics (args: { instanceId: string; startTime: Date; endTime: Date; period: number; cwClient: CloudWatch; }): Promise<{[ key: string ]: MetricDataResult}> { const { instanceId, startTime, endTime, period, cwClient } = args; const metrics: {[ key: string ]: MetricDataResult} = {}; let nextToken; do { const metricDataResponse = await cwClient.getMetricData({ MetricDataQueries: this.getMetricDataQueries(instanceId, period), StartTime: startTime, EndTime: endTime }); const { MetricDataResults, NextToken } = metricDataResponse || {}; MetricDataResults?.forEach((metricData: MetricDataResult) => { const { Id, Timestamps = [], Values = [] } = metricData; if (!metrics[Id]) { metrics[Id] = metricData; } else { metrics[Id].Timestamps.push(...Timestamps); metrics[Id].Values.push(...Values); } }); nextToken = NextToken; } while (nextToken); return metrics; } private getInstanceNetworkSetting (networkSetting: string): number | string { const numValue = networkSetting.split(' ').find(word => !Number.isNaN(Number(word))); if (!isNil(numValue)) return Number(numValue); return networkSetting; } async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEc2InstanceUtilizationOverrides) { const ec2Client = new EC2({ credentials, region }); const autoScalingClient = new AutoScaling({ credentials, region }); const cwClient = new CloudWatch({ credentials, region }); const pricingClient = new Pricing({ credentials, region }); this.instances = await this.describeAllInstances(ec2Client, overrides?.instanceIds); const instanceIds = this.instances.map(i => i.InstanceId); const idPartitions = chunk(instanceIds, 50); for (const partition of idPartitions) { const { AutoScalingInstances = [] } = await autoScalingClient.describeAutoScalingInstances({ InstanceIds: partition }); const asgInstances = AutoScalingInstances.map(instance => instance.InstanceId); this.instanceIds.push( ...partition.filter(instanceId => !asgInstances.includes(instanceId)) ); } this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId)); if (this.instances.length === 0) return; const instanceTypeNames = this.instances.map(i => i.InstanceType); const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client); const allInstanceTypes = Object.values(_InstanceType); for (const instanceId of this.instanceIds) { const instanceArn = Arns.Ec2(region, this.accountId, instanceId); const instance = this.instances.find(i => i.InstanceId === instanceId); const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType); const instanceFamily = instanceType.InstanceType?.split('.')?.at(0); const now = dayjs(); const startTime = now.subtract(2, 'weeks'); const fiveMinutes = 5 * 60; const metrics = await this.getMetrics({ instanceId, startTime: startTime.toDate(), endTime: now.toDate(), period: fiveMinutes, cwClient }); const { [AVG_CPU]: avgCpuMetrics, [MAX_CPU]: maxCpuMetrics, [DISK_READ_OPS]: diskReadOps, [DISK_WRITE_OPS]: diskWriteOps, [MAX_NETWORK_BYTES_IN]: maxNetworkBytesIn, [MAX_NETWORK_BYTES_OUT]: maxNetworkBytesOut, [AVG_NETWORK_BYTES_IN]: avgNetworkBytesIn, [AVG_NETWORK_BYTES_OUT]: avgNetworkBytesOut } = metrics; const { isStable: avgCpuIsStable } = getStabilityStats(avgCpuMetrics.Values); const { max: maxCpu, isStable: maxCpuIsStable } = getStabilityStats(maxCpuMetrics.Values); const lowCpuUtilization = ( (avgCpuIsStable && maxCpuIsStable) || maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html ); const allDiskReads = stats.sum(diskReadOps.Values); const allDiskWrites = stats.sum(diskWriteOps.Values); const totalDiskIops = allDiskReads + allDiskWrites; const { isStable: networkInIsStable, mean: networkInAvg } = getStabilityStats(avgNetworkBytesIn.Values); const { isStable: networkOutIsStable, mean: networkOutAvg } = getStabilityStats(avgNetworkBytesOut.Values); const avgNetworkThroughputMb = (networkInAvg + networkOutAvg) / (Math.pow(1024, 2)); const lowNetworkUtilization = ( (networkInIsStable && networkOutIsStable) || // v Source: https://www.trendmicro.com/cloudoneconformity/knowledge-base/aws/EC2/idle-instance.html (avgNetworkThroughputMb < 5) ); const cost = await getInstanceCost(pricingClient, instanceType.InstanceType); if ( lowCpuUtilization && totalDiskIops === 0 && lowNetworkUtilization ) { this.addScenario(instanceArn, 'unused', { value: 'true', delete: { action: 'terminateInstance', isActionable: true, reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' + 'and network traffic.', monthlySavings: cost } }); } else { // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization const networkInMax = stats.max(maxNetworkBytesIn.Values); const networkOutMax = stats.max(maxNetworkBytesOut.Values); const optimizedVcpuCount = Math.ceil(maxCpu * instanceType.VCpuInfo.DefaultVCpus); const minimumNetworkThroughput = Math.ceil((networkInMax + networkOutMax) / (Math.pow(1024, 3))); const currentNetworkThroughput = this.getInstanceNetworkSetting(instanceType.NetworkInfo.NetworkPerformance); const currentNetworkThroughputIsDefined = typeof currentNetworkThroughput === 'number'; const instanceTypeNamesInFamily = allInstanceTypes.filter(it => it.startsWith(`${instanceFamily}.`)); const cachedInstanceTypes = await cache.getOrElse( instanceFamily, async () => JSON.stringify(await this.getInstanceTypes(instanceTypeNamesInFamily, ec2Client)) ); const instanceTypesInFamily = JSON.parse(cachedInstanceTypes || '[]'); const smallerInstances = instanceTypesInFamily.filter((it: InstanceTypeInfo) => { const availableNetworkThroughput = this.getInstanceNetworkSetting(it.NetworkInfo.NetworkPerformance); const availableNetworkThroughputIsDefined = typeof availableNetworkThroughput === 'number'; return ( it.VCpuInfo.DefaultVCpus >= optimizedVcpuCount && it.VCpuInfo.DefaultVCpus <= instanceType.VCpuInfo.DefaultVCpus ) && ( (currentNetworkThroughputIsDefined && availableNetworkThroughputIsDefined) ? ( availableNetworkThroughput >= minimumNetworkThroughput && availableNetworkThroughput <= currentNetworkThroughput ) : // Best we can do for t2 burstable network defs is find one that's the same because they're not // quantifiable currentNetworkThroughput === availableNetworkThroughput ); }).sort((a: InstanceTypeInfo, b: InstanceTypeInfo) => { const aNetwork = this.getInstanceNetworkSetting(a.NetworkInfo.NetworkPerformance); const aNetworkIsNumeric = typeof aNetwork === 'number'; const bNetwork = this.getInstanceNetworkSetting(b.NetworkInfo.NetworkPerformance); const bNetworkIsNumeric = typeof bNetwork === 'number'; const networkScore = (aNetworkIsNumeric && bNetworkIsNumeric) ? (aNetwork < bNetwork ? -1 : 1) : 0; const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1; return networkScore + vCpuScore; }); const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0); if (targetInstanceType) { const targetInstanceCost = await getInstanceCost(pricingClient, targetInstanceType.InstanceType); const monthlySavings = cost - targetInstanceCost; this.addScenario(instanceArn, 'overAllocated', { value: 'overAllocated', scaleDown: { action: 'scaleDownInstance', isActionable: false, reason: 'This EC2 instance appears to be over allocated based on its CPU and network utilization. We ' + `suggest scaling down to a ${targetInstanceType.InstanceType}`, monthlySavings } }); } } await this.fillData( instanceArn, credentials, region, { resourceId: instanceId, region, monthlyCost: cost,
hourlyCost: getHourlyCost(cost) }
); AwsEc2InstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, instanceArn, 'AWS/EC2', metricName, [{ Name: 'InstanceId', Value: instanceId }]); }); } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } // this.getEstimatedMaxMonthlySavings(); } async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.terminateInstances({ InstanceIds: [instanceId] }); // TODO: Remove scenario? } async scaleDownInstance ( awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string, instanceType: string ) { const credentials = await awsCredentialsProvider.getCredentials(); const ec2Client = new EC2({ credentials, region }); await ec2Client.modifyInstanceAttribute({ InstanceId: instanceId, InstanceType: { Value: instanceType } }); } }
src/service-utilizations/aws-ec2-instance-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.979626476764679 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.9041218757629395 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8809137344360352 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8690406680107117 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8582597970962524 } ]
typescript
hourlyCost: getHourlyCost(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/service-utilizations/aws-service-utilization-factory.ts", "retrieved_chunk": "import { AwsEcsUtilization } from './aws-ecs-utilization.js';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nexport class AwsServiceUtilizationFactory {\n static createObject (awsService: AwsResourceType): AwsServiceUtilization<string> {\n switch (awsService) {\n case AwsResourceTypes.CloudwatchLogs:\n return new AwsCloudwatchLogsUtilization();\n case AwsResourceTypes.S3Bucket: \n return new s3Utilization(); \n case AwsResourceTypes.RdsInstance: ", "score": 0.8401991128921509 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " instanceIds: string[];\n}\nexport class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> {\n instanceIds: string[];\n instances: Instance[];\n accountId: string;\n DEBUG_MODE: boolean;\n constructor (enableDebugMode?: boolean) {\n super();\n this.instanceIds = [];", "score": 0.8298550844192505 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings: number\n}\nexport type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy';\nexport class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> {\n s3Client: S3;\n cwClient: CloudWatch;\n bucketCostData: { [ bucketName: string ]: S3CostData };\n constructor () {\n super();\n this.bucketCostData = {};", "score": 0.8294739127159119 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.8270796537399292 }, { "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": 0.8235337734222412 } ]
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": " field.report(messages.creditCard, 'creditCard', field, {\n providersList: 'credit',\n })\n }\n } else {\n const matchesAnyProvider = providers.find((provider) =>\n helpers.isCreditCard(value as string, { provider })\n )\n if (!matchesAnyProvider) {\n field.report(messages.creditCard, 'creditCard', field, {", "score": 0.7150173783302307 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 0.7126610279083252 }, { "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": 0.7110023498535156 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],", "score": 0.7061259746551514 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " providers: providers,\n providersList: providers.join('/'),\n })\n }\n }\n})\n/**\n * Validates the value to be a valid passport number\n */\nexport const passportRule = createRule<", "score": 0.7052282094955444 } ]
typescript
(typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [
IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.907471776008606 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 0.9019373655319214 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.9008125066757202 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.isOptional = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow custom transformed values\n */\nclass TransformModifier<", "score": 0.8941916823387146 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8903870582580566 } ]
typescript
IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
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": " isActionable: true,\n reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' +\n 'and network traffic.', \n monthlySavings: cost\n }\n });\n } else {\n // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization\n const networkInMax = stats.max(maxNetworkBytesIn.Values);\n const networkOutMax = stats.max(maxNetworkBytesOut.Values);", "score": 0.866620659828186 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8613664507865906 }, { "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": 0.8586622476577759 }, { "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": 0.8585350513458252 }, { "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": 0.8564078211784363 } ]
typescript
await this.fillData( natGatewayArn, credentials, region, {
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await
rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 0.9166107177734375 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8298853039741516 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " Namespace: 'AWS/EC2',\n MetricName: metricName,\n Dimensions: [{\n Name: 'InstanceId',\n Value: instanceId\n }]\n },\n Period: period,\n Stat: statistic\n };", "score": 0.8191791772842407 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8062729835510254 }, { "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": 0.8055023550987244 } ]
typescript
rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await
rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8870620727539062 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.864973783493042 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8642638921737671 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8637993335723877 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8618725538253784 } ]
typescript
rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name;
const bucketArn = Arns.S3(bucketName);
await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " 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": 0.8670045137405396 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8583590388298035 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8577752113342285 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8549818992614746 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8541306257247925 } ]
typescript
const bucketArn = Arns.S3(bucketName);
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.fillData( bucketArn, credentials, region, { resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost =
(bucketBytes / ONE_GB_IN_BYTES) * 0.022;
/* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " 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": 0.8707512021064758 }, { "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": 0.8613452315330505 }, { "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": 0.8611856698989868 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'\n }\n },\n {\n Id: 'bytesOutToDestination',\n MetricStat: {", "score": 0.8471290469169617 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Maximum'\n }\n },\n {\n Id: 'bytesInFromDestination',\n MetricStat: {", "score": 0.8466784954071045 } ]
typescript
(bucketBytes / ONE_GB_IN_BYTES) * 0.022;
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export
interface ErrorReporterContract extends BaseReporter {
createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>", "score": 0.8849735260009766 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 0.8818864822387695 }, { "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": 0.8810566663742065 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 0.8773725628852844 }, { "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": 0.8733415603637695 } ]
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/aws-service-utilization.ts", "retrieved_chunk": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.7565968036651611 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.7532719373703003 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.7393619418144226 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n );\n }\n function sidePanel (){ \n const serviceUtil = sidePanelService && filteredServices[sidePanelService];\n const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data;\n //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination'];\n const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => (\n <Box bg=\"#EDF2F7\" p={2} color=\"black\" marginBottom='8px'> \n <InfoIcon marginRight={'8px'} />", "score": 0.734952986240387 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.7325769066810608 } ]
typescript
.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { 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/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": 0.8465493321418762 }, { "filename": "src/schema/union/builder.ts", "retrieved_chunk": " */\nunion.if = function unionIf<Schema extends SchemaTypes>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n schema: Schema\n) {\n return new UnionConditional<Schema>(conditon, schema)\n}\n/**\n * Wrap object properties inside an else conditon\n */", "score": 0.84532231092453 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " * meta: { userId: auth.user.id },\n * errorReporter,\n * messagesProvider\n * })\n * ```\n */\n validate(\n data: any,\n ...[options]: [undefined] extends MetaData\n ? [options?: ValidationOptions<MetaData> | undefined]", "score": 0.8374327421188354 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8360652923583984 }, { "filename": "src/messages_provider/simple_messages_provider.ts", "retrieved_chunk": " output = Object.hasOwn(output, token) ? output[token] : undefined\n }\n return output\n })\n }\n /**\n * Returns a validation message for a given field + rule.\n */\n getMessage(rawMessage: string, rule: string, field: FieldContext, args?: Record<string, any>) {\n const fieldName = this.#fields[field.name] || field.name", "score": 0.8350371718406677 } ]
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/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": 0.8792536854743958 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.8772026300430298 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\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),\n conditions: this.#schemas.map((schema) => {", "score": 0.8697073459625244 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {\n return {\n type: 'tuple',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,", "score": 0.858660101890564 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.857913613319397 } ]
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/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8044240474700928 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.7918137311935425 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.787321925163269 }, { "filename": "src/service-utilizations/aws-account-utilization.tsx", "retrieved_chunk": " const pricingClient = new Pricing({ \n credentials: await awsCredentialsProvider.getCredentials(),\n region: region\n });\n await pricingClient.describeServices({}).catch((e) => { \n if(e.Code === 'AccessDeniedException'){ \n this.addScenario('PriceListAPIs', 'hasPermissionsForPriceList', {\n value: 'false',\n optimize: {\n action: '', ", "score": 0.786407470703125 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n return metricDataRes.MetricDataResults;\n }\n private async getRegionalUtilization (credentials: any, region: string) {\n const allNatGateways = await this.getAllNatGateways(credentials, region);\n const analyzeNatGateway = async (natGateway: NatGateway) => {\n const natGatewayId = natGateway.NatGatewayId;\n const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);\n const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId);\n const activeConnectionCount = get(results, '[0].Values[0]') as number;", "score": 0.783973217010498 } ]
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-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8562867045402527 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.855021595954895 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8537477850914001 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8527663350105286 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.8519648313522339 } ]
typescript
protected addData (resourceArn: string, dataType: keyof Data, value: any) {
import get from 'lodash.get'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { Bucket, S3 } from '@aws-sdk/client-s3'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns, ONE_GB_IN_BYTES } from '../types/constants.js'; type S3CostData = { monthlyCost: number, monthlySavings: number } export type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy'; export class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> { s3Client: S3; cwClient: CloudWatch; bucketCostData: { [ bucketName: string ]: S3CostData }; constructor () { super(); this.bucketCostData = {}; } async doAction (awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string) { const s3Client = new S3({ credentials: await awsCredentialsProvider.getCredentials() }); const resourceId = resourceArn.split(':').at(-1); if (actionName === 'enableIntelligientTiering') { await this.enableIntelligientTiering(s3Client, resourceId); } } async enableIntelligientTiering (s3Client: S3, bucketName: string, userInput?: any) { let configurationId = userInput?.configurationId || `${bucketName}-tiering-configuration`; if(configurationId.length > 63){ configurationId = configurationId.substring(0, 63); } return await s3Client.putBucketIntelligentTieringConfiguration({ Bucket: bucketName, Id: configurationId, IntelligentTieringConfiguration: { Id: configurationId, Status: 'Enabled', Tierings: [ { AccessTier: 'ARCHIVE_ACCESS', Days: 90 }, { AccessTier: 'DEEP_ARCHIVE_ACCESS', Days: 180 } ] } }); } async getRegionalUtilization (credentials: any, region: string) { this.s3Client = new S3({ credentials, region }); this.cwClient = new CloudWatch({ credentials, region }); const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets; const analyzeS3Bucket = async (bucket: Bucket) => { const bucketName = bucket.Name; const bucketArn = Arns.S3(bucketName); await this.getLifecyclePolicy(bucketArn, bucketName, region); await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region); const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0; await this.
fillData( bucketArn, credentials, region, {
resourceId: bucketName, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); }; await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } async getIntelligentTieringConfiguration (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { const res = await this.s3Client.listBucketIntelligentTieringConfigurations({ Bucket: bucketName }); if (!res.IntelligentTieringConfigurationList) { const { monthlySavings } = await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasIntelligentTiering', { value: 'false', optimize: { action: 'enableIntelligientTiering', isActionable: true, reason: 'Intelligient tiering is not enabled for this bucket', monthlySavings } }); } } } async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) { const response = await this.s3Client.getBucketLocation({ Bucket: bucketName }); if ( response.LocationConstraint === region || (region === 'us-east-1' && response.LocationConstraint === undefined) ) { await this.s3Client.getBucketLifecycleConfiguration({ Bucket: bucketName }).catch(async (e) => { if(e.Code === 'NoSuchLifecycleConfiguration'){ await this.setAndGetBucketCostData(bucketName); this.addScenario(bucketArn, 'hasLifecyclePolicy', { value: 'false', optimize: { action: '', isActionable: false, reason: 'This bucket does not have a lifecycle policy', monthlySavings: 0 } }); } }); } } async setAndGetBucketCostData (bucketName: string) { if (!(bucketName in this.bucketCostData)) { const res = await this.cwClient.getMetricData({ StartTime: new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/S3', MetricName: 'BucketSizeBytes', Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } } ] }); const bucketBytes = get(res, 'MetricDataResults[0].Values[0]', 0); const monthlyCost = (bucketBytes / ONE_GB_IN_BYTES) * 0.022; /* TODO: improve estimate * Based on idea that lower tiers will contain less data * Uses arbitrary percentages to separate amount of data in tiers */ const frequentlyAccessedBytes = (0.5 * bucketBytes) / ONE_GB_IN_BYTES; const infrequentlyAccessedBytes = (0.25 * bucketBytes) / ONE_GB_IN_BYTES; const archiveInstantAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const archiveAccess = (0.1 * bucketBytes) / ONE_GB_IN_BYTES; const deepArchiveAccess = (0.05 * bucketBytes) / ONE_GB_IN_BYTES; const newMonthlyCost = (frequentlyAccessedBytes * 0.022) + (infrequentlyAccessedBytes * 0.0125) + (archiveInstantAccess * 0.004) + (archiveAccess * 0.0036) + (deepArchiveAccess * 0.00099); this.bucketCostData[bucketName] = { monthlyCost, monthlySavings: monthlyCost - newMonthlyCost }; } return this.bucketCostData[bucketName]; } findActionFromOverrides (_overrides: AwsServiceOverrides){ if(_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action; } else{ return ''; } } }
src/service-utilizations/aws-s3-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8959689140319824 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8355621099472046 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8331326246261597 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8243356943130493 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8209407329559326 } ]
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": 0.7889865636825562 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7884739637374878 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " Object.entries(resource.scenarios).forEach(([sType, details]) => {\n if (Object.hasOwn(details, actionType)) {\n filteredScenarios[sType] = details;\n }\n });\n if (!filteredScenarios || isEmpty(filteredScenarios)) {\n return aggUtil;\n }\n aggUtil[id] = {\n ...resource,", "score": 0.7717766165733337 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );\n await utilizationCache.set(service, this.utilization[service]);\n }\n return this.utilization;", "score": 0.7680437564849854 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.7674764394760132 } ]
typescript
scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } }
public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; }
public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " instances.push(...reservation.Instances?.filter(i => !isNil(i.InstanceId)) || []);\n });\n nextToken = response?.NextToken;\n } while (nextToken);\n return instances;\n }\n private getMetricDataQueries (instanceId: string, period: number): MetricDataQuery[] {\n function metricStat (metricName: string, statistic: string) {\n return {\n Metric: {", "score": 0.8323127031326294 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " EndTime: new Date(Date.now()),\n Period: 43200,\n Statistics: ['Sum'],\n Dimensions: [{\n Name: 'VolumeId',\n Value: volumeId\n }]\n });\n const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { \n return data.Sum;", "score": 0.8196521401405334 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8188802599906921 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " }\n ]\n },\n Period: period,\n Stat: 'Sum'\n }\n };\n }\n private getApigRequestCountQuery (apiId: string, period: number): MetricDataQuery {\n return {", "score": 0.8185619115829468 }, { "filename": "src/service-utilizations/aws-autoscaling-groups-utilization.tsx", "retrieved_chunk": " Name: 'AutoScalingGroupName', \n Value: groupName\n }], \n Unit: 'Percent'\n }); \n const cpuValues = metricStats.Datapoints.map((data) => { \n return data.Maximum;\n });\n return Math.max(...cpuValues);\n }", "score": 0.8185117244720459 } ]
typescript
public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; }
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn
= Arns.Ebs(region, this.accountId, volumeId);
const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0; await this.fillData( volumeArn, credentials, region, { resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await rateLimitMap(volumes, 5, 5, analyzeEbsVolume); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'hasAttachedInstances', { value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8884655237197876 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.8859540820121765 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8847718238830566 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.8823022246360779 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " });\n return metricDataRes.MetricDataResults;\n }\n private async getRegionalUtilization (credentials: any, region: string) {\n const allNatGateways = await this.getAllNatGateways(credentials, region);\n const analyzeNatGateway = async (natGateway: NatGateway) => {\n const natGatewayId = natGateway.NatGatewayId;\n const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId);\n const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId);\n const activeConnectionCount = get(results, '[0].Values[0]') as number;", "score": 0.8807637691497803 } ]
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": 0.7889865636825562 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7884739637374878 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " Object.entries(resource.scenarios).forEach(([sType, details]) => {\n if (Object.hasOwn(details, actionType)) {\n filteredScenarios[sType] = details;\n }\n });\n if (!filteredScenarios || isEmpty(filteredScenarios)) {\n return aggUtil;\n }\n aggUtil[id] = {\n ...resource,", "score": 0.7717766165733337 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );\n await utilizationCache.set(service, this.utilization[service]);\n }\n return this.utilization;", "score": 0.7680437564849854 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.7674764394760132 } ]
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": 0.7889865636825562 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7884739637374878 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " Object.entries(resource.scenarios).forEach(([sType, details]) => {\n if (Object.hasOwn(details, actionType)) {\n filteredScenarios[sType] = details;\n }\n });\n if (!filteredScenarios || isEmpty(filteredScenarios)) {\n return aggUtil;\n }\n aggUtil[id] = {\n ...resource,", "score": 0.7717766165733337 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );\n await utilizationCache.set(service, this.utilization[service]);\n }\n return this.utilization;", "score": 0.7680437564849854 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.7674764394760132 } ]
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/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.85001140832901 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8461901545524597 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8434031009674072 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.842530369758606 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8381485342979431 } ]
typescript
await this.fillData( volumeArn, credentials, region, {
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": 0.8319302797317505 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " credentials,\n region\n });\n const allS3Buckets = (await this.s3Client.listBuckets({})).Buckets;\n const analyzeS3Bucket = async (bucket: Bucket) => {\n const bucketName = bucket.Name;\n const bucketArn = Arns.S3(bucketName);\n await this.getLifecyclePolicy(bucketArn, bucketName, region);\n await this.getIntelligentTieringConfiguration(bucketArn, bucketName, region);\n const monthlyCost = this.bucketCostData[bucketName]?.monthlyCost || 0;", "score": 0.8217693567276001 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " this.instances = this.instances.filter(i => this.instanceIds.includes(i.InstanceId));\n if (this.instances.length === 0) return;\n const instanceTypeNames = this.instances.map(i => i.InstanceType);\n const instanceTypes = await this.getInstanceTypes(instanceTypeNames, ec2Client);\n const allInstanceTypes = Object.values(_InstanceType);\n for (const instanceId of this.instanceIds) {\n const instanceArn = Arns.Ec2(region, this.accountId, instanceId);\n const instance = this.instances.find(i => i.InstanceId === instanceId);\n const instanceType = instanceTypes.find(it => it.InstanceType === instance.InstanceType);\n const instanceFamily = instanceType.InstanceType?.split('.')?.at(0);", "score": 0.8106307983398438 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8061527013778687 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.7969909310340881 } ]
typescript
await this.fillData(dbInstanceArn, credentials, this.region, {
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { DescribeVolumesCommandOutput, EC2 } from '@aws-sdk/client-ec2'; import { AwsServiceOverrides } from '../types/types.js'; import { Volume } from '@aws-sdk/client-ec2'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Arns } from '../types/constants.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; export type ebsVolumesUtilizationScenarios = 'hasAttachedInstances' | 'volumeReadWriteOps'; const EbsVolumesMetrics = ['VolumeWriteOps', 'VolumeReadOps']; export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> { accountId: string; volumeCosts: { [ volumeId: string ]: number }; constructor () { super(); this.volumeCosts = {}; } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = (resourceArn.split(':').at(-1)).split('/').at(-1); if (actionName === 'deleteEBSVolume') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region: region }); await this.deleteEBSVolume(ec2Client, resourceId); } } async deleteEBSVolume (ec2Client: EC2, volumeId: string){ await ec2Client.deleteVolume({ VolumeId: volumeId }); } async getAllVolumes (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let volumes: Volume[] = []; let describeVolumesRes: DescribeVolumesCommandOutput; do { describeVolumesRes = await ec2Client.describeVolumes({ NextToken: describeVolumesRes?.NextToken }); volumes = [ ...volumes, ...describeVolumesRes?.Volumes || [] ]; } while (describeVolumesRes?.NextToken); return volumes; } getVolumeCost (volume: Volume) { if (volume.VolumeId in this.volumeCosts) { return this.volumeCosts[volume.VolumeId]; } let cost = 0; const storage = volume.Size || 0; switch (volume.VolumeType) { case 'gp3': { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } case 'gp2': { cost = 0.10 * storage; break; } case 'io2': { let iops = volume.Iops || 0; let iopsCost = 0; if (iops > 64000) { const iopsCharged = iops - 640000; iopsCost += (0.032 * iopsCharged); iops -= iopsCharged; } if (iops > 32000) { const iopsCharged = iops - 320000; iopsCost += (0.046 * iopsCharged); iops -= iopsCharged; } iopsCost += (0.065 * iops); cost = (0.125 * volume.Size) + iopsCost; break; } case 'io1': { cost = (0.125 * storage) + (0.065 * volume.Iops); break; } case 'st1': { cost = 0.045 * storage; break; } case 'sc1': { cost = 0.015 * storage; break; } default: { const iops = volume.Iops || 0; const throughput = volume.Throughput || 0; cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput); break; } } this.volumeCosts[volume.VolumeId] = cost; return cost; } async getRegionalUtilization (credentials: any, region: string) { const volumes = await this.getAllVolumes(credentials, region); const analyzeEbsVolume = async (volume: Volume) => { const volumeId = volume.VolumeId; const volumeArn = Arns.Ebs(region, this.accountId, volumeId); const cloudWatchClient = new CloudWatch({ credentials, region }); this.checkForUnusedVolume(volume, volumeArn); await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn); const monthlyCost = this.volumeCosts[volumeArn] || 0; await this.fillData( volumeArn, credentials, region, { resourceId: volumeId, region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) } ); EbsVolumesMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, volumeId, 'AWS/EBS', metricName, [{ Name: 'VolumeId', Value: volumeId }]); }); }; await
rateLimitMap(volumes, 5, 5, analyzeEbsVolume);
} async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } checkForUnusedVolume (volume: Volume, volumeArn: string) { if(!volume.Attachments || volume.Attachments.length === 0){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'hasAttachedInstances', { value: 'false', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'This EBS volume does not have any attahcments', monthlySavings: cost } }); } } async getReadWriteVolume (cloudWatchClient: CloudWatch, volume: Volume, volumeArn: string){ const volumeId = volume.VolumeId; const writeOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeWriteOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const readOpsMetricRes = await cloudWatchClient.getMetricStatistics({ Namespace: 'AWS/EBS', MetricName: 'VolumeReadOps', StartTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), EndTime: new Date(Date.now()), Period: 43200, Statistics: ['Sum'], Dimensions: [{ Name: 'VolumeId', Value: volumeId }] }); const writeMetricStats = writeOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const readMetricStats = readOpsMetricRes.Datapoints.map((data) => { return data.Sum; }); const allMetricStats = [...readMetricStats, ...writeMetricStats]; if(allMetricStats.length === 0 || allMetricStats.every( element => element === 0 )){ const cost = this.getVolumeCost(volume); this.addScenario(volumeArn, 'volumeReadWriteOps', { value: '0', delete: { action: 'deleteEBSVolume', isActionable: true, reason: 'No operations performed on this volume in the last week', monthlySavings: cost } }); } } }
src/service-utilizations/ebs-volumes-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.9139044284820557 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " Namespace: 'AWS/EC2',\n MetricName: metricName,\n Dimensions: [{\n Name: 'InstanceId',\n Value: instanceId\n }]\n },\n Period: period,\n Stat: statistic\n };", "score": 0.8719496726989746 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8562611937522888 }, { "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": 0.8470863699913025 }, { "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": 0.8432554006576538 } ]
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/rds-utilization.tsx", "retrieved_chunk": " 'AWS/RDS', \n metricName, \n [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]);\n });\n }\n }\n async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){\n if (!metrics.databaseConnections) {\n const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstanceArn, 'hasDatabaseConnections', {", "score": 0.8457050919532776 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n}", "score": 0.8361195921897888 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.8285001516342163 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8267189264297485 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " const cost = await getInstanceCost(pricingClient, instanceType.InstanceType);\n if (\n lowCpuUtilization &&\n totalDiskIops === 0 &&\n lowNetworkUtilization\n ) {\n this.addScenario(instanceArn, 'unused', {\n value: 'true',\n delete: {\n action: 'terminateInstance',", "score": 0.8250992298126221 } ]
typescript
addScenario(volumeArn, 'hasAttachedInstances', {
import React from 'react'; import get from 'lodash.get'; import { BaseProvider, BaseWidget } from '@tinystacks/ops-core'; import { AwsResourceType, Utilization, actionTypeToEnum, HistoryEvent } from '../types/types.js'; import { RecommendationsOverrides, HasActionType, HasUtilization, Regions } from '../types/utilization-recommendations-types.js'; import { UtilizationRecommendationsUi } from './utilization-recommendations-ui/utilization-recommendations-ui.js'; import { filterUtilizationForActionType } from '../utils/utilization.js'; import { AwsUtilizationRecommendations as AwsUtilizationRecommendationsType } from '../ops-types.js'; export type AwsUtilizationRecommendationsProps = AwsUtilizationRecommendationsType & HasActionType & HasUtilization & Regions; export class AwsUtilizationRecommendations extends BaseWidget { utilization?: { [key: AwsResourceType | string]: Utilization<string> }; sessionHistory: HistoryEvent[]; allRegions?: string[]; region?: string; constructor (props: AwsUtilizationRecommendationsProps) { super(props); this.utilization = props.utilization; this.region = props.region || 'us-east-1'; this.sessionHistory = props.sessionHistory || []; this.allRegions = props.allRegions; } static fromJson (props: AwsUtilizationRecommendationsProps) { return new AwsUtilizationRecommendations(props); } toJson () { return { ...super.toJson(), utilization: this.utilization, sessionHistory: this.sessionHistory, allRegions: this.allRegions, region: this.region }; } async getData (providers: BaseProvider[], overrides?: RecommendationsOverrides) { const depMap = { utils: '../utils/utils.js' }; const { getAwsCredentialsProvider, getAwsUtilizationProvider, listAllRegions } = await import(depMap.utils); const utilProvider = getAwsUtilizationProvider(providers); const awsCredsProvider = getAwsCredentialsProvider(providers); this.allRegions = await listAllRegions(awsCredsProvider); if (overrides?.refresh) { await utilProvider.hardRefresh(awsCredsProvider, this.region); } this.sessionHistory = await utilProvider.getSessionHistory(); if (overrides?.region) { this.region = overrides.region; await utilProvider.hardRefresh(awsCredsProvider, this.region); } this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region); if (overrides?.resourceActions) { const { actionType, resourceArns } = overrides.resourceActions; const resourceArnsSet = new Set<string>(resourceArns); const filteredServices =
filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);
for (const serviceUtil of Object.keys(filteredServices)) { const filteredServiceUtil = Object.keys(filteredServices[serviceUtil]) .filter(resArn => resourceArnsSet.has(resArn)); for (const resourceArn of filteredServiceUtil) { const resource = filteredServices[serviceUtil][resourceArn]; for (const scenario of Object.keys(resource.scenarios)) { await utilProvider.doAction( serviceUtil, awsCredsProvider, get(resource.scenarios[scenario], `${actionType}.action`), actionTypeToEnum[actionType], resourceArn, get(resource.data, 'region', 'us-east-1') ); } } } } } render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) { function onResourcesAction (resourceArns: string[], actionType: string) { overridesCallback({ resourceActions: { resourceArns, actionType } }); } function onRefresh () { overridesCallback({ refresh: true }); } function onRegionChange (region: string) { overridesCallback({ region }); } return ( <UtilizationRecommendationsUi utilization={this.utilization || {}} sessionHistory={this.sessionHistory} onResourcesAction={onResourcesAction} onRefresh={onRefresh} allRegions={this.allRegions || []} region={this.region} onRegionChange={onRegionChange} /> ); } }
src/widgets/aws-utilization-recommendations.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );\n await utilizationCache.set(service, this.utilization[service]);\n }\n return this.utilization;", "score": 0.8602993488311768 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n async getUtilization (\n credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n if (serviceOverrides?.forceRefesh) {\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );", "score": 0.8504096269607544 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.8276330232620239 }, { "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": 0.8218792676925659 }, { "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": 0.8216190338134766 } ]
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/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": 0.8607996702194214 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8424444198608398 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " onRemoveResource: (resourceArn: string) => void;\n}\ninterface HasResourcesAction {\n onResourcesAction: (resourceArns: string[], actionType: string) => void;\n}\ninterface Refresh {\n onRefresh: () => void;\n}\nexport type UtilizationRecommendationsWidget = Widget & HasActionType & HasUtilization & {\n region: string", "score": 0.8311318159103394 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8299208283424377 }, { "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": 0.8268299698829651 } ]
typescript
: { [service: string]: Utilization<string> }): number {
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-cloudwatch-logs-utilization.ts", "retrieved_chunk": " const logGroupName = logGroup?.logGroupName;\n // get data and cost estimate for stored bytes \n const storedBytes = logGroup?.storedBytes || 0;\n const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03;\n const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED';\n const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0;\n const monthlyStorageCost = storedBytesCost + dataProtectionCost;\n // get data and cost estimate for ingested bytes\n const describeLogStreamsRes = await cwLogsClient.describeLogStreams({\n logGroupName,", "score": 0.8447989225387573 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " if (volume.VolumeId in this.volumeCosts) {\n return this.volumeCosts[volume.VolumeId];\n }\n let cost = 0;\n const storage = volume.Size || 0;\n switch (volume.VolumeType) {\n case 'gp3': {\n const iops = volume.Iops || 0;\n const throughput = volume.Throughput || 0;\n cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput);", "score": 0.8327318429946899 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n case 'sc1': {\n cost = 0.015 * storage;\n break;\n }\n default: {\n const iops = volume.Iops || 0;\n const throughput = volume.Throughput || 0;\n cost = (0.08 * storage) + (0.005 * iops) + (0.040 * throughput);\n break;", "score": 0.8239679336547852 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " isActionable: true,\n reason: 'This EC2 instance appears to be unused based on its CPU utilization, disk IOPS, ' +\n 'and network traffic.', \n monthlySavings: cost\n }\n });\n } else {\n // TODO: For burstable instance types, we need to factor in credit consumption and baseline utilization\n const networkInMax = stats.max(maxNetworkBytesIn.Values);\n const networkOutMax = stats.max(maxNetworkBytesOut.Values);", "score": 0.823208212852478 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8152564167976379 } ]
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-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": 0.8664908409118652 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8633633852005005 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8551452159881592 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8527675867080688 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8393999338150024 } ]
typescript
: getHourlyCost(monthlyCost) });
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName:
string, serviceUtil: Utilization<string>) {
const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.8340022563934326 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": " setSelectedResourceArns(selectedResourceArns.filter((r: string) => r !== resourceArn));\n }}\n onResourcesAction={onResourcesAction}\n utilization={utilization}\n onBack={() => { \n setWizardStep(WizardSteps.TABLE);\n }}\n />);\n }\n return (", "score": 0.8189305067062378 }, { "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": 0.8072786927223206 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.800202488899231 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " scenarios: filteredScenarios \n };\n return aggUtil;\n }, {});\n return actionFilteredServiceUtil;\n}\nexport function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number {\n let total = 0;\n Object.keys(filtered).forEach((s) => {\n if (!filtered[s] || isEmpty(filtered[s])) return;", "score": 0.797627329826355 } ]
typescript
string, serviceUtil: Utilization<string>) {
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/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.8479092121124268 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " actionTypeToEnum[actionType],\n resourceArn,\n get(resource.data, 'region', 'us-east-1')\n );\n }\n }\n }\n }\n }\n render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) {", "score": 0.8349345922470093 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8325792551040649 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8303273916244507 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.8297497034072876 } ]
typescript
?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
import isEmpty from 'lodash.isempty'; import { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js'; export function filterUtilizationForActionType ( utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[] ): { [service: string]: Utilization<string> } { const filtered: { [service: string]: Utilization<string> } = {}; if (!utilization) { return filtered; } Object.keys(utilization).forEach((service) => { filtered[service] = filterServiceForActionType(utilization, service, actionType, session); }); return filtered; } export function filterServiceForActionType ( utilization: { [service: string]: Utilization<string> }, service: string, actionType: ActionType, session: HistoryEvent[] ) { const resourcesInProgress = session.map((historyevent) => { return historyevent.resourceArn; }); const serviceUtil = utilization[service]; const actionFilteredServiceUtil = Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => { if(resourcesInProgress.includes(id)){ delete aggUtil[id]; return aggUtil; } const filteredScenarios: Scenarios<string> = {}; Object.entries(resource.scenarios).forEach(([sType, details]) => { if (Object.hasOwn(details, actionType)) { filteredScenarios[sType] = details; } }); if (!filteredScenarios || isEmpty(filteredScenarios)) { return aggUtil; } aggUtil[id] = { ...resource, scenarios: filteredScenarios }; return aggUtil; }, {}); return actionFilteredServiceUtil; } export function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(filtered).forEach((s) => { if (!filtered[s] || isEmpty(filtered[s])) return; total += Object.keys(filtered[s]).length; }); return total; }
export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {
const result: { [ key in ActionType ]: number } = { [ActionType.OPTIMIZE]: 0, [ActionType.DELETE]: 0, [ActionType.SCALE_DOWN]: 0 }; session.forEach((historyEvent) => { result[historyEvent.actionType] ++; }); return result; } export function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; total += Object.keys(utilization[service]).length; }); return total; } export function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); let totalSavings = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; Object.keys(utilization[service]).forEach((resource) => { totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0; }); }); return usd.format(totalSavings); } export function sentenceCase (name: string): string { const result = name.replace(/([A-Z])/g, ' $1'); return result[0].toUpperCase() + result.substring(1).toLowerCase(); } export function splitServiceName (name: string) { return name?.split(/(?=[A-Z])/).join(' '); }
src/utils/utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/components/recommendation-overview.tsx", "retrieved_chunk": " </Box>\n </SimpleGrid>\n );\n}\nfunction getTotalRecommendationValues (\n utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[]\n) { \n const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);\n const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const totalResources = getTotalNumberOfResources(utilizations);", "score": 0.8386325836181641 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.7949214577674866 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.7948991060256958 }, { "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": 0.7928104996681213 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n toJson (): AwsUtilizationProviderProps {\n return {\n ...super.toJson(),\n services: this.services,\n utilization: this.utilization\n };\n }\n initServices (services: AwsResourceType[]) {\n this.services = services;", "score": 0.7857565879821777 } ]
typescript
export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } {
import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { AwsServiceUtilization } from './aws-service-utilization.js'; import { AwsServiceOverrides } from '../types/types.js'; import { RDS, DBInstance, DescribeDBInstancesCommandOutput } from '@aws-sdk/client-rds'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { Pricing } from '@aws-sdk/client-pricing'; import get from 'lodash.get'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { getHourlyCost } from '../utils/utils.js'; const oneMonthAgo = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000)); // monthly costs type StorageAndIOCosts = { totalStorageCost: number, iopsCost: number, throughputCost?: number }; // monthly costs type RdsCosts = StorageAndIOCosts & { totalCost: number, instanceCost: number } type RdsMetrics = { totalIops: number; totalThroughput: number; freeStorageSpace: number; totalBackupStorageBilled: number; cpuUtilization: number; databaseConnections: number; }; export type rdsInstancesUtilizationScenarios = 'hasDatabaseConnections' | 'cpuUtilization' | 'shouldScaleDownStorage' | 'hasAutoScalingEnabled'; const rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization']; export class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> { private instanceCosts: { [instanceId: string]: RdsCosts }; private rdsClient: RDS; private cwClient: CloudWatch; private pricingClient: Pricing; private region: string; async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteInstance') { const rdsClient = new RDS({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split(':').at(-1); await this.deleteInstance(rdsClient, resourceId); } } constructor () { super(); this.instanceCosts = {}; } async deleteInstance (rdsClient: RDS, dbInstanceIdentifier: string){ await rdsClient.deleteDBInstance({ DBInstanceIdentifier: dbInstanceIdentifier }); } async getRdsInstanceMetrics (dbInstance: DBInstance): Promise<RdsMetrics> { const res = await this.cwClient.getMetricData({ MetricDataQueries: [ { Id: 'readIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeIops', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteIOPS', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'readThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'ReadThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'writeThroughput', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'WriteThroughput', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'freeStorageSpace', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'FreeStorageSpace', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'totalBackupStorageBilled', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'TotalBackupStorageBilled', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Average' } }, { Id: 'cpuUtilization', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'CPUUtilization', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Maximum', Unit: 'Percent' } }, { Id: 'databaseConnections', MetricStat: { Metric: { Namespace: 'AWS/RDS', MetricName: 'DatabaseConnections', Dimensions: [{ Name: 'DBInstanceIdentifier', Value: dbInstance.DBInstanceIdentifier }] }, Period: 30 * 24 * 12 * 300, // 1 month, Stat: 'Sum' } } ], StartTime: oneMonthAgo, EndTime: new Date() }); const readIops = get(res, 'MetricDataResults[0].Values[0]', 0); const writeIops = get(res, 'MetricDataResults[1].Values[0]', 0); const readThroughput = get(res, 'MetricDataResults[2].Values[0]', 0); const writeThroughput = get(res, 'MetricDataResults[3].Values[0]', 0); const freeStorageSpace = get(res, 'MetricDataResults[4].Values[0]', 0); const totalBackupStorageBilled = get(res, 'MetricDataResults[5].Values[0]', 0); const cpuUtilization = get(res, 'MetricDataResults[6].Values[6]', 0); const databaseConnections = get(res, 'MetricDataResults[7].Values[0]', 0); return { totalIops: readIops + writeIops, totalThroughput: readThroughput + writeThroughput, freeStorageSpace, totalBackupStorageBilled, cpuUtilization, databaseConnections }; } private getAuroraCosts ( storageUsedInGB: number, totalBackupStorageBilled: number, totalIops: number ): StorageAndIOCosts { const storageCost = storageUsedInGB * 0.10; const backupStorageCost = (totalBackupStorageBilled / ONE_GB_IN_BYTES) * 0.021; const iopsCost = (totalIops / 1000000) * 0.20; // per 1 million requests return { totalStorageCost: storageCost + backupStorageCost, iopsCost }; } private getOtherDbCosts ( dbInstance: DBInstance, storageUsedInGB: number, totalIops: number, totalThroughput: number ): StorageAndIOCosts { let storageCost = 0; let iopsCost = 0; let throughputCost = 0; if (dbInstance.StorageType === 'gp2') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; } else { storageCost = storageUsedInGB * 0.115; } } else if (dbInstance.StorageType === 'gp3') { if (dbInstance.MultiAZ) { storageCost = storageUsedInGB * 0.23; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.04 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.160 : 0; } else { storageCost = storageUsedInGB * 0.115; iopsCost = totalIops > 3000 ? (totalIops - 3000) * 0.02 : 0; // verify throughput metrics are in MB/s throughputCost = totalThroughput > 125 ? (totalThroughput - 125) * 0.080 : 0; } } else { if (dbInstance.MultiAZ) { storageCost = (dbInstance.AllocatedStorage || 0) * 0.25; iopsCost = (dbInstance.Iops || 0) * 0.20; } else { storageCost = (dbInstance.AllocatedStorage || 0) * 0.125; iopsCost = (dbInstance.Iops || 0) * 0.10; } } return { totalStorageCost: storageCost, iopsCost, throughputCost }; } private getStorageAndIOCosts (dbInstance: DBInstance, metrics: RdsMetrics) { const { totalIops, totalThroughput, freeStorageSpace, totalBackupStorageBilled } = metrics; const dbInstanceClass = dbInstance.DBInstanceClass; const storageUsedInGB = dbInstance.AllocatedStorage ? dbInstance.AllocatedStorage - (freeStorageSpace / ONE_GB_IN_BYTES) : 0; if (dbInstanceClass.startsWith('aurora')) { return this.getAuroraCosts(storageUsedInGB, totalBackupStorageBilled, totalIops); } else { // mysql, postgresql, mariadb, oracle, sql server return this.getOtherDbCosts(dbInstance, storageUsedInGB, totalIops, totalThroughput); } } /* easier to hard code for now but saving for later * volumeName is instance.storageType * need to call for Provisioned IOPS and Database Storage async getRdsStorageCost () { const res = await pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'volumeName', Value: 'io1' }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: 'us-east-1' }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: 'Single-AZ' }, { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'Provisioned IOPS' }, ] }); } */ // TODO: implement serverless cost? // TODO: implement i/o optimized cost? async getRdsInstanceCosts (dbInstance: DBInstance, metrics: RdsMetrics) { if (dbInstance.DBInstanceIdentifier in this.instanceCosts) { return this.instanceCosts[dbInstance.DBInstanceIdentifier]; } let dbEngine = ''; if (dbInstance.Engine.startsWith('aurora')) { if (dbInstance.Engine.endsWith('mysql')) { dbEngine = 'Aurora MySQL'; } else { dbEngine = 'Aurora PostgreSQL'; } } else { dbEngine = dbInstance.Engine; } try { const res = await this.pricingClient.getProducts({ ServiceCode: 'AmazonRDS', Filters: [ { Type: 'TERM_MATCH', Field: 'instanceType', Value: dbInstance.DBInstanceClass }, { Type: 'TERM_MATCH', Field: 'regionCode', Value: this.region }, { Type: 'TERM_MATCH', Field: 'databaseEngine', Value: dbEngine }, { Type: 'TERM_MATCH', Field: 'deploymentOption', Value: dbInstance.MultiAZ ? 'Multi-AZ' : 'Single-AZ' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; const instanceCost = pricePerHour * 24 * 30; const { totalStorageCost, iopsCost, throughputCost = 0 } = this.getStorageAndIOCosts(dbInstance, metrics); const totalCost = instanceCost + totalStorageCost + iopsCost + throughputCost; const rdsCosts = { totalCost, instanceCost, totalStorageCost, iopsCost, throughputCost } as RdsCosts; this.instanceCosts[dbInstance.DBInstanceIdentifier] = rdsCosts; return rdsCosts; } catch (e) { return { totalCost: 0, instanceCost: 0, totalStorageCost: 0, iopsCost: 0, throughputCost: 0 } as RdsCosts; } } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides ): Promise<void> { const credentials = await awsCredentialsProvider.getCredentials(); this.region = regions[0]; this.rdsClient = new RDS({ credentials, region: this.region }); this.cwClient = new CloudWatch({ credentials, region: this.region }); this.pricingClient = new Pricing({ credentials, region: this.region }); let dbInstances: DBInstance[] = []; let describeDBInstancesRes: DescribeDBInstancesCommandOutput; do { describeDBInstancesRes = await this.rdsClient.describeDBInstances({}); dbInstances = [ ...dbInstances, ...describeDBInstancesRes.DBInstances ]; } while (describeDBInstancesRes?.Marker); for (const dbInstance of dbInstances) { const dbInstanceId = dbInstance.DBInstanceIdentifier; const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId; const metrics = await this.getRdsInstanceMetrics(dbInstance); await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn); await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn); await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn); const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost; await this.fillData(dbInstanceArn, credentials, this.region, { resourceId: dbInstanceId, region: this.region, monthlyCost, hourlyCost: getHourlyCost(monthlyCost) }); rdsInstanceMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, this.region, dbInstanceId, 'AWS/RDS', metricName, [{ Name: 'DBInstanceIdentifier', Value: dbInstanceId }]); }); } } async getDatabaseConnections (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (!metrics.databaseConnections) { const { totalCost } = await this.getRdsInstanceCosts(dbInstance, metrics); this
.addScenario(dbInstanceArn, 'hasDatabaseConnections', {
value: 'false', delete: { action: 'deleteInstance', isActionable: true, reason: 'This instance does not have any db connections', monthlySavings: totalCost } }); } } async checkInstanceStorage (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string) { //if theres a maxallocatedstorage then storage auto-scaling is enabled if(!dbInstance.MaxAllocatedStorage){ await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'hasAutoScalingEnabled', { value: 'false', optimize: { action: '', //didnt find an action for this, need to do it in the console isActionable: false, reason: 'This instance does not have storage auto-scaling turned on', monthlySavings: 0 } }); } if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', { value: 'true', scaleDown: { action: '', isActionable: false, reason: 'This instance has more than half of its allocated storage still available', monthlySavings: 0 } }); } } async getCPUUtilization (metrics: RdsMetrics, dbInstance: DBInstance, dbInstanceArn: string){ if (metrics.cpuUtilization < 50) { await this.getRdsInstanceCosts(dbInstance, metrics); this.addScenario(dbInstanceArn, 'cpuUtilization', { value: metrics.cpuUtilization.toString(), scaleDown: { action: '', isActionable: false, reason: 'Max CPU Utilization is under 50%', monthlySavings: 0 } }); } } }
src/service-utilizations/rds-utilization.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.846088171005249 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.8447879552841187 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " {\n Id: AVG_NETWORK_BYTES_OUT,\n MetricStat: metricStat('NetworkOut', 'Average')\n }\n ];\n }\n private async getInstanceTypes (instanceTypeNames: string[], ec2Client: EC2): Promise<InstanceTypeInfo[]> {\n const instanceTypes = [];\n let nextToken;\n do {", "score": 0.8379496932029724 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8270428776741028 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8269238471984863 } ]
typescript
.addScenario(dbInstanceArn, 'hasDatabaseConnections', {
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": " function onRegionChange (region: string) {\n overridesCallback({\n region\n });\n }\n return (\n <UtilizationRecommendationsUi\n utilization={this.utilization || {}}\n sessionHistory={this.sessionHistory}\n onResourcesAction={onResourcesAction}", "score": 0.8420417308807373 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " const numOptimizeChanges = getNumberOfResourcesFromFilteredActions(optimizeChanges);\n const inProgressActions = getNumberOfResourcesInProgress(sessionHistory);\n function actionSummaryStack (\n actionType: ActionType, icon: JSX.Element, actionLabel: string, \n numResources: number, description: string, numResourcesInProgress: number\n ) {\n return (\n <Stack w=\"100%\" p='2' pl='5' pr='5'>\n <Flex>\n <Box w='20px'>", "score": 0.8257409334182739 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { CHECKBOX_CELL_MAX_WIDTH } from './recommendations-table.js';\nimport { splitServiceName } from '../../utils/utilization.js';\nexport default function ServiceTableRow (props: ServiceTableRowProps) {\n const { serviceUtil, serviceName, children, isChecked, onServiceCheckChange } = props;\n const { isOpen, onToggle } = useDisclosure();\n return (\n <React.Fragment>\n <Tr key={serviceName}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox ", "score": 0.8061572909355164 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " resourceArns: string[];\n onBack: () => void;\n};\nexport type ServiceTableRowProps = {\n serviceUtil: Utilization<string>;\n serviceName: string;\n children?: React.ReactNode;\n onServiceCheckChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n isChecked: boolean;\n};", "score": 0.7917917966842651 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": "}\nexport function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) {\n const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props;\n const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY);\n const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]);\n const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE);\n if (wizardStep === WizardSteps.SUMMARY) {\n return (\n <RecommendationsActionSummary\n utilization={utilization}", "score": 0.7905802726745605 } ]
typescript
RecommendationOverview utilizations={this.utilization} sessionHistory={this.sessionHistory}/> </Stack> );
/* 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": " 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": 0.8891353607177734 }, { "filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx", "retrieved_chunk": " aria-label={'downCaret'}\n leftIcon={<ChevronDownIcon/>}\n size='lg'\n colorScheme='black'\n >\n Related Resources\n </Button>\n <Spacer/>\n <Table size='sm' marginTop='12px'>\n <Thead>", "score": 0.8551938533782959 }, { "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": 0.8288365006446838 }, { "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": 0.8286239504814148 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.8226000070571899 } ]
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/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.8245959281921387 }, { "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": 0.8209330439567566 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8206053972244263 }, { "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": 0.8148412704467773 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " 'hasAutoScalingEnabled';\nconst rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization'];\nexport class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> {\n private instanceCosts: { [instanceId: string]: RdsCosts };\n private rdsClient: RDS;\n private cwClient: CloudWatch;\n private pricingClient: Pricing;\n private region: string;\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string", "score": 0.8128104209899902 } ]
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": 0.8376790285110474 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.8363240957260132 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " <Text fontSize='sm' color='gray.500'>$19625</Text>\n <br />\n </Stack> */}\n <Spacer />\n <Stack>\n {/* TODO */}\n {/* <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel}</Button> */}\n <Button variant='link' size='sm' onClick={() => onRemoveResource(resourceArn)}>\n {'Don\\'t ' + actionTypeText[actionType]}\n </Button>", "score": 0.8270790576934814 }, { "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": 0.8260842561721802 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.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\n onClick={() => props.onContinue(checkedResources)}\n colorScheme='red'\n size='sm'", "score": 0.8235132694244385 } ]
typescript
{allRegions.map(region => <MenuItem onClick={() => onRegionChange(region)}>{region}</MenuItem> )}
/* 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": 0.8392272591590881 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8114492297172546 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.7996383905410767 }, { "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": 0.7982861399650574 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": "export function ConfirmRecommendations (props: ConfirmRecommendationsProps) {\n const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props;\n const { isOpen, onOpen, onClose } = useDisclosure();\n const [confirmationText, setConfirmationText] = useState<string>('');\n const [error, setError] = useState<string | undefined>(undefined);\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const resourceFilteredServices = new Set<string>();\n Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => {\n for (const resourceArn of resourceArns) {", "score": 0.7964717149734497 } ]
typescript
{sentenceCase(th)}
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/confirm-single-recommendation.tsx", "retrieved_chunk": " <Text fontSize='sm' color='gray.500'>$19625</Text>\n <br />\n </Stack> */}\n <Spacer />\n <Stack>\n {/* TODO */}\n {/* <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel}</Button> */}\n <Button variant='link' size='sm' onClick={() => onRemoveResource(resourceArn)}>\n {'Don\\'t ' + actionTypeText[actionType]}\n </Button>", "score": 0.813430666923523 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " const { isOpen, onClose } = useDisclosure();\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1) + ' now';\n return (\n <Stack w=\"100%\" pb='2' pt='2'>\n <Flex>\n <Stack>\n <Text>{resourceArn}</Text>\n </Stack>\n {/* TODO */}\n {/* <Stack>", "score": 0.8121503591537476 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " return Object.keys(serviceUtil).map(resArn => (\n <>\n <Tr key={resArn}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox\n isChecked={checkedResources.includes(resArn)}\n onChange={onResourceCheckChange(resArn, serviceName)} />\n </Td>\n <Td\n maxW={RESOURCE_PROPERTY_MAX_WIDTH}", "score": 0.79457688331604 }, { "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": 0.7914560437202454 }, { "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": 0.7890938520431519 } ]
typescript
ConfirmSingleRecommendation resourceArn={rarn}
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/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.8571752309799194 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.8460502624511719 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " actionTypeToEnum[actionType],\n resourceArn,\n get(resource.data, 'region', 'us-east-1')\n );\n }\n }\n }\n }\n }\n render (_children: any, overridesCallback?: (overrides: RecommendationsOverrides) => void) {", "score": 0.8419712781906128 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8397691249847412 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8390506505966187 } ]
typescript
_overridesCallback?: (overrides: AwsUtilizationOverrides) => void ): JSX.Element {
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-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.9228839874267578 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.9043997526168823 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.9042090177536011 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.8967258334159851 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8898200392723083 } ]
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": " serviceUtil={serviceUtil}\n children={resourcesTable(service, serviceUtil)}\n key={service + 'table'}\n onServiceCheckChange={onServiceCheckChange(service)}\n isChecked={checkedServices.includes(service)}\n />\n );\n }\n function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) {\n const tableHeadersSet = new Set<string>();", "score": 0.7862515449523926 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " colorScheme='red'\n size='sm'\n onClick={() => {\n onResourcesAction([resourceArn], actionType);\n onRemoveResource(resourceArn);\n }}\n >\n {actionLabel}\n </Button>\n </ModalBody>", "score": 0.7843930721282959 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " function onRegionChange (region: string) {\n overridesCallback({\n region\n });\n }\n return (\n <UtilizationRecommendationsUi\n utilization={this.utilization || {}}\n sessionHistory={this.sessionHistory}\n onResourcesAction={onResourcesAction}", "score": 0.7710490226745605 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": " onRemoveResource: (resourceArn: string) => void;\n}\ninterface HasResourcesAction {\n onResourcesAction: (resourceArns: string[], actionType: string) => void;\n}\ninterface Refresh {\n onRefresh: () => void;\n}\nexport type UtilizationRecommendationsWidget = Widget & HasActionType & HasUtilization & {\n region: string", "score": 0.7672920227050781 }, { "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": 0.7637253999710083 } ]
typescript
={(checkedResources) => {
import isEmpty from 'lodash.isempty'; import { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js'; export function filterUtilizationForActionType ( utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[] ): { [service: string]: Utilization<string> } { const filtered: { [service: string]: Utilization<string> } = {}; if (!utilization) { return filtered; } Object.keys(utilization).forEach((service) => { filtered[service] = filterServiceForActionType(utilization, service, actionType, session); }); return filtered; } export function filterServiceForActionType ( utilization: { [service: string]: Utilization<string> }, service: string, actionType: ActionType, session: HistoryEvent[] ) { const resourcesInProgress = session.map((historyevent) => { return historyevent.resourceArn; }); const serviceUtil = utilization[service]; const actionFilteredServiceUtil = Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => { if(resourcesInProgress.includes(id)){ delete aggUtil[id]; return aggUtil; } const filteredScenarios: Scenarios<string> = {}; Object.entries(resource.scenarios).forEach(([sType, details]) => { if (Object
.hasOwn(details, actionType)) {
filteredScenarios[sType] = details; } }); if (!filteredScenarios || isEmpty(filteredScenarios)) { return aggUtil; } aggUtil[id] = { ...resource, scenarios: filteredScenarios }; return aggUtil; }, {}); return actionFilteredServiceUtil; } export function getNumberOfResourcesFromFilteredActions (filtered: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(filtered).forEach((s) => { if (!filtered[s] || isEmpty(filtered[s])) return; total += Object.keys(filtered[s]).length; }); return total; } export function getNumberOfResourcesInProgress (session: HistoryEvent[]): { [ key in ActionType ]: number } { const result: { [ key in ActionType ]: number } = { [ActionType.OPTIMIZE]: 0, [ActionType.DELETE]: 0, [ActionType.SCALE_DOWN]: 0 }; session.forEach((historyEvent) => { result[historyEvent.actionType] ++; }); return result; } export function getTotalNumberOfResources ( utilization: { [service: string]: Utilization<string> }): number { let total = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; total += Object.keys(utilization[service]).length; }); return total; } export function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); let totalSavings = 0; Object.keys(utilization).forEach((service) => { if (!utilization[service] || isEmpty(utilization[service])) return; Object.keys(utilization[service]).forEach((resource) => { totalSavings += utilization[service][resource].data?.maxMonthlySavings || 0; }); }); return usd.format(totalSavings); } export function sentenceCase (name: string): string { const result = name.replace(/([A-Z])/g, ' $1'); return result[0].toUpperCase() + result.substring(1).toLowerCase(); } export function splitServiceName (name: string) { return name?.split(/(?=[A-Z])/).join(' '); }
src/utils/utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.8351455926895142 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.8263740539550781 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.8043291568756104 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.7659010887145996 }, { "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": 0.7613940238952637 } ]
typescript
.hasOwn(details, actionType)) {
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {
SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })}
</Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " colorScheme='red'\n size='sm'\n onClick={() => {\n onResourcesAction([resourceArn], actionType);\n onRemoveResource(resourceArn);\n }}\n >\n {actionLabel}\n </Button>\n </ModalBody>", "score": 0.7910110354423523 }, { "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": 0.7682012319564819 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n {resourceFilteredServiceTables}\n </Box>\n <Modal isOpen={isOpen} onClose={() => {\n setError(undefined);\n setConfirmationText(undefined);\n onClose();\n }}>\n <ModalOverlay />\n <ModalContent>", "score": 0.7505910992622375 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " <Menu>\n <MenuButton as={Button} rightIcon={<ChevronDownIcon />}>\n {regionLabel}\n </MenuButton>\n <MenuList minW=\"0\" w={150} h={40} sx={{ overflow:'scroll' }}>\n {allRegions.map(region => \n <MenuItem onClick={() => onRegionChange(region)}>{region}</MenuItem>\n )}\n </MenuList>\n </Menu>", "score": 0.7490025162696838 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.7468559145927429 } ]
typescript
SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })}
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <ServiceTableRow serviceName={service} serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {
SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })}
</Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx", "retrieved_chunk": " aria-label={'downCaret'}\n leftIcon={<ChevronDownIcon/>}\n size='lg'\n colorScheme='black'\n >\n Related Resources\n </Button>\n <Spacer/>\n <Table size='sm' marginTop='12px'>\n <Thead>", "score": 0.8551004528999329 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": " aria-label={isOpen ? 'upCaret' : 'downCaret'}\n rightIcon={isOpen ? <ChevronUpIcon />: <ChevronDownIcon/>}\n size='sm'\n colorScheme='purple'\n fontWeight='1px'\n >\n {isOpen ? 'Hide resources' : 'Show resources'}\n </Button>\n </Td>\n </Tr>", "score": 0.8505392670631409 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " <Box>\n <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> \n { <><ArrowBackIcon /> Back </> } \n </Button>\n </Box>\n <Box>\n <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel} all</Button>\n </Box>\n </Flex>\n <hr />", "score": 0.8405407071113586 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " colorScheme='red'\n size='sm'\n onClick={() => {\n onResourcesAction([resourceArn], actionType);\n onRemoveResource(resourceArn);\n }}\n >\n {actionLabel}\n </Button>\n </ModalBody>", "score": 0.8341352939605713 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-single-recommendation.tsx", "retrieved_chunk": " <Text fontSize='sm' color='gray.500'>$19625</Text>\n <br />\n </Stack> */}\n <Spacer />\n <Stack>\n {/* TODO */}\n {/* <Button colorScheme='red' size='sm' onClick={onOpen}>{actionLabel}</Button> */}\n <Button variant='link' size='sm' onClick={() => onRemoveResource(resourceArn)}>\n {'Don\\'t ' + actionTypeText[actionType]}\n </Button>", "score": 0.8159555792808533 } ]
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/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.8398751020431519 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8323190808296204 }, { "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": 0.8263589143753052 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " 'hasAutoScalingEnabled';\nconst rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization'];\nexport class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> {\n private instanceCosts: { [instanceId: string]: RdsCosts };\n private rdsClient: RDS;\n private cwClient: CloudWatch;\n private pricingClient: Pricing;\n private region: string;\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string", "score": 0.8250642418861389 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.8116426467895508 } ]
typescript
serviceUtil: Utilization<string>;
/* eslint-disable max-len */ import React, { useState } from 'react'; import { Box, Button, Checkbox, Flex, Heading, Spacer, Stack, Table, TableContainer, Tbody, Td, Th, Thead, Tooltip, Tr, Icon } from '@chakra-ui/react'; import { ArrowBackIcon } from '@chakra-ui/icons'; import { TbRefresh } from 'react-icons/tb/index.js'; import isEmpty from 'lodash.isempty'; import ServiceTableRow from './service-table-row.js'; import { Utilization, actionTypeText, ActionType } from '../../types/types.js'; import { filterUtilizationForActionType, sentenceCase, splitServiceName } from '../../utils/utilization.js'; import { RecommendationsTableProps } from '../../types/utilization-recommendations-types.js'; import { Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeader, DrawerBody } from '@chakra-ui/react'; import { ChevronDownIcon, InfoIcon, ExternalLinkIcon } from '@chakra-ui/icons'; import SidePanelMetrics from './side-panel-usage.js'; import SidePanelRelatedResources from './side-panel-related-resources.js'; export const CHECKBOX_CELL_MAX_WIDTH = '16px'; export const RESOURCE_PROPERTY_MAX_WIDTH = '100px'; const RESOURCE_VALUE_MAX_WIDTH = '170px'; export function RecommendationsTable (props: RecommendationsTableProps) { const { utilization, actionType, onRefresh, sessionHistory } = props; const [checkedResources, setCheckedResources] = useState<string[]>([]); const [checkedServices, setCheckedServices] = useState<string[]>([]); const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined); const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined); const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined); const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory); const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); // #region actions function onServiceCheckChange (serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { const cascadedCheckedResources = [...checkedResources]; Object.keys(filteredServices[serviceName]).forEach((resArn) => { if (!cascadedCheckedResources.includes(resArn)) { cascadedCheckedResources.push(resArn); } }); setCheckedResources(cascadedCheckedResources); setCheckedServices([...checkedServices, serviceName]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => !filteredServices[serviceName][id])); } }; } function onResourceCheckChange (resArn: string, serviceName: string) { return (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.checked) { setCheckedResources([...checkedResources, resArn]); } else { setCheckedServices(checkedServices.filter(s => s !== serviceName)); setCheckedResources(checkedResources.filter(id => id !== resArn)); } }; } // #endregion // #region render function serviceTableRow (service: string) { const serviceUtil = filteredServices[service]; if (!serviceUtil || isEmpty(serviceUtil)) { return <></>; } return ( <
ServiceTableRow serviceName={service}
serviceUtil={serviceUtil} children={resourcesTable(service, serviceUtil)} key={service + 'table'} onServiceCheckChange={onServiceCheckChange(service)} isChecked={checkedServices.includes(service)} /> ); } function resourcesTable (serviceName: string, serviceUtil: Utilization<string>) { const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; const tableHeadersDom = actionType === ActionType.DELETE ? [...tableHeaders].map(th => <Th key={th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden'> {sentenceCase(th)} </Th> ): undefined; const taskRows = Object.keys(serviceUtil).map(resArn => ( <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > {serviceUtil[resArn]?.data?.resourceId || resArn} </Tooltip> </Td> {tableHeaders.map(th => <Td key={resArn + 'scenario' + th} maxW={RESOURCE_VALUE_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn].scenarios[th] ? serviceUtil[resArn].scenarios[th][actionType]?.reason : undefined } aria-label='A tooltip' bg='purple.400' color='white' > <Box> {serviceUtil[resArn].scenarios[th]?.value || null} {serviceUtil[resArn].scenarios[th]?.value ? <InfoIcon marginLeft={'8px'} color='black' />: null} </Box> </Tooltip> </Td> )} <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.monthlyCost ? usd.format(serviceUtil[resArn].data.monthlyCost) : 'Coming soon!' } </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > { serviceUtil[resArn]?.data?.hourlyCost ? usd.format(serviceUtil[resArn].data.hourlyCost) : 'Coming soon!' } </Td> <Td> <Button variant='link' onClick={ () => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); }} size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> )); return ( <Stack key={serviceName + 'resource-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table variant="simple"> <Thead bgColor="gray.50"> <Tr> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Resource ID</Th> {tableHeadersDom} <Th>Estimated Cost/Mo</Th> <Th>Estimated Cost/Hr</Th> <Th /> </Tr> </Thead> <Tbody>{actionType === ActionType.DELETE ? taskRows: taskRowsForOptimize(serviceName, serviceUtil)}</Tbody> </Table> </TableContainer> </Stack> ); } function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){ const tableHeadersSet = new Set<string>(); Object.keys(serviceUtil).forEach(resArn => Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s)) ); const tableHeaders = [...tableHeadersSet]; return Object.keys(serviceUtil).map(resArn => ( <> <Tr key={resArn}> <Td w={CHECKBOX_CELL_MAX_WIDTH}> <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Tooltip label={serviceUtil[resArn]?.data?.resourceId || resArn} aria-label='A tooltip' bg='purple.400' color='white' > { serviceUtil[resArn]?.data?.resourceId || resArn } </Tooltip> </Td> <Td key={resArn + 'cost/mo'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.monthlyCost)} </Td> <Td key={resArn + 'cost/hr'} maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > {usd.format(serviceUtil[resArn].data.hourlyCost)} </Td> <Td maxW={RESOURCE_PROPERTY_MAX_WIDTH} overflow='hidden' textOverflow='ellipsis' > <Button variant='link' onClick={() => { setShowSideModal(true); setSidePanelResourceArn(resArn); setSidePanelService(serviceName); } } size='sm' colorScheme='purple' fontWeight='1px' > {'Details'} </Button> </Td> </Tr> <Tr> <Td colSpan={4}> <Stack key={'optimize-task-rows-table'}> <TableContainer border="1px" borderRadius="6px" borderColor="gray.100" > <Table size='sm'> <Tbody> {tableHeaders.map(th => serviceUtil[resArn].scenarios[th] && serviceUtil[resArn].scenarios[th][actionType]?.reason && ( <Tr> <Td w={CHECKBOX_CELL_MAX_WIDTH}> { ( isEmpty(serviceUtil[resArn].scenarios[th][actionType]?.action) || !serviceUtil[resArn].scenarios[th][actionType]?.isActionable ) ? <Checkbox isDisabled/> : <Checkbox isChecked={checkedResources.includes(resArn)} onChange={onResourceCheckChange(resArn, serviceName)} /> } </Td> <Td key={resArn + 'scenario' + th} > { serviceUtil[resArn].scenarios[th][actionType]?.reason } </Td> </Tr> ) )} </Tbody> </Table> </TableContainer> </Stack> </Td> </Tr> </> )); } function table () { if (!utilization || isEmpty(utilization)) { return <>No recommendations available!</>; } return ( <TableContainer border="1px" borderColor="gray.100"> <Table variant="simple"> <Thead bgColor="gray.50"> <Th w={CHECKBOX_CELL_MAX_WIDTH}></Th> <Th>Service</Th> <Th># Resources</Th> <Th>Details</Th> </Thead> <Tbody> {Object.keys(utilization).map(serviceTableRow)} </Tbody> </Table> </TableContainer> ); } function sidePanel (){ const serviceUtil = sidePanelService && filteredServices[sidePanelService]; const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data; //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination']; const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => ( <Box bg="#EDF2F7" p={2} color="black" marginBottom='8px'> <InfoIcon marginRight={'8px'} /> {serviceUtil[sidePanelResourceArn].scenarios[scenario][actionType].reason} </Box> )); return ( <Drawer isOpen={showSideModal} onClose={() => { setShowSideModal(false); }} placement='right' size='xl' > <DrawerOverlay /> <DrawerContent marginTop='50px'> <DrawerCloseButton /> <DrawerHeader> <Flex> <Box> <Heading fontSize='xl'> { splitServiceName(sidePanelService)} </Heading> </Box> <Spacer/> <Box marginRight='40px'> <Button colorScheme='orange' size='sm' rightIcon={<ExternalLinkIcon />} /*onClick={ () => { window.open(getAwsLink(data.resourceId || sidePanelResourceArn, sidePanelService as AwsResourceType, data?.region)); }}*/ > View in AWS </Button> </Box> </Flex> </DrawerHeader> <DrawerBody> <TableContainer> <Table size='sm'> <Thead> <Tr> <Th maxW={'250px'} overflow='hidden' textOverflow='ellipsis' textTransform='none' > {data?.resourceId || sidePanelResourceArn} </Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.region}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.monthlyCost ? usd.format(data.monthlyCost) : 'Coming soon!'}</Th> <Th maxW={RESOURCE_PROPERTY_MAX_WIDTH} textTransform='none'> {data?.hourlyCost ? usd.format(data.hourlyCost) : 'Coming soon!'}</Th> </Tr> </Thead> <Tbody> <Tr> <Td color='gray.500'>Resource ID</Td> <Td color='gray.500'> Region </Td> <Td color='gray.500'> Cost/mo </Td> <Td color='gray.500'> Cost/hr </Td> </Tr> </Tbody> </Table> </TableContainer> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Adjustments </Button> {adjustments} </Box> <Box marginTop='20px'> <Button variant='ghost' aria-label={'downCaret'} leftIcon={<ChevronDownIcon/>} size='lg' colorScheme='black' > Usage </Button> </Box> <Box> {SidePanelMetrics({ metrics: serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics })} </Box> <Box> {SidePanelRelatedResources({ data: serviceUtil && serviceUtil[sidePanelResourceArn]?.data })} </Box> <Flex pt='1'> <Spacer/> <Spacer/> </Flex> </DrawerBody> </DrawerContent> </Drawer> ); } return ( <Stack pt="3" pb="3" w="100%"> <Flex pl='4' pr='4'> <Box> <Heading as='h4' size='md'>Review resources to {actionTypeText[actionType]}</Heading> </Box> <Button colorScheme="purple" variant="outline" marginLeft={'8px'} size='sm' border='0px' onClick={() => onRefresh()} > <Icon as={TbRefresh} /> </Button> <Spacer /> <Box> <Button colorScheme='gray' size='sm' marginRight={'8px'} onClick={() => props.onBack()}> { <><ArrowBackIcon /> Back </> } </Button> </Box> <Box> <Button onClick={() => props.onContinue(checkedResources)} colorScheme='red' size='sm' > Continue </Button> </Box> </Flex> <Stack pb='2' w="100%"> {table()} </Stack> {sidePanel()} </Stack> ); // #endregion }
src/widgets/utilization-recommendations-ui/recommendations-table.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": " if (Object.hasOwn(serviceUtil, resourceArn)) {\n resourceFilteredServices.add(serviceName);\n break;\n }\n }\n });\n const resourceFilteredServiceTables = [...resourceFilteredServices].map((s) => {\n return (\n <Box borderRadius='6px' key={s} mb='3'>\n <HStack bgColor='gray.50' p='1'>", "score": 0.8310794830322266 }, { "filename": "src/widgets/utilization-recommendations-ui/service-table-row.tsx", "retrieved_chunk": "import { CHECKBOX_CELL_MAX_WIDTH } from './recommendations-table.js';\nimport { splitServiceName } from '../../utils/utilization.js';\nexport default function ServiceTableRow (props: ServiceTableRowProps) {\n const { serviceUtil, serviceName, children, isChecked, onServiceCheckChange } = props;\n const { isOpen, onToggle } = useDisclosure();\n return (\n <React.Fragment>\n <Tr key={serviceName}>\n <Td w={CHECKBOX_CELL_MAX_WIDTH}>\n <Checkbox ", "score": 0.8267698287963867 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n async getUtilization (\n credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n if (serviceOverrides?.forceRefesh) {\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );", "score": 0.8030838966369629 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n toJson (): AwsUtilizationProviderProps {\n return {\n ...super.toJson(),\n services: this.services,\n utilization: this.utilization\n };\n }\n initServices (services: AwsResourceType[]) {\n this.services = services;", "score": 0.800139307975769 }, { "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": 0.7974632978439331 } ]
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": 0.9226229786872864 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 0.9181445837020874 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " Namespace: 'AWS/EC2',\n MetricName: metricName,\n Dimensions: [{\n Name: 'InstanceId',\n Value: instanceId\n }]\n },\n Period: period,\n Stat: statistic\n };", "score": 0.8511773347854614 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'\n }\n },\n {\n Id: 'bytesOutToDestination',\n MetricStat: {", "score": 0.8400024771690369 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Maximum'\n }\n },\n {\n Id: 'bytesInFromDestination',\n MetricStat: {", "score": 0.8364304304122925 } ]
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/recommendations-table.tsx", "retrieved_chunk": " </>\n ));\n }\n function table () {\n if (!utilization || isEmpty(utilization)) {\n return <>No recommendations available!</>;\n }\n return (\n <TableContainer border=\"1px\" borderColor=\"gray.100\">\n <Table variant=\"simple\">", "score": 0.80255526304245 }, { "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": 0.7931649684906006 }, { "filename": "src/widgets/utilization-recommendations-ui/side-panel-related-resources.tsx", "retrieved_chunk": " </Table>\n </Box> : null;\n return ( \n <Stack>\n {relatedResourcesSection}\n {tagsSection}\n </Stack>\n );\n}", "score": 0.7890017628669739 }, { "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": 0.787172794342041 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " function onRegionChange (region: string) {\n overridesCallback({\n region\n });\n }\n return (\n <UtilizationRecommendationsUi\n utilization={this.utilization || {}}\n sessionHistory={this.sessionHistory}\n onResourcesAction={onResourcesAction}", "score": 0.7842803001403809 } ]
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": 0.8807001709938049 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings\n }\n });\n }\n }\n }\n async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) {\n const response = await this.s3Client.getBucketLocation({\n Bucket: bucketName\n });", "score": 0.8579062223434448 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8563641309738159 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.8514593839645386 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });\n }\n await this.fillData(\n natGatewayArn,\n credentials,", "score": 0.842131495475769 } ]
typescript
await this.fillData( instanceArn, credentials, region, {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this
.fillData( logGroupArn, credentials, region, {
resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.903134822845459 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " action: 'deleteNatGateway',\n isActionable: true,\n reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.',\n monthlySavings: this.cost\n }\n });\n }\n await this.fillData(\n natGatewayArn,\n credentials,", "score": 0.8743544816970825 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " optimize: { \n action: '', \n isActionable: false,\n reason: 'This bucket does not have a lifecycle policy',\n monthlySavings: 0\n }\n });\n }\n });\n }", "score": 0.841423511505127 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ]\n },\n Period: period,\n Stat: 'Sum'\n }\n };\n }\n private async getMetrics (args: {\n service: Service,\n startTime: Date;", "score": 0.8395702838897705 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings\n }\n });\n }\n }\n }\n async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) {\n const response = await this.s3Client.getBucketLocation({\n Bucket: bucketName\n });", "score": 0.8373916149139404 } ]
typescript
.fillData( logGroupArn, credentials, region, {
import cached from 'cached'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { BaseProvider } from '@tinystacks/ops-core'; import { ActionType, AwsResourceType, AwsServiceOverrides, AwsUtilizationOverrides, HistoryEvent, Utilization } from './types/types.js'; import { AwsServiceUtilization } from './service-utilizations/aws-service-utilization.js'; import { AwsServiceUtilizationFactory } from './service-utilizations/aws-service-utilization-factory.js'; import { AwsUtilizationProvider as AwsUtilizationProviderType } from './ops-types.js'; const utilizationCache = cached<Utilization<string>>('utilization', { backend: { type: 'memory' } }); const sessionHistoryCache = cached<Array<HistoryEvent>>('session-history', { backend: { type: 'memory' } }); type AwsUtilizationProviderProps = AwsUtilizationProviderType & { utilization?: { [key: AwsResourceType | string]: Utilization<string> }; region?: string; }; class AwsUtilizationProvider extends BaseProvider { static type = 'AwsUtilizationProvider'; services: AwsResourceType[]; utilizationClasses: { [key: AwsResourceType | string]: AwsServiceUtilization<string> }; utilization: { [key: AwsResourceType | string]: Utilization<string> }; region: string; constructor (props: AwsUtilizationProviderProps) { super(props); const { services } = props; this.utilizationClasses = {}; this.utilization = {}; this.initServices(services || [ 'Account', 'CloudwatchLogs', 'Ec2Instance', 'EcsService', 'NatGateway', 'S3Bucket', 'EbsVolume', 'RdsInstance' ]); } static fromJson (props: AwsUtilizationProviderProps) { return new AwsUtilizationProvider(props); } toJson (): AwsUtilizationProviderProps { return { ...super.toJson(), services: this.services, utilization: this.utilization }; } initServices (services: AwsResourceType[]) { this.services = services; for (const service of this.services) { this.utilizationClasses[service] = AwsServiceUtilizationFactory.
createObject(service);
} } async refreshUtilizationData ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, region: string, overrides?: AwsServiceOverrides ): Promise<Utilization<string>> { try { await this.utilizationClasses[service]?.getUtilization(credentialsProvider, [ region ], overrides); return this.utilizationClasses[service]?.utilization; } catch (e) { console.error(e); return {}; } } async doAction ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, actionName: string, actionType: ActionType, resourceArn: string, region: string ) { const event: HistoryEvent = { service, actionType, actionName, resourceArn, region, timestamp: new Date().toISOString() }; const history: HistoryEvent[] = await this.getSessionHistory(); history.push(event); await this.utilizationClasses[service].doAction(credentialsProvider, actionName, resourceArn, region); await sessionHistoryCache.set('history', history); } async hardRefresh ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } return this.utilization; } async getUtilization ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; if (serviceOverrides?.forceRefesh) { this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } else { this.utilization[service] = await utilizationCache.getOrElse( service, async () => await this.refreshUtilizationData(service, credentialsProvider, region, serviceOverrides) ); } } return this.utilization; } async getSessionHistory (): Promise<HistoryEvent[]> { return sessionHistoryCache.getOrElse('history', []); } } export { AwsUtilizationProvider };
src/aws-utilization-provider.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8424142003059387 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " }\n static fromJson (object: AwsUtilizationProps): AwsUtilization {\n return new AwsUtilization(object);\n }\n toJson (): AwsUtilizationProps {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n region: this.region, \n sessionHistory: this.sessionHistory", "score": 0.8373459577560425 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " region: string\n}\nexport class AwsUtilization extends BaseWidget {\n utilization: { [ serviceName: string ] : Utilization<string> };\n sessionHistory: HistoryEvent[];\n region: string;\n constructor (props: AwsUtilizationProps) {\n super(props);\n this.region = props.region || 'us-east-1';\n this.utilization = props.utilization || {};", "score": 0.8311489820480347 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": "export class AwsUtilizationRecommendations extends BaseWidget {\n utilization?: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n allRegions?: string[];\n region?: string;\n constructor (props: AwsUtilizationRecommendationsProps) {\n super(props);\n this.utilization = props.utilization;\n this.region = props.region || 'us-east-1';\n this.sessionHistory = props.sessionHistory || [];", "score": 0.8295087814331055 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.8290188908576965 } ]
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": " 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": 0.8764978647232056 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " cluster: service.clusterArn,\n containerInstances: tasks.map(task => task.containerInstanceArn)\n });\n containerInstance = containerInstanceResponse?.containerInstances?.at(0);\n }\n const uniqueEc2Instances = containerInstanceResponse.containerInstances.reduce<Set<string>>((acc, instance) => {\n acc.add(instance.ec2InstanceId);\n return acc;\n }, new Set<string>());\n const numEc2Instances = uniqueEc2Instances.size;", "score": 0.8463682532310486 }, { "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": 0.8422378301620483 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " return instanceFamily;\n }\n private async getInstanceTypes (instanceTypeNames: string[]): Promise<InstanceTypeInfo[]> {\n const instanceTypes = [];\n let nextToken;\n do {\n const instanceTypeResponse: DescribeInstanceTypesCommandOutput = await this.ec2Client.describeInstanceTypes({\n InstanceTypes: instanceTypeNames,\n NextToken: nextToken\n });", "score": 0.8375920653343201 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " } while (describeDBInstancesRes?.Marker);\n for (const dbInstance of dbInstances) {\n const dbInstanceId = dbInstance.DBInstanceIdentifier;\n const dbInstanceArn = dbInstance.DBInstanceArn || dbInstanceId;\n const metrics = await this.getRdsInstanceMetrics(dbInstance);\n await this.getDatabaseConnections(metrics, dbInstance, dbInstanceArn);\n await this.checkInstanceStorage(metrics, dbInstance, dbInstanceArn);\n await this.getCPUUtilization(metrics, dbInstance, dbInstanceArn);\n const monthlyCost = this.instanceCosts[dbInstanceId]?.totalCost;\n await this.fillData(dbInstanceArn, credentials, this.region, {", "score": 0.8194847702980042 } ]
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 vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.7898081541061401 }, { "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": 0.7837135791778564 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.7685429453849792 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const lowCpuUtilization = (\n (avgCpuIsStable && maxCpuIsStable) ||\n maxCpu < 10 // Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html\n );\n const { isStable: avgMemoryIsStable } = getStabilityStats(avgMemoryMetrics.Values);\n const {\n max: maxMemory,\n isStable: maxMemoryIsStable\n } = getStabilityStats(maxMemoryMetrics.Values);\n const lowMemoryUtilization = (", "score": 0.7581457495689392 }, { "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": 0.7544886469841003 } ]
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": 0.9181758165359497 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8711050152778625 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region", "score": 0.8533332943916321 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'LogGroupName', Value: logGroupName }]);\n });\n }\n };\n await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides\n ) {", "score": 0.836225152015686 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings\n }\n });\n }\n }\n }\n async getLifecyclePolicy (bucketArn: string, bucketName: string, region: string) {\n const response = await this.s3Client.getBucketLocation({\n Bucket: bucketName\n });", "score": 0.8331512212753296 } ]
typescript
.fillData( natGatewayArn, 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-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9399477243423462 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8893120288848877 }, { "filename": "src/types/types.ts", "retrieved_chunk": "import { Tag } from '@aws-sdk/client-ec2';\nexport type Data = {\n region: string,\n resourceId: string,\n associatedResourceId?: string,\n stack?: string,\n hourlyCost?: number,\n monthlyCost?: number,\n maxMonthlySavings?: number,\n [ key: string ]: any;", "score": 0.8690941333770752 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8643210530281067 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8562562465667725 } ]
typescript
getHourlyCost(cost) }
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn =
Arns.NatGateway(region, this.accountId, natGatewayId);
const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost: getHourlyCost(this.cost) } ); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " }\n }\n this.volumeCosts[volume.VolumeId] = cost;\n return cost;\n }\n async getRegionalUtilization (credentials: any, region: string) {\n const volumes = await this.getAllVolumes(credentials, region);\n const analyzeEbsVolume = async (volume: Volume) => {\n const volumeId = volume.VolumeId;\n const volumeArn = Arns.Ebs(region, this.accountId, volumeId);", "score": 0.8909534215927124 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " storedBytes,\n lastEventTime,\n monthlyStorageCost,\n totalMonthlyCost: logIngestionCost + monthlyStorageCost,\n associatedResourceId\n };\n }\n private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) {\n const allLogGroups = await this.getAllLogGroups(credentials, region);\n const analyzeLogGroup = async (logGroup: LogGroup) => {", "score": 0.8665236830711365 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n }\n async deleteService (\n awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();", "score": 0.862406313419342 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.8610411882400513 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8608859777450562 } ]
typescript
Arns.NatGateway(region, this.accountId, natGatewayId);
import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { DescribeNatGatewaysCommandOutput, EC2, NatGateway } from '@aws-sdk/client-ec2'; import { Pricing } from '@aws-sdk/client-pricing'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import get from 'lodash.get'; import { Arns } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getAccountId, getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; /** * const DEFAULT_RECOMMENDATION = 'review this NAT Gateway and the Route Tables associated with its VPC. If another' + * 'NAT Gateway exists in the VPC, repoint routes to that gateway and delete this gateway. If this is the only' + * 'NAT Gateway in your VPC and resources depend on network traffic, retain this gateway.'; */ type AwsNatGatewayUtilizationScenarioTypes = 'activeConnectionCount' | 'totalThroughput'; const AwsNatGatewayMetrics = ['ActiveConnectionCount', 'BytesInFromDestination']; export class AwsNatGatewayUtilization extends AwsServiceUtilization<AwsNatGatewayUtilizationScenarioTypes> { accountId: string; cost: number; constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { if (actionName === 'deleteNatGateway') { const ec2Client = new EC2({ credentials: await awsCredentialsProvider.getCredentials(), region }); const resourceId = resourceArn.split('/')[1]; await this.deleteNatGateway(ec2Client, resourceId); } } async deleteNatGateway (ec2Client: EC2, natGatewayId: string) { await ec2Client.deleteNatGateway({ NatGatewayId: natGatewayId }); } private async getAllNatGateways (credentials: any, region: string) { const ec2Client = new EC2({ credentials, region }); let allNatGateways: NatGateway[] = []; let describeNatGatewaysRes: DescribeNatGatewaysCommandOutput; do { describeNatGatewaysRes = await ec2Client.describeNatGateways({ NextToken: describeNatGatewaysRes?.NextToken }); allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []]; } while (describeNatGatewaysRes?.NextToken); return allNatGateways; } private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) { const cwClient = new CloudWatch({ credentials, region }); const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000)); const metricDataRes = await cwClient.getMetricData({ MetricDataQueries: [ { Id: 'activeConnectionCount', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'ActiveConnectionCount', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Maximum' } }, { Id: 'bytesInFromDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesInFromSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesInFromSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToDestination', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToDestination', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } }, { Id: 'bytesOutToSource', MetricStat: { Metric: { Namespace: 'AWS/NATGateway', MetricName: 'BytesOutToSource', Dimensions: [{ Name: 'NatGatewayId', Value: natGatewayId }] }, Period: 5 * 60, // 5 minutes Stat: 'Sum' } } ], StartTime: fiveMinutesAgo, EndTime: new Date() }); return metricDataRes.MetricDataResults; } private async getRegionalUtilization (credentials: any, region: string) { const allNatGateways = await this.getAllNatGateways(credentials, region); const analyzeNatGateway = async (natGateway: NatGateway) => { const natGatewayId = natGateway.NatGatewayId; const natGatewayArn = Arns.NatGateway(region, this.accountId, natGatewayId); const results = await this.getNatGatewayMetrics(credentials, region, natGatewayId); const activeConnectionCount = get(results, '[0].Values[0]') as number; if (activeConnectionCount === 0) { this.addScenario(natGatewayArn, 'activeConnectionCount', { value: activeConnectionCount.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 active connections over the past week. It appears to be unused.', monthlySavings: this.cost } }); } const totalThroughput = get(results, '[1].Values[0]', 0) + get(results, '[2].Values[0]', 0) + get(results, '[3].Values[0]', 0) + get(results, '[4].Values[0]', 0); if (totalThroughput === 0) { this.addScenario(natGatewayArn, 'totalThroughput', { value: totalThroughput.toString(), delete: { action: 'deleteNatGateway', isActionable: true, reason: 'This NAT Gateway has had 0 total throughput over the past week. It appears to be unused.', monthlySavings: this.cost } }); } await this.fillData( natGatewayArn, credentials, region, { resourceId: natGatewayId, region, monthlyCost: this.cost, hourlyCost
: getHourlyCost(this.cost) }
); AwsNatGatewayMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, natGatewayArn, 'AWS/NATGateway', metricName, [{ Name: 'NatGatewayId', Value: natGatewayId }]); }); }; await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); this.accountId = await getAccountId(credentials); this.cost = await this.getNatGatewayPrice(credentials); for (const region of regions) { await this.getRegionalUtilization(credentials, region); } } private async getNatGatewayPrice (credentials: any) { const pricingClient = new Pricing({ credentials, // global but have to specify region region: 'us-east-1' }); const res = await pricingClient.getProducts({ ServiceCode: 'AmazonEC2', Filters: [ { Type: 'TERM_MATCH', Field: 'productFamily', Value: 'NAT Gateway' }, { Type: 'TERM_MATCH', Field: 'usageType', Value: 'NatGateway-Hours' } ] }); const onDemandData = JSON.parse(res.PriceList[0] as string).terms.OnDemand; const onDemandKeys = Object.keys(onDemandData); const priceDimensionsData = onDemandData[onDemandKeys[0]].priceDimensions; const priceDimensionsKeys = Object.keys(priceDimensionsData); const pricePerHour = priceDimensionsData[priceDimensionsKeys[0]].pricePerUnit.USD; // monthly cost return pricePerHour * 24 * 30; } }
src/service-utilizations/aws-nat-gateway-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.9167476296424866 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.9026936888694763 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8693907856941223 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8672367334365845 }, { "filename": "src/types/types.ts", "retrieved_chunk": "import { Tag } from '@aws-sdk/client-ec2';\nexport type Data = {\n region: string,\n resourceId: string,\n associatedResourceId?: string,\n stack?: string,\n hourlyCost?: number,\n monthlyCost?: number,\n maxMonthlySavings?: number,\n [ key: string ]: any;", "score": 0.8408769369125366 } ]
typescript
: getHourlyCost(this.cost) }
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": 0.7463794946670532 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.745927095413208 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " monthlySavings: 0\n }\n });\n }\n if (metrics.freeStorageSpace >= (dbInstance.AllocatedStorage / 2)) {\n await this.getRdsInstanceCosts(dbInstance, metrics);\n this.addScenario(dbInstance.DBInstanceIdentifier, 'shouldScaleDownStorage', {\n value: 'true',\n scaleDown: { \n action: '', ", "score": 0.7320494651794434 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n );\n }\n function sidePanel (){ \n const serviceUtil = sidePanelService && filteredServices[sidePanelService];\n const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data;\n //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination'];\n const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => (\n <Box bg=\"#EDF2F7\" p={2} color=\"black\" marginBottom='8px'> \n <InfoIcon marginRight={'8px'} />", "score": 0.7312756776809692 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.7252699136734009 } ]
typescript
_overrides.scenarioType === 'hasIntelligentTiering'){ return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0;
const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03;
const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) { const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8692074418067932 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " allNatGateways = [...allNatGateways, ...describeNatGatewaysRes?.NatGateways || []];\n } while (describeNatGatewaysRes?.NextToken);\n return allNatGateways;\n }\n private async getNatGatewayMetrics (credentials: any, region: string, natGatewayId: string) {\n const cwClient = new CloudWatch({\n credentials,\n region\n });\n const fiveMinutesAgo = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000));", "score": 0.8676126599311829 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " for (const region of regions) {\n await this.getRegionalUtilization(credentials, region, overrides);\n }\n // this.getEstimatedMaxMonthlySavings();\n }\n async terminateInstance (awsCredentialsProvider: AwsCredentialsProvider, instanceId: string, region: string) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ec2Client = new EC2({\n credentials,\n region", "score": 0.8663933873176575 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.863007664680481 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " ]\n }\n });\n }\n async getRegionalUtilization (credentials: any, region: string) {\n this.s3Client = new S3({\n credentials,\n region\n });\n this.cwClient = new CloudWatch({", "score": 0.8574162721633911 } ]
typescript
const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03;
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/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": 0.8433403372764587 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " instanceIds: string[];\n}\nexport class AwsEc2InstanceUtilization extends AwsServiceUtilization<AwsEc2InstanceUtilizationScenarioTypes> {\n instanceIds: string[];\n instances: Instance[];\n accountId: string;\n DEBUG_MODE: boolean;\n constructor (enableDebugMode?: boolean) {\n super();\n this.instanceIds = [];", "score": 0.8427185416221619 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": "class AwsUtilizationProvider extends BaseProvider {\n static type = 'AwsUtilizationProvider';\n services: AwsResourceType[];\n utilizationClasses: {\n [key: AwsResourceType | string]: AwsServiceUtilization<string>\n };\n utilization: {\n [key: AwsResourceType | string]: Utilization<string>\n };\n region: string;", "score": 0.8393499851226807 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " monthlySavings: number\n}\nexport type s3UtilizationScenarios = 'hasIntelligentTiering' | 'hasLifecyclePolicy';\nexport class s3Utilization extends AwsServiceUtilization<s3UtilizationScenarios> {\n s3Client: S3;\n cwClient: CloudWatch;\n bucketCostData: { [ bucketName: string ]: S3CostData };\n constructor () {\n super();\n this.bucketCostData = {};", "score": 0.8329504728317261 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " 'hasAutoScalingEnabled';\nconst rdsInstanceMetrics = ['DatabaseConnections', 'FreeStorageSpace', 'CPUUtilization'];\nexport class rdsInstancesUtilization extends AwsServiceUtilization<rdsInstancesUtilizationScenarios> {\n private instanceCosts: { [instanceId: string]: RdsCosts };\n private rdsClient: RDS;\n private cwClient: CloudWatch;\n private pricingClient: Pricing;\n private region: string;\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string", "score": 0.8304445147514343 } ]
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-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.830291211605072 }, { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " await this.fillData(\n bucketArn,\n credentials,\n region,\n {\n resourceId: bucketName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }", "score": 0.8297371864318848 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " region,\n {\n resourceId: volumeId,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n EbsVolumesMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8221650719642639 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.8203967809677124 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.8169913291931152 } ]
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/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " const cloudWatchClient = new CloudWatch({ \n credentials, \n region\n });\n this.checkForUnusedVolume(volume, volumeArn);\n await this.getReadWriteVolume(cloudWatchClient, volume, volumeArn);\n const monthlyCost = this.volumeCosts[volumeArn] || 0;\n await this.fillData(\n volumeArn,\n credentials,", "score": 0.898003876209259 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " monthlyCost: totalMonthlyCost,\n hourlyCost: getHourlyCost(totalMonthlyCost)\n }\n );\n AwsCloudWatchLogsMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n logGroupArn,\n 'AWS/Logs', ", "score": 0.8376507759094238 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " resourceId: dbInstanceId,\n region: this.region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n });\n rdsInstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n this.region, \n dbInstanceId,", "score": 0.8342452645301819 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " credentials,\n region,\n {\n resourceId: service.serviceName,\n region,\n monthlyCost,\n hourlyCost: getHourlyCost(monthlyCost)\n }\n );\n AwsEcsMetrics.forEach(async (metricName) => { ", "score": 0.8254461288452148 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " monthlyCost: cost,\n hourlyCost: getHourlyCost(cost)\n }\n );\n AwsEc2InstanceMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(\n credentials, \n region, \n instanceArn,\n 'AWS/EC2', ", "score": 0.8252577781677246 } ]
typescript
this.fillData( bucketArn, credentials, region, {
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.
resourceId, data.associatedResourceId );
this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8715431690216064 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8618277311325073 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8276211023330688 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " ): Promise<void> {\n if (actionName === 'deleteInstance') {\n const rdsClient = new RDS({\n credentials: await awsCredentialsProvider.getCredentials(),\n region\n });\n const resourceId = resourceArn.split(':').at(-1);\n await this.deleteInstance(rdsClient, resourceId);\n }\n }", "score": 0.8272700905799866 }, { "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": 0.8266221880912781 } ]
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": " 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": 0.8690736293792725 }, { "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": 0.8594852685928345 }, { "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": 0.8594262003898621 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Sum'\n }\n },\n {\n Id: 'bytesOutToDestination',\n MetricStat: {", "score": 0.8462007641792297 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " Value: natGatewayId\n }]\n },\n Period: 5 * 60, // 5 minutes\n Stat: 'Maximum'\n }\n },\n {\n Id: 'bytesInFromDestination',\n MetricStat: {", "score": 0.8457273840904236 } ]
typescript
bucketBytes / ONE_GB_IN_BYTES) * 0.022;
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) {
this.addData(resourceArn, key, data[key]);
} await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId, data.associatedResourceId ); this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": "export class ebsVolumesUtilization extends AwsServiceUtilization<ebsVolumesUtilizationScenarios> {\n accountId: string;\n volumeCosts: { [ volumeId: string ]: number };\n constructor () {\n super();\n this.volumeCosts = {};\n }\n async doAction (\n awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string\n ): Promise<void> {", "score": 0.8469785451889038 }, { "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": 0.8426870107650757 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.8423349857330322 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.841240406036377 }, { "filename": "src/types/types.ts", "retrieved_chunk": " [ resourceArn: string ]: Resource<ScenarioTypes>\n}\nexport type UserInput = { [ key: string ]: any }\nexport type AwsServiceOverrides = {\n resourceArn: string,\n scenarioType: string,\n delete?: boolean,\n scaleDown?: boolean,\n optimize?: boolean,\n forceRefesh?: boolean,", "score": 0.8372716903686523 } ]
typescript
this.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/aws-utilization-provider.ts", "retrieved_chunk": " credentialsProvider: AwsCredentialsProvider,\n actionName: string,\n actionType: ActionType,\n resourceArn: string,\n region: string\n ) {\n const event: HistoryEvent = {\n service,\n actionType,\n actionName,", "score": 0.8617329597473145 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " } while (nextToken);\n return instanceTypes;\n }\n private async getMetrics (args: {\n instanceId: string;\n startTime: Date;\n endTime: Date; \n period: number;\n cwClient: CloudWatch;\n }): Promise<{[ key: string ]: MetricDataResult}> {", "score": 0.8489429354667664 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " endTime: Date; \n period: number;\n }): Promise<{[ key: string ]: MetricDataResult}> {\n const {\n service,\n startTime,\n endTime,\n period\n } = args;\n const {", "score": 0.844467282295227 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8421250581741333 }, { "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": 0.8356842398643494 } ]
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": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.7821172475814819 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {", "score": 0.7811887264251709 }, { "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": 0.7764871120452881 }, { "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": 0.7698111534118652 }, { "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": 0.7603859901428223 } ]
typescript
, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric;
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": " scenario.scaleDown?.monthlySavings || 0,\n scenario.optimize?.monthlySavings || 0\n );\n });\n const maxSavingsForResource = Math.max(...maxSavingsPerScenario);\n this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource);\n }\n }\n protected async getSidePanelMetrics (\n credentials: any, region: string, resourceArn: string, ", "score": 0.7719571590423584 }, { "filename": "src/service-utilizations/aws-service-utilization.ts", "retrieved_chunk": " }).catch(() => { return; });\n }\n }\n protected getEstimatedMaxMonthlySavings (resourceArn: string) {\n // for (const resourceArn in this.utilization) {\n if (resourceArn in this.utilization) {\n const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios;\n const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => {\n return Math.max(\n scenario.delete?.monthlySavings || 0,", "score": 0.7658531665802002 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " region,\n {\n resourceId: natGatewayId,\n region,\n monthlyCost: this.cost,\n hourlyCost: getHourlyCost(this.cost)\n }\n );\n AwsNatGatewayMetrics.forEach(async (metricName) => { \n await this.getSidePanelMetrics(", "score": 0.7624130249023438 }, { "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": 0.752281129360199 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " const vCpuScore = a.VCpuInfo.DefaultVCpus < b.VCpuInfo.DefaultVCpus ? -1 : 1;\n const memoryScore = a.MemoryInfo.SizeInMiB < b.MemoryInfo.SizeInMiB ? -1 : 1;\n return memoryScore + vCpuScore;\n });\n const targetInstanceType: InstanceTypeInfo | undefined = smallerInstances?.at(0);\n if (targetInstanceType) {\n const targetMonthlyInstanceCost = await getInstanceCost(this.pricingClient, targetInstanceType.InstanceType);\n const targetMonthlyCost = targetMonthlyInstanceCost * numEc2Instances;\n this.addScenario(service.serviceArn, 'overAllocated', {\n value: 'true',", "score": 0.7521930932998657 } ]
typescript
return this.utilization[_overrides.resourceArn].scenarios.hasIntelligentTiering.optimize.action;
import { CloudFormation } from '@aws-sdk/client-cloudformation'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { Data, Metric, Resource, Scenario, Utilization, MetricData } from '../types/types'; import { CloudWatch, Dimension } from '@aws-sdk/client-cloudwatch'; export abstract class AwsServiceUtilization<ScenarioTypes extends string> { private _utilization: Utilization<ScenarioTypes>; constructor () { this._utilization = {}; } /* TODO: all services have a sub getRegionalUtilization function that needs to be deprecated * since calls are now region specific */ abstract getUtilization ( awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: any ): void | Promise<void>; abstract doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceId: string, region: string ): void | Promise<void>; protected addScenario (resourceArn: string, scenarioType: ScenarioTypes, scenario: Scenario) { if (!(resourceArn in this.utilization)) { this.utilization[resourceArn] = { scenarios: {}, data: {}, metrics: {} } as Resource<ScenarioTypes>; } this.utilization[resourceArn].scenarios[scenarioType] = scenario; } protected async fillData ( resourceArn: string, credentials: any, region: string, data: { [ key: keyof Data ]: Data[keyof Data] } ) { for (const key in data) { this.addData(resourceArn, key, data[key]); } await this.identifyCloudformationStack( credentials, region, resourceArn, data.resourceId,
data.associatedResourceId );
this.getEstimatedMaxMonthlySavings(resourceArn); } protected addData (resourceArn: string, dataType: keyof Data, value: any) { // only add data if recommendation exists for resource if (resourceArn in this.utilization) { this.utilization[resourceArn].data[dataType] = value; } } protected addMetric (resourceArn: string, metricName: string, metric: Metric){ if(resourceArn in this.utilization){ this.utilization[resourceArn].metrics[metricName] = metric; } } protected async identifyCloudformationStack ( credentials: any, region: string, resourceArn: string, resourceId: string, associatedResourceId?: string ) { if (resourceArn in this.utilization) { const cfnClient = new CloudFormation({ credentials, region }); await cfnClient.describeStackResources({ PhysicalResourceId: associatedResourceId ? associatedResourceId : resourceId }).then((res) => { const stack = res.StackResources[0].StackId; this.addData(resourceArn, 'stack', stack); }).catch(() => { return; }); } } protected getEstimatedMaxMonthlySavings (resourceArn: string) { // for (const resourceArn in this.utilization) { if (resourceArn in this.utilization) { const scenarios = (this.utilization as Utilization<string>)[resourceArn].scenarios; const maxSavingsPerScenario = Object.values(scenarios).map((scenario) => { return Math.max( scenario.delete?.monthlySavings || 0, scenario.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 ); }); const maxSavingsForResource = Math.max(...maxSavingsPerScenario); this.addData(resourceArn, 'maxMonthlySavings', maxSavingsForResource); } } protected async getSidePanelMetrics ( credentials: any, region: string, resourceArn: string, nameSpace: string, metricName: string, dimensions: Dimension[] ){ if(resourceArn in this.utilization){ const cloudWatchClient = new CloudWatch({ credentials: credentials, region: region }); const endTime = new Date(Date.now()); const startTime = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); //7 days ago const period = 43200; const metrics = await cloudWatchClient.getMetricStatistics({ Namespace: nameSpace, MetricName: metricName, StartTime: startTime, EndTime: endTime, Period: period, Statistics: ['Average'], Dimensions: dimensions }); const values: MetricData[] = metrics.Datapoints.map(dp => ({ timestamp: dp.Timestamp.getTime(), value: dp.Average })).sort((dp1, dp2) => dp1.timestamp - dp2.timestamp); const metricResuls: Metric = { yAxisLabel: metrics.Label || metricName, values: values }; this.addMetric(resourceArn , metricName, metricResuls); } } public set utilization (utilization: Utilization<ScenarioTypes>) { this._utilization = utilization; } public get utilization () { return this._utilization; } }
src/service-utilizations/aws-service-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " });\n }\n }\n await this.fillData(\n instanceArn,\n credentials,\n region,\n {\n resourceId: instanceId,\n region,", "score": 0.8647961616516113 }, { "filename": "src/service-utilizations/aws-cloudwatch-logs-utilization.ts", "retrieved_chunk": " });\n }\n await this.fillData(\n logGroupArn,\n credentials,\n region,\n {\n resourceId: logGroupName,\n ...(associatedResourceId && { associatedResourceId }),\n region,", "score": 0.8633326292037964 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " ): Promise<void> {\n if (actionName === 'deleteInstance') {\n const rdsClient = new RDS({\n credentials: await awsCredentialsProvider.getCredentials(),\n region\n });\n const resourceId = resourceArn.split(':').at(-1);\n await this.deleteInstance(rdsClient, resourceId);\n }\n }", "score": 0.8308790922164917 }, { "filename": "src/service-utilizations/rds-utilization.tsx", "retrieved_chunk": " ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.region = regions[0];\n this.rdsClient = new RDS({\n credentials,\n region: this.region\n });\n this.cwClient = new CloudWatch({ \n credentials, \n region: this.region", "score": 0.8267366886138916 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " awsCredentialsProvider: AwsCredentialsProvider, clusterName: string, serviceArn: string, region: string,\n cpu: number, memory: number\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n const ecsClient = new ECS({\n credentials,\n region\n });\n const serviceResponse = await ecsClient.describeServices({\n cluster: clusterName,", "score": 0.8236725926399231 } ]
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/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7821710109710693 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.7747938632965088 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " Object.entries(resource.scenarios).forEach(([sType, details]) => {\n if (Object.hasOwn(details, actionType)) {\n filteredScenarios[sType] = details;\n }\n });\n if (!filteredScenarios || isEmpty(filteredScenarios)) {\n return aggUtil;\n }\n aggUtil[id] = {\n ...resource,", "score": 0.7697648406028748 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.7559380531311035 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n );\n }\n function sidePanel (){ \n const serviceUtil = sidePanelService && filteredServices[sidePanelService];\n const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data;\n //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination'];\n const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => (\n <Box bg=\"#EDF2F7\" p={2} color=\"black\" marginBottom='8px'> \n <InfoIcon marginRight={'8px'} />", "score": 0.7522499561309814 } ]
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/utils/utilization.ts", "retrieved_chunk": " return historyevent.resourceArn;\n }); \n const serviceUtil = utilization[service];\n const actionFilteredServiceUtil = \n Object.entries(serviceUtil).reduce<Utilization<string>>((aggUtil, [id, resource]) => {\n if(resourcesInProgress.includes(id)){ \n delete aggUtil[id];\n return aggUtil;\n }\n const filteredScenarios: Scenarios<string> = {};", "score": 0.7817946672439575 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " for (const serviceUtil of Object.keys(filteredServices)) {\n const filteredServiceUtil = Object.keys(filteredServices[serviceUtil])\n .filter(resArn => resourceArnsSet.has(resArn));\n for (const resourceArn of filteredServiceUtil) {\n const resource = filteredServices[serviceUtil][resourceArn];\n for (const scenario of Object.keys(resource.scenarios)) {\n await utilProvider.doAction(\n serviceUtil,\n awsCredsProvider, \n get(resource.scenarios[scenario], `${actionType}.action`),", "score": 0.7746241092681885 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " Object.entries(resource.scenarios).forEach(([sType, details]) => {\n if (Object.hasOwn(details, actionType)) {\n filteredScenarios[sType] = details;\n }\n });\n if (!filteredScenarios || isEmpty(filteredScenarios)) {\n return aggUtil;\n }\n aggUtil[id] = {\n ...resource,", "score": 0.7674486637115479 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n </Stack>\n );\n }\n function taskRowsForOptimize (serviceName: string, serviceUtil: Utilization<string>){\n const tableHeadersSet = new Set<string>();\n Object.keys(serviceUtil).forEach(resArn =>\n Object.keys(serviceUtil[resArn].scenarios).forEach(s => tableHeadersSet.add(s))\n );\n const tableHeaders = [...tableHeadersSet];", "score": 0.7550182342529297 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": " </TableContainer>\n );\n }\n function sidePanel (){ \n const serviceUtil = sidePanelService && filteredServices[sidePanelService];\n const data = serviceUtil && serviceUtil[sidePanelResourceArn]?.data;\n //const metric = serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['CPUUtilization'] || serviceUtil && serviceUtil[sidePanelResourceArn]?.metrics['BytesInFromDestination'];\n const adjustments = serviceUtil && Object.keys(serviceUtil[sidePanelResourceArn]?.scenarios).map(scenario => (\n <Box bg=\"#EDF2F7\" p={2} color=\"black\" marginBottom='8px'> \n <InfoIcon marginRight={'8px'} />", "score": 0.7539863586425781 } ]
typescript
.scaleDown?.monthlySavings || 0, scenario.optimize?.monthlySavings || 0 );