Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/core/src/awsService/cloudWatchLogs/activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import { changeLogSearchParams } from './changeLogSearch'
import { CloudWatchLogsNode } from './explorer/cloudWatchLogsNode'
import { loadAndOpenInitialLogStreamFile, LogStreamCodeLensProvider } from './document/logStreamsCodeLensProvider'
import { tailLogGroup } from './commands/tailLogGroup'

export async function activate(context: vscode.ExtensionContext, configuration: Settings): Promise<void> {
const registry = LogDataRegistry.instance
Expand Down Expand Up @@ -89,6 +90,14 @@

Commands.register('aws.cwl.changeFilterPattern', async () => changeLogSearchParams(registry, 'filterPattern')),

Commands.register('aws.cwl.changeTimeFilter', async () => changeLogSearchParams(registry, 'timeFilter'))
Commands.register('aws.cwl.changeTimeFilter', async () => changeLogSearchParams(registry, 'timeFilter')),

Check failure on line 94 in packages/core/src/awsService/cloudWatchLogs/activation.ts

View workflow job for this annotation

GitHub Actions / lint (16.x, stable)

Delete `····`
Commands.register('aws.cwl.tailLogGroup', async (node: LogGroupNode | CloudWatchLogsNode) => {
const logGroupInfo =
node instanceof LogGroupNode
? { regionName: node.regionCode, groupName: node.logGroup.logGroupName! }
: undefined
await tailLogGroup(logGroupInfo)
}),

Check failure on line 101 in packages/core/src/awsService/cloudWatchLogs/activation.ts

View workflow job for this annotation

GitHub Actions / lint (16.x, stable)

Delete `,`
)
}
107 changes: 107 additions & 0 deletions packages/core/src/awsService/cloudWatchLogs/commands/tailLogGroup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

import * as nls from 'vscode-nls'
import { DefaultCloudWatchLogsClient } from '../../../shared/clients/cloudWatchLogsClient'
import { createBackButton, createExitButton, createHelpButton } from '../../../shared/ui/buttons'
import { createInputBox } from '../../../shared/ui/inputPrompter'
import { DataQuickPickItem } from '../../../shared/ui/pickerPrompter'
import { Wizard } from '../../../shared/wizards/wizard'
import { CloudWatchLogsGroupInfo } from '../registry/logDataRegistry'
import { RegionSubmenu, RegionSubmenuResponse } from '../../../shared/ui/common/regionSubmenu'
import { CancellationError } from '../../../shared/utilities/timeoutUtils'
import { LogStreamFilterResponse, LogStreamFilterSubmenu } from '../liveTailLogStreamSubmenu'
import { getLogger } from '../../../shared'

const localize = nls.loadMessageBundle()

export interface TailLogGroupWizardResponse {
regionLogGroupSubmenuResponse: RegionSubmenuResponse<string>
logStreamFilter: LogStreamFilterResponse
filterPattern: string
}

export async function tailLogGroup(logData?: { regionName: string; groupName: string }): Promise<void> {
const wizard = new TailLogGroupWizard(logData)
const wizardResponse = await wizard.run()
if (!wizardResponse) {
throw new CancellationError('user')
}

//TODO: Remove Log. For testing while we aren't yet consuming the wizardResponse.
getLogger().info(JSON.stringify(wizardResponse))
}

export class TailLogGroupWizard extends Wizard<TailLogGroupWizardResponse> {
public constructor(logGroupInfo?: CloudWatchLogsGroupInfo) {
super({
initState: {
regionLogGroupSubmenuResponse: logGroupInfo
? {
data: logGroupInfo.groupName,
region: logGroupInfo.regionName,
}
: undefined,
},
})
this.form.regionLogGroupSubmenuResponse.bindPrompter(createRegionLogGroupSubmenu)
this.form.logStreamFilter.bindPrompter((state) => {
if (!state.regionLogGroupSubmenuResponse?.data) {
throw Error('LogGroupName is null')
}
return new LogStreamFilterSubmenu(
state.regionLogGroupSubmenuResponse.data,
state.regionLogGroupSubmenuResponse.region
)
})
this.form.filterPattern.bindPrompter((state) => createFilterPatternPrompter())
}
}

