private static synchronized String getLambdaName(String service) { String lambdaName = serviceAndNametoLambdaName.get(service); if (lambdaName == null) { AWSLambdaClient lambdaClient = new AWSLambdaClient(); ListFunctionsResult lambdas = lambdaClient.listFunctions(); for (FunctionConfiguration lambda : lambdas.getFunctions()) { log.info("Have lambda with name {}", lambda.getFunctionName()); String[] components = lambda.getFunctionName().split("\\-"); if (components.length > 1) { // lambda format // stack-function-random serviceAndNametoLambdaName.put(components[1], lambda.getFunctionName()); } } } lambdaName = serviceAndNametoLambdaName.get(service); log.info("am returning {} for lambda with name {}", lambdaName, service); return lambdaName; }
public String translate(final String testPhrase, final String language) { final Map<String, Slot> slots = new HashMap<>(); slots.put("termA", Slot.builder().withName("termA").withValue(testPhrase).build()); slots.put("termB", Slot.builder().withName("termB").build()); slots.put("language", Slot.builder().withName("language").withValue(language).build()); final SpeechletRequestEnvelope envelope = givenIntentSpeechletRequestEnvelope("Translate", slots); final ObjectMapper mapper = new ObjectMapper(); String response = null; try { final AWSLambdaClient awsLambda = new AWSLambdaClient(); final InvokeRequest invokeRequest = new InvokeRequest() .withInvocationType(InvocationType.RequestResponse) .withFunctionName(lambdaName) .withPayload(mapper.writeValueAsString(envelope)); final InvokeResult invokeResult = awsLambda.invoke(invokeRequest); response = new String(invokeResult.getPayload().array()); } catch (JsonProcessingException e) { log.error(e.getMessage()); } return response; }
@Before public void setup() throws Exception { kmsClient = mock(AWSKMSClient.class); urlResolver = mock(UrlResolver.class); lambdaClient = mock(AWSLambdaClient.class); mockWebServer = new MockWebServer(); mockWebServer.start(); vaultUrl = "http://localhost:" + mockWebServer.getPort(); when(urlResolver.resolve()).thenReturn(vaultUrl); mockStatic(Regions.class); when(Regions.getCurrentRegion()).thenReturn(RegionUtils.getRegion("us-west-2")); whenNew(AWSLambdaClient.class).withNoArguments().thenReturn(lambdaClient); whenNew(AWSKMSClient.class).withAnyArguments().thenReturn(kmsClient); }
@Inject public BackendServiceFactory(InjectionManager serviceLocator) { awsLambdaClient = new AWSLambdaClient(); awsLambdaClient.configureRegion(BACKEND_SERVICE_REGION); backendService = Feign.builder() .client(FeignLambdaServiceInvokerClient.builder() .setRegion(BACKEND_SERVICE_REGION) .setFunctionName(BACKEND_SERVICE_FUNCTION_NAME) .build()) .decoder(new JacksonDecoder()) .encoder(new JacksonEncoder()) .logger(new Slf4jLogger()) .target(new LambdaServiceFunctionTarget<BackendService>(BackendService.class) { @Override public Request apply(RequestTemplate input) { // TODO inject the context directly => requires the context to be bound as proxy Context lambdaContext = serviceLocator.getInstance(Context.class); // propagate the AWS request ID => the called service can log the original AWS request ID input.header("X-Base-Aws-Request-Id", lambdaContext.getAwsRequestId()); return super.apply(input); } }); }
private String createLambda(AWSLambdaClient lambdaClient, String handler, String name, String description) { CreateFunctionRequest request = new CreateFunctionRequest(); request.setCode(buildFunctionCode()); request.setDescription(description); request.setFunctionName(name); request.setHandler(handler); request.setMemorySize(memory); request.setPublish(true); // assume or create a role? request.setRole(lambdaRoleARN); request.setRuntime("java8"); request.setTimeout(handlerTimeout); CreateFunctionResult result = lambdaClient.createFunction(request); return result.getFunctionArn(); }
private String updateLambdaConfiguration(AWSLambdaClient lambdaClient, String functionName, String description, String handlerMethod) { UpdateFunctionConfigurationRequest request = new UpdateFunctionConfigurationRequest(); request.setDescription(description); request.setFunctionName(functionName); request.setHandler(handlerMethod); request.setMemorySize(memory); request.setRole(lambdaRoleARN); request.setTimeout(handlerTimeout); UpdateFunctionConfigurationResult result = lambdaClient .updateFunctionConfiguration(request); return result.getFunctionArn(); }
/** * 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()))); }
private String updateLambdaCode(AWSLambdaClient lambdaClient, String functionName) { UpdateFunctionCodeRequest request = new UpdateFunctionCodeRequest(); request.setFunctionName(functionName); request.setPublish(true); request.setS3Bucket(codeS3Bucket); request.setS3Key(artifactName); request.setS3ObjectVersion(codeS3Version); UpdateFunctionCodeResult result = lambdaClient .updateFunctionCode(request); return result.getFunctionArn(); }
public AWSLambdaClient getClient() { if(useDefaultAWSCredentials){ return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) .withRegion(Region.getRegion(Regions.fromName(region))); } else { return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) .withRegion(Region.getRegion(Regions.fromName(region))); } }
@SuppressWarnings("unchecked") @Override public void execute() throws MojoExecutionException, MojoFailureException { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(basePackage)).setScanners( new SubTypesScanner())); Set<Class<?>> lambdaTypes = reflections .getTypesAnnotatedWith(Lambda.class); AWSLambdaClient lambdaClient = new AWSLambdaClient(); for (Class<?> type : lambdaTypes) { Set<Method> lambdaHandlers = ReflectionUtils.getAllMethods(type, ReflectionUtils.withAnnotation(LambdaHandler.class)); if (lambdaHandlers.isEmpty()) { getLog().warn( "No methods annotated with @LambdaHandler found in type: " + type.getName()); continue; } if (lambdaHandlers.size() > 1) { getLog().warn( "More than one method annotated with @LambdaHandler found in type: " + type.getName()); continue; } String handlerMethod = type.getName() + ":" + lambdaHandlers.iterator().next().getName(); Lambda lambdaData = type.getAnnotation(Lambda.class); GetFunctionRequest getFunctionReq = new GetFunctionRequest(); GetFunctionResult getFunctionRes = lambdaClient .getFunction(getFunctionReq); if (getFunctionRes != null) { if (needsConfigurationUpdate(getFunctionRes, lambdaData.name(), handlerMethod)) { updateLambdaConfiguration(lambdaClient, lambdaData.name(), lambdaData.description(), handlerMethod); } else if (needsCodeUpdate(getFunctionRes)) { updateLambdaCode(lambdaClient, lambdaData.name()); } else { getLog().warn( "Configuration and code is up to date, nothing to change."); } } else { createLambda(lambdaClient, handlerMethod, lambdaData.name(), lambdaData.description()); } } }
public LambdaDeployService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
public LambdaInvokeService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
/** * Gets an AWS Lambda cloud function client instance. This client can be used * to directly invoke Lambda cloud functions with JSON parameters and results. * @return lambda client */ public AWSLambdaClient getCloudFunctionClient() { return new AWSLambdaClient(identityManager.getCredentialsProvider(), clientConfiguration); }