com.amazonaws.services.lambda.model.FunctionConfiguration Java Examples

The following examples show how to use com.amazonaws.services.lambda.model.FunctionConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void deleteAllVersions(AWSLambda client, String functionName) throws Exception {
	TaskListener listener = Execution.this.getContext().get(TaskListener.class);
	listener.getLogger().format("Looking for old versions functionName=%s%n", functionName);
	List<String> aliasedVersions = client.listAliases(new ListAliasesRequest()
			.withFunctionName(functionName)).getAliases().stream()
			.map( (alias) -> alias.getFunctionVersion())
			.collect(Collectors.toList());
	listener.getLogger().format("Found alises functionName=%s alias=%s%n", functionName, aliasedVersions);
	List<FunctionConfiguration> allVersions = findAllVersions(client, functionName);
	listener.getLogger().format("Found old versions functionName=%s count=%d%n", functionName, allVersions.size());
	List<FunctionConfiguration> filteredVersions = allVersions.stream()
		.filter( (function) -> {
			ZonedDateTime parsedDateTime = DateTimeUtils.parse(function.getLastModified());
			return parsedDateTime.isBefore(this.step.versionCutoff);
		})
		.filter( (function) -> !"$LATEST".equals(function.getVersion()))
		.filter( (function) -> !aliasedVersions.contains(function.getVersion()))
		.collect(Collectors.toList());
	for (FunctionConfiguration functionConfiguration : filteredVersions) {
		listener.getLogger().format("Deleting old version functionName=%s version=%s lastModified=%s%n", functionName, functionConfiguration.getVersion(), functionConfiguration.getLastModified());
		client.deleteFunction(new DeleteFunctionRequest()
				.withFunctionName(functionName)
				.withQualifier(functionConfiguration.getVersion())
		);
	}
}
 
Example #2
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteSingleFunction() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult());
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("v1").withLastModified(ZonedDateTime.now().format(DateTimeFormatter.ISO_ZONED_DATE_TIME)),
					new FunctionConfiguration().withVersion("v2").withLastModified("2018-02-05T11:15:12Z")
					))
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(functionName: 'foo', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).deleteFunction(new DeleteFunctionRequest()
			.withQualifier("v2")
			.withFunctionName("foo")
			);
	Mockito.verify(this.awsLambda).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #3
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void ignoreLatest() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult());
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("$LATEST").withLastModified(ZonedDateTime.now().minusDays(15).format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
					))
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(functionName: 'foo', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #4
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void ignoreAliases() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult()
			.withAliases(
				new AliasConfiguration().withFunctionVersion("myVersion")
			)
			);
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("myVersion").withLastModified(ZonedDateTime.now().minusDays(15).format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
					))
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(functionName: 'foo', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #5
Source File: ListFunctions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        // snippet-start:[lambda.java1.list.main]
        ListFunctionsResult functionResult = null;

        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            functionResult = awsLambda.listFunctions();

            List<FunctionConfiguration> list = functionResult.getFunctions();

            for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                FunctionConfiguration config = (FunctionConfiguration)iter.next();

                System.out.println("The function name is "+config.getFunctionName());
            }

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.list.main]
    }
 
Example #6
Source File: LambdaVH.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new lambda VH.
 *
 * @param lambda the lambda
 * @param tagsList the tags list
 */
public LambdaVH(FunctionConfiguration lambda,Map<String,String> tagsList){
	this.lambda = lambda;
	this.tags = new ArrayList<>();
	Iterator<Entry<String, String>> it = tagsList.entrySet().iterator();
	while(it.hasNext()){
		Entry<String, String> entry = it.next();
		Tag tag = new Tag();
		tag.setKey(entry.getKey());
		tag.setValue(entry.getValue());
		tags.add(tag);
	}
}
 
