com.amazonaws.services.lambda.AWSLambda Java Examples

The following examples show how to use com.amazonaws.services.lambda.AWSLambda. 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: 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 #3
Source File: DeleteFunction.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Please specify a function name");
            System.exit(1);
        }

        // snippet-start:[lambda.java1.delete.main]
        String functionName = args[0];
        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            DeleteFunctionRequest delFunc = new DeleteFunctionRequest();
            delFunc.withFunctionName(functionName);

            //Delete the functiom
            awsLambda.deleteFunction(delFunc);
            System.out.println("The function is deleted");

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.delete.main]
    }
 
Example #4
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRaceConditionOnRecorderInitialization() {
    AWSXRay.setGlobalRecorder(null);
    // TracingHandler will not have the initialized recorder
    AWSLambda lambda = AWSLambdaClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();

    mockHttpClient(lambda, "null");

    // Now init the global recorder
    AWSXRayRecorder recorder = AWSXRayRecorderBuilder.defaultRecorder();
    recorder.setContextMissingStrategy(new LogErrorContextMissingStrategy());
    AWSXRay.setGlobalRecorder(recorder);

    // Test logic
    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);
}
 
Example #5
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() {
    // Setup test
    AWSLambda lambda = AWSLambdaClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();
    mockHttpClient(lambda, "null"); // Lambda returns "null" on successful fn. with no return value

    // Test logic
    Segment segment = AWSXRay.beginSegment("test");

    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);

    Assert.assertEquals(1, segment.getSubsegments().size());
    Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
    Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
 
Example #6
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private String enableCloudWatchRule(Rule existingRule, String userId, RuleState ruleState) throws PacManException {
	AWSLambda awsLambdaClient = amazonClient.getAWSLambdaClient(config.getRule().getLambda().getRegion());
	if (!checkIfPolicyAvailableForLambda(config.getRule().getLambda().getFunctionName(), awsLambdaClient)) {
		createPolicyForLambda(config.getRule().getLambda().getFunctionName(), awsLambdaClient);
	}
	
	EnableRuleRequest enableRuleRequest = new EnableRuleRequest().withName(existingRule.getRuleUUID());
	EnableRuleResult enableRuleResult = amazonClient.getAmazonCloudWatchEvents(config.getRule().getLambda().getRegion()).enableRule(enableRuleRequest);
	if (enableRuleResult.getSdkHttpMetadata() != null) {
		if(enableRuleResult.getSdkHttpMetadata().getHttpStatusCode() == 200) {
			existingRule.setUserId(userId);
			existingRule.setModifiedDate(new Date());
			existingRule.setStatus(ruleState.name());
			ruleRepository.save(existingRule);
			invokeRule(awsLambdaClient, existingRule, null, null);
			return String.format(AdminConstants.RULE_DISABLE_ENABLE_SUCCESS, ruleState.name().toLowerCase());
		}else {
			throw new PacManException(CLOUDWATCH_RULE_ENABLE_FAILURE);
		}
	} else {
		throw new PacManException(CLOUDWATCH_RULE_ENABLE_FAILURE);
	}
}
 
Example #7
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> invokeAllRules(List<String> ruleIds) {
	AWSLambda awsLambdaClient = amazonClient.getAWSLambdaClient(config.getRule().getLambda().getRegion());
	Map<String, Object> responseLists = Maps.newHashMap();
	List<String> successList = Lists.newArrayList();
	List<String> failedList = Lists.newArrayList();
	for(String ruleId: ruleIds) {
		Rule ruleInstance = ruleRepository.findById(ruleId).get();
		boolean isInvoked = invokeRule(awsLambdaClient, ruleInstance, null, Lists.newArrayList());
		if(isInvoked) {
			successList.add(ruleId);
		} else {
			failedList.add(ruleId);
		}
	}
	responseLists.put("successList", successList);
	responseLists.put("failedList", failedList);
	return responseLists;
}
 
