-
Notifications
You must be signed in to change notification settings - Fork 55
Add s3 file ingestion sample to examples source tree for M1 release. #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c3fd97e
Add s3 file ingestion sample to examples source tree for M1 release.
kggilmer af5fac4
Updates based on PR feedback.
kggilmer 9f198c9
Tweaks to comments and constants
kggilmer 03c1873
Another tweak to avoid invalid log message in error case
kggilmer 9e8973b
fix bucket name and log bytes downloaded
kggilmer 8178acd
Merge branch 'main' into feat-s3-example
kggilmer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
|
|
||
| # AWS SDK | ||
| awsSdkKotlinVersion=0.1.0 | ||
| awsSdkKotlinVersion=0.2.0 | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| plugins { | ||
| kotlin("jvm") | ||
| } | ||
|
|
||
| val awsSdkKotlinVersion: String by project | ||
|
|
||
| dependencies { | ||
| implementation(kotlin("stdlib")) | ||
| implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3") | ||
| implementation("aws.sdk.kotlin:s3:$awsSdkKotlinVersion") | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| /* | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0. | ||
| */ | ||
| import aws.sdk.kotlin.services.s3.S3Client | ||
| import aws.sdk.kotlin.services.s3.model.* | ||
| import kotlinx.coroutines.flow.* | ||
| import kotlinx.coroutines.runBlocking | ||
| import software.aws.clientrt.content.ByteStream | ||
| import software.aws.clientrt.content.fromFile | ||
| import software.aws.clientrt.content.writeToFile | ||
| import java.io.File | ||
| import java.nio.file.Files | ||
|
|
||
| /** | ||
| * This program reads media files from a specified directory and uploads media files to S3. | ||
| * After uploading it will then download uploaded files back into a local directory. | ||
| * | ||
| * Any file with the extension `.avi` will be processed. To test create a text file and | ||
| * name it such that it matches the [filenameMetadataRegex] regex, ex: | ||
| * `title_2000.avi`. | ||
| * | ||
| * When running the sample adjust the following path constants as needed for your local environment. | ||
| */ | ||
| const val bucketName = "s3-media-ingestion-example" | ||
| const val ingestionDirPath = "/tmp/media-in" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question are these meant to be changed by the user? These paths are *unix specific.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added some notes in the file |
||
| const val completedDirPath = "/tmp/media-processed" | ||
| const val failedDirPath = "/tmp/media-failed" | ||
| const val downloadDirPath = "/tmp/media-down" | ||
|
|
||
| // media metadata is extracted from filename: <title>_<year>.avi | ||
| val filenameMetadataRegex = "([\\w\\s]+)_([\\d]+).avi".toRegex() | ||
|
|
||
| fun main(): Unit = runBlocking { | ||
| val client = S3Client { region = "us-east-2" } | ||
|
|
||
| try { | ||
| // Setup | ||
| client.ensureBucketExists(bucketName) | ||
| listOf(completedDirPath, failedDirPath, downloadDirPath).forEach { validateDirectory(it) } | ||
| val ingestionDir = validateDirectory(ingestionDirPath) | ||
|
|
||
| // Upload files | ||
| val uploadResults = ingestionDir | ||
| .walk() | ||
| .asFlow() | ||
| .mapNotNull(::mediaMetadataExtractor) | ||
| .map { mediaMetadata -> client.uploadToS3(mediaMetadata) } | ||
| .toList() | ||
|
|
||
| moveFiles(uploadResults) | ||
|
|
||
| // Print results of operation | ||
| val (successes, failures) = uploadResults.partition { it is Success } | ||
| when (failures.isEmpty()) { | ||
| true -> println("Media uploaded successfully: $successes") | ||
| false -> println("Successfully uploaded: $successes \nFailed to upload: $failures") | ||
| } | ||
|
|
||
| // Download files to verify | ||
| client.listObjects(ListObjectsRequest { bucket = bucketName }).contents?.forEach { obj -> | ||
| client.getObject(GetObjectRequest { key = obj.key; bucket = bucketName }) { response -> | ||
| val outputFile = File(downloadDirPath, obj.key!!) | ||
| response.body?.writeToFile(outputFile).also { size -> | ||
| println("Downloaded $outputFile ($size bytes) from S3") | ||
| } | ||
| } | ||
| } | ||
| } finally { | ||
| client.close() | ||
| } | ||
| } | ||
|
|
||
| /** Check for valid S3 configuration based on account */ | ||
| suspend fun S3Client.ensureBucketExists(bucketName: String) { | ||
| if (!bucketExists(bucketName)) { | ||
| createBucket( | ||
| CreateBucketRequest { | ||
| bucket = bucketName | ||
| createBucketConfiguration { | ||
| locationConstraint = BucketLocationConstraint.UsEast2 | ||
| } | ||
| } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /** Upload to S3 if file not already uploaded */ | ||
| suspend fun S3Client.uploadToS3(mediaMetadata: MediaMetadata): UploadResult { | ||
| if (keyExists(bucketName, mediaMetadata.s3KeyName)) | ||
| return FileExistsError("${mediaMetadata.s3KeyName} already uploaded.", mediaMetadata) | ||
|
|
||
| return try { | ||
| putObject( | ||
| PutObjectRequest { | ||
| bucket = bucketName | ||
| key = mediaMetadata.s3KeyName | ||
| body = ByteStream.fromFile(mediaMetadata.file) | ||
| metadata = mediaMetadata.toMap() | ||
| } | ||
| ) | ||
| Success("$bucketName/${mediaMetadata.s3KeyName}", mediaMetadata) | ||
| } catch (e: Exception) { // Checking Service Exception coming in future release | ||
| UploadError(e, mediaMetadata) | ||
| } | ||
| } | ||
|
|
||
| /** Determine if a object exists in a bucket */ | ||
| suspend fun S3Client.keyExists(s3bucket: String, s3key: String) = | ||
| try { | ||
| headObject( | ||
| HeadObjectRequest { | ||
| bucket = s3bucket | ||
| key = s3key | ||
| } | ||
| ) | ||
| true | ||
| } catch (e: Exception) { // Checking Service Exception coming in future release | ||
| false | ||
| } | ||
|
|
||
| /** Determine if a object exists in a bucket */ | ||
| suspend fun S3Client.bucketExists(s3bucket: String) = | ||
| try { | ||
| headBucket(HeadBucketRequest { bucket = s3bucket }) | ||
| true | ||
| } catch (e: Exception) { // Checking Service Exception coming in future release | ||
| false | ||
| } | ||
|
|
||
| /** Move files to directories based on upload results */ | ||
| fun moveFiles(uploadResults: List<UploadResult>) = | ||
| uploadResults | ||
| .map { uploadResult -> uploadResult.mediaMetadata.file.toPath() to (uploadResult is Success) } | ||
| .forEach { (file, uploadSuccess) -> | ||
| val targetFilePath = if (uploadSuccess) completedDirPath else failedDirPath | ||
| val targetPath = File(targetFilePath) | ||
| Files.move(file, File(targetPath, file.fileName.toString()).toPath()) | ||
| } | ||
|
|
||
| // Classes for S3 upload results | ||
| sealed class UploadResult { abstract val mediaMetadata: MediaMetadata } | ||
| data class Success(val location: String, override val mediaMetadata: MediaMetadata) : UploadResult() | ||
| data class UploadError(val error: Throwable, override val mediaMetadata: MediaMetadata) : UploadResult() | ||
| data class FileExistsError(val reason: String, override val mediaMetadata: MediaMetadata) : UploadResult() | ||
|
|
||
| // Classes, properties, and functions for media metadata | ||
| data class MediaMetadata(val title: String, val year: Int, val file: File) | ||
| val MediaMetadata.s3KeyName get() = "$title-$year" | ||
| fun MediaMetadata.toMap() = mapOf("title" to title, "year" to year.toString()) | ||
| fun mediaMetadataExtractor(file: File): MediaMetadata? { | ||
| if (!file.isFile || file.length() == 0L) return null | ||
|
|
||
| val matchResult = filenameMetadataRegex.find(file.name) ?: return null | ||
|
|
||
| val (title, year) = matchResult.destructured | ||
| return MediaMetadata(title, year.toInt(), file) | ||
| } | ||
|
|
||
| /** Validate file path and optionally create directory */ | ||
| fun validateDirectory(dirPath: String): File { | ||
| val dir = File(dirPath) | ||
|
|
||
| require(dir.isDirectory || !dir.exists()) { "Unable to use $dir" } | ||
|
|
||
| if (!dir.exists()) require(dir.mkdirs()) { "Unable to create $dir" } | ||
|
|
||
| return dir | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| rootProject.name = "aws-sdk-kotlin-examples" | ||
|
|
||
| include(":dynamodb-movies") | ||
| include(":s3-media-ingestion") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion
probably move the coroutines version to the root
examplesproject so that we only have to change in one place for all examples?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure but how? I tried a few obvious variations, looked in our source tree and did some searching but didn't find anything that worked. Can you point me to an example?