Example #7
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch lambda info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchLambdaInfoTest() throws Exception {
    
    mockStatic(AWSLambdaClientBuilder.class);
    AWSLambda lamdaClient = PowerMockito.mock(AWSLambda.class);
    AWSLambdaClientBuilder awsLambdaClientBuilder = PowerMockito.mock(AWSLambdaClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(awsLambdaClientBuilder.standard()).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.withCredentials(anyObject())).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.withRegion(anyString())).thenReturn(awsLambdaClientBuilder);
    when(awsLambdaClientBuilder.build()).thenReturn(lamdaClient);
    
    ListFunctionsResult listFunctionsResult = new ListFunctionsResult();
    List<FunctionConfiguration> functions = new ArrayList<>();
    FunctionConfiguration functionConfiguration = new FunctionConfiguration();
    functionConfiguration.setFunctionArn("functionArn");
    functions.add(functionConfiguration);
    listFunctionsResult.setFunctions(functions);
    when(lamdaClient.listFunctions(anyObject())).thenReturn(listFunctionsResult);
    
    ListTagsResult listTagsResult = new ListTagsResult();
    listTagsResult.setTags(new HashMap<>());
    when(lamdaClient.listTags(anyObject())).thenReturn(listTagsResult);
    assertThat(inventoryUtil.fetchLambdaInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #8
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private List<FunctionConfiguration> findAllVersions(AWSLambda client, String functionName) {
	List<FunctionConfiguration> list = new LinkedList<>();
	ListVersionsByFunctionRequest request = new ListVersionsByFunctionRequest()
		.withFunctionName(functionName);
	do {
		ListVersionsByFunctionResult result = client.listVersionsByFunction(request);
		list.addAll(result.getVersions());
		request.setMarker(result.getNextMarker());
	} while (request.getMarker() != null);

	return list;
}
 
Example #9
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void paginatedResponse() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult());
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withNextMarker("baz")
			);
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo").withMarker("baz")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("v2").withLastModified("2018-02-05T11:15:12Z")
					))
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(functionName: 'foo', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).deleteFunction(new DeleteFunctionRequest()
			.withQualifier("v2")
			.withFunctionName("foo")
			);
	Mockito.verify(this.awsLambda, Mockito.times(2)).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #10
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteCloudFormationStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult());
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("v1").withLastModified(ZonedDateTime.now().format(DateTimeFormatter.ISO_ZONED_DATE_TIME)),
					new FunctionConfiguration().withVersion("v2").withLastModified("2018-02-05T11:15:12Z")
					))
			);
	Mockito.when(this.cloudformation.describeStackResources(new DescribeStackResourcesRequest().withStackName("baz"))).thenReturn(new DescribeStackResourcesResult().withStackResources(
				new StackResource()
				.withResourceType("AWS::Lambda::Function")
				.withPhysicalResourceId("foo"),
				new StackResource()
				.withResourceType("AWS::Baz::Function")
				.withPhysicalResourceId("bar")
				)
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(stackName: 'baz', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).deleteFunction(new DeleteFunctionRequest()
			.withQualifier("v2")
			.withFunctionName("foo")
			);
	Mockito.verify(this.awsLambda).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #11
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Fetch lambda info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static  Map<String,List<LambdaVH>> fetchLambdaInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){

	Map<String,List<LambdaVH>> functions = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Lambda\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				AWSLambda lamdaClient = AWSLambdaClientBuilder.standard().
					 	withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				ListFunctionsResult listFnRslt ;
				List<FunctionConfiguration> functionsTemp ;
				List<LambdaVH> lambdaList = new ArrayList<>();
				String nextMarker = null;
				do{
					listFnRslt = lamdaClient.listFunctions(new ListFunctionsRequest().withMarker(nextMarker));
					functionsTemp = listFnRslt.getFunctions();
					if( !functionsTemp.isEmpty() ) {
						functionsTemp.forEach( function -> {
							Map<String,String> tags = lamdaClient.listTags(new ListTagsRequest().withResource(function.getFunctionArn())).getTags();
							LambdaVH  lambda = new LambdaVH(function, tags);
							lambdaList.add(lambda);
						});
					}
					nextMarker = listFnRslt.getNextMarker();
				}while(nextMarker!=null);

				if( !lambdaList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Lambda " +region.getName() + " >> "+lambdaList.size());
					functions.put(accountId+delimiter+accountName+delimiter+region.getName(),lambdaList);
				}
			}
		}catch(Exception e){
			if(region.isServiceSupported(AWSLambda.ENDPOINT_PREFIX)){
				log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
				ErrorManageUtil.uploadError(accountId,region.getName(),"lambda",e.getMessage());
			}
		}
	}
	return functions ;
}