List of usage examples for com.amazonaws.services.lambda.model InvokeRequest InvokeRequest
InvokeRequest
From source file:br.com.ingenieux.mojo.beanstalk.bundle.CodeCommitFastDeployMojo.java
License:Apache License
@Override protected String lookupVersionLabelForCommitId(String commitId) throws Exception { String s3Bucket = getService().createStorageLocation().getS3Bucket(); ObjectNode payload = objectMapper.createObjectNode(); payload.put("applicationName", applicationName); payload.put("commitId", commitId); payload.put("repoName", repoName); payload.put("description", versionDescription); payload.put("accessKey", getAWSCredentials().getCredentials().getAWSAccessKeyId()); payload.put("secretKey", getAWSCredentials().getCredentials().getAWSSecretKey()); payload.put("region", getRegion().getName()); payload.put("targetPath", format("s3://%s/apps/%s/versions/git-%s.zip", s3Bucket, applicationName, commitId)); AWSLambda lambda = getClientFactory().getService(AWSLambdaClient.class); final String payloadAsString = objectMapper.writeValueAsString(payload); getLog().info("Calling beanstalk-codecommit-deployer with arguments set to: " + redact(payloadAsString)); final InvokeResult invoke = lambda.invoke(new InvokeRequest() .withFunctionName("beanstalker-codecommit-deployer").withPayload(payloadAsString)); String resultAsString = new String(invoke.getPayload().array(), "utf-8"); if (isNotBlank(invoke.getFunctionError())) { final String errorMessage = "Unexpected: " + invoke.getFunctionError(); getLog().info(errorMessage);//from w w w. j av a 2 s . co m throw new RuntimeException(errorMessage); } else { List<String> messages = objectMapper.readValue(resultAsString, new TypeReference<List<String>>() { }); for (String m : messages) { getLog().info(m); } } return super.lookupVersionLabelForCommitId(commitId); }
From source file:com.netflix.spinnaker.clouddriver.lambda.deploy.ops.InvokeLambdaAtomicOperation.java
License:Apache License
private InvokeResult invokeFunction(String functionName, String payload) { AWSLambda client = getLambdaClient(); InvokeRequest req = new InvokeRequest().withFunctionName(functionName).withLogType(LogType.Tail) .withPayload(payload);/*from w w w. j a v a2 s . c o m*/ String qualifierRegex = "|[a-zA-Z0-9$_-]+"; if (description.getQualifier().matches(qualifierRegex)) { req.setQualifier(description.getQualifier()); } InvokeResult result = client.invoke(req); updateTaskStatus("Finished Invoking of AWS Lambda Function Operation..."); return result; }
From source file:com.nike.cerberus.operation.gateway.CreateCloudFrontSecurityGroupUpdaterLambdaOperation.java
License:Apache License
/** * Forces the lambda to run and sync the IPs for CloudFront to be white listed on the origin elb *//*from w w w . j a va 2s.c o m*/ private void forceLambdaToUpdateSgs(String arn) { String json; try { json = IOUtils.toString(this.getClass().getClassLoader() .getResourceAsStream("aws-ip-space-change-sns-sample-event.json")); } catch (IOException e) { String msg = "Failed to load mock sns message, to force Lambda first run"; logger.error(msg, e); throw new RuntimeException(msg, e); } // this will fail InvokeResult result = awsLambda.invoke(new InvokeRequest().withFunctionName(arn) .withPayload(String.format(json, BAD_HASH)).withLogType(LogType.Tail)); // collect the error so we can parse it for the latest hash String log = new String(Base64.getDecoder().decode(result.getLogResult()), Charset.forName("UTF-8")); Pattern pattern = Pattern.compile("MD5 Mismatch: got\\s(.*?)\\sexp.*?"); Matcher matcher = pattern.matcher(log); boolean matched = matcher.find(); if (!matched) { throw new RuntimeException("failed to extract hash from: " + log); } String realHash = matcher.group(1); result = awsLambda.invoke(new InvokeRequest().withFunctionName(arn) .withPayload(String.format(json, realHash)).withLogType(LogType.Tail)); logger.info("Forcing the Lambda to run and update Security Groups"); logger.info(new String(result.getPayload().array(), Charset.forName("UTF-8"))); }
From source file:example.lambda.InvokeLambdaFunction.java
License:Apache License
public static void main(String[] args) { String function_name = "HelloFunction"; String function_input = "{\"who\":\"AWS SDK for Java\"}"; AWSLambda lambda = AWSLambdaClientBuilder.defaultClient(); InvokeRequest req = new InvokeRequest().withFunctionName(function_name) .withPayload(ByteBuffer.wrap(function_input.getBytes())); InvokeResult res = lambda.invoke(req); if (res.getStatusCode() == 200) { System.out.println("Lambda function returned:"); ByteBuffer response_payload = res.getPayload(); System.out.println(new String(response_payload.array())); } else {/* w w w . j av a2 s .co m*/ System.out.format("Received a non-OK response from AWS: %d\n", res.getStatusCode()); } }
From source file:example.lambda.InvokeLambdaFunctionAsync.java
License:Apache License
public static void main(String[] args) { String function_name = "HelloFunction"; String function_input = "{\"who\":\"AWS SDK for Java\"}"; AWSLambdaAsync lambda = AWSLambdaAsyncClientBuilder.defaultClient(); InvokeRequest req = new InvokeRequest().withFunctionName(function_name) .withPayload(ByteBuffer.wrap(function_input.getBytes())); Future<InvokeResult> future_res = lambda.invokeAsync(req); System.out.print("Waiting for future"); while (future_res.isDone() == false) { System.out.print("."); try {//from w w w .j ava 2 s .c o m Thread.sleep(1000); } catch (InterruptedException e) { System.err.println("\nThread.sleep() was interrupted!"); System.exit(1); } } try { InvokeResult res = future_res.get(); if (res.getStatusCode() == 200) { System.out.println("\nLambda function returned:"); ByteBuffer response_payload = res.getPayload(); System.out.println(new String(response_payload.array())); } else { System.out.format("Received a non-OK response from AWS: %d\n", res.getStatusCode()); } } catch (InterruptedException | ExecutionException e) { System.err.println(e.getMessage()); System.exit(1); } System.exit(0); }
From source file:example.lambda.InvokeLambdaFunctionCallback.java
License:Apache License
public static void main(String[] args) { String function_name = "HelloFunction"; String function_input = "{\"who\":\"AWS SDK for Java\"}"; AWSLambdaAsync lambda = AWSLambdaAsyncClientBuilder.defaultClient(); InvokeRequest req = new InvokeRequest().withFunctionName(function_name) .withPayload(ByteBuffer.wrap(function_input.getBytes())); Future<InvokeResult> future_res = lambda.invokeAsync(req, new AsyncLambdaHandler()); System.out.print("Waiting for async callback"); while (!future_res.isDone() && !future_res.isCancelled()) { // perform some other tasks... try {//from w w w .j a v a 2 s . c o m Thread.sleep(1000); } catch (InterruptedException e) { System.err.println("Thread.sleep() was interrupted!"); System.exit(0); } System.out.print("."); } }
From source file:jp.classmethod.aws.gradle.lambda.AWSLambdaInvokeTask.java
License:Apache License
@TaskAction public void invokeFunction() throws FileNotFoundException, IOException { // to enable conventionMappings feature String functionName = getFunctionName(); if (functionName == null) { throw new GradleException("functionName is required"); }/*from www.j a v a 2 s . com*/ AWSLambdaPluginExtension ext = getProject().getExtensions().getByType(AWSLambdaPluginExtension.class); AWSLambda lambda = ext.getClient(); InvokeRequest request = new InvokeRequest().withFunctionName(functionName) .withInvocationType(getInvocationType()).withLogType(getLogType()) .withClientContext(getClientContext()).withQualifier(getQualifier()); setupPayload(request); invokeResult = lambda.invoke(request); getLogger().info("Invoke Lambda function requested: {}", functionName); }
From source file:org.alanwilliamson.amazon.lambda.LambdaAsyncExecute.java
License:Open Source License
/** * Executes a lambda function and returns the result of the execution. *///from ww w. j a v a 2 s.com @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; }
From source file:org.alanwilliamson.amazon.lambda.LambdaExecute.java
License:Open Source License
/** * Executes a lambda function and returns the result of the execution. *//* w w w .jav a2 s . c om*/ @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; } }
From source file:org.apache.nifi.processors.aws.lambda.PutLambda.java
License:Apache License
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { FlowFile flowFile = session.get();/*from w ww . j ava 2 s . co m*/ if (flowFile == null) { return; } final String functionName = context.getProperty(AWS_LAMBDA_FUNCTION_NAME).getValue(); final String qualifier = context.getProperty(AWS_LAMBDA_FUNCTION_QUALIFIER).getValue(); // Max size of message is 6 MB if (flowFile.getSize() > MAX_REQUEST_SIZE) { getLogger().error("Max size for request body is 6mb but was {} for flow file {} for function {}", new Object[] { flowFile.getSize(), flowFile, functionName }); session.transfer(flowFile, REL_FAILURE); return; } final AWSLambdaClient client = getClient(); try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(functionName) .withLogType(LogType.Tail).withInvocationType(InvocationType.RequestResponse) .withPayload(ByteBuffer.wrap(baos.toByteArray())).withQualifier(qualifier); long startTime = System.nanoTime(); InvokeResult result = client.invoke(invokeRequest); flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_STATUS_CODE, result.getStatusCode().toString()); if (!StringUtils.isBlank(result.getLogResult())) { flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_LOG, new String(Base64.decode(result.getLogResult()), Charset.defaultCharset())); } if (result.getPayload() != null) { flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_PAYLOAD, new String(result.getPayload().array(), Charset.defaultCharset())); } if (!StringUtils.isBlank(result.getFunctionError())) { flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_FUNCTION_ERROR, result.getFunctionError()); session.transfer(flowFile, REL_FAILURE); } else { session.transfer(flowFile, REL_SUCCESS); final long totalTimeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); session.getProvenanceReporter().send(flowFile, functionName, totalTimeMillis); } } catch (final InvalidRequestContentException | InvalidParameterValueException | RequestTooLargeException | ResourceNotFoundException | UnsupportedMediaTypeException unrecoverableException) { getLogger().error("Failed to invoke lambda {} with unrecoverable exception {} for flow file {}", new Object[] { functionName, unrecoverableException, flowFile }); flowFile = populateExceptionAttributes(session, flowFile, unrecoverableException); session.transfer(flowFile, REL_FAILURE); } catch (final TooManyRequestsException retryableServiceException) { getLogger().error( "Failed to invoke lambda {} with exception {} for flow file {}, therefore penalizing flowfile", new Object[] { functionName, retryableServiceException, flowFile }); flowFile = populateExceptionAttributes(session, flowFile, retryableServiceException); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); context.yield(); } catch (final AmazonServiceException unrecoverableServiceException) { getLogger().error("Failed to invoke lambda {} with exception {} for flow file {} sending to fail", new Object[] { functionName, unrecoverableServiceException, flowFile }); flowFile = populateExceptionAttributes(session, flowFile, unrecoverableServiceException); session.transfer(flowFile, REL_FAILURE); context.yield(); } catch (final Exception exception) { getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}", new Object[] { functionName, exception, flowFile }); session.transfer(flowFile, REL_FAILURE); context.yield(); } }