Gistrec

AWS Lambda C++ download file from s3

Nov 30th, 2019
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.05 KB | None | 0 0
  1. #include <aws/core/Aws.h>
  2. #include <aws/core/utils/logging/LogLevel.h>
  3. #include <aws/core/utils/logging/ConsoleLogSystem.h>
  4. #include <aws/core/utils/logging/LogMacros.h>
  5. #include <aws/core/utils/json/JsonSerializer.h>
  6. #include <aws/core/utils/HashingUtils.h>
  7. #include <aws/core/platform/Environment.h>
  8. #include <aws/core/client/ClientConfiguration.h>
  9. #include <aws/core/auth/AWSCredentialsProvider.h>
  10. #include <aws/s3/S3Client.h>
  11. #include <aws/s3/model/GetObjectRequest.h>
  12. #include <aws/lambda-runtime/runtime.h>
  13. #include <iostream>
  14. #include <memory>
  15. #include <fstream>
  16.  
  17. using namespace aws::lambda_runtime;
  18.  
  19.  
  20. char const TAG[] = "LAMBDA_ALLOC";
  21.  
  22. enum class Status {
  23.     Success,
  24.     Failure
  25. };
  26.  
  27. std::string download_file(Aws::S3::S3Client const& client,
  28.                           Aws::String       const& bucket,
  29.                           Aws::String       const& key,
  30.                           Aws::String            & output)
  31. {
  32.     Aws::S3::Model::GetObjectRequest request;
  33.  
  34.     request.WithBucket(bucket).WithKey(key);
  35.  
  36.     auto outcome = client.GetObject(request);
  37.     if (outcome.IsSuccess()) {
  38.         AWS_LOGSTREAM_INFO(TAG, "Download completed!");
  39.  
  40.         Aws::StringStream ss;
  41.         ss << outcome.GetResult().GetBody().rdbuf();
  42.  
  43.         output = ss.str();
  44.         return "";
  45.     }else {
  46.         AWS_LOGSTREAM_ERROR(TAG, "Failed with error: " << outcome.GetError());
  47.         return outcome.GetError().GetMessage();
  48.     }
  49. }
  50.  
  51. static invocation_response getResponse(Status status, const std::string& body) {
  52.     Aws::Utils::Json::JsonValue response;
  53.     response.WithString("body", body.c_str()).WithInteger("statusCode", 200);
  54.     std::string payload = response.View().WriteCompact();
  55.  
  56.     if (status == Status::Failure) return invocation_response::success(payload, "");
  57.     else return invocation_response::success(payload, "application/json");
  58. }
  59.  
  60. static invocation_response my_handler(invocation_request const& req, Aws::S3::S3Client const& client) {
  61.     Aws::Utils::Json::JsonValue json(req.payload);
  62.     if (!json.WasParseSuccessful()) {
  63.         return getResponse(Status::Failure, "InvalidJSON: Failed to parse input JSON");
  64.     }
  65.  
  66.     return getResponse(Status::Failure, a);
  67.  
  68.     auto query = json.View().GetObject("queryStringParameters");
  69.  
  70.     if (!query.ValueExists("s3bucket") || !query.GetObject("s3bucket").IsString() ||
  71.         !query.ValueExists("s3key")    || !query.GetObject("s3key").IsString())
  72.     {
  73.         return getResponse(Status::Failure, "InvalidJSON: Missing input value s3bucket or s3key");
  74.     }
  75.  
  76.     auto bucket = query.GetString("s3bucket");
  77.     auto key    = query.GetString("s3key");
  78.  
  79.     AWS_LOGSTREAM_INFO(TAG, "Attempting to download file from s3://" << bucket << "/" << key);
  80.  
  81.     Aws::String file;
  82.     auto err = download_file(client, bucket, key, file);
  83.     if (!err.empty()) {
  84.         return getResponse(Status::Failure, std::string("DownloadFailure: ") + err);
  85.     }
  86.  
  87.     return getResponse(Status::Success, file);
  88. }
  89.  
  90.  
  91. std::function<std::shared_ptr<Aws::Utils::Logging::LogSystemInterface>()> GetConsoleLoggerFactory()
  92. {
  93.     return [] {
  94.         return Aws::MakeShared<Aws::Utils::Logging::ConsoleLogSystem>(
  95.             "console_logger", Aws::Utils::Logging::LogLevel::Trace);
  96.     };
  97. }
  98.  
  99.  
  100. int main() {
  101.     using namespace Aws;
  102.     SDKOptions options;
  103.     options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
  104.     options.loggingOptions.logger_create_fn = GetConsoleLoggerFactory();
  105.     InitAPI(options);
  106.     {
  107.         Client::ClientConfiguration config;
  108.         config.region = Aws::Environment::GetEnv("AWS_REGION");
  109.         config.caFile = "/etc/pki/tls/certs/ca-bundle.crt";
  110.  
  111.         auto credentialsProvider = Aws::MakeShared<Aws::Auth::EnvironmentAWSCredentialsProvider>(TAG);
  112.         S3::S3Client client(credentialsProvider, config);
  113.         auto handler_fn = [&client](aws::lambda_runtime::invocation_request const& req) {
  114.             return my_handler(req, client);
  115.         };
  116.         run_handler(handler_fn);
  117.     }
  118.     ShutdownAPI(options);
  119.     return 0;
  120. }
Add Comment
Please, Sign In to add comment