Example #8
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private boolean invokeRule(AWSLambda awsLambdaClient, Rule ruleDetails, String invocationId, List<Map<String, Object>> additionalRuleParams) {
	String ruleParams = ruleDetails.getRuleParams();
	if(invocationId != null) {
		Map<String, Object> ruleParamDetails;
		try {
			ruleParamDetails = mapper.readValue(ruleDetails.getRuleParams(), new TypeReference<Map<String, Object>>(){});
			ruleParamDetails.put("invocationId", invocationId);
			ruleParamDetails.put("additionalParams", mapper.writeValueAsString(additionalRuleParams));
			ruleParams = mapper.writeValueAsString(ruleParamDetails);
		} catch (Exception exception) {
			log.error(UNEXPECTED_ERROR_OCCURRED, exception);
		} 
	}
	String functionName = config.getRule().getLambda().getFunctionName();
	ByteBuffer payload = ByteBuffer.wrap(ruleParams.getBytes());
	InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(functionName).withPayload(payload);
	InvokeResult invokeResult = awsLambdaClient.invoke(invokeRequest);
	if (invokeResult.getStatusCode() == 200) {
		return true;
	} else {
		return false;
	}
}
 
Example #9
Source File: BaseHandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Test
public void tagsDuplicate() throws HandlerException {
  BaseHandler.CONFIG_FILE = "/config/handler_config_tags_duplicate.json";

  TestContext context = new TestContext();
  context.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test:test_tags");

  AWSLambdaClientFactory mockFactory = mock(AWSLambdaClientFactory.class);
  AWSLambda mockLambda = mock(AWSLambda.class);
  doReturn(mockLambda).when(mockFactory).newInstance();

  ListTagsResult mockResult = mock(ListTagsResult.class);
  HashMap<String, String> functionTags = new HashMap<String, String>() {
    {
      put("f1", "foo");
      put("f2", "foo");
    }
  };
  doReturn(functionTags).when(mockResult).getTags();
  doReturn(mockResult).when(mockLambda).listTags(any());

  handler.lambdaClientFactory = mockFactory;
  handler.init(context);
  Map<String, String> actual = handler.monitor.getTagsMap();

  HashMap<String, String> expected = new HashMap<String, String>() {
    {
      put("f1", "foo");
      put("f2", "foo");
      put("u1", "bar");
    }
  };

  assertTrue(actual.entrySet().containsAll(expected.entrySet()));
}
 
Example #10
Source File: BaseHandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaFunctionTags() throws HandlerException {
  BaseHandler.CONFIG_FILE = "/config/handler_config_tags.json";

  TestContext context = new TestContext();
  context.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test:test_tags");

  AWSLambdaClientFactory mockFactory = mock(AWSLambdaClientFactory.class);
  AWSLambda mockLambda = mock(AWSLambda.class);
  doReturn(mockLambda).when(mockFactory).newInstance();

  ListTagsResult mockResult = mock(ListTagsResult.class);
  HashMap<String, String> expected = new HashMap<String, String>() {
    {
      put("t1", "foo");
      put("t2", "bar");
    }
  };
  doReturn(expected).when(mockResult).getTags();
  doReturn(mockResult).when(mockLambda).listTags(any());

  handler.lambdaClientFactory = mockFactory;
  handler.init(context);
  Map<String, String> actual = handler.monitor.getTagsMap();

  assertTrue(actual.entrySet().containsAll(expected.entrySet()));
}
 
Example #11
Source File: BaseHandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Test
public void tagsCloudformation() throws HandlerException {
  BaseHandler.CONFIG_FILE = "/config/handler_config_tags_duplicate.json";

  TestContext context = new TestContext();
  context.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test:test_tags");

  AWSLambdaClientFactory mockFactory = mock(AWSLambdaClientFactory.class);
  AWSLambda mockLambda = mock(AWSLambda.class);
  doReturn(mockLambda).when(mockFactory).newInstance();

  ListTagsResult mockResult = mock(ListTagsResult.class);
  HashMap<String, String> functionTags = new HashMap<String, String>() {
    {
      put("f1", "foo");
      put("aws:cloudformation:foo", "foo");
      put("aws:cloudformation:bar", "bar");
    }
  };
  doReturn(functionTags).when(mockResult).getTags();
  doReturn(mockResult).when(mockLambda).listTags(any());

  handler.lambdaClientFactory = mockFactory;
  handler.init(context);
  Map<String, String> actual = handler.monitor.getTagsMap();

  HashMap<String, String> expected = new HashMap<String, String>() {
    {
      put("f1", "foo");
      put("u1", "bar");
    }
  };

  assertTrue(actual.entrySet().containsAll(expected.entrySet()));
}
 
