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

The following examples show how to use com.amazonaws.services.lambda.model.InvocationType. 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: InvocationClientTest.java    From kafka-connect-lambda with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckPayloadSizeForInvocationTypeWithInvocationFailureModeDropContinues() {
    InvocationResponse testResp = null;
    RequestTooLargeException ex = null;

    InvocationClient client = newClientWithFailureMode(InvocationFailure.DROP);

    try {
        testResp = client.checkPayloadSizeForInvocationType(
            "testpayload".getBytes(),
            InvocationType.RequestResponse,
            Instant.now(),
            new RequestTooLargeException("Request payload is too large!"));
    } catch (RequestTooLargeException e) {
        ex = e;
    }

    assertNull(ex);
    assertNotNull(testResp);
    assertEquals(413, testResp.getStatusCode().intValue());
}
 
Example #2
Source File: LambdaInvokeServiceTest.java    From aws-lambda-jenkins-plugin with MIT License 6 votes vote down vote up
@Test
public void testInvokeLambdaFunctionAsynchronousError() throws Exception {
    InvokeConfig invokeConfig = new InvokeConfig("function", "{\"key1\": \"value1\"}", false, null);

    when(awsLambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(new InvokeResult().withFunctionError("Handled"));

    try {
        lambdaInvokeService.invokeLambdaFunction(invokeConfig);
        fail("Should fail with LambdaInvokeException");
    } catch (LambdaInvokeException lie){
        assertEquals("Function returned error of type: Handled", lie.getMessage());
    }

    verify(awsLambdaClient, times(1)).invoke(invokeRequestArg.capture());
    InvokeRequest invokeRequest = invokeRequestArg.getValue();
    assertEquals("function", invokeRequest.getFunctionName());
    assertEquals("{\"key1\": \"value1\"}", new String(invokeRequest.getPayload().array(), Charset.forName("UTF-8")));
    assertEquals(InvocationType.Event.toString(), invokeRequest.getInvocationType());
    verify(jenkinsLogger).log(eq("Lambda invoke request:%n%s%nPayload:%n%s%n"), anyVararg());
    verify(jenkinsLogger).log(eq("Lambda invoke response:%n%s%nPayload:%n%s%n"), anyVararg());
}
 
Example #3
Source File: LambdaInvokeServiceTest.java    From aws-lambda-jenkins-plugin with MIT License 6 votes vote down vote up
@Test
public void testInvokeLambdaFunctionAsynchronous() throws Exception {
    InvokeConfig invokeConfig = new InvokeConfig("function", "{\"key1\": \"value1\"}", false, null);

    when(awsLambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(new InvokeResult());

    String result = lambdaInvokeService.invokeLambdaFunction(invokeConfig);

    verify(awsLambdaClient, times(1)).invoke(invokeRequestArg.capture());
    InvokeRequest invokeRequest = invokeRequestArg.getValue();
    assertEquals("function", invokeRequest.getFunctionName());
    assertEquals("{\"key1\": \"value1\"}", new String(invokeRequest.getPayload().array(), Charset.forName("UTF-8")));
    assertEquals(InvocationType.Event.toString(), invokeRequest.getInvocationType());
    verify(jenkinsLogger).log(eq("Lambda invoke request:%n%s%nPayload:%n%s%n"), anyVararg());
    verify(jenkinsLogger).log(eq("Lambda invoke response:%n%s%nPayload:%n%s%n"), anyVararg());
    assertEquals("", result);
}
 
Example #4
Source File: SkillClient.java    From alexa-meets-polly with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: InvocationClientTest.java    From kafka-connect-lambda with Apache License 2.0 5 votes vote down vote up
@Test(expected = RequestTooLargeException.class)
public void testCheckPayloadSizeForInvocationTypeWithInvocationFailureModeStopThrowsException() {
    InvocationClient client = newClientWithFailureMode(InvocationFailure.STOP);

    client.checkPayloadSizeForInvocationType(
        "testpayload".getBytes(),
        InvocationType.RequestResponse,
        Instant.now(),
        new RequestTooLargeException("Request payload is too large!"));
}
 
Example #6
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 #7
Source File: LambdaInvokeServiceTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testInvokeLambdaFunctionSynchronous() throws Exception {
    final String logBase64 = "bGFtYmRh";
    final String log = "lambda";
    final String requestPayload = "{\"key1\": \"value1\"}";
    final String responsePayload = "{\"key2\": \"value2\"}";

    InvokeConfig invokeConfig = new InvokeConfig("function", requestPayload, true, null);

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()));

    when(awsLambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    String result = lambdaInvokeService.invokeLambdaFunction(invokeConfig);

    verify(awsLambdaClient, times(1)).invoke(invokeRequestArg.capture());
    InvokeRequest invokeRequest = invokeRequestArg.getValue();
    assertEquals("function", invokeRequest.getFunctionName());
    assertEquals(LogType.Tail.toString(), invokeRequest.getLogType());
    assertEquals(requestPayload, new String(invokeRequest.getPayload().array(), Charset.forName("UTF-8")));
    assertEquals(InvocationType.RequestResponse.toString(), invokeRequest.getInvocationType());

    ArgumentCaptor<String> stringArgs = ArgumentCaptor.forClass(String.class);
    verify(jenkinsLogger).log(eq("Lambda invoke request:%n%s%nPayload:%n%s%n"), stringArgs.capture());
    List<String> stringArgValues = stringArgs.getAllValues();
    assertEquals(Arrays.asList(invokeRequest.toString(), requestPayload), stringArgValues);

    verify(jenkinsLogger).log(eq("Log:%n%s%n"), eq(log));

    stringArgs = ArgumentCaptor.forClass(String.class);
    verify(jenkinsLogger).log(eq("Lambda invoke response:%n%s%nPayload:%n%s%n"), stringArgs.capture());
    stringArgValues = stringArgs.getAllValues();
    assertEquals(Arrays.asList(invokeResult.toString(), responsePayload), stringArgValues);

    assertEquals(responsePayload, result);
}
 
Example #8
Source File: LambdaInvokeService.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
/**
 * Synchronously or asynchronously invokes an AWS Lambda function.
 * If synchronously invoked, the AWS Lambda log is collected and the response payload is returned
 * @param invokeConfig AWS Lambda invocation configuration
 * @return response payload
 */
public String invokeLambdaFunction(InvokeConfig invokeConfig) throws LambdaInvokeException {
    InvokeRequest invokeRequest = new InvokeRequest()
            .withFunctionName(invokeConfig.getFunctionName())
            .withPayload(invokeConfig.getPayload());

    if(invokeConfig.isSynchronous()){
        invokeRequest
                .withInvocationType(InvocationType.RequestResponse)
                .withLogType(LogType.Tail);
    } else {
        invokeRequest
                .withInvocationType(InvocationType.Event);
    }
    logger.log("Lambda invoke request:%n%s%nPayload:%n%s%n", invokeRequest.toString(), invokeConfig.getPayload());

    InvokeResult invokeResult = client.invoke(invokeRequest);
    String payload = "";
    if(invokeResult.getPayload() != null){
        payload = new String(invokeResult.getPayload().array(), Charset.forName("UTF-8"));
    }
    logger.log("Lambda invoke response:%n%s%nPayload:%n%s%n", invokeResult.toString(), payload);

    if(invokeResult.getLogResult() != null){
        logger.log("Log:%n%s%n", new String(Base64.decode(invokeResult.getLogResult()), Charset.forName("UTF-8")));
    }

    if(StringUtils.isNotEmpty(invokeResult.getFunctionError())){
        throw new LambdaInvokeException("Function returned error of type: " + invokeResult.getFunctionError());
    }

    return payload;
}
 
Example #9
Source File: AlexaLambdaEndpoint.java    From alexa-skills-kit-tester-java with Apache License 2.0 5 votes vote down vote up
public Optional<AlexaResponse> fire(AlexaRequest request, String payload) {
    final InvocationType invocationType = request.expectsResponse() ? InvocationType.RequestResponse : InvocationType.Event;
    final InvokeRequest invokeRequest = new InvokeRequest()
            .withInvocationType(invocationType)
            .withFunctionName(lambdaFunctionName)
            .withPayload(payload);
    log.info(String.format("->[INFO] Invoke lambda function '%s'.", lambdaFunctionName));
    log.debug(String.format("->[INFO] with request payload '%s'.", payload));
    final InvokeResult invokeResult = lambdaClient.invoke(invokeRequest);
    return invocationType.equals(InvocationType.RequestResponse) ?
            Optional.of(new AlexaResponse(request, payload, new String(invokeResult.getPayload().array()))) : Optional.empty();
}
 
Example #10
Source File: AwsLambdaSinkConnectorConfig.java    From kafka-connect-aws-lambda with Apache License 2.0 5 votes vote down vote up
@Override
public void ensureValid(String name, Object invocationType) {
  try {
    InvocationType.fromValue(((String) invocationType).trim());
  } catch (Exception e) {
    throw new ConfigException(name, invocationType, "Value must be one of: " +
      Utils.join(InvocationType.values(), ", "));
  }
}
 
Example #11
Source File: LambdaFunctionClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the remote lambda function and returns the decompressed response as bytes.
 */
@Override
protected void invoke(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  final RemoteFunctionConfig remoteFunction = getConnectorConfig().remoteFunction;
  logger.debug(marker, "Invoking remote lambda function with id '{}' Event size is: {}", remoteFunction.id, bytes.length);

  InvokeRequest invokeReq = new InvokeRequest()
      .withFunctionName(((AWSLambda) remoteFunction).lambdaARN)
      .withPayload(ByteBuffer.wrap(bytes))
      .withInvocationType(fireAndForget ? InvocationType.Event : InvocationType.RequestResponse);

  asyncClient.invokeAsync(invokeReq, new AsyncHandler<InvokeRequest, InvokeResult>() {
    @Override
    public void onError(Exception exception) {
      if (callback == null) {
        logger.error(marker, "Error sending event to remote lambda function", exception);
      }
      else {
        callback.handle(Future.failedFuture(getWHttpException(marker, exception)));
      }
    }

    @Override
    public void onSuccess(InvokeRequest request, InvokeResult result) {
      byte[] responseBytes = new byte[result.getPayload().remaining()];
      result.getPayload().get(responseBytes);
      callback.handle(Future.succeededFuture(responseBytes));
    }
  });
}
 
Example #12
Source File: InvocationClient.java    From kafka-connect-lambda with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param payload a byte array representation of the payload sent to AWS Lambda service
 * @param event   enumeration type to determine if we are sending in aynch, sync, or no-op mode
 * @param start   time instance when Lambda invocation was started
 * @param e       exception indicative of the payload size being over the max allowable
 * @return        a rolled up Lambda invocation response
 * @throws        RequestTooLargeException is rethrown if the failure mode is set to stop immediately
 */
InvocationResponse checkPayloadSizeForInvocationType(final byte[] payload, final InvocationType event, final Instant start, final RequestTooLargeException e) {
    switch (event) {

        case Event:
            if (payload.length > maxAsyncPayloadSizeBytes) {
                LOGGER.error("{} bytes payload exceeded {} bytes invocation limit for asynchronous Lambda call", payload.length, maxAsyncPayloadSizeBytes);
            }
            break;

        case RequestResponse:
            if (payload.length > maxSyncPayloadSizeBytes) {
                LOGGER.error("{} bytes payload exceeded {} bytes invocation limit for synchronous Lambda call", payload.length, maxSyncPayloadSizeBytes);
            }
            break;

        default:
            LOGGER.info("Dry run call to Lambda with payload size {}", payload.length);
            break;
    }

    if (failureMode.equals(InvocationFailure.STOP)) {
        throw e;
    }
    // Drop message and continue
    return new InvocationResponse(413, e.getLocalizedMessage(), e.getLocalizedMessage(), start, Instant.now());
}
 
Example #13
Source File: PutLambda.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    FlowFile flowFile = session.get();
    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();
    }
}
 