export function createRegionLogGroupSubmenu(): RegionSubmenu<string> {
return new RegionSubmenu(
getLogGroupQuickPickOptions,
{
title: localize('AWS.cwl.tailLogGroup.logGroupPromptTitle', 'Select Log Group to tail'),
buttons: [createExitButton()],
},
{ title: localize('AWS.cwl.tailLogGroup.regionPromptTitle', 'Select Region for Log Group') },
'LogGroups'
)
}

async function getLogGroupQuickPickOptions(regionCode: string): Promise<DataQuickPickItem<string>[]> {
const client = new DefaultCloudWatchLogsClient(regionCode)
const logGroups = client.describeLogGroups()

const logGroupsOptions: DataQuickPickItem<string>[] = []

for await (const logGroupObject of logGroups) {
if (!logGroupObject.arn || !logGroupObject.logGroupName) {
throw Error('LogGroupObject name or arn undefined')
}

logGroupsOptions.push({
label: logGroupObject.logGroupName,
data: formatLogGroupArn(logGroupObject.arn),
})
}

return logGroupsOptions
}

function formatLogGroupArn(logGroupArn: string): string {
return logGroupArn.endsWith(':*') ? logGroupArn.substring(0, logGroupArn.length - 2) : logGroupArn
}

export function createFilterPatternPrompter() {
const helpUri = 'https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html'
return createInputBox({
title: 'Provide log event filter pattern',
placeholder: 'filter pattern (case sensitive; empty matches all)',
prompt: 'Optional pattern to use to filter the results to include only log events that match the pattern.',
buttons: [createHelpButton(helpUri), createBackButton(), createExitButton()],
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import { Prompter, PromptResult } from '../../shared/ui/prompter'
import { DefaultCloudWatchLogsClient } from '../../shared/clients/cloudWatchLogsClient'
import { createCommonButtons } from '../../shared/ui/buttons'
import { createInputBox, InputBoxPrompter } from '../../shared/ui/inputPrompter'
import { createQuickPick, DataQuickPickItem, QuickPickPrompter } from '../../shared/ui/pickerPrompter'
import { pageableToCollection } from '../../shared/utilities/collectionUtils'
import { CloudWatchLogs } from 'aws-sdk'
import { isValidResponse, StepEstimator } from '../../shared/wizards/wizard'
import { isNonNullable } from '../../shared/utilities/tsUtils'

export enum LogStreamFilterType {
MENU = 'menu',
PREFIX = 'prefix',
SPECIFIC = 'specific',
ALL = 'all',
}

export interface LogStreamFilterResponse {
readonly filter?: string
readonly type: LogStreamFilterType
}

export class LogStreamFilterSubmenu extends Prompter<LogStreamFilterResponse> {
private logStreamPrefixRegEx = /^[^:*]*$/
private currentState: LogStreamFilterType = LogStreamFilterType.MENU
private steps?: [current: number, total: number]
private region: string
private logGroupArn: string
public defaultPrompter: QuickPickPrompter<LogStreamFilterType> = this.createMenuPrompter()

public constructor(logGroupArn: string, region: string) {
super()
this.region = region
this.logGroupArn = logGroupArn
}

public createMenuPrompter() {
const helpUri = 'https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartLiveTail.html'
const prompter = createQuickPick(this.menuOptions, {
title: 'Select LogStream filter type',
buttons: createCommonButtons(helpUri),
})
return prompter
}

private get menuOptions(): DataQuickPickItem<LogStreamFilterType>[] {
const options: DataQuickPickItem<LogStreamFilterType>[] = []
options.push({
label: 'All',
detail: 'Include log events from all LogStreams in the selected LogGroup',
data: LogStreamFilterType.ALL,
})
options.push({
label: 'Specific',
detail: 'Include log events from only a specific LogStream',
data: LogStreamFilterType.SPECIFIC,
})
options.push({
label: 'Prefix',
detail: 'Include log events from LogStreams that begin with a provided prefix',
data: LogStreamFilterType.PREFIX,
})
return options
}

public createLogStreamPrefixBox(): InputBoxPrompter {
const helpUri =
'https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartLiveTail.html#CWL-StartLiveTail-request-logStreamNamePrefixes'
return createInputBox({
title: 'Enter LogStream prefix',
placeholder: 'logStream prefix (case sensitive; empty matches all)',
prompt: 'Only log events in the LogStreams that have names that start with the prefix that you specify here are included in the Live Tail session',
validateInput: (input) => this.validateLogStreamPrefix(input),
buttons: createCommonButtons(helpUri),
})
}

public validateLogStreamPrefix(prefix: string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

should this have a specific test or do you think its covered by the existing tests you wrote?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It should be covered via the existing tests

if (prefix.length > 512) {
return 'LogStream prefix cannot be longer than 512 characters'
}

if (!this.logStreamPrefixRegEx.test(prefix)) {
return 'LogStream prefix must match pattern: [^:*]*'
}
}

public createLogStreamSelector(): QuickPickPrompter<string> {
const helpUri =
'https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartLiveTail.html#CWL-StartLiveTail-request-logStreamNames'
const client = new DefaultCloudWatchLogsClient(this.region)
const request: CloudWatchLogs.DescribeLogStreamsRequest = {
logGroupIdentifier: this.logGroupArn,
orderBy: 'LastEventTime',
descending: true,
}
const requester = (request: CloudWatchLogs.DescribeLogStreamsRequest) => client.describeLogStreams(request)
const collection = pageableToCollection(requester, request, 'nextToken', 'logStreams')

const items = collection
.filter(isNonNullable)
.map((streams) => streams!.map((stream) => ({ data: stream.logStreamName!, label: stream.logStreamName! })))

return createQuickPick(items, {
title: 'Select LogStream',
buttons: createCommonButtons(helpUri),
})
}

private switchState(newState: LogStreamFilterType) {
this.currentState = newState
}

protected async promptUser(): Promise<PromptResult<LogStreamFilterResponse>> {
while (true) {
switch (this.currentState) {
case LogStreamFilterType.MENU: {
const prompter = this.createMenuPrompter()
this.steps && prompter.setSteps(this.steps[0], this.steps[1])

const resp = await prompter.prompt()
if (resp === LogStreamFilterType.PREFIX) {
this.switchState(LogStreamFilterType.PREFIX)
} else if (resp === LogStreamFilterType.SPECIFIC) {
this.switchState(LogStreamFilterType.SPECIFIC)
} else if (resp === LogStreamFilterType.ALL) {
return { filter: undefined, type: resp }
} else {
return undefined
}

break
}
case LogStreamFilterType.PREFIX: {
const resp = await this.createLogStreamPrefixBox().prompt()
if (isValidResponse(resp)) {
return { filter: resp, type: LogStreamFilterType.PREFIX }
}
this.switchState(LogStreamFilterType.MENU)
break
}
case LogStreamFilterType.SPECIFIC: {
const resp = await this.createLogStreamSelector().prompt()
if (isValidResponse(resp)) {
return { filter: resp, type: LogStreamFilterType.SPECIFIC }
}
this.switchState(LogStreamFilterType.MENU)
break
}
}
}
}

public setSteps(current: number, total: number): void {
this.steps = [current, total]
}

// Unused
public get recentItem(): any {
return
}
public set recentItem(response: any) {}
public setStepEstimator(estimator: StepEstimator<LogStreamFilterResponse>): void {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

import { TailLogGroupWizard } from '../../../../awsService/cloudWatchLogs/commands/tailLogGroup'
import { createWizardTester } from '../../../shared/wizards/wizardTestUtils'

describe('TailLogGroupWizard', async function () {
it('prompts regionLogGroup submenu first if context not provided', async function () {
const wizard = new TailLogGroupWizard()
const tester = await createWizardTester(wizard)
tester.regionLogGroupSubmenuResponse.assertShowFirst()
tester.logStreamFilter.assertShowSecond()
tester.filterPattern.assertShowThird()
})

it('skips regionLogGroup submenu if context provided', async function () {
const wizard = new TailLogGroupWizard({
groupName: 'test-groupName',
regionName: 'test-regionName',
})
const tester = await createWizardTester(wizard)
tester.regionLogGroupSubmenuResponse.assertDoesNotShow()
tester.logStreamFilter.assertShowFirst()
tester.filterPattern.assertShowSecond()
})
})
Loading
Loading