Example #12
Source File: InvokeLambdaStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Object run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);
	AWSLambda client = AWSClientFactory.create(AWSLambdaClientBuilder.standard(), this.getContext());

	String functionName = this.step.getFunctionName();

	listener.getLogger().format("Invoke Lambda function %s%n", functionName);

	InvokeRequest request = new InvokeRequest();
	request.withFunctionName(functionName);
	request.withPayload(this.step.getPayloadAsString());
	request.withLogType(LogType.Tail);

	InvokeResult result = client.invoke(request);

	listener.getLogger().append(this.getLogResult(result));
	String functionError = result.getFunctionError();
	if (functionError != null) {
		throw new RuntimeException("Invoke lambda failed! " + this.getPayloadAsString(result));
	}
	if (this.step.isReturnValueAsString()) {
		return this.getPayloadAsString(result);
	} else {
		return JsonUtils.fromString(this.getPayloadAsString(result));
	}
}
 
Example #13
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 #14
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void deleteAllStackFunctionVersions(AWSLambda client, String stackName) throws Exception  {
	TaskListener listener = Execution.this.getContext().get(TaskListener.class);
	listener.getLogger().format("Deleting old versions from stackName=%s%n", stackName);
	AmazonCloudFormation cloudformation = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getContext());
	DescribeStackResourcesResult result = cloudformation.describeStackResources(new DescribeStackResourcesRequest()
			.withStackName(stackName)
	);
	for (StackResource stackResource : result.getStackResources()) {
		if ("AWS::Lambda::Function".equals(stackResource.getResourceType())) {
			deleteAllVersions(client, stackResource.getPhysicalResourceId());
		}
	}
}
 
Example #15
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public String run() throws Exception {

	AWSLambda client = AWSClientFactory.create(AWSLambdaClientBuilder.standard(), this.getContext());

	if (this.step.functionName != null) {
		deleteAllVersions(client, this.step.functionName);
	}

	if (this.step.stackName != null) {
		deleteAllStackFunctionVersions(client, this.step.stackName);
	}
	return null;
}
 
Example #16
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setupSdk() throws Exception {
	PowerMockito.mockStatic(AWSClientFactory.class);
	this.awsLambda = Mockito.mock(AWSLambda.class);
	this.cloudformation = Mockito.mock(AmazonCloudFormation.class);
	PowerMockito.when(AWSClientFactory.create(Mockito.any(AwsSyncClientBuilder.class), Mockito.any(StepContext.class)))
		.thenAnswer( (x) -> {
			if (x.getArgumentAt(0, AwsSyncClientBuilder.class) instanceof AWSLambdaClientBuilder) {
				return awsLambda;
			} else {
				return cloudformation;
			}
		});
}
 
Example #17
Source File: FeignLambdaServiceInvokerClient.java    From jrestless with Apache License 2.0 5 votes vote down vote up
FeignLambdaServiceInvokerClient(LambdaInvokerFactory.Builder builder, AWSLambda awsLambdaClient,
		String functionName, String functionAlias, String functionVersion) {
	requireNonNull(awsLambdaClient);
	requireNonNull(functionName);
	service = builder
			.lambdaFunctionNameResolver((method, annotation, config) -> functionName)
			.functionAlias(functionAlias)
			.functionVersion(functionVersion)
			.lambdaClient(awsLambdaClient)
			.build(LambdaInvokerService.class);
}
 
Example #18
Source File: FeignLambdaServiceInvokerClient.java    From jrestless with Apache License 2.0 5 votes vote down vote up
protected AWSLambda resolveAwsLambdaClient() {
	AWSLambda resolvedClient = awsLambdaClient;
	if (resolvedClient == null && region != null) {
		resolvedClient = AWSLambdaClientBuilder.standard().withRegion(region).build();
	}
	return requireToBuild(resolvedClient, "an awsLambdaClient or a region is required");
}
 