Example #14
Source File: AwsLambdaSinkConnectorConfig.java    From kafka-connect-aws-lambda with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
  return "[" + Utils.join(InvocationType.values(), ", ") + "]";
}
 
Example #15
Source File: AwsLambdaSinkConnectorConfig.java    From kafka-connect-aws-lambda with Apache License 2.0 4 votes vote down vote up
@Override
public List<Object> validValues(String name, Map<String, Object> connectorConfigs) {
  return Arrays.asList(InvocationType.values());
}
 
Example #16
Source File: AwsLambdaSinkConnectorConfig.java    From kafka-connect-aws-lambda with Apache License 2.0 4 votes vote down vote up
private InvocationType getAwsLambdaInvocationType() {
  return InvocationType.fromValue(this.getString(INVOCATION_TYPE_CONFIG));
}
 
Example #17
Source File: LambdaInvokeServiceTest.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
@Test
public void testInvokeLambdaFunctionSynchronousError() throws Exception {
    final String logBase64 = "bGFtYmRh";
    final String log = "lambda";
    final String requestPayload = "{\"key1\": \"value1\"}";
    final String responsePayload = "{\"errorMessage\":\"event_fail\"}";

    InvokeConfig invokeConfig = new InvokeConfig("function", requestPayload, true, null);

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()))
            .withFunctionError("Unhandled");

    when(awsLambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    try {
        lambdaInvokeService.invokeLambdaFunction(invokeConfig);
        fail("Should fail with LambdaInvokeException");
    } catch (LambdaInvokeException lie){
        assertEquals("Function returned error of type: Unhandled", lie.getMessage());
    }

    verify(awsLambdaClient, times(1)).invoke(invokeRequestArg.capture());
    InvokeRequest invokeRequest = invokeRequestArg.getValue();
    assertEquals("function", invokeRequest.getFunctionName());
    assertEquals(LogType.Tail.toString(), invokeRequest.getLogType());
    assertEquals(requestPayload, new String(invokeRequest.getPayload().array(), Charset.forName("UTF-8")));
    assertEquals(InvocationType.RequestResponse.toString(), invokeRequest.getInvocationType());

    ArgumentCaptor<String> stringArgs = ArgumentCaptor.forClass(String.class);
    verify(jenkinsLogger).log(eq("Lambda invoke request:%n%s%nPayload:%n%s%n"), stringArgs.capture());
    List<String> stringArgValues = stringArgs.getAllValues();
    assertEquals(Arrays.asList(invokeRequest.toString(), requestPayload), stringArgValues);

    verify(jenkinsLogger).log(eq("Log:%n%s%n"), eq(log));

    stringArgs = ArgumentCaptor.forClass(String.class);
    verify(jenkinsLogger).log(eq("Lambda invoke response:%n%s%nPayload:%n%s%n"), stringArgs.capture());
    stringArgValues = stringArgs.getAllValues();
    assertEquals(Arrays.asList(invokeResult.toString(), responsePayload), stringArgValues);
}
 
Example #18
Source File: LambdaExecute.java    From openbd-core with GNU General Public License v3.0 4 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.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;
	}

}
 
Example #19
Source File: PutLambda.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    FlowFile flowFile = session.get();
    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();
    }
}