-
Notifications
You must be signed in to change notification settings - Fork 332
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
Extract the native component without copying it into memory #198
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 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 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
98 changes: 98 additions & 0 deletions
98
...esis-producer/src/main/java/com/amazonaws/services/kinesis/producer/HashedFileCopier.java
This file contains 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,98 @@ | ||
/* | ||
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Amazon Software License (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/asl/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
package com.amazonaws.services.kinesis.producer; | ||
|
||
import java.io.File; | ||
import java.io.FileInputStream; | ||
import java.io.FileOutputStream; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.nio.channels.FileLock; | ||
import java.security.DigestInputStream; | ||
import java.security.DigestOutputStream; | ||
import java.security.MessageDigest; | ||
import java.util.Arrays; | ||
|
||
import javax.xml.bind.DatatypeConverter; | ||
|
||
import org.apache.commons.io.IOUtils; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class HashedFileCopier { | ||
private static final Logger log = LoggerFactory.getLogger(HashedFileCopier.class); | ||
|
||
static final String MESSAGE_DIGEST_ALGORITHM = "SHA-1"; | ||
|
||
public static File copyFileFrom(InputStream sourceData, File destinationDirectory, String fileNameFormat) | ||
throws Exception { | ||
File tempFile = null; | ||
try { | ||
tempFile = File.createTempFile("kpl", ".tmp", destinationDirectory); | ||
log.debug("Extracting file with format {}", fileNameFormat); | ||
FileOutputStream fileOutputStream = new FileOutputStream(tempFile); | ||
|
||
DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, | ||
MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM)); | ||
IOUtils.copy(sourceData, digestOutputStream); | ||
digestOutputStream.close(); | ||
byte[] digest = digestOutputStream.getMessageDigest().digest(); | ||
log.debug("Calculated digest of new file: {}", Arrays.toString(digest)); | ||
String digestHex = DatatypeConverter.printHexBinary(digest); | ||
File finalFile = new File(destinationDirectory, String.format(fileNameFormat, digestHex)); | ||
File lockFile = new File(destinationDirectory, String.format(fileNameFormat + ".lock", digestHex)); | ||
log.debug("Preparing to check and copy {} to {}", tempFile.getAbsolutePath(), finalFile.getAbsolutePath()); | ||
try (FileOutputStream lockFOS = new FileOutputStream(lockFile); | ||
FileLock lock = lockFOS.getChannel().lock()) { | ||
if (finalFile.exists() && finalFile.length() == tempFile.length()) { | ||
byte[] existingFileDigest = null; | ||
try (DigestInputStream digestInputStream = new DigestInputStream(new FileInputStream(finalFile), | ||
MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM))) { | ||
byte[] discardedBytes = new byte[8192]; | ||
while (digestInputStream.read(discardedBytes) != -1) { | ||
// | ||
// This is just used for the side affect of the digest input stream | ||
// | ||
} | ||
existingFileDigest = digestInputStream.getMessageDigest().digest(); | ||
} | ||
if (Arrays.equals(digest, existingFileDigest)) { | ||
// | ||
// The existing file matches the expected file, it's ok to just drop out now | ||
// | ||
log.info("'{}' already exists, and matches. Not overwriting.", finalFile.getAbsolutePath()); | ||
return finalFile; | ||
} | ||
log.warn( | ||
"Detected a mismatch between the existing file, and the new file. " | ||
+ "Will overwrite the existing file. " + "Existing: {} -- New File: {}", | ||
Arrays.toString(existingFileDigest), Arrays.toString(digest)); | ||
} | ||
|
||
if (!tempFile.renameTo(finalFile)) { | ||
log.error("Failed to rename '{}' to '{}'", tempFile.getAbsolutePath(), finalFile.getAbsolutePath()); | ||
throw new IOException("Failed to rename extracted file"); | ||
} | ||
} | ||
return finalFile; | ||
} finally { | ||
if (tempFile != null && tempFile.exists()) { | ||
if (!tempFile.delete()) { | ||
log.warn("Unable to delete temp file: {}", tempFile.getAbsolutePath()); | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains 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
130 changes: 130 additions & 0 deletions
130
...-producer/src/test/java/com/amazonaws/services/kinesis/producer/HashedFileCopierTest.java
This file contains 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,130 @@ | ||
/* | ||
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Amazon Software License (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/asl/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
package com.amazonaws.services.kinesis.producer; | ||
|
||
import static org.hamcrest.CoreMatchers.equalTo; | ||
import static org.junit.Assert.assertThat; | ||
|
||
import java.io.File; | ||
import java.io.FileOutputStream; | ||
import java.io.InputStream; | ||
import java.nio.charset.Charset; | ||
import java.nio.file.Files; | ||
import java.security.DigestInputStream; | ||
import java.security.MessageDigest; | ||
|
||
import javax.xml.bind.DatatypeConverter; | ||
|
||
import org.apache.commons.io.IOUtils; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
|
||
public class HashedFileCopierTest { | ||
|
||
private File tempDir; | ||
|
||
@Before | ||
public void before() throws Exception { | ||
tempDir = File.createTempFile("kpl-unit-tests", ""); | ||
tempDir.delete(); | ||
tempDir.mkdirs(); | ||
} | ||
|
||
@Test | ||
public void normalFileCopyTest() throws Exception { | ||
|
||
File resultFile = HashedFileCopier.copyFileFrom(testDataInputStream(), tempDir, "res-file.%s.txt"); | ||
File expectedFile = new File(tempDir, "res-file." + hexDigestForTestData() + ".txt"); | ||
|
||
assertThat(resultFile, equalTo(expectedFile)); | ||
assertThat(expectedFile.exists(), equalTo(true)); | ||
|
||
byte[] writtenBytes = Files.readAllBytes(resultFile.toPath()); | ||
byte[] expectedBytes = IOUtils.toByteArray(testDataInputStream()); | ||
|
||
assertThat(writtenBytes, equalTo(expectedBytes)); | ||
|
||
} | ||
|
||
@Test | ||
public void fileExistsTest() throws Exception { | ||
String executableFormat = "res-file.%s.txt"; | ||
File expectedFile = new File(tempDir, String.format(executableFormat, hexDigestForTestData())); | ||
try (FileOutputStream fso = new FileOutputStream(expectedFile)) { | ||
IOUtils.copy(testDataInputStream(), fso); | ||
} | ||
File resultFile = HashedFileCopier.copyFileFrom(testDataInputStream(), tempDir, executableFormat); | ||
assertThat(resultFile, equalTo(expectedFile)); | ||
|
||
byte[] expectedData = testDataBytes(); | ||
byte[] actualData = Files.readAllBytes(resultFile.toPath()); | ||
|
||
assertThat(actualData, equalTo(expectedData)); | ||
} | ||
|
||
@Test | ||
public void lengthMismatchTest() throws Exception { | ||
String executableFormat = "res-file.%s.txt"; | ||
File expectedFile = new File(tempDir, String.format(executableFormat, hexDigestForTestData())); | ||
FileOutputStream fso = new FileOutputStream(expectedFile); | ||
IOUtils.copy(testDataInputStream(), fso); | ||
fso.write("This is some extra crap".getBytes(Charset.forName("UTF-8"))); | ||
fso.close(); | ||
|
||
File resultFile = HashedFileCopier.copyFileFrom(testDataInputStream(), tempDir, executableFormat); | ||
assertThat(resultFile, equalTo(expectedFile)); | ||
|
||
byte[] expectedData = testDataBytes(); | ||
byte[] actualData = Files.readAllBytes(resultFile.toPath()); | ||
|
||
assertThat(actualData, equalTo(expectedData)); | ||
} | ||
|
||
@Test | ||
public void hashMismatchTest() throws Exception { | ||
String executableFormat = "res-file.%s.txt"; | ||
File expectedFile = new File(tempDir, String.format(executableFormat, hexDigestForTestData())); | ||
byte[] testData = testDataBytes(); | ||
testData[10] = (byte)~testData[10]; | ||
|
||
Files.write(expectedFile.toPath(), testData); | ||
|
||
File resultFile = HashedFileCopier.copyFileFrom(testDataInputStream(), tempDir, executableFormat); | ||
assertThat(resultFile, equalTo(expectedFile)); | ||
|
||
byte[] expectedData = testDataBytes(); | ||
byte[] actualData = Files.readAllBytes(resultFile.toPath()); | ||
|
||
assertThat(actualData, equalTo(expectedData)); | ||
} | ||
|
||
private String hexDigestForTestData() throws Exception { | ||
return DatatypeConverter.printHexBinary(hashForTestData()); | ||
} | ||
|
||
private byte[] testDataBytes() throws Exception { | ||
return IOUtils.toByteArray(testDataInputStream()); | ||
} | ||
|
||
private byte[] hashForTestData() throws Exception { | ||
DigestInputStream dis = new DigestInputStream(testDataInputStream(), MessageDigest.getInstance(HashedFileCopier.MESSAGE_DIGEST_ALGORITHM)); | ||
IOUtils.toByteArray(dis); | ||
return dis.getMessageDigest().digest(); | ||
} | ||
|
||
private InputStream testDataInputStream() { | ||
return this.getClass().getClassLoader().getResourceAsStream("test-data/test.txt"); | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
26 changes: 26 additions & 0 deletions
26
java/amazon-kinesis-producer/src/test/resources/logback.xml
This file contains 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,26 @@ | ||
<?xml version="1.0" encoding="UTF-8" ?> | ||
<!-- | ||
~ Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
~ | ||
~ Licensed under the Amazon Software License (the "License"). | ||
~ You may not use this file except in compliance with the License. | ||
~ A copy of the License is located at | ||
~ | ||
~ http://aws.amazon.com/asl/ | ||
~ | ||
~ or in the "license" file accompanying this file. This file is distributed | ||
~ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
~ express or implied. See the License for the specific language governing | ||
~ permissions and limitations under the License. | ||
--> | ||
<configuration> | ||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> | ||
<encoder> | ||
<pattern>%d [%thread] %-5level %logger{36} [%mdc{ShardId:-NONE}] - %msg %n</pattern> | ||
</encoder> | ||
</appender> | ||
|
||
<root level="DEBUG"> | ||
<appender-ref ref="CONSOLE" /> | ||
</root> | ||
</configuration> |
1 change: 1 addition & 0 deletions
1
java/amazon-kinesis-producer/src/test/resources/test-data/test.txt
This file contains 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 @@ | ||
This is a test |
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.
Should the deletion belong to @after?
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.
File.createTempFile actually creates the file, but I really want a directory.
Thinking about it I looked for a better solution and found it on Files.createTempDirectory.