public static void invokeLambda(String function, Object payload, boolean async) { String payloadString = GSON.toJson(payload); AWSLambda lambda = AWSLambdaProvider.getLambdaClient(); InvokeRequest request = new InvokeRequest() .withFunctionName(function) .withInvocationType(async ? InvocationType.Event : InvocationType.RequestResponse) .withPayload(payloadString); lambda.invoke(request); }
private boolean addPermission(String apiId, String region, String accountNumber, String serviceArn, String serviceName, AWSLambda lambdaClient, String permString) { boolean ret = false; if ( ! permString.startsWith("/")) permString = "/" + permString; getLog().info("Adding permission to lambda: " + permString); AddPermissionRequest apReq = new AddPermissionRequest() .withFunctionName(serviceName) .withAction("lambda:InvokeFunction") .withSourceArn("arn:aws:execute-api:" + region + ":" + accountNumber + ":" + apiId + permString) .withPrincipal("apigateway.amazonaws.com") .withStatementId(UUID.randomUUID().toString()); // Now update the permissions AddPermissionResult apRes = lambdaClient.addPermission(apReq); getLog().info("Statement: " + apRes.getStatement()); ret = apRes.getSdkHttpMetadata().getHttpStatusCode() == 201; getLog().info("Status: " + apRes.getSdkHttpMetadata().getHttpStatusCode()); return ret; }
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); }
@Inject public CreateCloudFrontSecurityGroupUpdaterLambdaOperation(final CloudFormationService cloudFormationService, final EnvironmentMetadata environmentMetadata, @Named(CF_OBJECT_MAPPER) final ObjectMapper cloudformationObjectMapper, AWSLambda awsLambda, AmazonS3 amazonS3) { this.cloudFormationService = cloudFormationService; this.cloudformationObjectMapper = cloudformationObjectMapper; this.environmentMetadata = environmentMetadata; this.awsLambda = awsLambda; this.amazonS3 = amazonS3; final Region region = Region.getRegion(Regions.US_EAST_1); AmazonCloudFormation amazonCloudFormation = new AmazonCloudFormationClient(); amazonCloudFormation.setRegion(region); amazonSNS = new AmazonSNSClient(); amazonSNS.setRegion(region); }
void deploy(AwsKeyPair keyPair, String region, String zipFilename, String functionName, Proxy proxy) { long t = System.currentTimeMillis(); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); AWSLambda lambda = AWSLambdaClientBuilder.standard().withCredentials(credentials) .withClientConfiguration(Util.createConfiguration(proxy)).withRegion(region).build(); byte[] bytes; try { bytes = IOUtils.toByteArray(new FileInputStream(zipFilename)); } catch (IOException e) { throw new RuntimeException(e); } DecimalFormat df = new DecimalFormat("0.000"); log.info("deploying " + zipFilename + ", length=" + df.format(bytes.length / 1024.0 / 1024.0) + "MB, to functionName=" + functionName); lambda.updateFunctionCode( // new UpdateFunctionCodeRequest() // .withFunctionName(functionName) // .withPublish(true) // .withZipFile(ByteBuffer.wrap(bytes))); log.info("deployed in " + (System.currentTimeMillis() - t) + "ms"); }
public static AWSLambda getLambdaClient() { String smr_stage = System.getenv().get("SMR_STAGE"); if (smr_stage.equals("DEV")) return FakeAWSLambdaHolder.LAMBDA_CLIENT; else return AWSLambdaHolder.LAMBDA_CLIENT; }
@Test public void lambdaSingletonTest() throws Exception { AWSLambda firstInstance = AWSLambdaProvider.getLambdaClient(); AWSLambda secondInstance = AWSLambdaProvider.getLambdaClient(); assertTrue(firstInstance == secondInstance); }
@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(); AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration()); ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); BasicHttpEntity responseBody = new BasicHttpEntity(); responseBody.setContent(new ByteArrayInputStream("null".getBytes(StandardCharsets.UTF_8))); // Lambda returns "null" on successful fn. with no return value httpResponse.setEntity(responseBody); try { Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)); } catch (IOException e) { } Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient); Whitebox.setInternalState(lambda, "client", amazonHttpClient); // Test logic Segment segment = AWSXRay.beginSegment("test"); InvokeRequest request = new InvokeRequest(); request.setFunctionName("testFunctionName"); InvokeResult r = lambda.invoke(request); System.out.println(r.getStatusCode()); System.out.println(r); Assert.assertEquals(1, segment.getSubsegments().size()); Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation")); System.out.println(segment.getSubsegments().get(0).getAws()); Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name")); }
public FeignLambdaServiceInvokerClient(@Nonnull AWSLambda awsLambdaClient, @Nonnull String functionName, @Nullable String functionAlias, @Nullable String functionVersion) { this(LambdaInvokerFactory.builder(), awsLambdaClient, functionName, functionAlias, functionVersion); }
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"); }
@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); }
@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); }
@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()); }
/** * Looks up the assigned role for the running Lambda via the GetFunctionConfiguration API. Requests a token from * Cerberus and attempts to decrypt it as that role. */ @Override protected void authenticate() { final Region currentRegion = RegionUtils.getRegion(this.region); final AWSLambda lambdaClient = new AWSLambdaClient(); lambdaClient.setRegion(currentRegion); final GetFunctionConfigurationResult functionConfiguration = lambdaClient.getFunctionConfiguration( new GetFunctionConfigurationRequest() .withFunctionName(functionName) .withQualifier(qualifier)); final String roleArn = functionConfiguration.getRole(); if (StringUtils.isBlank(roleArn)) { throw new IllegalStateException("Lambda function has no assigned role, aborting Cerberus authentication."); } final Matcher roleArnMatcher = IAM_ROLE_ARN_PATTERN.matcher(roleArn); if (!roleArnMatcher.matches()) { throw new IllegalStateException("Lambda function assigned role is not a valid IAM role ARN."); } try { getAndSetToken(roleArn, currentRegion); return; } catch (AmazonClientException ace) { LOGGER.warn("Unexpected error communicating with AWS services.", ace); } catch (JsonSyntaxException jse) { LOGGER.error("The decrypted auth response was not in the expected format!", jse); } catch (VaultClientException sce) { LOGGER.warn("Unable to acquire Vault token for IAM role: " + roleArn, sce); } throw new VaultClientException("Unable to acquire token with Lambda instance role."); }
/** * Binds all the Amazon services used. */ @Override protected void configure() { final Region region = Region.getRegion(Regions.fromName(regionName)); bind(AmazonEC2.class).toInstance(createAmazonClientInstance(AmazonEC2Client.class, region)); bind(AmazonCloudFormation.class).toInstance(createAmazonClientInstance(AmazonCloudFormationClient.class, region)); bind(AmazonIdentityManagement.class).toInstance(createAmazonClientInstance(AmazonIdentityManagementClient.class, region)); bind(AWSKMS.class).toInstance(createAmazonClientInstance(AWSKMSClient.class, region)); bind(AmazonS3.class).toInstance(createAmazonClientInstance(AmazonS3Client.class, region)); bind(AmazonAutoScaling.class).toInstance(createAmazonClientInstance(AmazonAutoScalingClient.class, region)); bind(AWSSecurityTokenService.class).toInstance(createAmazonClientInstance(AWSSecurityTokenServiceClient.class, region)); bind(AWSLambda.class).toInstance(createAmazonClientInstance(AWSLambdaClient.class, region)); bind(AmazonSNS.class).toInstance(createAmazonClientInstance(AmazonSNSClient.class, region)); }
protected AWSLambda getLambdaClient() { if (lambdaClient != null) { return lambdaClient; } return lambdaClient = new AWSLambdaClient(getAWSCredentialsProvideChain()).withRegion(Region.getRegion(Regions.fromName(deployment.getRegion()))); }
@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); }
@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); }
@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); }
@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); }
/** * 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; }
FunctionInvoker(LambdaFunctionService lambdaFunctionService, AWSLambda awsLambda) { this.lambdaFunctionService = lambdaFunctionService; this.awsLambda = awsLambda; }
public AWSLambda getAwsLambda() { return awsLambda; }
FunctionInvoker(FunctionService functionService, AWSLambda awsLambda) { this.functionService = functionService; this.awsLambda = awsLambda; }
public AWSLambda getLambdaClient() { return AWSLambdaClientBuilder.standard() .withRegion(Regions.US_EAST_1) .withCredentials(new LambdaCredentialsProvider(amazonProperties)) .build(); }
public Builder setAwsLambdaClient(AWSLambda awsLambdaClient) { this.awsLambdaClient = awsLambdaClient; return this; }
FeignLambdaServiceInvokerClient create(AWSLambda awsLambdaClient, String functionName, String functionAlias, String functionVersion) { return new FeignLambdaServiceInvokerClient(awsLambdaClient, functionName, functionAlias, functionVersion); }
FeignLambdaServiceInvokerClient init(AWSLambda awsLambdaClient, String functionName, String functionAlias, String functionVersion) { FeignLambdaServiceInvokerClient lambdaClient = new FeignLambdaServiceInvokerClient(lambdaInvokerFactoryBuilder, awsLambdaClient, functionName, functionAlias, functionVersion); return lambdaClient; }
public AWSLambda getLambdaClient() { return this.lambdaClient; }
public AlexaLambdaEndpointBuilder withLambdaClient(final AWSLambda lambdaClient) { this.lambdaClient = lambdaClient; return this; }
/** * 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.RequestResponse ); 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 and process the results InvokeResult result = awsLambda.invoke( invokeRequest ); // Convert the returned result ByteBuffer resultPayload = result.getPayload(); String resultJson = new String( resultPayload.array(), "UTF-8" ); Map<String, Object> resultMap = Jackson.fromJsonString( resultJson, Map.class ); return tagUtils.convertToCfData( resultMap ); } catch ( Exception e ) { throwException( _session, "AmazonLambdaExecute: " + e.getMessage() ); return cfBooleanData.FALSE; } }