Example #19
Source File: FeignLambdaInvokerServiceClientBuilderTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void setFunctionName_LambdaClientGiven_ShouldUseLambdaClient() {
	AWSLambda myLambdaClient = mock(AWSLambda.class);
	builder.setFunctionName(FUNCTION_NAME);
	builder.setAwsLambdaClient(myLambdaClient);
	builder.build();
	verify(builder).create(myLambdaClient, FUNCTION_NAME, null, null);
}
 
Example #20
Source File: FeignLambdaInvokerServiceClientBuilderTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void setFunctionName_LambdaClientAndRegionGiven_ShouldUseLambdaClient() {
	AWSLambda myLambdaClient = mock(AWSLambda.class);
	builder.setFunctionName(FUNCTION_NAME);
	builder.setRegion(Regions.AP_NORTHEAST_1);
	builder.setAwsLambdaClient(myLambdaClient);
	builder.build();
	verify(builder).create(myLambdaClient, FUNCTION_NAME, null, null);
}
 
Example #21
Source File: FeignLambdaServiceInvokerClientTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void init_LambdaClientGiven_ShouldUseOnInvocationBuilder() {
	AWSLambda myLambdaClient = mock(AWSLambda.class);
	FeignLambdaServiceInvokerClient invokerClient = init(myLambdaClient, FUNCTION_NAME, null, null);
	verify(lambdaInvokerFactoryBuilder).lambdaClient(myLambdaClient);
	verify(lambdaInvokerFactoryBuilder).lambdaFunctionNameResolver(eqFn(FUNCTION_NAME));
	verify(lambdaInvokerFactoryBuilder).functionAlias(isNull());
	verify(lambdaInvokerFactoryBuilder).functionVersion(isNull());
	verify(lambdaInvokerFactoryBuilder).build(LambdaInvokerService.class);
	assertEquals(service, invokerClient.getInvokerService());
}
 
Example #22
Source File: LambdaUploadBuildStepVariablesTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetLambdaClientConfig() throws Exception {
    LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", "full", false, null, false, "subnet1, subnet2", "secgroup");
    variables.expandVariables(new EnvVars());
    LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();

    AWSLambda lambda = lambdaClientConfig.getClient();
    assertNotNull(lambda);
}
 
Example #23
Source File: LambdaUploadVariablesTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetLambdaClientConfig() throws Exception {
    LambdaUploadVariables variables = new LambdaUploadVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", true, false, "full", null, false, "subnet1, subnet2", "secgroup");
    variables.expandVariables(new EnvVars());
    LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();

    AWSLambda lambda = lambdaClientConfig.getClient();
    assertNotNull(lambda);
}
 
Example #24
Source File: LambdaPublishBuildStepVariablesTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetLambdaClientConfig() throws Exception {
    LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION");
    variables.expandVariables(new EnvVars());
    LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();

    AWSLambda lambda = lambdaClientConfig.getClient();
    assertNotNull(lambda);
}
 
Example #25
Source File: LambdaPublishVariablesTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetLambdaClientConfig() throws Exception {
    LambdaPublishVariables variables = new LambdaPublishVariables(false, "KEY", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION");
    variables.expandVariables(new EnvVars());
    LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();

    AWSLambda lambda = lambdaClientConfig.getClient();
    assertNotNull(lambda);
}
 
Example #26
Source File: LambdaAsyncExecute.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Executes a lambda function and returns the result of the execution.
 */
@Override
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {

	AmazonKey amazonKey = getAmazonKey( _session, argStruct );

	// Arguments to extract
	String payload = getNamedStringParam( argStruct, "payload", null );
	String functionName = getNamedStringParam( argStruct, "function", null );
	String qualifier = getNamedStringParam( argStruct, "qualifier", null );

	try {

		// Construct the Lambda Client
		InvokeRequest invokeRequest = new InvokeRequest();
		invokeRequest.setInvocationType( InvocationType.Event );
		invokeRequest.setLogType( LogType.Tail );
		invokeRequest.setFunctionName( functionName );
		invokeRequest.setPayload( payload );
		if ( qualifier != null ) {
			invokeRequest.setQualifier( qualifier );
		}

		// Lambda client must be created with credentials
		BasicAWSCredentials awsCreds = new BasicAWSCredentials( amazonKey.getKey(), amazonKey.getSecret() );
		AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
				.withRegion( amazonKey.getAmazonRegion().toAWSRegion().getName() )
				.withCredentials( new AWSStaticCredentialsProvider( awsCreds ) ).build();

		// Execute
		awsLambda.invoke( invokeRequest );

	} catch ( Exception e ) {
		throwException( _session, "AmazonLambdaAsyncExecute: " + e.getMessage() );
		return cfBooleanData.FALSE;
	}

	return cfBooleanData.TRUE;
}
 
Example #27
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AWSLambda awsLambda() {
    return decorateWithConfigsAndBuild(
        AWSLambdaClientBuilder.standard(),
        LocalstackDocker::getEndpointLambda
    );
}
 
Example #28
Source File: JobExecutionManagerServiceImpl.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private void invokeRule(AWSLambda awsLambdaClient, String lambdaFunctionName, String params) {
	InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(lambdaFunctionName).withPayload(ByteBuffer.wrap(params.getBytes()));
	InvokeResult invokeResult = awsLambdaClient.invoke(invokeRequest);
	if (invokeResult.getStatusCode() == 200) {
		invokeResult.getPayload();
	} else {
		log.error("Received a non-OK response from AWS: "+invokeResult.getStatusCode());
	}
}
 
Example #29
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public String invokeRule(String ruleId, List<Map<String, Object>> ruleOptionalParams) {
	Rule ruleDetails = ruleRepository.findById(ruleId).get();
	AWSLambda awsLambdaClient = amazonClient.getAWSLambdaClient(config.getRule().getLambda().getRegion());
	String invocationId = AdminUtils.getReferenceId();
	boolean invokeStatus = invokeRule(awsLambdaClient, ruleDetails, invocationId, ruleOptionalParams);
	if(invokeStatus) {
		return invocationId;
	} else {
		return null;
	}
}
 
Example #30
Source File: RuleServiceImpl.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private void createUpdateCloudWatchEventRule(final Rule ruleDetails) {	
	try {
		PutRuleRequest ruleRequest = new PutRuleRequest()
			.withName(ruleDetails.getRuleUUID())
	    	.withDescription(ruleDetails.getRuleId());
			 ruleRequest.withScheduleExpression("cron(".concat(ruleDetails.getRuleFrequency()).concat(")"));

		AWSLambda awsLambdaClient = amazonClient.getAWSLambdaClient(config.getRule().getLambda().getRegion());
		
		if (!checkIfPolicyAvailableForLambda(config.getRule().getLambda().getFunctionName(), awsLambdaClient)) {
			createPolicyForLambda(config.getRule().getLambda().getFunctionName(), awsLambdaClient);
		}
	
		if (ruleDetails.getStatus().equalsIgnoreCase(RuleState.ENABLED.name())) {
			ruleRequest.setState(RuleState.ENABLED);
		} else {
			ruleRequest.setState(RuleState.DISABLED);
		}

		PutRuleResult ruleResult = amazonClient.getAmazonCloudWatchEvents(config.getRule().getLambda().getRegion()).putRule(ruleRequest);
		if (ruleResult.getRuleArn() != null) {
			ruleDetails.setRuleArn(ruleResult.getRuleArn());
			boolean isLambdaFunctionLinked = linkTargetWithRule(ruleDetails);
			if(!isLambdaFunctionLinked) { 
				//message.put(RuleConst.SUCCESS.getName(), false);
				//message.put(RuleConst.MESSAGE.getName(), "Unexpected Error Occured!");
			} else {
				ruleRepository.save(ruleDetails);
				invokeRule(awsLambdaClient, ruleDetails, null, null);
			}
		} else {
			//message.put(RuleConst.SUCCESS.getName(), false);
			//message.put(RuleConst.MESSAGE.getName(), "Unexpected Error Occured!");
		}
	} catch(Exception exception) {
		log.error(UNEXPECTED_ERROR_OCCURRED, exception);
	}
}