You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@storm.apache.org by sr...@apache.org on 2017/11/14 07:01:16 UTC
[1/4] storm git commit: STORM-2810: Fix resource leaks in storm-hdfs
tests
Repository: storm
Updated Branches:
refs/heads/1.1.x-branch ed005ab5f -> a0308efd6
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSpout.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSpout.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSpout.java
index f60cbf3..057787d 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSpout.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSpout.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -15,14 +16,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.storm.hdfs.spout;
import org.apache.storm.Config;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.hadoop.hdfs.DistributedFileSystem;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.storm.hdfs.common.HdfsUtils;
@@ -57,703 +56,707 @@ import java.util.List;
import java.util.Map;
import org.apache.storm.hdfs.common.HdfsUtils.Pair;
-
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.ClassRule;
public class TestHdfsSpout {
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
- public File baseFolder;
- private Path source;
- private Path archive;
- private Path badfiles;
-
-
- public TestHdfsSpout() {
- }
-
- static MiniDFSCluster.Builder builder;
- static MiniDFSCluster hdfsCluster;
- static DistributedFileSystem fs;
- static String hdfsURI;
- static Configuration conf = new Configuration();
-
- @BeforeClass
- public static void setupClass() throws IOException {
- builder = new MiniDFSCluster.Builder(new Configuration());
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
- }
-
- @AfterClass
- public static void teardownClass() throws IOException {
- fs.close();
- hdfsCluster.shutdown();
- }
-
-
- @Before
- public void setup() throws Exception {
- baseFolder = tempFolder.newFolder("hdfsspout");
- source = new Path(baseFolder.toString() + "/source");
- fs.mkdirs(source);
- archive = new Path(baseFolder.toString() + "/archive");
- fs.mkdirs(archive);
- badfiles = new Path(baseFolder.toString() + "/bad");
- fs.mkdirs(badfiles);
- }
-
- @After
- public void shutDown() throws IOException {
- fs.delete(new Path(baseFolder.toString()), true);
- }
-
- @Test
- public void testSimpleText_noACK() throws IOException {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 5);
-
- Path file2 = new Path(source.toString() + "/file2.txt");
- createTextFile(file2, 5);
-
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1);
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
-
- runSpout(spout,"r11");
-
- Path arc1 = new Path(archive.toString() + "/file1.txt");
- Path arc2 = new Path(archive.toString() + "/file2.txt");
- checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2);
- }
-
- @Test
- public void testSimpleText_ACK() throws IOException {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 5);
-
- Path file2 = new Path(source.toString() + "/file2.txt");
- createTextFile(file2, 5);
-
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1);
-
- Map conf = getCommonConfigs();
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); // enable ACKing
- openSpout(spout, 0, conf);
-
- // consume file 1
- runSpout(spout, "r6", "a0", "a1", "a2", "a3", "a4");
- Path arc1 = new Path(archive.toString() + "/file1.txt");
- checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1);
-
- // consume file 2
- runSpout(spout, "r6", "a5", "a6", "a7", "a8", "a9");
- Path arc2 = new Path(archive.toString() + "/file2.txt");
- checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2);
- }
-
- @Test
- public void testResumeAbandoned_Text_NoAck() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 6);
-
- final Integer lockExpirySec = 1;
-
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1000); // effectively disable commits based on time
- spout.setLockTimeoutSec(lockExpirySec);
-
-
- HdfsSpout spout2 = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout2.setCommitFrequencyCount(1);
- spout2.setCommitFrequencySec(1000); // effectively disable commits based on time
- spout2.setLockTimeoutSec(lockExpirySec);
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
- openSpout(spout2, 1, conf);
-
- // consume file 1 partially
- List<String> res = runSpout(spout, "r2");
- Assert.assertEquals(2, res.size());
-
- // abandon file
- FileLock lock = getField(spout, "lock");
- TestFileLock.closeUnderlyingLockFile(lock);
- Thread.sleep(lockExpirySec * 2 * 1000);
-
- // check lock file presence
- Assert.assertTrue(fs.exists(lock.getLockFile()));
-
- // create another spout to take over processing and read a few lines
- List<String> res2 = runSpout(spout2, "r3");
- Assert.assertEquals(3, res2.size());
-
- // check lock file presence
- Assert.assertTrue(fs.exists(lock.getLockFile()));
-
- // check lock file contents
- List<String> contents = readTextFile(fs, lock.getLockFile().toString());
- Assert.assertFalse(contents.isEmpty());
-
- // finish up reading the file
- res2 = runSpout(spout2, "r2");
- Assert.assertEquals(4, res2.size());
-
- // check lock file is gone
- Assert.assertFalse(fs.exists(lock.getLockFile()));
- FileReader rdr = getField(spout2, "reader");
- Assert.assertNull(rdr);
- Assert.assertTrue(getBoolField(spout2, "fileReadCompletely"));
+ @ClassRule
+ public static MiniDFSClusterRule DFS_CLUSTER_RULE = new MiniDFSClusterRule();
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+ public File baseFolder;
- }
-
- @Test
- public void testResumeAbandoned_Seq_NoAck() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.seq");
- createSeqFile(fs, file1, 6);
-
- final Integer lockExpirySec = 1;
-
- HdfsSpout spout = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1000); // effectively disable commits based on time
- spout.setLockTimeoutSec(lockExpirySec);
-
-
- HdfsSpout spout2 = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields);
- spout2.setCommitFrequencyCount(1);
- spout2.setCommitFrequencySec(1000); // effectively disable commits based on time
- spout2.setLockTimeoutSec(lockExpirySec);
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
- openSpout(spout2, 1, conf);
-
- // consume file 1 partially
- List<String> res = runSpout(spout, "r2");
- Assert.assertEquals(2, res.size());
- // abandon file
- FileLock lock = getField(spout, "lock");
- TestFileLock.closeUnderlyingLockFile(lock);
- Thread.sleep(lockExpirySec * 2 * 1000);
-
- // check lock file presence
- Assert.assertTrue(fs.exists(lock.getLockFile()));
-
- // create another spout to take over processing and read a few lines
- List<String> res2 = runSpout(spout2, "r3");
- Assert.assertEquals(3, res2.size());
-
- // check lock file presence
- Assert.assertTrue(fs.exists(lock.getLockFile()));
-
- // check lock file contents
- List<String> contents = getTextFileContents(fs, lock.getLockFile());
- Assert.assertFalse(contents.isEmpty());
-
- // finish up reading the file
- res2 = runSpout(spout2, "r3");
- Assert.assertEquals(4, res2.size());
+ private Path source;
+ private Path archive;
+ private Path badfiles;
- // check lock file is gone
- Assert.assertFalse(fs.exists(lock.getLockFile()));
- FileReader rdr = getField(spout2, "reader");
- Assert.assertNull( rdr );
- Assert.assertTrue(getBoolField(spout2, "fileReadCompletely"));
- }
+ private static DistributedFileSystem fs;
+ private static final Configuration conf = new Configuration();
- private void checkCollectorOutput_txt(MockCollector collector, Path... txtFiles) throws IOException {
- ArrayList<String> expected = new ArrayList<>();
- for (Path txtFile : txtFiles) {
- List<String> lines= getTextFileContents(fs, txtFile);
- expected.addAll(lines);
+ @BeforeClass
+ public static void setupClass() throws IOException {
+ fs = DFS_CLUSTER_RULE.getDfscluster().getFileSystem();
}
- List<String> actual = new ArrayList<>();
- for (Pair<HdfsSpout.MessageId, List<Object>> item : collector.items) {
- actual.add(item.getValue().get(0).toString());
+ @AfterClass
+ public static void teardownClass() throws IOException {
+ fs.close();
}
- Assert.assertEquals(expected, actual);
- }
- private List<String> getTextFileContents(FileSystem fs, Path txtFile) throws IOException {
- ArrayList<String> result = new ArrayList<>();
- FSDataInputStream istream = fs.open(txtFile);
- InputStreamReader isreader = new InputStreamReader(istream,"UTF-8");
- BufferedReader reader = new BufferedReader(isreader);
+ @Before
+ public void setup() throws Exception {
+ baseFolder = tempFolder.newFolder("hdfsspout");
+ source = new Path(baseFolder.toString() + "/source");
+ fs.mkdirs(source);
+ archive = new Path(baseFolder.toString() + "/archive");
+ fs.mkdirs(archive);
+ badfiles = new Path(baseFolder.toString() + "/bad");
+ fs.mkdirs(badfiles);
+ }
- for( String line = reader.readLine(); line!=null; line = reader.readLine() ) {
- result.add(line);
+ @After
+ public void shutDown() throws IOException {
+ fs.delete(new Path(baseFolder.toString()), true);
}
- isreader.close();
- return result;
- }
+ @Test
+ public void testSimpleText_noACK() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 5);
- private void checkCollectorOutput_seq(MockCollector collector, Path... seqFiles) throws IOException {
- ArrayList<String> expected = new ArrayList<>();
- for (Path seqFile : seqFiles) {
- List<String> lines= getSeqFileContents(fs, seqFile);
- expected.addAll(lines);
- }
- Assert.assertTrue(expected.equals(collector.lines));
- }
-
- private List<String> getSeqFileContents(FileSystem fs, Path... seqFiles) throws IOException {
- ArrayList<String> result = new ArrayList<>();
-
- for (Path seqFile : seqFiles) {
- Path file = new Path(fs.getUri().toString() + seqFile.toString());
- SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(file));
- try {
- Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
- Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
- while (reader.next(key, value)) {
- String keyValStr = Arrays.asList(key, value).toString();
- result.add(keyValStr);
+ Path file2 = new Path(source.toString() + "/file2.txt");
+ createTextFile(file2, 5);
+
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1);
+
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+
+ runSpout(spout, "r11");
+
+ Path arc1 = new Path(archive.toString() + "/file1.txt");
+ Path arc2 = new Path(archive.toString() + "/file2.txt");
+ checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2);
}
- } finally {
- reader.close();
- }
- }// for
- return result;
- }
-
- private List<String> listDir(Path p) throws IOException {
- ArrayList<String> result = new ArrayList<>();
- RemoteIterator<LocatedFileStatus> fileNames = fs.listFiles(p, false);
- while ( fileNames.hasNext() ) {
- LocatedFileStatus fileStatus = fileNames.next();
- result.add(Path.getPathWithoutSchemeAndAuthority(fileStatus.getPath()).toString());
}
- return result;
- }
+ @Test
+ public void testSimpleText_ACK() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 5);
- @Test
- public void testMultipleFileConsumption_Ack() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 5);
+ Path file2 = new Path(source.toString() + "/file2.txt");
+ createTextFile(file2, 5);
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1);
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1);
+ Map conf = getCommonConfigs();
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); // enable ACKing
+ openSpout(spout, 0, conf);
- Map conf = getCommonConfigs();
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); // enable ACKing
- openSpout(spout, 0, conf);
+ // consume file 1
+ runSpout(spout, "r6", "a0", "a1", "a2", "a3", "a4");
+ Path arc1 = new Path(archive.toString() + "/file1.txt");
+ checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1);
- // read few lines from file1 dont ack
- runSpout(spout, "r3");
- FileReader reader = getField(spout, "reader");
- Assert.assertNotNull(reader);
- Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+ // consume file 2
+ runSpout(spout, "r6", "a5", "a6", "a7", "a8", "a9");
+ Path arc2 = new Path(archive.toString() + "/file2.txt");
+ checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2);
+ }
+ }
- // read remaining lines
- runSpout(spout, "r3");
- reader = getField(spout, "reader");
- Assert.assertNotNull(reader);
- Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely") );
+ @Test
+ public void testResumeAbandoned_Text_NoAck() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 6);
+
+ final Integer lockExpirySec = 1;
+
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1000); // effectively disable commits based on time
+ spout.setLockTimeoutSec(lockExpirySec);
+
+ try (AutoCloseableHdfsSpout closeableSpout2 = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout2 = closeableSpout2.spout;
+ spout2.setCommitFrequencyCount(1);
+ spout2.setCommitFrequencySec(1000); // effectively disable commits based on time
+ spout2.setLockTimeoutSec(lockExpirySec);
+
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+ openSpout(spout2, 1, conf);
+
+ // consume file 1 partially
+ List<String> res = runSpout(spout, "r2");
+ Assert.assertEquals(2, res.size());
+
+ // abandon file
+ FileLock lock = getField(spout, "lock");
+ TestFileLock.closeUnderlyingLockFile(lock);
+ Thread.sleep(lockExpirySec * 2 * 1000);
+
+ // check lock file presence
+ Assert.assertTrue(fs.exists(lock.getLockFile()));
+
+ // create another spout to take over processing and read a few lines
+ List<String> res2 = runSpout(spout2, "r3");
+ Assert.assertEquals(3, res2.size());
+
+ // check lock file presence
+ Assert.assertTrue(fs.exists(lock.getLockFile()));
+
+ // check lock file contents
+ List<String> contents = readTextFile(fs, lock.getLockFile().toString());
+ Assert.assertFalse(contents.isEmpty());
+
+ // finish up reading the file
+ res2 = runSpout(spout2, "r2");
+ Assert.assertEquals(4, res2.size());
+
+ // check lock file is gone
+ Assert.assertFalse(fs.exists(lock.getLockFile()));
+ FileReader rdr = getField(spout2, "reader");
+ Assert.assertNull(rdr);
+ Assert.assertTrue(getBoolField(spout2, "fileReadCompletely"));
+ }
+ }
+ }
- // ack few
- runSpout(spout, "a0", "a1", "a2");
- reader = getField(spout, "reader");
- Assert.assertNotNull(reader);
- Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+ @Test
+ public void testResumeAbandoned_Seq_NoAck() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.seq");
+ createSeqFile(fs, file1, 6);
+
+ final Integer lockExpirySec = 1;
+
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1000); // effectively disable commits based on time
+ spout.setLockTimeoutSec(lockExpirySec);
+
+ try (AutoCloseableHdfsSpout closeableSpout2 = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields)) {
+ HdfsSpout spout2 = closeableSpout2.spout;
+ spout2.setCommitFrequencyCount(1);
+ spout2.setCommitFrequencySec(1000); // effectively disable commits based on time
+ spout2.setLockTimeoutSec(lockExpirySec);
+
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+ openSpout(spout2, 1, conf);
+
+ // consume file 1 partially
+ List<String> res = runSpout(spout, "r2");
+ Assert.assertEquals(2, res.size());
+ // abandon file
+ FileLock lock = getField(spout, "lock");
+ TestFileLock.closeUnderlyingLockFile(lock);
+ Thread.sleep(lockExpirySec * 2 * 1000);
+
+ // check lock file presence
+ Assert.assertTrue(fs.exists(lock.getLockFile()));
+
+ // create another spout to take over processing and read a few lines
+ List<String> res2 = runSpout(spout2, "r3");
+ Assert.assertEquals(3, res2.size());
+
+ // check lock file presence
+ Assert.assertTrue(fs.exists(lock.getLockFile()));
+
+ // check lock file contents
+ List<String> contents = getTextFileContents(fs, lock.getLockFile());
+ Assert.assertFalse(contents.isEmpty());
+
+ // finish up reading the file
+ res2 = runSpout(spout2, "r3");
+ Assert.assertEquals(4, res2.size());
+
+ // check lock file is gone
+ Assert.assertFalse(fs.exists(lock.getLockFile()));
+ FileReader rdr = getField(spout2, "reader");
+ Assert.assertNull(rdr);
+ Assert.assertTrue(getBoolField(spout2, "fileReadCompletely"));
+ }
+ }
+ }
- //ack rest
- runSpout(spout, "a3", "a4");
- reader = getField(spout, "reader");
- Assert.assertNull(reader);
- Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+ private void checkCollectorOutput_txt(MockCollector collector, Path... txtFiles) throws IOException {
+ ArrayList<String> expected = new ArrayList<>();
+ for (Path txtFile : txtFiles) {
+ List<String> lines = getTextFileContents(fs, txtFile);
+ expected.addAll(lines);
+ }
+ List<String> actual = new ArrayList<>();
+ for (Pair<HdfsSpout.MessageId, List<Object>> item : collector.items) {
+ actual.add(item.getValue().get(0).toString());
+ }
+ Assert.assertEquals(expected, actual);
+ }
- // go to next file
- Path file2 = new Path(source.toString() + "/file2.txt");
- createTextFile(file2, 5);
+ private List<String> getTextFileContents(FileSystem fs, Path txtFile) throws IOException {
+ ArrayList<String> result = new ArrayList<>();
+ FSDataInputStream istream = fs.open(txtFile);
+ InputStreamReader isreader = new InputStreamReader(istream, "UTF-8");
+ BufferedReader reader = new BufferedReader(isreader);
- // Read 1 line
- runSpout(spout, "r1");
- Assert.assertNotNull(getField(spout, "reader"));
- Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+ for (String line = reader.readLine(); line != null; line = reader.readLine()) {
+ result.add(line);
+ }
+ isreader.close();
+ return result;
+ }
- // ack 1 tuple
- runSpout(spout, "a5");
- Assert.assertNotNull(getField(spout, "reader"));
- Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+ private void checkCollectorOutput_seq(MockCollector collector, Path... seqFiles) throws IOException {
+ ArrayList<String> expected = new ArrayList<>();
+ for (Path seqFile : seqFiles) {
+ List<String> lines = getSeqFileContents(fs, seqFile);
+ expected.addAll(lines);
+ }
+ Assert.assertTrue(expected.equals(collector.lines));
+ }
+ private List<String> getSeqFileContents(FileSystem fs, Path... seqFiles) throws IOException {
+ ArrayList<String> result = new ArrayList<>();
+
+ for (Path seqFile : seqFiles) {
+ Path file = new Path(fs.getUri().toString() + seqFile.toString());
+ SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(file));
+ try {
+ Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
+ Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
+ while (reader.next(key, value)) {
+ String keyValStr = Arrays.asList(key, value).toString();
+ result.add(keyValStr);
+ }
+ } finally {
+ reader.close();
+ }
+ }// for
+ return result;
+ }
- // read and ack remaining lines
- runSpout(spout, "r5", "a6", "a7", "a8", "a9");
- Assert.assertNull(getField(spout, "reader"));
- Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
- }
+ private List<String> listDir(Path p) throws IOException {
+ ArrayList<String> result = new ArrayList<>();
+ RemoteIterator<LocatedFileStatus> fileNames = fs.listFiles(p, false);
+ while (fileNames.hasNext()) {
+ LocatedFileStatus fileStatus = fileNames.next();
+ result.add(Path.getPathWithoutSchemeAndAuthority(fileStatus.getPath()).toString());
+ }
+ return result;
+ }
- private static <T> T getField(HdfsSpout spout, String fieldName) throws NoSuchFieldException, IllegalAccessException {
- Field readerFld = HdfsSpout.class.getDeclaredField(fieldName);
- readerFld.setAccessible(true);
- return (T) readerFld.get(spout);
- }
+ @Test
+ public void testMultipleFileConsumption_Ack() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 5);
+
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1);
+
+ Map conf = getCommonConfigs();
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); // enable ACKing
+ openSpout(spout, 0, conf);
+
+ // read few lines from file1 dont ack
+ runSpout(spout, "r3");
+ FileReader reader = getField(spout, "reader");
+ Assert.assertNotNull(reader);
+ Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+
+ // read remaining lines
+ runSpout(spout, "r3");
+ reader = getField(spout, "reader");
+ Assert.assertNotNull(reader);
+ Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+
+ // ack few
+ runSpout(spout, "a0", "a1", "a2");
+ reader = getField(spout, "reader");
+ Assert.assertNotNull(reader);
+ Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+
+ //ack rest
+ runSpout(spout, "a3", "a4");
+ reader = getField(spout, "reader");
+ Assert.assertNull(reader);
+ Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+
+ // go to next file
+ Path file2 = new Path(source.toString() + "/file2.txt");
+ createTextFile(file2, 5);
+
+ // Read 1 line
+ runSpout(spout, "r1");
+ Assert.assertNotNull(getField(spout, "reader"));
+ Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+
+ // ack 1 tuple
+ runSpout(spout, "a5");
+ Assert.assertNotNull(getField(spout, "reader"));
+ Assert.assertEquals(false, getBoolField(spout, "fileReadCompletely"));
+
+ // read and ack remaining lines
+ runSpout(spout, "r5", "a6", "a7", "a8", "a9");
+ Assert.assertNull(getField(spout, "reader"));
+ Assert.assertEquals(true, getBoolField(spout, "fileReadCompletely"));
+ }
+ }
- private static boolean getBoolField(HdfsSpout spout, String fieldName) throws NoSuchFieldException, IllegalAccessException {
- Field readerFld = HdfsSpout.class.getDeclaredField(fieldName);
- readerFld.setAccessible(true);
- return readerFld.getBoolean(spout);
- }
+ private static <T> T getField(HdfsSpout spout, String fieldName) throws NoSuchFieldException, IllegalAccessException {
+ Field readerFld = HdfsSpout.class.getDeclaredField(fieldName);
+ readerFld.setAccessible(true);
+ return (T) readerFld.get(spout);
+ }
+ private static boolean getBoolField(HdfsSpout spout, String fieldName) throws NoSuchFieldException, IllegalAccessException {
+ Field readerFld = HdfsSpout.class.getDeclaredField(fieldName);
+ readerFld.setAccessible(true);
+ return readerFld.getBoolean(spout);
+ }
- @Test
- public void testSimpleSequenceFile() throws IOException {
- //1) create a couple files to consume
- source = new Path("/tmp/hdfsspout/source");
- fs.mkdirs(source);
- archive = new Path("/tmp/hdfsspout/archive");
- fs.mkdirs(archive);
+ @Test
+ public void testSimpleSequenceFile() throws Exception {
+ //1) create a couple files to consume
+ source = new Path("/tmp/hdfsspout/source");
+ fs.mkdirs(source);
+ archive = new Path("/tmp/hdfsspout/archive");
+ fs.mkdirs(archive);
- Path file1 = new Path(source + "/file1.seq");
- createSeqFile(fs, file1, 5);
+ Path file1 = new Path(source + "/file1.seq");
+ createSeqFile(fs, file1, 5);
- Path file2 = new Path(source + "/file2.seq");
- createSeqFile(fs, file2, 5);
+ Path file2 = new Path(source + "/file2.seq");
+ createSeqFile(fs, file2, 5);
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
- HdfsSpout spout = makeSpout(Configs.SEQ, SequenceFileReader.defaultFields);
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
+ // consume both files
+ List<String> res = runSpout(spout, "r11");
+ Assert.assertEquals(10, res.size());
- // consume both files
- List<String> res = runSpout(spout, "r11");
- Assert.assertEquals(10, res.size());
+ Assert.assertEquals(2, listDir(archive).size());
- Assert.assertEquals(2, listDir(archive).size());
+ Path f1 = new Path(archive + "/file1.seq");
+ Path f2 = new Path(archive + "/file2.seq");
+ checkCollectorOutput_seq((MockCollector) spout.getCollector(), f1, f2);
+ }
+ }
- Path f1 = new Path(archive + "/file1.seq");
- Path f2 = new Path(archive + "/file2.seq");
+ @Test
+ public void testReadFailures() throws Exception {
+ // 1) create couple of input files to read
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ Path file2 = new Path(source.toString() + "/file2.txt");
+
+ createTextFile(file1, 6);
+ createTextFile(file2, 7);
+ Assert.assertEquals(2, listDir(source).size());
+
+ // 2) run spout
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(MockTextFailingReader.class.getName(), MockTextFailingReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+
+ List<String> res = runSpout(spout, "r11");
+ String[] expected = new String[]{"[line 0]", "[line 1]", "[line 2]", "[line 0]", "[line 1]", "[line 2]"};
+ Assert.assertArrayEquals(expected, res.toArray());
+
+ // 3) make sure 6 lines (3 from each file) were read in all
+ Assert.assertEquals(((MockCollector) spout.getCollector()).lines.size(), 6);
+ ArrayList<Path> badFiles = HdfsUtils.listFilesByModificationTime(fs, badfiles, 0);
+ Assert.assertEquals(badFiles.size(), 2);
+ }
+ }
- checkCollectorOutput_seq((MockCollector) spout.getCollector(), f1, f2);
- }
+ // check lock creation/deletion and contents
+ @Test
+ public void testLocking() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 10);
+
+ // 0) config spout to log progress in lock file for each tuple
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(1);
+ spout.setCommitFrequencySec(1000); // effectively disable commits based on time
+
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+
+ // 1) read initial lines in file, then check if lock exists
+ List<String> res = runSpout(spout, "r5");
+ Assert.assertEquals(5, res.size());
+ List<String> lockFiles = listDir(spout.getLockDirPath());
+ Assert.assertEquals(1, lockFiles.size());
+
+ // 2) check log file content line count == tuples emitted + 1
+ List<String> lines = readTextFile(fs, lockFiles.get(0));
+ Assert.assertEquals(lines.size(), res.size() + 1);
+
+ // 3) read remaining lines in file, then ensure lock is gone
+ runSpout(spout, "r6");
+ lockFiles = listDir(spout.getLockDirPath());
+ Assert.assertEquals(0, lockFiles.size());
+
+ // 4) --- Create another input file and reverify same behavior ---
+ Path file2 = new Path(source.toString() + "/file2.txt");
+ createTextFile(file2, 10);
+
+ // 5) read initial lines in file, then check if lock exists
+ res = runSpout(spout, "r5");
+ Assert.assertEquals(15, res.size());
+ lockFiles = listDir(spout.getLockDirPath());
+ Assert.assertEquals(1, lockFiles.size());
+
+ // 6) check log file content line count == tuples emitted + 1
+ lines = readTextFile(fs, lockFiles.get(0));
+ Assert.assertEquals(6, lines.size());
+
+ // 7) read remaining lines in file, then ensure lock is gone
+ runSpout(spout, "r6");
+ lockFiles = listDir(spout.getLockDirPath());
+ Assert.assertEquals(0, lockFiles.size());
+ }
+ }
- @Test
- public void testReadFailures() throws Exception {
- // 1) create couple of input files to read
- Path file1 = new Path(source.toString() + "/file1.txt");
- Path file2 = new Path(source.toString() + "/file2.txt");
-
- createTextFile(file1, 6);
- createTextFile(file2, 7);
- Assert.assertEquals(2, listDir(source).size());
-
- // 2) run spout
- HdfsSpout spout = makeSpout(MockTextFailingReader.class.getName(), MockTextFailingReader.defaultFields);
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
+ @Test
+ public void testLockLoggingFreqCount() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 10);
- List<String> res = runSpout(spout, "r11");
- String[] expected = new String[] {"[line 0]","[line 1]","[line 2]","[line 0]","[line 1]","[line 2]"};
- Assert.assertArrayEquals(expected, res.toArray());
+ // 0) config spout to log progress in lock file for each tuple
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(2); // 1 lock log entry every 2 tuples
+ spout.setCommitFrequencySec(1000); // Effectively disable commits based on time
- // 3) make sure 6 lines (3 from each file) were read in all
- Assert.assertEquals(((MockCollector) spout.getCollector()).lines.size(), 6);
- ArrayList<Path> badFiles = HdfsUtils.listFilesByModificationTime(fs, badfiles, 0);
- Assert.assertEquals(badFiles.size(), 2);
- }
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
- // check lock creation/deletion and contents
- @Test
- public void testLocking() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 10);
+ // 1) read 5 lines in file,
+ runSpout(spout, "r5");
- // 0) config spout to log progress in lock file for each tuple
+ // 2) check log file contents
+ String lockFile = listDir(spout.getLockDirPath()).get(0);
+ List<String> lines = readTextFile(fs, lockFile);
+ Assert.assertEquals(lines.size(), 3);
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(1);
- spout.setCommitFrequencySec(1000); // effectively disable commits based on time
-
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
-
- // 1) read initial lines in file, then check if lock exists
- List<String> res = runSpout(spout, "r5");
- Assert.assertEquals(5, res.size());
- List<String> lockFiles = listDir(spout.getLockDirPath());
- Assert.assertEquals(1, lockFiles.size());
-
- // 2) check log file content line count == tuples emitted + 1
- List<String> lines = readTextFile(fs, lockFiles.get(0));
- Assert.assertEquals(lines.size(), res.size()+1);
-
- // 3) read remaining lines in file, then ensure lock is gone
- runSpout(spout, "r6");
- lockFiles = listDir(spout.getLockDirPath());
- Assert.assertEquals(0, lockFiles.size());
-
-
- // 4) --- Create another input file and reverify same behavior ---
- Path file2 = new Path(source.toString() + "/file2.txt");
- createTextFile(file2, 10);
-
- // 5) read initial lines in file, then check if lock exists
- res = runSpout(spout, "r5");
- Assert.assertEquals(15, res.size());
- lockFiles = listDir(spout.getLockDirPath());
- Assert.assertEquals(1, lockFiles.size());
-
- // 6) check log file content line count == tuples emitted + 1
- lines = readTextFile(fs, lockFiles.get(0));
- Assert.assertEquals(6, lines.size());
-
- // 7) read remaining lines in file, then ensure lock is gone
- runSpout(spout, "r6");
- lockFiles = listDir(spout.getLockDirPath());
- Assert.assertEquals(0, lockFiles.size());
- }
-
- @Test
- public void testLockLoggingFreqCount() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 10);
-
- // 0) config spout to log progress in lock file for each tuple
-
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(2); // 1 lock log entry every 2 tuples
- spout.setCommitFrequencySec(1000); // Effectively disable commits based on time
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
-
- // 1) read 5 lines in file,
- runSpout(spout, "r5");
-
- // 2) check log file contents
- String lockFile = listDir(spout.getLockDirPath()).get(0);
- List<String> lines = readTextFile(fs, lockFile);
- Assert.assertEquals(lines.size(), 3);
-
- // 3) read 6th line and see if another log entry was made
- runSpout(spout, "r1");
- lines = readTextFile(fs, lockFile);
- Assert.assertEquals(lines.size(), 4);
- }
-
- @Test
- public void testLockLoggingFreqSec() throws Exception {
- Path file1 = new Path(source.toString() + "/file1.txt");
- createTextFile(file1, 10);
-
- // 0) config spout to log progress in lock file for each tuple
- HdfsSpout spout = makeSpout(Configs.TEXT, TextFileReader.defaultFields);
- spout.setCommitFrequencyCount(0); // disable it
- spout.setCommitFrequencySec(2); // log every 2 sec
-
- Map conf = getCommonConfigs();
- openSpout(spout, 0, conf);
-
- // 1) read 5 lines in file
- runSpout(spout, "r5");
-
- // 2) check log file contents
- String lockFile = listDir(spout.getLockDirPath()).get(0);
- List<String> lines = readTextFile(fs, lockFile);
- Assert.assertEquals(lines.size(), 1);
- Thread.sleep(3000); // allow freq_sec to expire
-
- // 3) read another line and see if another log entry was made
- runSpout(spout, "r1");
- lines = readTextFile(fs, lockFile);
- Assert.assertEquals(2, lines.size());
- }
-
- private static List<String> readTextFile(FileSystem fs, String f) throws IOException {
- Path file = new Path(f);
- FSDataInputStream x = fs.open(file);
- BufferedReader reader = new BufferedReader(new InputStreamReader(x));
- String line = null;
- ArrayList<String> result = new ArrayList<>();
- while( (line = reader.readLine()) !=null )
- result.add( line );
- return result;
- }
-
-
- private Map getCommonConfigs() {
- Map conf = new HashMap();
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "0");
- return conf;
- }
-
- private HdfsSpout makeSpout(String readerType, String[] outputFields) {
- HdfsSpout spout = new HdfsSpout().withOutputFields(outputFields)
- .setReaderType(readerType)
- .setHdfsUri(hdfsCluster.getURI().toString())
- .setSourceDir(source.toString())
- .setArchiveDir(archive.toString())
- .setBadFilesDir(badfiles.toString());
-
- return spout;
- }
-
- private void openSpout(HdfsSpout spout, int spoutId, Map conf) {
- MockCollector collector = new MockCollector();
- spout.open(conf, new MockTopologyContext(spoutId), collector);
- }
-
- /**
- * Execute a sequence of calls on HdfsSpout.
- *
- * @param cmds: set of commands to run,
- * e.g. "r,r,r,r,a1,f2,...". The commands are:
- * r[N] - receive() called N times
- * aN - ack, item number: N
- * fN - fail, item number: N
- */
-
- private List<String> runSpout(HdfsSpout spout, String... cmds) {
- MockCollector collector = (MockCollector) spout.getCollector();
- for(String cmd : cmds) {
- if(cmd.startsWith("r")) {
- int count = 1;
- if(cmd.length() > 1) {
- count = Integer.parseInt(cmd.substring(1));
- }
- for(int i=0; i<count; ++i) {
- spout.nextTuple();
- }
+ // 3) read 6th line and see if another log entry was made
+ runSpout(spout, "r1");
+ lines = readTextFile(fs, lockFile);
+ Assert.assertEquals(lines.size(), 4);
}
- else if(cmd.startsWith("a")) {
- int n = Integer.parseInt(cmd.substring(1));
- Pair<HdfsSpout.MessageId, List<Object>> item = collector.items.get(n);
- spout.ack(item.getKey());
+ }
+
+ @Test
+ public void testLockLoggingFreqSec() throws Exception {
+ Path file1 = new Path(source.toString() + "/file1.txt");
+ createTextFile(file1, 10);
+
+ // 0) config spout to log progress in lock file for each tuple
+ try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) {
+ HdfsSpout spout = closeableSpout.spout;
+ spout.setCommitFrequencyCount(0); // disable it
+ spout.setCommitFrequencySec(2); // log every 2 sec
+
+ Map conf = getCommonConfigs();
+ openSpout(spout, 0, conf);
+
+ // 1) read 5 lines in file
+ runSpout(spout, "r5");
+
+ // 2) check log file contents
+ String lockFile = listDir(spout.getLockDirPath()).get(0);
+ List<String> lines = readTextFile(fs, lockFile);
+ Assert.assertEquals(lines.size(), 1);
+ Thread.sleep(3000); // allow freq_sec to expire
+
+ // 3) read another line and see if another log entry was made
+ runSpout(spout, "r1");
+ lines = readTextFile(fs, lockFile);
+ Assert.assertEquals(2, lines.size());
}
- else if(cmd.startsWith("f")) {
- int n = Integer.parseInt(cmd.substring(1));
- Pair<HdfsSpout.MessageId, List<Object>> item = collector.items.get(n);
- spout.fail(item.getKey());
+ }
+
+ private static List<String> readTextFile(FileSystem fs, String f) throws IOException {
+ Path file = new Path(f);
+ FSDataInputStream x = fs.open(file);
+ BufferedReader reader = new BufferedReader(new InputStreamReader(x));
+ String line = null;
+ ArrayList<String> result = new ArrayList<>();
+ while ((line = reader.readLine()) != null) {
+ result.add(line);
}
- }
- return collector.lines;
+ return result;
}
- private void createTextFile(Path file, int lineCount) throws IOException {
- FSDataOutputStream os = fs.create(file);
- int size = 0;
- for (int i = 0; i < lineCount; i++) {
- os.writeBytes("line " + i + System.lineSeparator());
- String msg = "line " + i + System.lineSeparator();
- size += msg.getBytes().length;
+ private Map getCommonConfigs() {
+ Map conf = new HashMap();
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "0");
+ return conf;
}
- os.close();
- }
+ private AutoCloseableHdfsSpout makeSpout(String readerType, String[] outputFields) {
+ HdfsSpout spout = new HdfsSpout().withOutputFields(outputFields)
+ .setReaderType(readerType)
+ .setHdfsUri(DFS_CLUSTER_RULE.getDfscluster().getURI().toString())
+ .setSourceDir(source.toString())
+ .setArchiveDir(archive.toString())
+ .setBadFilesDir(badfiles.toString());
+ return new AutoCloseableHdfsSpout(spout);
+ }
- private static void createSeqFile(FileSystem fs, Path file, int rowCount) throws IOException {
+ private static class AutoCloseableHdfsSpout implements AutoCloseable {
- Configuration conf = new Configuration();
- try {
- if(fs.exists(file)) {
- fs.delete(file, false);
- }
+ private final HdfsSpout spout;
- SequenceFile.Writer w = SequenceFile.createWriter(fs, conf, file, IntWritable.class, Text.class );
- for (int i = 0; i < rowCount; i++) {
- w.append(new IntWritable(i), new Text("line " + i));
- }
- w.close();
- System.out.println("done");
- } catch (IOException e) {
- e.printStackTrace();
+ public AutoCloseableHdfsSpout(HdfsSpout spout) {
+ this.spout = spout;
+ }
+ @Override
+ public void close() throws Exception {
+ spout.close();
+ }
}
- }
-
+ private void openSpout(HdfsSpout spout, int spoutId, Map conf) {
+ MockCollector collector = new MockCollector();
+ spout.open(conf, new MockTopologyContext(spoutId), collector);
+ }
- static class MockCollector extends SpoutOutputCollector {
- //comma separated offsets
- public ArrayList<String> lines;
- public ArrayList<Pair<HdfsSpout.MessageId, List<Object> > > items;
+ /**
+ * Execute a sequence of calls on HdfsSpout.
+ *
+ * @param cmds: set of commands to run, e.g. "r,r,r,r,a1,f2,...". The commands are: r[N] - receive() called N times aN - ack, item
+ * number: N fN - fail, item number: N
+ */
+ private List<String> runSpout(HdfsSpout spout, String... cmds) {
+ MockCollector collector = (MockCollector) spout.getCollector();
+ for (String cmd : cmds) {
+ if (cmd.startsWith("r")) {
+ int count = 1;
+ if (cmd.length() > 1) {
+ count = Integer.parseInt(cmd.substring(1));
+ }
+ for (int i = 0; i < count; ++i) {
+ spout.nextTuple();
+ }
+ } else if (cmd.startsWith("a")) {
+ int n = Integer.parseInt(cmd.substring(1));
+ Pair<HdfsSpout.MessageId, List<Object>> item = collector.items.get(n);
+ spout.ack(item.getKey());
+ } else if (cmd.startsWith("f")) {
+ int n = Integer.parseInt(cmd.substring(1));
+ Pair<HdfsSpout.MessageId, List<Object>> item = collector.items.get(n);
+ spout.fail(item.getKey());
+ }
+ }
+ return collector.lines;
+ }
- public MockCollector() {
- super(null);
- lines = new ArrayList<>();
- items = new ArrayList<>();
+ private void createTextFile(Path file, int lineCount) throws IOException {
+ FSDataOutputStream os = fs.create(file);
+ int size = 0;
+ for (int i = 0; i < lineCount; i++) {
+ os.writeBytes("line " + i + System.lineSeparator());
+ String msg = "line " + i + System.lineSeparator();
+ size += msg.getBytes().length;
+ }
+ os.close();
}
+ private static void createSeqFile(FileSystem fs, Path file, int rowCount) throws IOException {
+ Configuration conf = new Configuration();
+ try {
+ if (fs.exists(file)) {
+ fs.delete(file, false);
+ }
- @Override
- public List<Integer> emit(String streamId, List<Object> tuple, Object messageId) {
- lines.add(tuple.toString());
- items.add(HdfsUtils.Pair.of(messageId, tuple));
- return null;
- }
+ SequenceFile.Writer w = SequenceFile.createWriter(fs, conf, file, IntWritable.class, Text.class);
+ for (int i = 0; i < rowCount; i++) {
+ w.append(new IntWritable(i), new Text("line " + i));
+ }
+ w.close();
+ System.out.println("done");
+ } catch (IOException e) {
+ e.printStackTrace();
- @Override
- public void emitDirect(int arg0, String arg1, List<Object> arg2, Object arg3) {
- throw new UnsupportedOperationException("NOT Implemented");
+ }
}
- @Override
- public void reportError(Throwable arg0) {
- throw new UnsupportedOperationException("NOT Implemented");
- }
+ static class MockCollector extends SpoutOutputCollector {
+ //comma separated offsets
- @Override
- public long getPendingCount() {
- return 0;
- }
- } // class MockCollector
+ public ArrayList<String> lines;
+ public ArrayList<Pair<HdfsSpout.MessageId, List<Object>>> items;
+
+ public MockCollector() {
+ super(null);
+ lines = new ArrayList<>();
+ items = new ArrayList<>();
+ }
+ @Override
+ public List<Integer> emit(String streamId, List<Object> tuple, Object messageId) {
+ lines.add(tuple.toString());
+ items.add(HdfsUtils.Pair.of(messageId, tuple));
+ return null;
+ }
+ @Override
+ public void emitDirect(int arg0, String arg1, List<Object> arg2, Object arg3) {
+ throw new UnsupportedOperationException("NOT Implemented");
+ }
- // Throws IOExceptions for 3rd & 4th call to next(), succeeds on 5th, thereafter
- // throws ParseException. Effectively produces 3 lines (1,2 & 3) from each file read
- static class MockTextFailingReader extends TextFileReader {
- public static final String[] defaultFields = {"line"};
- int readAttempts = 0;
+ @Override
+ public void reportError(Throwable arg0) {
+ throw new UnsupportedOperationException("NOT Implemented");
+ }
- public MockTextFailingReader(FileSystem fs, Path file, Map conf) throws IOException {
- super(fs, file, conf);
- }
+ @Override
+ public long getPendingCount() {
+ return 0;
+ }
+ } // class MockCollector
- @Override
- public List<Object> next() throws IOException, ParseException {
- readAttempts++;
- if (readAttempts == 3 || readAttempts ==4) {
- throw new IOException("mock test exception");
- } else if (readAttempts > 5 ) {
- throw new ParseException("mock test exception", null);
- }
- return super.next();
- }
- }
+ // Throws IOExceptions for 3rd & 4th call to next(), succeeds on 5th, thereafter
+ // throws ParseException. Effectively produces 3 lines (1,2 & 3) from each file read
+ static class MockTextFailingReader extends TextFileReader {
- static class MockTopologyContext extends TopologyContext {
- private final int componentId;
+ public static final String[] defaultFields = {"line"};
+ int readAttempts = 0;
- public MockTopologyContext(int componentId) {
- // StormTopology topology, Map stormConf, Map<Integer, String> taskToComponent, Map<String, List<Integer>> componentToSortedTasks, Map<String, Map<String, Fields>> componentToStreamToFields, String stormId, String codeDir, String pidDir, Integer taskId, Integer workerPort, List<Integer> workerTasks, Map<String, Object> defaultResources, Map<String, Object> userResources, Map<String, Object> executorData, Map<Integer, Map<Integer, Map<String, IMetric>>> registeredMetrics, Atom openOrPrepareWasCalled
- super(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
- this.componentId = componentId;
- }
+ public MockTextFailingReader(FileSystem fs, Path file, Map conf) throws IOException {
+ super(fs, file, conf);
+ }
- public String getThisComponentId() {
- return Integer.toString( componentId );
+ @Override
+ public List<Object> next() throws IOException, ParseException {
+ readAttempts++;
+ if (readAttempts == 3 || readAttempts == 4) {
+ throw new IOException("mock test exception");
+ } else if (readAttempts > 5) {
+ throw new ParseException("mock test exception", null);
+ }
+ return super.next();
+ }
}
- }
+ static class MockTopologyContext extends TopologyContext {
+
+ private final int componentId;
+
+ public MockTopologyContext(int componentId) {
+ // StormTopology topology, Map stormConf, Map<Integer, String> taskToComponent, Map<String, List<Integer>> componentToSortedTasks, Map<String, Map<String, Fields>> componentToStreamToFields, String stormId, String codeDir, String pidDir, Integer taskId, Integer workerPort, List<Integer> workerTasks, Map<String, Object> defaultResources, Map<String, Object> userResources, Map<String, Object> executorData, Map<Integer, Map<Integer, Map<String, IMetric>>> registeredMetrics, Atom openOrPrepareWasCalled
+ super(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
+ this.componentId = componentId;
+ }
+
+ public String getThisComponentId() {
+ return Integer.toString(componentId);
+ }
+
+ }
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestProgressTracker.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestProgressTracker.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestProgressTracker.java
index 0bb44af..48aa4b6 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestProgressTracker.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestProgressTracker.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,13 +10,10 @@
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License 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 org.apache.storm.hdfs.spout;
import org.apache.hadoop.conf.Configuration;
@@ -33,92 +31,89 @@ import java.io.IOException;
public class TestProgressTracker {
- private FileSystem fs;
- private Configuration conf = new Configuration();
-
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
- public File baseFolder;
-
- @Before
- public void setUp() throws Exception {
- fs = FileSystem.getLocal(conf);
- }
-
- @Test
- public void testBasic() throws Exception {
- ProgressTracker tracker = new ProgressTracker();
- baseFolder = tempFolder.newFolder("trackertest");
-
- Path file = new Path( baseFolder.toString() + Path.SEPARATOR + "testHeadTrimming.txt" );
- createTextFile(file, 10);
-
- // create reader and do some checks
- TextFileReader reader = new TextFileReader(fs, file, null);
- FileOffset pos0 = tracker.getCommitPosition();
- Assert.assertNull(pos0);
-
- TextFileReader.Offset currOffset = reader.getFileOffset();
- Assert.assertNotNull(currOffset);
- Assert.assertEquals(0, currOffset.charOffset);
-
- // read 1st line and ack
- Assert.assertNotNull(reader.next());
- TextFileReader.Offset pos1 = reader.getFileOffset();
- tracker.recordAckedOffset(pos1);
-
- TextFileReader.Offset pos1b = (TextFileReader.Offset) tracker.getCommitPosition();
- Assert.assertEquals(pos1, pos1b);
-
- // read 2nd line and ACK
- Assert.assertNotNull(reader.next());
- TextFileReader.Offset pos2 = reader.getFileOffset();
- tracker.recordAckedOffset(pos2);
-
- tracker.dumpState(System.err);
- TextFileReader.Offset pos2b = (TextFileReader.Offset) tracker.getCommitPosition();
- Assert.assertEquals(pos2, pos2b);
-
-
- // read lines 3..7, don't ACK .. commit pos should remain same
- Assert.assertNotNull(reader.next());//3
- TextFileReader.Offset pos3 = reader.getFileOffset();
- Assert.assertNotNull(reader.next());//4
- TextFileReader.Offset pos4 = reader.getFileOffset();
- Assert.assertNotNull(reader.next());//5
- TextFileReader.Offset pos5 = reader.getFileOffset();
- Assert.assertNotNull(reader.next());//6
- TextFileReader.Offset pos6 = reader.getFileOffset();
- Assert.assertNotNull(reader.next());//7
- TextFileReader.Offset pos7 = reader.getFileOffset();
-
- // now ack msg 5 and check
- tracker.recordAckedOffset(pos5);
- Assert.assertEquals(pos2, tracker.getCommitPosition()); // should remain unchanged @ 2
- tracker.recordAckedOffset(pos4);
- Assert.assertEquals(pos2, tracker.getCommitPosition()); // should remain unchanged @ 2
- tracker.recordAckedOffset(pos3);
- Assert.assertEquals(pos5, tracker.getCommitPosition()); // should be at 5
-
- tracker.recordAckedOffset(pos6);
- Assert.assertEquals(pos6, tracker.getCommitPosition()); // should be at 6
- tracker.recordAckedOffset(pos6); // double ack on same msg
- Assert.assertEquals(pos6, tracker.getCommitPosition()); // should still be at 6
-
- tracker.recordAckedOffset(pos7);
- Assert.assertEquals(pos7, tracker.getCommitPosition()); // should be at 7
-
- tracker.dumpState(System.err);
- }
-
-
-
- private void createTextFile(Path file, int lineCount) throws IOException {
- FSDataOutputStream os = fs.create(file);
- for (int i = 0; i < lineCount; i++) {
- os.writeBytes("line " + i + System.lineSeparator());
+ private FileSystem fs;
+ private Configuration conf = new Configuration();
+
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+ public File baseFolder;
+
+ @Before
+ public void setUp() throws Exception {
+ fs = FileSystem.getLocal(conf);
+ }
+
+ @Test
+ public void testBasic() throws Exception {
+ ProgressTracker tracker = new ProgressTracker();
+ baseFolder = tempFolder.newFolder("trackertest");
+
+ Path file = new Path(baseFolder.toString() + Path.SEPARATOR + "testHeadTrimming.txt");
+ createTextFile(file, 10);
+
+ // create reader and do some checks
+ TextFileReader reader = new TextFileReader(fs, file, null);
+ FileOffset pos0 = tracker.getCommitPosition();
+ Assert.assertNull(pos0);
+
+ TextFileReader.Offset currOffset = reader.getFileOffset();
+ Assert.assertNotNull(currOffset);
+ Assert.assertEquals(0, currOffset.charOffset);
+
+ // read 1st line and ack
+ Assert.assertNotNull(reader.next());
+ TextFileReader.Offset pos1 = reader.getFileOffset();
+ tracker.recordAckedOffset(pos1);
+
+ TextFileReader.Offset pos1b = (TextFileReader.Offset) tracker.getCommitPosition();
+ Assert.assertEquals(pos1, pos1b);
+
+ // read 2nd line and ACK
+ Assert.assertNotNull(reader.next());
+ TextFileReader.Offset pos2 = reader.getFileOffset();
+ tracker.recordAckedOffset(pos2);
+
+ tracker.dumpState(System.err);
+ TextFileReader.Offset pos2b = (TextFileReader.Offset) tracker.getCommitPosition();
+ Assert.assertEquals(pos2, pos2b);
+
+ // read lines 3..7, don't ACK .. commit pos should remain same
+ Assert.assertNotNull(reader.next());//3
+ TextFileReader.Offset pos3 = reader.getFileOffset();
+ Assert.assertNotNull(reader.next());//4
+ TextFileReader.Offset pos4 = reader.getFileOffset();
+ Assert.assertNotNull(reader.next());//5
+ TextFileReader.Offset pos5 = reader.getFileOffset();
+ Assert.assertNotNull(reader.next());//6
+ TextFileReader.Offset pos6 = reader.getFileOffset();
+ Assert.assertNotNull(reader.next());//7
+ TextFileReader.Offset pos7 = reader.getFileOffset();
+
+ // now ack msg 5 and check
+ tracker.recordAckedOffset(pos5);
+ Assert.assertEquals(pos2, tracker.getCommitPosition()); // should remain unchanged @ 2
+ tracker.recordAckedOffset(pos4);
+ Assert.assertEquals(pos2, tracker.getCommitPosition()); // should remain unchanged @ 2
+ tracker.recordAckedOffset(pos3);
+ Assert.assertEquals(pos5, tracker.getCommitPosition()); // should be at 5
+
+ tracker.recordAckedOffset(pos6);
+ Assert.assertEquals(pos6, tracker.getCommitPosition()); // should be at 6
+ tracker.recordAckedOffset(pos6); // double ack on same msg
+ Assert.assertEquals(pos6, tracker.getCommitPosition()); // should still be at 6
+
+ tracker.recordAckedOffset(pos7);
+ Assert.assertEquals(pos7, tracker.getCommitPosition()); // should be at 7
+
+ tracker.dumpState(System.err);
+ }
+
+ private void createTextFile(Path file, int lineCount) throws IOException {
+ try (FSDataOutputStream os = fs.create(file)) {
+ for (int i = 0; i < lineCount; i++) {
+ os.writeBytes("line " + i + System.lineSeparator());
+ }
+ }
}
- os.close();
- }
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/testing/MiniDFSClusterRule.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/testing/MiniDFSClusterRule.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/testing/MiniDFSClusterRule.java
new file mode 100644
index 0000000..d80796a
--- /dev/null
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/testing/MiniDFSClusterRule.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2017 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.storm.hdfs.testing;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+public class MiniDFSClusterRule implements TestRule {
+
+ private static final String TEST_BUILD_DATA = "test.build.data";
+
+ private final Java7Supplier<Configuration> hadoopConfSupplier;
+ private Configuration hadoopConf;
+ private MiniDFSCluster dfscluster;
+
+ public static interface Java7Supplier<T> {
+ T get();
+ }
+
+ public MiniDFSClusterRule() {
+ this(new Java7Supplier<Configuration>() {
+ @Override
+ public Configuration get() {
+ return new Configuration();
+ }
+ });
+ }
+
+ public MiniDFSClusterRule(Java7Supplier<Configuration> hadoopConfSupplier) {
+ this.hadoopConfSupplier = hadoopConfSupplier;
+ }
+
+ public Configuration getHadoopConf() {
+ return hadoopConf;
+ }
+
+ public MiniDFSCluster getDfscluster() {
+ return dfscluster;
+ }
+
+ @Override
+ public Statement apply(Statement base, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ try {
+ System.setProperty(TEST_BUILD_DATA, "target/test/data");
+ hadoopConf = hadoopConfSupplier.get();
+ dfscluster = new MiniDFSCluster.Builder(hadoopConf).numDataNodes(3).build();
+ dfscluster.waitActive();
+ } finally {
+ if (dfscluster != null) {
+ dfscluster.shutdown();
+ }
+ System.clearProperty(TEST_BUILD_DATA);
+ }
+ }
+ };
+ }
+
+}
[4/4] storm git commit: STORM-2810: Fix resource leaks in storm-hdfs
tests
Posted by sr...@apache.org.
STORM-2810: Fix resource leaks in storm-hdfs tests
Project: http://git-wip-us.apache.org/repos/asf/storm/repo
Commit: http://git-wip-us.apache.org/repos/asf/storm/commit/a0308efd
Tree: http://git-wip-us.apache.org/repos/asf/storm/tree/a0308efd
Diff: http://git-wip-us.apache.org/repos/asf/storm/diff/a0308efd
Branch: refs/heads/1.1.x-branch
Commit: a0308efd6c934416206183561194f3470e415edb
Parents: ed005ab
Author: Stig Rohde Døssing <sr...@apache.org>
Authored: Sat Nov 11 18:23:00 2017 +0100
Committer: Stig Rohde Døssing <sr...@apache.org>
Committed: Tue Nov 14 07:53:33 2017 +0100
----------------------------------------------------------------------
.../storm/hdfs/blobstore/HdfsBlobStoreImpl.java | 14 +-
.../storm/hdfs/bolt/AbstractHdfsBolt.java | 28 +-
.../org/apache/storm/hdfs/spout/HdfsSpout.java | 1484 +++++++++---------
.../hdfs/avro/TestFixedAvroSerializer.java | 13 +-
.../hdfs/avro/TestGenericAvroSerializer.java | 11 +-
.../storm/hdfs/blobstore/BlobStoreTest.java | 897 ++++++-----
.../hdfs/blobstore/HdfsBlobStoreImplTest.java | 288 ++--
.../hdfs/bolt/AvroGenericRecordBoltTest.java | 142 +-
.../apache/storm/hdfs/bolt/TestHdfsBolt.java | 108 +-
.../storm/hdfs/bolt/TestSequenceFileBolt.java | 71 +-
.../apache/storm/hdfs/spout/TestDirLock.java | 281 ++--
.../apache/storm/hdfs/spout/TestFileLock.java | 679 ++++----
.../storm/hdfs/spout/TestHdfsSemantics.java | 311 ++--
.../apache/storm/hdfs/spout/TestHdfsSpout.java | 1235 +++++++--------
.../storm/hdfs/spout/TestProgressTracker.java | 179 +--
.../storm/hdfs/testing/MiniDFSClusterRule.java | 78 +
16 files changed, 2945 insertions(+), 2874 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImpl.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImpl.java b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImpl.java
index a4c88ce..e90e2d3 100644
--- a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImpl.java
+++ b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImpl.java
@@ -45,9 +45,10 @@ public class HdfsBlobStoreImpl {
private static final long FULL_CLEANUP_FREQ = 60 * 60 * 1000l;
private static final int BUCKETS = 1024;
- private static final Timer timer = new Timer("HdfsBlobStore cleanup thread", true);
private static final String BLOBSTORE_DATA = "data";
+ private Timer timer;
+
public class KeyInHashDirIterator implements Iterator<String> {
private int currentBucket = 0;
private Iterator<String> it = null;
@@ -112,7 +113,6 @@ public class HdfsBlobStoreImpl {
private Path _fullPath;
private FileSystem _fs;
- private TimerTask _cleanup = null;
private Configuration _hadoopConf;
// blobstore directory is private!
@@ -141,7 +141,7 @@ public class HdfsBlobStoreImpl {
Object shouldCleanup = conf.get(Config.BLOBSTORE_CLEANUP_ENABLE);
if (Utils.getBoolean(shouldCleanup, false)) {
LOG.debug("Starting hdfs blobstore cleaner");
- _cleanup = new TimerTask() {
+ TimerTask cleanup = new TimerTask() {
@Override
public void run() {
try {
@@ -151,7 +151,8 @@ public class HdfsBlobStoreImpl {
}
}
};
- timer.scheduleAtFixedRate(_cleanup, 0, FULL_CLEANUP_FREQ);
+ timer = new Timer("HdfsBlobStore cleanup thread", true);
+ timer.scheduleAtFixedRate(cleanup, 0, FULL_CLEANUP_FREQ);
}
}
@@ -304,9 +305,8 @@ public class HdfsBlobStoreImpl {
}
public void shutdown() {
- if (_cleanup != null) {
- _cleanup.cancel();
- _cleanup = null;
+ if (timer != null) {
+ timer.cancel();
}
}
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/bolt/AbstractHdfsBolt.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/bolt/AbstractHdfsBolt.java b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/bolt/AbstractHdfsBolt.java
index 12f835c..7a2402c 100644
--- a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/bolt/AbstractHdfsBolt.java
+++ b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/bolt/AbstractHdfsBolt.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -49,6 +50,7 @@ import java.util.Timer;
import java.util.TimerTask;
public abstract class AbstractHdfsBolt extends BaseRichBolt {
+
private static final Logger LOG = LoggerFactory.getLogger(AbstractHdfsBolt.class);
private static final Integer DEFAULT_RETRY_COUNT = 3;
/**
@@ -95,14 +97,19 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
/**
* Marked as final to prevent override. Subclasses should implement the doPrepare() method.
+ *
* @param conf
* @param topologyContext
* @param collector
*/
public final void prepare(Map conf, TopologyContext topologyContext, OutputCollector collector){
this.writeLock = new Object();
- if (this.syncPolicy == null) throw new IllegalStateException("SyncPolicy must be specified.");
- if (this.rotationPolicy == null) throw new IllegalStateException("RotationPolicy must be specified.");
+ if (this.syncPolicy == null) {
+ throw new IllegalStateException("SyncPolicy must be specified.");
+ }
+ if (this.rotationPolicy == null) {
+ throw new IllegalStateException("RotationPolicy must be specified.");
+ }
if (this.fsUrl == null) {
throw new IllegalStateException("File system URL must be specified.");
}
@@ -215,10 +222,8 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
}
/**
- * A tuple must be mapped to a writer based on two factors:
- * - bolt specific logic that must separate tuples into different files in the same directory (see the avro bolt
- * for an example of this)
- * - the directory the tuple will be partioned into
+ * A tuple must be mapped to a writer based on two factors: - bolt specific logic that must separate tuples into different files in the
+ * same directory (see the avro bolt for an example of this) - the directory the tuple will be partioned into
*
* @param tuple
* @return
@@ -252,6 +257,11 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
+ @Override
+ public void cleanup() {
+ this.rotationTimer.cancel();
+ }
+
private void syncAllWriters() throws IOException {
for (AbstractHDFSWriter writer : writers.values()) {
writer.sync();
@@ -281,8 +291,7 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
final String partitionPath = this.partitioner.getPartitionPath(tuple);
final int rotation;
- if (rotationCounterMap.containsKey(partitionPath))
- {
+ if (rotationCounterMap.containsKey(partitionPath)) {
rotation = rotationCounterMap.get(partitionPath) + 1;
} else {
rotation = 0;
@@ -300,6 +309,7 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
abstract protected AbstractHDFSWriter makeNewWriter(Path path, Tuple tuple) throws IOException;
static class WritersMap extends LinkedHashMap<String, AbstractHDFSWriter> {
+
final long maxWriters;
public WritersMap(long maxWriters) {
@@ -312,4 +322,4 @@ public abstract class AbstractHdfsBolt extends BaseRichBolt {
return this.size() > this.maxWriters;
}
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/HdfsSpout.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/HdfsSpout.java b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/HdfsSpout.java
index b7627f2..38a791b 100644
--- a/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/HdfsSpout.java
+++ b/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/HdfsSpout.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,13 +10,10 @@
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License 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 org.apache.storm.hdfs.spout;
import java.io.IOException;
@@ -47,800 +45,810 @@ import org.apache.storm.tuple.Fields;
public class HdfsSpout extends BaseRichSpout {
- // user configurable
- private String hdfsUri; // required
- private String readerType; // required
- private Fields outputFields; // required
+ // user configurable
+ private String hdfsUri; // required
+ private String readerType; // required
+ private Fields outputFields; // required
- private String sourceDir; // required
- private Path sourceDirPath; // required
+ private String sourceDir; // required
+ private Path sourceDirPath; // required
- private String archiveDir; // required
- private Path archiveDirPath; // required
+ private String archiveDir; // required
+ private Path archiveDirPath; // required
- private String badFilesDir; // required
- private Path badFilesDirPath; // required
+ private String badFilesDir; // required
+ private Path badFilesDirPath; // required
- private String lockDir;
- private Path lockDirPath;
+ private String lockDir;
+ private Path lockDirPath;
- private int commitFrequencyCount = Configs.DEFAULT_COMMIT_FREQ_COUNT;
- private int commitFrequencySec = Configs.DEFAULT_COMMIT_FREQ_SEC;
- private int maxOutstanding = Configs.DEFAULT_MAX_OUTSTANDING;
- private int lockTimeoutSec = Configs.DEFAULT_LOCK_TIMEOUT;
- private boolean clocksInSync = true;
+ private int commitFrequencyCount = Configs.DEFAULT_COMMIT_FREQ_COUNT;
+ private int commitFrequencySec = Configs.DEFAULT_COMMIT_FREQ_SEC;
+ private int maxOutstanding = Configs.DEFAULT_MAX_OUTSTANDING;
+ private int lockTimeoutSec = Configs.DEFAULT_LOCK_TIMEOUT;
+ private boolean clocksInSync = true;
- private String inprogress_suffix = ".inprogress"; // not configurable to prevent change between topology restarts
- private String ignoreSuffix = ".ignore";
+ private String inprogress_suffix = ".inprogress"; // not configurable to prevent change between topology restarts
+ private String ignoreSuffix = ".ignore";
- private String outputStreamName= null;
+ private String outputStreamName = null;
- // other members
- private static final Logger LOG = LoggerFactory.getLogger(HdfsSpout.class);
+ // other members
+ private static final Logger LOG = LoggerFactory.getLogger(HdfsSpout.class);
- private ProgressTracker tracker = null;
+ private ProgressTracker tracker = null;
- private FileSystem hdfs;
- private FileReader reader;
+ private FileSystem hdfs;
+ private FileReader reader;
- private SpoutOutputCollector collector;
- HashMap<MessageId, List<Object> > inflight = new HashMap<>();
- LinkedBlockingQueue<HdfsUtils.Pair<MessageId, List<Object>>> retryList = new LinkedBlockingQueue<>();
-
- private Configuration hdfsConfig;
-
- private Map conf = null;
- private FileLock lock;
- private String spoutId = null;
-
- HdfsUtils.Pair<Path,FileLock.LogEntry> lastExpiredLock = null;
- private long lastExpiredLockTime = 0;
-
- private long tupleCounter = 0;
- private boolean ackEnabled = false;
- private int acksSinceLastCommit = 0 ;
- private final AtomicBoolean commitTimeElapsed = new AtomicBoolean(false);
- private Timer commitTimer;
- private boolean fileReadCompletely = true;
-
- private String configKey = Configs.DEFAULT_HDFS_CONFIG_KEY; // key for hdfs Kerberos configs
-
- public HdfsSpout() {
- }
-
- public HdfsSpout setHdfsUri(String hdfsUri) {
- this.hdfsUri = hdfsUri;
- return this;
- }
-
- public HdfsSpout setReaderType(String readerType) {
- this.readerType = readerType;
- return this;
- }
-
- public HdfsSpout setSourceDir(String sourceDir) {
- this.sourceDir = sourceDir;
- return this;
- }
-
- public HdfsSpout setArchiveDir(String archiveDir) {
- this.archiveDir = archiveDir;
- return this;
- }
-
- public HdfsSpout setBadFilesDir(String badFilesDir) {
- this.badFilesDir = badFilesDir;
- return this;
- }
-
- public HdfsSpout setLockDir(String lockDir) {
- this.lockDir = lockDir;
- return this;
- }
-
- public HdfsSpout setCommitFrequencyCount(int commitFrequencyCount) {
- this.commitFrequencyCount = commitFrequencyCount;
- return this;
- }
-
- public HdfsSpout setCommitFrequencySec(int commitFrequencySec) {
- this.commitFrequencySec = commitFrequencySec;
- return this;
- }
-
- public HdfsSpout setMaxOutstanding(int maxOutstanding) {
- this.maxOutstanding = maxOutstanding;
- return this;
- }
-
- public HdfsSpout setLockTimeoutSec(int lockTimeoutSec) {
- this.lockTimeoutSec = lockTimeoutSec;
- return this;
- }
-
- public HdfsSpout setClocksInSync(boolean clocksInSync) {
- this.clocksInSync = clocksInSync;
- return this;
- }
-
-
- public HdfsSpout setIgnoreSuffix(String ignoreSuffix) {
- this.ignoreSuffix = ignoreSuffix;
- return this;
- }
-
- /** Output field names. Number of fields depends upon the reader type */
- public HdfsSpout withOutputFields(String... fields) {
- outputFields = new Fields(fields);
- return this;
- }
-
- /** set key name under which HDFS options are placed. (similar to HDFS bolt).
- * default key name is 'hdfs.config' */
- public HdfsSpout withConfigKey(String configKey) {
- this.configKey = configKey;
- return this;
- }
-
- /**
- * Set output stream name
- */
- public HdfsSpout withOutputStream(String streamName) {
- this.outputStreamName = streamName;
- return this;
- }
-
- public Path getLockDirPath() {
- return lockDirPath;
- }
-
- public SpoutOutputCollector getCollector() {
- return collector;
- }
-
- public void nextTuple() {
- LOG.trace("Next Tuple {}", spoutId);
- // 1) First re-emit any previously failed tuples (from retryList)
- if (!retryList.isEmpty()) {
- LOG.debug("Sending tuple from retry list");
- HdfsUtils.Pair<MessageId, List<Object>> pair = retryList.remove();
- emitData(pair.getValue(), pair.getKey());
- return;
- }
-
- if ( ackEnabled && tracker.size()>= maxOutstanding ) {
- LOG.warn("Waiting for more ACKs before generating new tuples. " +
- "Progress tracker size has reached limit {}, SpoutID {}"
- , maxOutstanding, spoutId);
- // Don't emit anything .. allow configured spout wait strategy to kick in
- return;
- }
-
- // 2) If no failed tuples to be retried, then send tuples from hdfs
- while (true) {
- try {
- // 3) Select a new file if one is not open already
- if (reader == null) {
- reader = pickNextFile();
- if (reader == null) {
- LOG.debug("Currently no new files to process under : " + sourceDirPath);
- return;
- } else {
- fileReadCompletely=false;
- }
- }
- if ( fileReadCompletely ) { // wait for more ACKs before proceeding
- return;
- }
- // 4) Read record from file, emit to collector and record progress
- List<Object> tuple = reader.next();
- if (tuple != null) {
- fileReadCompletely= false;
- ++tupleCounter;
- MessageId msgId = new MessageId(tupleCounter, reader.getFilePath(), reader.getFileOffset());
- emitData(tuple, msgId);
-
- if ( !ackEnabled ) {
- ++acksSinceLastCommit; // assume message is immediately ACKed in non-ack mode
- commitProgress(reader.getFileOffset());
- } else {
- commitProgress(tracker.getCommitPosition());
- }
- return;
- } else {
- fileReadCompletely = true;
- if ( !ackEnabled ) {
- markFileAsDone(reader.getFilePath());
- }
- }
- } catch (IOException e) {
- LOG.error("I/O Error processing at file location " + getFileProgress(reader), e);
- // don't emit anything .. allow configured spout wait strategy to kick in
- return;
- } catch (ParseException e) {
- LOG.error("Parsing error when processing at file location " + getFileProgress(reader) +
- ". Skipping remainder of file.", e);
- markFileAsBad(reader.getFilePath());
- // Note: We don't return from this method on ParseException to avoid triggering the
- // spout wait strategy (due to no emits). Instead we go back into the loop and
- // generate a tuple from next file
- }
- } // while
- }
-
- // will commit progress into lock file if commit threshold is reached
- private void commitProgress(FileOffset position) {
- if ( position==null ) {
- return;
- }
- if ( lock!=null && canCommitNow() ) {
- try {
- String pos = position.toString();
- lock.heartbeat(pos);
- LOG.debug("{} Committed progress. {}", spoutId, pos);
- acksSinceLastCommit = 0;
- commitTimeElapsed.set(false);
- setupCommitElapseTimer();
- } catch (IOException e) {
- LOG.error("Unable to commit progress Will retry later. Spout ID = " + spoutId, e);
- }
- }
- }
-
- private void setupCommitElapseTimer() {
- if ( commitFrequencySec<=0 ) {
- return;
- }
- TimerTask timerTask = new TimerTask() {
- @Override
- public void run() {
- commitTimeElapsed.set(true);
- }
- };
- commitTimer.schedule(timerTask, commitFrequencySec * 1000);
- }
-
- private static String getFileProgress(FileReader reader) {
- return reader.getFilePath() + " " + reader.getFileOffset();
- }
-
- private void markFileAsDone(Path filePath) {
- try {
- Path newFile = renameCompletedFile(reader.getFilePath());
- LOG.info("Completed processing {}. Spout Id = {}", newFile, spoutId);
- } catch (IOException e) {
- LOG.error("Unable to archive completed file" + filePath + " Spout ID " + spoutId, e);
- }
- closeReaderAndResetTrackers();
- }
-
- private void markFileAsBad(Path file) {
- String fileName = file.toString();
- String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix));
- String originalName = new Path(fileNameMinusSuffix).getName();
- Path newFile = new Path( badFilesDirPath + Path.SEPARATOR + originalName);
-
- LOG.info("Moving bad file {} to {}. Processed it till offset {}. SpoutID= {}", originalName, newFile, tracker.getCommitPosition(), spoutId);
- try {
- if (!hdfs.rename(file, newFile) ) { // seems this can fail by returning false or throwing exception
- throw new IOException("Move failed for bad file: " + file); // convert false ret value to exception
- }
- } catch (IOException e) {
- LOG.warn("Error moving bad file: " + file + " to destination " + newFile + " SpoutId =" + spoutId, e);
- }
- closeReaderAndResetTrackers();
- }
-
- private void closeReaderAndResetTrackers() {
- inflight.clear();
- tracker.offsets.clear();
- retryList.clear();
-
- reader.close();
- reader = null;
- releaseLockAndLog(lock, spoutId);
- lock = null;
- }
-
- private static void releaseLockAndLog(FileLock fLock, String spoutId) {
- try {
- if ( fLock!=null ) {
- fLock.release();
- LOG.debug("Spout {} released FileLock. SpoutId = {}", fLock.getLockFile(), spoutId);
- }
- } catch (IOException e) {
- LOG.error("Unable to delete lock file : " +fLock.getLockFile() + " SpoutId =" + spoutId, e);
- }
- }
-
- protected void emitData(List<Object> tuple, MessageId id) {
- LOG.trace("Emitting - {}", id);
-
- if ( outputStreamName==null )
- collector.emit( tuple, id );
- else
- collector.emit( outputStreamName, tuple, id );
-
- inflight.put(id, tuple);
- }
-
- public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
- LOG.info("Opening HDFS Spout");
- this.conf = conf;
- this.commitTimer = new Timer();
- this.tracker = new ProgressTracker();
- this.hdfsConfig = new Configuration();
-
- this.collector = collector;
- this.hdfsConfig = new Configuration();
- this.tupleCounter = 0;
-
- // Hdfs related settings
- if ( this.hdfsUri==null && conf.containsKey(Configs.HDFS_URI) ) {
- this.hdfsUri = conf.get(Configs.HDFS_URI).toString();
- }
- if ( this.hdfsUri==null ) {
- throw new RuntimeException("HDFS Uri not set on spout");
- }
-
- try {
- this.hdfs = FileSystem.get(URI.create(hdfsUri), hdfsConfig);
- } catch (IOException e) {
- LOG.error("Unable to instantiate file system", e);
- throw new RuntimeException("Unable to instantiate file system", e);
- }
-
-
- if ( conf.containsKey(configKey) ) {
- Map<String, Object> map = (Map<String, Object>)conf.get(configKey);
- if ( map != null ) {
- for(String keyName : map.keySet()){
- LOG.info("HDFS Config override : {} = {} ", keyName, String.valueOf(map.get(keyName)));
- this.hdfsConfig.set(keyName, String.valueOf(map.get(keyName)));
- }
- try {
- HdfsSecurityUtil.login(conf, hdfsConfig);
- } catch (IOException e) {
- LOG.error("HDFS Login failed ", e);
- throw new RuntimeException(e);
- }
- } // if (map != null)
- }
+ private SpoutOutputCollector collector;
+ HashMap<MessageId, List<Object>> inflight = new HashMap<>();
+ LinkedBlockingQueue<HdfsUtils.Pair<MessageId, List<Object>>> retryList = new LinkedBlockingQueue<>();
+
+ private Configuration hdfsConfig;
+
+ private Map conf = null;
+ private FileLock lock;
+ private String spoutId = null;
+
+ HdfsUtils.Pair<Path, FileLock.LogEntry> lastExpiredLock = null;
+ private long lastExpiredLockTime = 0;
+
+ private long tupleCounter = 0;
+ private boolean ackEnabled = false;
+ private int acksSinceLastCommit = 0;
+ private final AtomicBoolean commitTimeElapsed = new AtomicBoolean(false);
+ private Timer commitTimer;
+ private boolean fileReadCompletely = true;
+
+ private String configKey = Configs.DEFAULT_HDFS_CONFIG_KEY; // key for hdfs Kerberos configs
- // Reader type config
- if ( readerType==null && conf.containsKey(Configs.READER_TYPE) ) {
- readerType = conf.get(Configs.READER_TYPE).toString();
+ public HdfsSpout() {
}
- checkValidReader(readerType);
- // -- source dir config
- if ( sourceDir==null && conf.containsKey(Configs.SOURCE_DIR) ) {
- sourceDir = conf.get(Configs.SOURCE_DIR).toString();
+ public HdfsSpout setHdfsUri(String hdfsUri) {
+ this.hdfsUri = hdfsUri;
+ return this;
}
- if ( sourceDir==null ) {
- LOG.error(Configs.SOURCE_DIR + " setting is required");
- throw new RuntimeException(Configs.SOURCE_DIR + " setting is required");
+
+ public HdfsSpout setReaderType(String readerType) {
+ this.readerType = readerType;
+ return this;
+ }
+
+ public HdfsSpout setSourceDir(String sourceDir) {
+ this.sourceDir = sourceDir;
+ return this;
}
- this.sourceDirPath = new Path( sourceDir );
- // -- archive dir config
- if ( archiveDir==null && conf.containsKey(Configs.ARCHIVE_DIR) ) {
- archiveDir = conf.get(Configs.ARCHIVE_DIR).toString();
+ public HdfsSpout setArchiveDir(String archiveDir) {
+ this.archiveDir = archiveDir;
+ return this;
}
- if ( archiveDir==null ) {
- LOG.error(Configs.ARCHIVE_DIR + " setting is required");
- throw new RuntimeException(Configs.ARCHIVE_DIR + " setting is required");
+
+ public HdfsSpout setBadFilesDir(String badFilesDir) {
+ this.badFilesDir = badFilesDir;
+ return this;
+ }
+
+ public HdfsSpout setLockDir(String lockDir) {
+ this.lockDir = lockDir;
+ return this;
}
- this.archiveDirPath = new Path( archiveDir );
- validateOrMakeDir(hdfs, archiveDirPath, "Archive");
- // -- bad files dir config
- if ( badFilesDir==null && conf.containsKey(Configs.BAD_DIR) ) {
- badFilesDir = conf.get(Configs.BAD_DIR).toString();
+ public HdfsSpout setCommitFrequencyCount(int commitFrequencyCount) {
+ this.commitFrequencyCount = commitFrequencyCount;
+ return this;
}
- if ( badFilesDir==null ) {
- LOG.error(Configs.BAD_DIR + " setting is required");
- throw new RuntimeException(Configs.BAD_DIR + " setting is required");
+
+ public HdfsSpout setCommitFrequencySec(int commitFrequencySec) {
+ this.commitFrequencySec = commitFrequencySec;
+ return this;
+ }
+
+ public HdfsSpout setMaxOutstanding(int maxOutstanding) {
+ this.maxOutstanding = maxOutstanding;
+ return this;
+ }
+
+ public HdfsSpout setLockTimeoutSec(int lockTimeoutSec) {
+ this.lockTimeoutSec = lockTimeoutSec;
+ return this;
}
- this.badFilesDirPath = new Path(badFilesDir);
- validateOrMakeDir(hdfs, badFilesDirPath, "bad files");
- // -- ignore file names config
- if ( conf.containsKey(Configs.IGNORE_SUFFIX) ) {
- this.ignoreSuffix = conf.get(Configs.IGNORE_SUFFIX).toString();
+ public HdfsSpout setClocksInSync(boolean clocksInSync) {
+ this.clocksInSync = clocksInSync;
+ return this;
}
- // -- lock dir config
- if ( lockDir==null && conf.containsKey(Configs.LOCK_DIR) ) {
- lockDir = conf.get(Configs.LOCK_DIR).toString();
+ public HdfsSpout setIgnoreSuffix(String ignoreSuffix) {
+ this.ignoreSuffix = ignoreSuffix;
+ return this;
}
- if ( lockDir==null ) {
- lockDir = getDefaultLockDir(sourceDirPath);
+
+ /**
+ * Output field names. Number of fields depends upon the reader type
+ */
+ public HdfsSpout withOutputFields(String... fields) {
+ outputFields = new Fields(fields);
+ return this;
}
- this.lockDirPath = new Path(lockDir);
- validateOrMakeDir(hdfs,lockDirPath, "locks");
+ /**
+ * set key name under which HDFS options are placed. (similar to HDFS bolt). default key name is 'hdfs.config'
+ */
+ public HdfsSpout withConfigKey(String configKey) {
+ this.configKey = configKey;
+ return this;
+ }
- // -- lock timeout
- if ( conf.get(Configs.LOCK_TIMEOUT) !=null ) {
- this.lockTimeoutSec = Integer.parseInt(conf.get(Configs.LOCK_TIMEOUT).toString());
+ /**
+ * Set output stream name
+ */
+ public HdfsSpout withOutputStream(String streamName) {
+ this.outputStreamName = streamName;
+ return this;
}
- // -- enable/disable ACKing
- Object ackers = conf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
- if ( ackers!=null ) {
- int ackerCount = Integer.parseInt(ackers.toString());
- this.ackEnabled = (ackerCount>0);
- LOG.debug("ACKer count = {}", ackerCount);
+ public Path getLockDirPath() {
+ return lockDirPath;
}
- else { // ackers==null when ackerCount not explicitly set on the topology
- this.ackEnabled = true;
- LOG.debug("ACK count not explicitly set on topology.");
+
+ public SpoutOutputCollector getCollector() {
+ return collector;
}
- LOG.info("ACK mode is {}", ackEnabled ? "enabled" : "disabled");
+ public void nextTuple() {
+ LOG.trace("Next Tuple {}", spoutId);
+ // 1) First re-emit any previously failed tuples (from retryList)
+ if (!retryList.isEmpty()) {
+ LOG.debug("Sending tuple from retry list");
+ HdfsUtils.Pair<MessageId, List<Object>> pair = retryList.remove();
+ emitData(pair.getValue(), pair.getKey());
+ return;
+ }
- // -- commit frequency - count
- if ( conf.get(Configs.COMMIT_FREQ_COUNT) != null ) {
- commitFrequencyCount = Integer.parseInt(conf.get(Configs.COMMIT_FREQ_COUNT).toString());
+ if (ackEnabled && tracker.size() >= maxOutstanding) {
+ LOG.warn("Waiting for more ACKs before generating new tuples. "
+ + "Progress tracker size has reached limit {}, SpoutID {}",
+ maxOutstanding, spoutId);
+ // Don't emit anything .. allow configured spout wait strategy to kick in
+ return;
+ }
+
+ // 2) If no failed tuples to be retried, then send tuples from hdfs
+ while (true) {
+ try {
+ // 3) Select a new file if one is not open already
+ if (reader == null) {
+ reader = pickNextFile();
+ if (reader == null) {
+ LOG.debug("Currently no new files to process under : " + sourceDirPath);
+ return;
+ } else {
+ fileReadCompletely = false;
+ }
+ }
+ if (fileReadCompletely) { // wait for more ACKs before proceeding
+ return;
+ }
+ // 4) Read record from file, emit to collector and record progress
+ List<Object> tuple = reader.next();
+ if (tuple != null) {
+ fileReadCompletely = false;
+ ++tupleCounter;
+ MessageId msgId = new MessageId(tupleCounter, reader.getFilePath(), reader.getFileOffset());
+ emitData(tuple, msgId);
+
+ if (!ackEnabled) {
+ ++acksSinceLastCommit; // assume message is immediately ACKed in non-ack mode
+ commitProgress(reader.getFileOffset());
+ } else {
+ commitProgress(tracker.getCommitPosition());
+ }
+ return;
+ } else {
+ fileReadCompletely = true;
+ if (!ackEnabled) {
+ markFileAsDone(reader.getFilePath());
+ }
+ }
+ } catch (IOException e) {
+ LOG.error("I/O Error processing at file location " + getFileProgress(reader), e);
+ // don't emit anything .. allow configured spout wait strategy to kick in
+ return;
+ } catch (ParseException e) {
+ LOG.error("Parsing error when processing at file location " + getFileProgress(reader)
+ + ". Skipping remainder of file.", e);
+ markFileAsBad(reader.getFilePath());
+ // Note: We don't return from this method on ParseException to avoid triggering the
+ // spout wait strategy (due to no emits). Instead we go back into the loop and
+ // generate a tuple from next file
+ }
+ } // while
+ }
+
+ // will commit progress into lock file if commit threshold is reached
+ private void commitProgress(FileOffset position) {
+ if (position == null) {
+ return;
+ }
+ if (lock != null && canCommitNow()) {
+ try {
+ String pos = position.toString();
+ lock.heartbeat(pos);
+ LOG.debug("{} Committed progress. {}", spoutId, pos);
+ acksSinceLastCommit = 0;
+ commitTimeElapsed.set(false);
+ setupCommitElapseTimer();
+ } catch (IOException e) {
+ LOG.error("Unable to commit progress Will retry later. Spout ID = " + spoutId, e);
+ }
+ }
}
- // -- commit frequency - seconds
- if ( conf.get(Configs.COMMIT_FREQ_SEC) != null ) {
- commitFrequencySec = Integer.parseInt(conf.get(Configs.COMMIT_FREQ_SEC).toString());
- if ( commitFrequencySec<=0 ) {
- throw new RuntimeException(Configs.COMMIT_FREQ_SEC + " setting must be greater than 0");
- }
- }
-
- // -- max outstanding tuples
- if ( conf.get(Configs.MAX_OUTSTANDING) !=null ) {
- maxOutstanding = Integer.parseInt(conf.get(Configs.MAX_OUTSTANDING).toString());
- }
+ private void setupCommitElapseTimer() {
+ if (commitFrequencySec <= 0) {
+ return;
+ }
+ TimerTask timerTask = new TimerTask() {
+ @Override
+ public void run() {
+ commitTimeElapsed.set(true);
+ }
+ };
+ commitTimer.schedule(timerTask, commitFrequencySec * 1000);
+ }
- // -- clocks in sync
- if ( conf.get(Configs.CLOCKS_INSYNC) !=null ) {
- clocksInSync = Boolean.parseBoolean(conf.get(Configs.CLOCKS_INSYNC).toString());
+ private static String getFileProgress(FileReader reader) {
+ return reader.getFilePath() + " " + reader.getFileOffset();
}
- // -- spout id
- spoutId = context.getThisComponentId();
+ private void markFileAsDone(Path filePath) {
+ try {
+ Path newFile = renameCompletedFile(reader.getFilePath());
+ LOG.info("Completed processing {}. Spout Id = {}", newFile, spoutId);
+ } catch (IOException e) {
+ LOG.error("Unable to archive completed file" + filePath + " Spout ID " + spoutId, e);
+ }
+ closeReaderAndResetTrackers();
+ }
- // setup timer for commit elapse time tracking
- setupCommitElapseTimer();
- }
+ private void markFileAsBad(Path file) {
+ String fileName = file.toString();
+ String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix));
+ String originalName = new Path(fileNameMinusSuffix).getName();
+ Path newFile = new Path(badFilesDirPath + Path.SEPARATOR + originalName);
- private static void validateOrMakeDir(FileSystem fs, Path dir, String dirDescription) {
- try {
- if ( fs.exists(dir) ) {
- if ( !fs.isDirectory(dir) ) {
- LOG.error(dirDescription + " directory is a file, not a dir. " + dir);
- throw new RuntimeException(dirDescription + " directory is a file, not a dir. " + dir);
+ LOG.info("Moving bad file {} to {}. Processed it till offset {}. SpoutID= {}", originalName, newFile, tracker.getCommitPosition(), spoutId);
+ try {
+ if (!hdfs.rename(file, newFile)) { // seems this can fail by returning false or throwing exception
+ throw new IOException("Move failed for bad file: " + file); // convert false ret value to exception
+ }
+ } catch (IOException e) {
+ LOG.warn("Error moving bad file: " + file + " to destination " + newFile + " SpoutId =" + spoutId, e);
}
- } else if ( ! fs.mkdirs(dir) ) {
- LOG.error("Unable to create " + dirDescription + " directory " + dir);
- throw new RuntimeException("Unable to create " + dirDescription + " directory " + dir);
- }
- } catch (IOException e) {
- LOG.error("Unable to create " + dirDescription + " directory " + dir, e);
- throw new RuntimeException("Unable to create " + dirDescription + " directory " + dir, e);
+ closeReaderAndResetTrackers();
}
- }
- private String getDefaultLockDir(Path sourceDirPath) {
- return sourceDirPath.toString() + Path.SEPARATOR + Configs.DEFAULT_LOCK_DIR;
- }
+ private void closeReaderAndResetTrackers() {
+ inflight.clear();
+ tracker.offsets.clear();
+ retryList.clear();
+
+ reader.close();
+ reader = null;
+ releaseLockAndLog(lock, spoutId);
+ lock = null;
+ }
- private static void checkValidReader(String readerType) {
- if ( readerType.equalsIgnoreCase(Configs.TEXT) || readerType.equalsIgnoreCase(Configs.SEQ) )
- return;
- try {
- Class<?> classType = Class.forName(readerType);
- classType.getConstructor(FileSystem.class, Path.class, Map.class);
- return;
- } catch (ClassNotFoundException e) {
- LOG.error(readerType + " not found in classpath.", e);
- throw new IllegalArgumentException(readerType + " not found in classpath.", e);
- } catch (NoSuchMethodException e) {
- LOG.error(readerType + " is missing the expected constructor for Readers.", e);
- throw new IllegalArgumentException(readerType + " is missing the expected constuctor for Readers.");
+ private static void releaseLockAndLog(FileLock fLock, String spoutId) {
+ try {
+ if (fLock != null) {
+ fLock.release();
+ LOG.debug("Spout {} released FileLock. SpoutId = {}", fLock.getLockFile(), spoutId);
+ }
+ } catch (IOException e) {
+ LOG.error("Unable to delete lock file : " + fLock.getLockFile() + " SpoutId =" + spoutId, e);
+ }
}
- }
- @Override
- public void ack(Object msgId) {
- LOG.trace("Ack received for msg {} on spout {}", msgId, spoutId);
- if ( !ackEnabled ) {
- return;
+ protected void emitData(List<Object> tuple, MessageId id) {
+ LOG.trace("Emitting - {}", id);
+
+ if (outputStreamName == null) {
+ collector.emit(tuple, id);
+ } else {
+ collector.emit(outputStreamName, tuple, id);
+ }
+
+ inflight.put(id, tuple);
}
- MessageId id = (MessageId) msgId;
- inflight.remove(id);
- ++acksSinceLastCommit;
- tracker.recordAckedOffset(id.offset);
- commitProgress(tracker.getCommitPosition());
- if ( fileReadCompletely && inflight.isEmpty() ) {
- markFileAsDone(reader.getFilePath());
- reader = null;
- }
- super.ack(msgId);
- }
-
- private boolean canCommitNow() {
-
- if ( commitFrequencyCount>0 && acksSinceLastCommit >= commitFrequencyCount ) {
- return true;
- }
- return commitTimeElapsed.get();
- }
-
- @Override
- public void fail(Object msgId) {
- LOG.trace("Fail received for msg id {} on spout {}", msgId, spoutId);
- super.fail(msgId);
- if ( ackEnabled ) {
- HdfsUtils.Pair<MessageId, List<Object>> item = HdfsUtils.Pair.of(msgId, inflight.remove(msgId));
- retryList.add(item);
- }
- }
-
- private FileReader pickNextFile() {
- try {
- // 1) If there are any abandoned files, pick oldest one
- lock = getOldestExpiredLock();
- if ( lock!=null ) {
- LOG.debug("Spout {} now took over ownership of abandoned FileLock {}", spoutId, lock.getLockFile());
- Path file = getFileForLockFile(lock.getLockFile(), sourceDirPath);
- String resumeFromOffset = lock.getLastLogEntry().fileOffset;
- LOG.info("Resuming processing of abandoned file : {}", file);
- return createFileReader(file, resumeFromOffset);
- }
-
- // 2) If no abandoned files, then pick oldest file in sourceDirPath, lock it and rename it
- Collection<Path> listing = HdfsUtils.listFilesByModificationTime(hdfs, sourceDirPath, 0);
-
- for (Path file : listing) {
- if (file.getName().endsWith(inprogress_suffix)) {
- continue;
- }
- if (file.getName().endsWith(ignoreSuffix)) {
- continue;
- }
- lock = FileLock.tryLock(hdfs, file, lockDirPath, spoutId);
- if (lock == null) {
- LOG.debug("Unable to get FileLock for {}, so skipping it.", file);
- continue; // could not lock, so try another file.
+
+ public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
+ LOG.info("Opening HDFS Spout");
+ this.conf = conf;
+ this.commitTimer = new Timer();
+ this.tracker = new ProgressTracker();
+ this.hdfsConfig = new Configuration();
+
+ this.collector = collector;
+ this.hdfsConfig = new Configuration();
+ this.tupleCounter = 0;
+
+ // Hdfs related settings
+ if (this.hdfsUri == null && conf.containsKey(Configs.HDFS_URI)) {
+ this.hdfsUri = conf.get(Configs.HDFS_URI).toString();
+ }
+ if (this.hdfsUri == null) {
+ throw new RuntimeException("HDFS Uri not set on spout");
}
+
try {
- Path newFile = renameToInProgressFile(file);
- FileReader result = createFileReader(newFile);
- LOG.info("Processing : {} ", file);
- return result;
+ this.hdfs = FileSystem.get(URI.create(hdfsUri), hdfsConfig);
+ } catch (IOException e) {
+ LOG.error("Unable to instantiate file system", e);
+ throw new RuntimeException("Unable to instantiate file system", e);
+ }
+
+ if (conf.containsKey(configKey)) {
+ Map<String, Object> map = (Map<String, Object>) conf.get(configKey);
+ if (map != null) {
+ for (String keyName : map.keySet()) {
+ LOG.info("HDFS Config override : {} = {} ", keyName, String.valueOf(map.get(keyName)));
+ this.hdfsConfig.set(keyName, String.valueOf(map.get(keyName)));
+ }
+ try {
+ HdfsSecurityUtil.login(conf, hdfsConfig);
+ } catch (IOException e) {
+ LOG.error("HDFS Login failed ", e);
+ throw new RuntimeException(e);
+ }
+ } // if (map != null)
+ }
+
+ // Reader type config
+ if (readerType == null && conf.containsKey(Configs.READER_TYPE)) {
+ readerType = conf.get(Configs.READER_TYPE).toString();
+ }
+ checkValidReader(readerType);
+
+ // -- source dir config
+ if (sourceDir == null && conf.containsKey(Configs.SOURCE_DIR)) {
+ sourceDir = conf.get(Configs.SOURCE_DIR).toString();
+ }
+ if (sourceDir == null) {
+ LOG.error(Configs.SOURCE_DIR + " setting is required");
+ throw new RuntimeException(Configs.SOURCE_DIR + " setting is required");
+ }
+ this.sourceDirPath = new Path(sourceDir);
+
+ // -- archive dir config
+ if (archiveDir == null && conf.containsKey(Configs.ARCHIVE_DIR)) {
+ archiveDir = conf.get(Configs.ARCHIVE_DIR).toString();
+ }
+ if (archiveDir == null) {
+ LOG.error(Configs.ARCHIVE_DIR + " setting is required");
+ throw new RuntimeException(Configs.ARCHIVE_DIR + " setting is required");
+ }
+ this.archiveDirPath = new Path(archiveDir);
+ validateOrMakeDir(hdfs, archiveDirPath, "Archive");
+
+ // -- bad files dir config
+ if (badFilesDir == null && conf.containsKey(Configs.BAD_DIR)) {
+ badFilesDir = conf.get(Configs.BAD_DIR).toString();
+ }
+ if (badFilesDir == null) {
+ LOG.error(Configs.BAD_DIR + " setting is required");
+ throw new RuntimeException(Configs.BAD_DIR + " setting is required");
+ }
+ this.badFilesDirPath = new Path(badFilesDir);
+ validateOrMakeDir(hdfs, badFilesDirPath, "bad files");
+
+ // -- ignore file names config
+ if (conf.containsKey(Configs.IGNORE_SUFFIX)) {
+ this.ignoreSuffix = conf.get(Configs.IGNORE_SUFFIX).toString();
+ }
+
+ // -- lock dir config
+ if (lockDir == null && conf.containsKey(Configs.LOCK_DIR)) {
+ lockDir = conf.get(Configs.LOCK_DIR).toString();
+ }
+ if (lockDir == null) {
+ lockDir = getDefaultLockDir(sourceDirPath);
+ }
+ this.lockDirPath = new Path(lockDir);
+ validateOrMakeDir(hdfs, lockDirPath, "locks");
+
+ // -- lock timeout
+ if (conf.get(Configs.LOCK_TIMEOUT) != null) {
+ this.lockTimeoutSec = Integer.parseInt(conf.get(Configs.LOCK_TIMEOUT).toString());
+ }
+
+ // -- enable/disable ACKing
+ Object ackers = conf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
+ if (ackers != null) {
+ int ackerCount = Integer.parseInt(ackers.toString());
+ this.ackEnabled = (ackerCount > 0);
+ LOG.debug("ACKer count = {}", ackerCount);
+ } else { // ackers==null when ackerCount not explicitly set on the topology
+ this.ackEnabled = true;
+ LOG.debug("ACK count not explicitly set on topology.");
+ }
+
+ LOG.info("ACK mode is {}", ackEnabled ? "enabled" : "disabled");
+
+ // -- commit frequency - count
+ if (conf.get(Configs.COMMIT_FREQ_COUNT) != null) {
+ commitFrequencyCount = Integer.parseInt(conf.get(Configs.COMMIT_FREQ_COUNT).toString());
+ }
+
+ // -- commit frequency - seconds
+ if (conf.get(Configs.COMMIT_FREQ_SEC) != null) {
+ commitFrequencySec = Integer.parseInt(conf.get(Configs.COMMIT_FREQ_SEC).toString());
+ if (commitFrequencySec <= 0) {
+ throw new RuntimeException(Configs.COMMIT_FREQ_SEC + " setting must be greater than 0");
+ }
+ }
+
+ // -- max outstanding tuples
+ if (conf.get(Configs.MAX_OUTSTANDING) != null) {
+ maxOutstanding = Integer.parseInt(conf.get(Configs.MAX_OUTSTANDING).toString());
+ }
+
+ // -- clocks in sync
+ if (conf.get(Configs.CLOCKS_INSYNC) != null) {
+ clocksInSync = Boolean.parseBoolean(conf.get(Configs.CLOCKS_INSYNC).toString());
+ }
+
+ // -- spout id
+ spoutId = context.getThisComponentId();
+
+ // setup timer for commit elapse time tracking
+ setupCommitElapseTimer();
+ }
+
+ @Override
+ public void close() {
+ this.commitTimer.cancel();
+ }
+
+ private static void validateOrMakeDir(FileSystem fs, Path dir, String dirDescription) {
+ try {
+ if (fs.exists(dir)) {
+ if (!fs.isDirectory(dir)) {
+ LOG.error(dirDescription + " directory is a file, not a dir. " + dir);
+ throw new RuntimeException(dirDescription + " directory is a file, not a dir. " + dir);
+ }
+ } else if (!fs.mkdirs(dir)) {
+ LOG.error("Unable to create " + dirDescription + " directory " + dir);
+ throw new RuntimeException("Unable to create " + dirDescription + " directory " + dir);
+ }
+ } catch (IOException e) {
+ LOG.error("Unable to create " + dirDescription + " directory " + dir, e);
+ throw new RuntimeException("Unable to create " + dirDescription + " directory " + dir, e);
+ }
+ }
+
+ private String getDefaultLockDir(Path sourceDirPath) {
+ return sourceDirPath.toString() + Path.SEPARATOR + Configs.DEFAULT_LOCK_DIR;
+ }
+
+ private static void checkValidReader(String readerType) {
+ if (readerType.equalsIgnoreCase(Configs.TEXT) || readerType.equalsIgnoreCase(Configs.SEQ)) {
+ return;
+ }
+ try {
+ Class<?> classType = Class.forName(readerType);
+ classType.getConstructor(FileSystem.class, Path.class, Map.class);
+ return;
+ } catch (ClassNotFoundException e) {
+ LOG.error(readerType + " not found in classpath.", e);
+ throw new IllegalArgumentException(readerType + " not found in classpath.", e);
+ } catch (NoSuchMethodException e) {
+ LOG.error(readerType + " is missing the expected constructor for Readers.", e);
+ throw new IllegalArgumentException(readerType + " is missing the expected constuctor for Readers.");
+ }
+ }
+
+ @Override
+ public void ack(Object msgId) {
+ LOG.trace("Ack received for msg {} on spout {}", msgId, spoutId);
+ if (!ackEnabled) {
+ return;
+ }
+ MessageId id = (MessageId) msgId;
+ inflight.remove(id);
+ ++acksSinceLastCommit;
+ tracker.recordAckedOffset(id.offset);
+ commitProgress(tracker.getCommitPosition());
+ if (fileReadCompletely && inflight.isEmpty()) {
+ markFileAsDone(reader.getFilePath());
+ reader = null;
+ }
+ super.ack(msgId);
+ }
+
+ private boolean canCommitNow() {
+
+ if (commitFrequencyCount > 0 && acksSinceLastCommit >= commitFrequencyCount) {
+ return true;
+ }
+ return commitTimeElapsed.get();
+ }
+
+ @Override
+ public void fail(Object msgId) {
+ LOG.trace("Fail received for msg id {} on spout {}", msgId, spoutId);
+ super.fail(msgId);
+ if (ackEnabled) {
+ HdfsUtils.Pair<MessageId, List<Object>> item = HdfsUtils.Pair.of(msgId, inflight.remove(msgId));
+ retryList.add(item);
+ }
+ }
+
+ private FileReader pickNextFile() {
+ try {
+ // 1) If there are any abandoned files, pick oldest one
+ lock = getOldestExpiredLock();
+ if (lock != null) {
+ LOG.debug("Spout {} now took over ownership of abandoned FileLock {}", spoutId, lock.getLockFile());
+ Path file = getFileForLockFile(lock.getLockFile(), sourceDirPath);
+ String resumeFromOffset = lock.getLastLogEntry().fileOffset;
+ LOG.info("Resuming processing of abandoned file : {}", file);
+ return createFileReader(file, resumeFromOffset);
+ }
+
+ // 2) If no abandoned files, then pick oldest file in sourceDirPath, lock it and rename it
+ Collection<Path> listing = HdfsUtils.listFilesByModificationTime(hdfs, sourceDirPath, 0);
+
+ for (Path file : listing) {
+ if (file.getName().endsWith(inprogress_suffix)) {
+ continue;
+ }
+ if (file.getName().endsWith(ignoreSuffix)) {
+ continue;
+ }
+ lock = FileLock.tryLock(hdfs, file, lockDirPath, spoutId);
+ if (lock == null) {
+ LOG.debug("Unable to get FileLock for {}, so skipping it.", file);
+ continue; // could not lock, so try another file.
+ }
+ try {
+ Path newFile = renameToInProgressFile(file);
+ FileReader result = createFileReader(newFile);
+ LOG.info("Processing : {} ", file);
+ return result;
+ } catch (Exception e) {
+ LOG.error("Skipping file " + file, e);
+ releaseLockAndLog(lock, spoutId);
+ continue;
+ }
+ }
+
+ return null;
+ } catch (IOException e) {
+ LOG.error("Unable to select next file for consumption " + sourceDirPath, e);
+ return null;
+ }
+ }
+
+ /**
+ * If clocks in sync, then acquires the oldest expired lock Else, on first call, just remembers the oldest expired lock, on next call
+ * check if the lock is updated. if not updated then acquires the lock
+ *
+ * @return a lock object
+ * @throws IOException
+ */
+ private FileLock getOldestExpiredLock() throws IOException {
+ // 1 - acquire lock on dir
+ DirLock dirlock = DirLock.tryLock(hdfs, lockDirPath);
+ if (dirlock == null) {
+ dirlock = DirLock.takeOwnershipIfStale(hdfs, lockDirPath, lockTimeoutSec);
+ if (dirlock == null) {
+ LOG.debug("Spout {} could not take over ownership of DirLock for {}", spoutId, lockDirPath);
+ return null;
+ }
+ LOG.debug("Spout {} now took over ownership of abandoned DirLock for {}", spoutId, lockDirPath);
+ } else {
+ LOG.debug("Spout {} now owns DirLock for {}", spoutId, lockDirPath);
+ }
+
+ try {
+ // 2 - if clocks are in sync then simply take ownership of the oldest expired lock
+ if (clocksInSync) {
+ return FileLock.acquireOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec, spoutId);
+ }
+
+ // 3 - if clocks are not in sync ..
+ if (lastExpiredLock == null) {
+ // just make a note of the oldest expired lock now and check if its still unmodified after lockTimeoutSec
+ lastExpiredLock = FileLock.locateOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec);
+ lastExpiredLockTime = System.currentTimeMillis();
+ return null;
+ }
+ // see if lockTimeoutSec time has elapsed since we last selected the lock file
+ if (hasExpired(lastExpiredLockTime)) {
+ return null;
+ }
+
+ // If lock file has expired, then own it
+ FileLock.LogEntry lastEntry = FileLock.getLastEntry(hdfs, lastExpiredLock.getKey());
+ if (lastEntry.equals(lastExpiredLock.getValue())) {
+ FileLock result = FileLock.takeOwnership(hdfs, lastExpiredLock.getKey(), lastEntry, spoutId);
+ lastExpiredLock = null;
+ return result;
+ } else {
+ // if lock file has been updated since last time, then leave this lock file alone
+ lastExpiredLock = null;
+ return null;
+ }
+ } finally {
+ dirlock.release();
+ LOG.debug("Released DirLock {}, SpoutID {} ", dirlock.getLockFile(), spoutId);
+ }
+ }
+
+ private boolean hasExpired(long lastModifyTime) {
+ return (System.currentTimeMillis() - lastModifyTime) < lockTimeoutSec * 1000;
+ }
+
+ /**
+ * Creates a reader that reads from beginning of file
+ *
+ * @param file file to read
+ * @return
+ * @throws IOException
+ */
+ private FileReader createFileReader(Path file)
+ throws IOException {
+ if (readerType.equalsIgnoreCase(Configs.SEQ)) {
+ return new SequenceFileReader(this.hdfs, file, conf);
+ }
+ if (readerType.equalsIgnoreCase(Configs.TEXT)) {
+ return new TextFileReader(this.hdfs, file, conf);
+ }
+ try {
+ Class<?> clsType = Class.forName(readerType);
+ Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class);
+ return (FileReader) constructor.newInstance(this.hdfs, file, conf);
} catch (Exception e) {
- LOG.error("Skipping file " + file, e);
- releaseLockAndLog(lock, spoutId);
- continue;
- }
- }
-
- return null;
- } catch (IOException e) {
- LOG.error("Unable to select next file for consumption " + sourceDirPath, e);
- return null;
- }
- }
-
- /**
- * If clocks in sync, then acquires the oldest expired lock
- * Else, on first call, just remembers the oldest expired lock, on next call check if the lock is updated. if not updated then acquires the lock
- * @return a lock object
- * @throws IOException
- */
- private FileLock getOldestExpiredLock() throws IOException {
- // 1 - acquire lock on dir
- DirLock dirlock = DirLock.tryLock(hdfs, lockDirPath);
- if (dirlock == null) {
- dirlock = DirLock.takeOwnershipIfStale(hdfs, lockDirPath, lockTimeoutSec);
- if (dirlock == null) {
- LOG.debug("Spout {} could not take over ownership of DirLock for {}", spoutId, lockDirPath);
- return null;
- }
- LOG.debug("Spout {} now took over ownership of abandoned DirLock for {}", spoutId, lockDirPath);
- } else {
- LOG.debug("Spout {} now owns DirLock for {}", spoutId, lockDirPath);
- }
-
- try {
- // 2 - if clocks are in sync then simply take ownership of the oldest expired lock
- if (clocksInSync) {
- return FileLock.acquireOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec, spoutId);
- }
-
- // 3 - if clocks are not in sync ..
- if ( lastExpiredLock == null ) {
- // just make a note of the oldest expired lock now and check if its still unmodified after lockTimeoutSec
- lastExpiredLock = FileLock.locateOldestExpiredLock(hdfs, lockDirPath, lockTimeoutSec);
- lastExpiredLockTime = System.currentTimeMillis();
- return null;
- }
- // see if lockTimeoutSec time has elapsed since we last selected the lock file
- if ( hasExpired(lastExpiredLockTime) ) {
- return null;
- }
-
- // If lock file has expired, then own it
- FileLock.LogEntry lastEntry = FileLock.getLastEntry(hdfs, lastExpiredLock.getKey());
- if ( lastEntry.equals(lastExpiredLock.getValue()) ) {
- FileLock result = FileLock.takeOwnership(hdfs, lastExpiredLock.getKey(), lastEntry, spoutId);
- lastExpiredLock = null;
- return result;
- } else {
- // if lock file has been updated since last time, then leave this lock file alone
- lastExpiredLock = null;
+ LOG.error(e.getMessage(), e);
+ throw new RuntimeException("Unable to instantiate " + readerType + " reader", e);
+ }
+ }
+
+ /**
+ * Creates a reader that starts reading from 'offset'
+ *
+ * @param file the file to read
+ * @param offset the offset string should be understandable by the reader type being used
+ * @return
+ * @throws IOException
+ */
+ private FileReader createFileReader(Path file, String offset)
+ throws IOException {
+ if (readerType.equalsIgnoreCase(Configs.SEQ)) {
+ return new SequenceFileReader(this.hdfs, file, conf, offset);
+ }
+ if (readerType.equalsIgnoreCase(Configs.TEXT)) {
+ return new TextFileReader(this.hdfs, file, conf, offset);
+ }
+
+ try {
+ Class<?> clsType = Class.forName(readerType);
+ Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class, String.class);
+ return (FileReader) constructor.newInstance(this.hdfs, file, conf, offset);
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ throw new RuntimeException("Unable to instantiate " + readerType, e);
+ }
+ }
+
+ /**
+ * Renames files with .inprogress suffix
+ *
+ * @return path of renamed file
+ * @throws if operation fails
+ */
+ private Path renameToInProgressFile(Path file)
+ throws IOException {
+ Path newFile = new Path(file.toString() + inprogress_suffix);
+ try {
+ if (hdfs.rename(file, newFile)) {
+ return newFile;
+ }
+ throw new RenameException(file, newFile);
+ } catch (IOException e) {
+ throw new RenameException(file, newFile, e);
+ }
+ }
+
+ /**
+ * Returns the corresponding input file in the 'sourceDirPath' for the specified lock file. If no such file is found then returns null
+ */
+ private Path getFileForLockFile(Path lockFile, Path sourceDirPath)
+ throws IOException {
+ String lockFileName = lockFile.getName();
+ Path dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName + inprogress_suffix);
+ if (hdfs.exists(dataFile)) {
+ return dataFile;
+ }
+ dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName);
+ if (hdfs.exists(dataFile)) {
+ return dataFile;
+ }
return null;
- }
- } finally {
- dirlock.release();
- LOG.debug("Released DirLock {}, SpoutID {} ", dirlock.getLockFile(), spoutId);
- }
- }
-
- private boolean hasExpired(long lastModifyTime) {
- return (System.currentTimeMillis() - lastModifyTime ) < lockTimeoutSec*1000;
- }
-
- /**
- * Creates a reader that reads from beginning of file
- * @param file file to read
- * @return
- * @throws IOException
- */
- private FileReader createFileReader(Path file)
- throws IOException {
- if ( readerType.equalsIgnoreCase(Configs.SEQ) ) {
- return new SequenceFileReader(this.hdfs, file, conf);
- }
- if ( readerType.equalsIgnoreCase(Configs.TEXT) ) {
- return new TextFileReader(this.hdfs, file, conf);
- }
- try {
- Class<?> clsType = Class.forName(readerType);
- Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class);
- return (FileReader) constructor.newInstance(this.hdfs, file, conf);
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- throw new RuntimeException("Unable to instantiate " + readerType + " reader", e);
- }
- }
-
-
- /**
- * Creates a reader that starts reading from 'offset'
- * @param file the file to read
- * @param offset the offset string should be understandable by the reader type being used
- * @return
- * @throws IOException
- */
- private FileReader createFileReader(Path file, String offset)
- throws IOException {
- if ( readerType.equalsIgnoreCase(Configs.SEQ) ) {
- return new SequenceFileReader(this.hdfs, file, conf, offset);
- }
- if ( readerType.equalsIgnoreCase(Configs.TEXT) ) {
- return new TextFileReader(this.hdfs, file, conf, offset);
- }
-
- try {
- Class<?> clsType = Class.forName(readerType);
- Constructor<?> constructor = clsType.getConstructor(FileSystem.class, Path.class, Map.class, String.class);
- return (FileReader) constructor.newInstance(this.hdfs, file, conf, offset);
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- throw new RuntimeException("Unable to instantiate " + readerType, e);
- }
- }
-
- /**
- * Renames files with .inprogress suffix
- * @return path of renamed file
- * @throws if operation fails
- */
- private Path renameToInProgressFile(Path file)
- throws IOException {
- Path newFile = new Path( file.toString() + inprogress_suffix );
- try {
- if (hdfs.rename(file, newFile)) {
- return newFile;
- }
- throw new RenameException(file, newFile);
- } catch (IOException e){
- throw new RenameException(file, newFile, e);
- }
- }
-
- /** Returns the corresponding input file in the 'sourceDirPath' for the specified lock file.
- * If no such file is found then returns null
- */
- private Path getFileForLockFile(Path lockFile, Path sourceDirPath)
- throws IOException {
- String lockFileName = lockFile.getName();
- Path dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName + inprogress_suffix);
- if ( hdfs.exists(dataFile) ) {
- return dataFile;
- }
- dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName);
- if ( hdfs.exists(dataFile) ) {
- return dataFile;
- }
- return null;
- }
-
-
- // renames files and returns the new file path
- private Path renameCompletedFile(Path file) throws IOException {
- String fileName = file.toString();
- String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix));
- String newName = new Path(fileNameMinusSuffix).getName();
-
- Path newFile = new Path( archiveDirPath + Path.SEPARATOR + newName );
- LOG.info("Completed consuming file {}", fileNameMinusSuffix);
- if ( !hdfs.rename(file, newFile) ) {
- throw new IOException("Rename failed for file: " + file);
- }
- LOG.debug("Renamed file {} to {} ", file, newFile);
- return newFile;
- }
-
- @Override
- public void declareOutputFields(OutputFieldsDeclarer declarer) {
- if (outputStreamName!=null) {
- declarer.declareStream(outputStreamName, outputFields);
- } else {
- declarer.declare(outputFields);
- }
- }
-
- static class MessageId implements Comparable<MessageId> {
- public long msgNumber; // tracks order in which msg came in
- public String fullPath;
- public FileOffset offset;
-
- public MessageId(long msgNumber, Path fullPath, FileOffset offset) {
- this.msgNumber = msgNumber;
- this.fullPath = fullPath.toString();
- this.offset = offset;
}
- @Override
- public String toString() {
- return "{'" + fullPath + "':" + offset + "}";
+ // renames files and returns the new file path
+ private Path renameCompletedFile(Path file) throws IOException {
+ String fileName = file.toString();
+ String fileNameMinusSuffix = fileName.substring(0, fileName.indexOf(inprogress_suffix));
+ String newName = new Path(fileNameMinusSuffix).getName();
+
+ Path newFile = new Path(archiveDirPath + Path.SEPARATOR + newName);
+ LOG.info("Completed consuming file {}", fileNameMinusSuffix);
+ if (!hdfs.rename(file, newFile)) {
+ throw new IOException("Rename failed for file: " + file);
+ }
+ LOG.debug("Renamed file {} to {} ", file, newFile);
+ return newFile;
}
@Override
- public int compareTo(MessageId rhs) {
- if ( msgNumber<rhs.msgNumber ) {
- return -1;
- }
- if ( msgNumber>rhs.msgNumber ) {
- return 1;
- }
- return 0;
+ public void declareOutputFields(OutputFieldsDeclarer declarer) {
+ if (outputStreamName != null) {
+ declarer.declareStream(outputStreamName, outputFields);
+ } else {
+ declarer.declare(outputFields);
+ }
}
- }
- private static class RenameException extends IOException {
- public final Path oldFile;
- public final Path newFile;
+ static class MessageId implements Comparable<MessageId> {
+
+ public long msgNumber; // tracks order in which msg came in
+ public String fullPath;
+ public FileOffset offset;
- public RenameException(Path oldFile, Path newFile) {
- super("Rename of " + oldFile + " to " + newFile + " failed");
- this.oldFile = oldFile;
- this.newFile = newFile;
+ public MessageId(long msgNumber, Path fullPath, FileOffset offset) {
+ this.msgNumber = msgNumber;
+ this.fullPath = fullPath.toString();
+ this.offset = offset;
+ }
+
+ @Override
+ public String toString() {
+ return "{'" + fullPath + "':" + offset + "}";
+ }
+
+ @Override
+ public int compareTo(MessageId rhs) {
+ if (msgNumber < rhs.msgNumber) {
+ return -1;
+ }
+ if (msgNumber > rhs.msgNumber) {
+ return 1;
+ }
+ return 0;
+ }
}
- public RenameException(Path oldFile, Path newFile, IOException cause) {
- super("Rename of " + oldFile + " to " + newFile + " failed", cause);
- this.oldFile = oldFile;
- this.newFile = newFile;
+ private static class RenameException extends IOException {
+
+ public final Path oldFile;
+ public final Path newFile;
+
+ public RenameException(Path oldFile, Path newFile) {
+ super("Rename of " + oldFile + " to " + newFile + " failed");
+ this.oldFile = oldFile;
+ this.newFile = newFile;
+ }
+
+ public RenameException(Path oldFile, Path newFile, IOException cause) {
+ super("Rename of " + oldFile + " to " + newFile + " failed", cause);
+ this.oldFile = oldFile;
+ this.newFile = newFile;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestFixedAvroSerializer.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestFixedAvroSerializer.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestFixedAvroSerializer.java
index a584f91..b588f5b 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestFixedAvroSerializer.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestFixedAvroSerializer.java
@@ -21,8 +21,7 @@ import org.apache.avro.Schema;
import org.junit.Assert;
import org.junit.Test;
-import java.util.ArrayList;
-import java.util.List;
+import org.junit.BeforeClass;
public class TestFixedAvroSerializer {
//These should match FixedAvroSerializer.config in the test resources
@@ -34,12 +33,13 @@ public class TestFixedAvroSerializer {
"\"name\":\"stormtest2\"," +
"\"fields\":[{\"name\":\"foobar1\",\"type\":\"string\"}," +
"{ \"name\":\"intint1\", \"type\":\"int\" }]}";
- private static final Schema schema1;
- private static final Schema schema2;
+ private static Schema schema1;
+ private static Schema schema2;
final AvroSchemaRegistry reg;
- static {
+ @BeforeClass
+ public static void setupClass() {
Schema.Parser parser = new Schema.Parser();
schema1 = parser.parse(schemaString1);
@@ -58,7 +58,8 @@ public class TestFixedAvroSerializer {
testTheSchema(schema2);
}
- @Test public void testDifferentFPs() {
+ @Test
+ public void testDifferentFPs() {
String fp1 = reg.getFingerprint(schema1);
String fp2 = reg.getFingerprint(schema2);
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestGenericAvroSerializer.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestGenericAvroSerializer.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestGenericAvroSerializer.java
index ddfdcf5..fb97782 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestGenericAvroSerializer.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/avro/TestGenericAvroSerializer.java
@@ -19,6 +19,7 @@ package org.apache.storm.hdfs.avro;
import org.apache.avro.Schema;
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
public class TestGenericAvroSerializer {
@@ -30,12 +31,13 @@ public class TestGenericAvroSerializer {
"\"name\":\"stormtest2\"," +
"\"fields\":[{\"name\":\"foobar1\",\"type\":\"string\"}," +
"{ \"name\":\"intint1\", \"type\":\"int\" }]}";
- private static final Schema schema1;
- private static final Schema schema2;
+ private static Schema schema1;
+ private static Schema schema2;
AvroSchemaRegistry reg = new GenericAvroSerializer();
- static {
+ @BeforeClass
+ public static void setupClass() {
Schema.Parser parser = new Schema.Parser();
schema1 = parser.parse(schemaString1);
@@ -50,7 +52,8 @@ public class TestGenericAvroSerializer {
testTheSchema(schema2);
}
- @Test public void testDifferentFPs() {
+ @Test
+ public void testDifferentFPs() {
String fp1 = reg.getFingerprint(schema1);
String fp2 = reg.getFingerprint(schema2);
[2/4] storm git commit: STORM-2810: Fix resource leaks in storm-hdfs
tests
Posted by sr...@apache.org.
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestDirLock.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestDirLock.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestDirLock.java
index b96f1ff..0d1f146 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestDirLock.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestDirLock.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,180 +10,170 @@
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License 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 org.apache.storm.hdfs.spout;
-
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HdfsConfiguration;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.Rule;
public class TestDirLock {
- static MiniDFSCluster.Builder builder;
- static MiniDFSCluster hdfsCluster;
- static FileSystem fs;
- static String hdfsURI;
- static HdfsConfiguration conf = new HdfsConfiguration();
- static final int LOCK_EXPIRY_SEC = 1;
- private Path locksDir = new Path("/tmp/lockdir");
-
- @BeforeClass
- public static void setupClass() throws IOException {
- conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY,"5000");
- builder = new MiniDFSCluster.Builder(new Configuration());
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
- }
-
- @AfterClass
- public static void teardownClass() throws IOException {
- fs.close();
- hdfsCluster.shutdown();
- }
-
- @Before
- public void setUp() throws Exception {
- assert fs.mkdirs(locksDir) ;
- }
-
- @After
- public void tearDown() throws Exception {
- fs.delete(locksDir, true);
- }
-
-
- @Test
- public void testBasicLocking() throws Exception {
- // 1 grab lock
- DirLock lock = DirLock.tryLock(fs, locksDir);
- Assert.assertTrue(fs.exists(lock.getLockFile()));
-
- // 2 try to grab another lock while dir is locked
- DirLock lock2 = DirLock.tryLock(fs, locksDir); // should fail
- Assert.assertNull(lock2);
-
- // 3 let go first lock
- lock.release();
- Assert.assertFalse(fs.exists(lock.getLockFile()));
-
- // 4 try locking again
- lock2 = DirLock.tryLock(fs, locksDir);
- Assert.assertTrue(fs.exists(lock2.getLockFile()));
- lock2.release();
- Assert.assertFalse(fs.exists(lock.getLockFile()));
- lock2.release(); // should be throw
- }
-
-
- @Test
- public void testConcurrentLocking() throws Exception {
- DirLockingThread[] thds = startThreads(100, locksDir);
- for (DirLockingThread thd : thds) {
- thd.join();
- if( !thd.cleanExit ) {
- System.err.println(thd.getName() + " did not exit cleanly");
- }
- Assert.assertTrue(thd.cleanExit);
- }
+ @Rule
+ public MiniDFSClusterRule DFS_CLUSTER_RULE = new MiniDFSClusterRule();
- Path lockFile = new Path(locksDir + Path.SEPARATOR + DirLock.DIR_LOCK_FILE);
- Assert.assertFalse(fs.exists(lockFile));
- }
+ private static final int LOCK_EXPIRY_SEC = 1;
- private DirLockingThread[] startThreads(int thdCount, Path dir)
- throws IOException {
- DirLockingThread[] result = new DirLockingThread[thdCount];
- for (int i = 0; i < thdCount; i++) {
- result[i] = new DirLockingThread(i, fs, dir);
+ private FileSystem fs;
+ private HdfsConfiguration conf = new HdfsConfiguration();
+ private final Path locksDir = new Path("/tmp/lockdir");
+
+ @Before
+ public void setUp() throws IOException {
+ conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY, "5000");
+ fs = DFS_CLUSTER_RULE.getDfscluster().getFileSystem();
+ assert fs.mkdirs(locksDir);
+ }
+
+ @After
+ public void teardownClass() throws IOException {
+ fs.delete(locksDir, true);
+ fs.close();
}
- for (DirLockingThread thd : result) {
- thd.start();
+ @Test
+ public void testBasicLocking() throws Exception {
+ // 1 grab lock
+ DirLock lock = DirLock.tryLock(fs, locksDir);
+ Assert.assertTrue(fs.exists(lock.getLockFile()));
+
+ // 2 try to grab another lock while dir is locked
+ DirLock lock2 = DirLock.tryLock(fs, locksDir); // should fail
+ Assert.assertNull(lock2);
+
+ // 3 let go first lock
+ lock.release();
+ Assert.assertFalse(fs.exists(lock.getLockFile()));
+
+ // 4 try locking again
+ lock2 = DirLock.tryLock(fs, locksDir);
+ Assert.assertTrue(fs.exists(lock2.getLockFile()));
+ lock2.release();
+ Assert.assertFalse(fs.exists(lock.getLockFile()));
+ lock2.release(); // should be throw
}
- return result;
- }
- @Test
- public void testLockRecovery() throws Exception {
- DirLock lock1 = DirLock.tryLock(fs, locksDir); // should pass
- Assert.assertNotNull(lock1);
+ @Test
+ public void testConcurrentLocking() throws Exception {
+ DirLockingThread[] threads = null;
+ try {
+ threads = startThreads(100, locksDir);
+ for (DirLockingThread thd : threads) {
+ thd.join(30_000);
+ Assert.assertTrue(thd.getName() + " did not exit cleanly", thd.cleanExit);
+ }
- DirLock lock2 = DirLock.takeOwnershipIfStale(fs, locksDir, LOCK_EXPIRY_SEC); // should fail
- Assert.assertNull(lock2);
+ Path lockFile = new Path(locksDir + Path.SEPARATOR + DirLock.DIR_LOCK_FILE);
+ Assert.assertFalse(fs.exists(lockFile));
+ } finally {
+ if (threads != null) {
+ for (DirLockingThread thread : threads) {
+ thread.interrupt();
+ thread.join(30_000);
+ if (thread.isAlive()) {
+ throw new RuntimeException("Failed to stop threads within 30 seconds, threads may leak into other tests");
+ }
+ }
+ }
+ }
+ }
- Thread.sleep(LOCK_EXPIRY_SEC*1000 + 500); // wait for lock to expire
- Assert.assertTrue(fs.exists(lock1.getLockFile()));
+ private DirLockingThread[] startThreads(int thdCount, Path dir)
+ throws IOException {
+ DirLockingThread[] result = new DirLockingThread[thdCount];
+ for (int i = 0; i < thdCount; i++) {
+ result[i] = new DirLockingThread(i, fs, dir);
+ }
+
+ for (DirLockingThread thd : result) {
+ thd.start();
+ }
+ return result;
+ }
- DirLock lock3 = DirLock.takeOwnershipIfStale(fs, locksDir, LOCK_EXPIRY_SEC); // should pass now
- Assert.assertNotNull(lock3);
- Assert.assertTrue(fs.exists(lock3.getLockFile()));
- lock3.release();
- Assert.assertFalse(fs.exists(lock3.getLockFile()));
- lock1.release(); // should not throw
- }
+ @Test
+ public void testLockRecovery() throws Exception {
+ DirLock lock1 = DirLock.tryLock(fs, locksDir); // should pass
+ Assert.assertNotNull(lock1);
- class DirLockingThread extends Thread {
+ DirLock lock2 = DirLock.takeOwnershipIfStale(fs, locksDir, LOCK_EXPIRY_SEC); // should fail
+ Assert.assertNull(lock2);
- private int thdNum;
- private final FileSystem fs;
- private final Path dir;
- public boolean cleanExit = false;
+ Thread.sleep(LOCK_EXPIRY_SEC * 1000 + 500); // wait for lock to expire
+ Assert.assertTrue(fs.exists(lock1.getLockFile()));
- public DirLockingThread(int thdNum,FileSystem fs, Path dir)
- throws IOException {
- this.thdNum = thdNum;
- this.fs = fs;
- this.dir = dir;
+ DirLock lock3 = DirLock.takeOwnershipIfStale(fs, locksDir, LOCK_EXPIRY_SEC); // should pass now
+ Assert.assertNotNull(lock3);
+ Assert.assertTrue(fs.exists(lock3.getLockFile()));
+ lock3.release();
+ Assert.assertFalse(fs.exists(lock3.getLockFile()));
+ lock1.release(); // should not throw
}
- @Override
- public void run() {
- Thread.currentThread().setName("DirLockingThread-" + thdNum);
- DirLock lock = null;
- try {
- do {
- System.err.println("Trying lock " + getName());
- lock = DirLock.tryLock(fs, dir);
- System.err.println("Acquired lock " + getName());
- if(lock==null) {
- System.out.println("Retrying lock - " + getName());
- }
- } while (lock==null);
- cleanExit= true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally {
- try {
- if(lock!=null) {
- lock.release();
- System.err.println("Released lock " + getName());
+ class DirLockingThread extends Thread {
+
+ private int thdNum;
+ private final FileSystem fs;
+ private final Path dir;
+ public boolean cleanExit = false;
+
+ public DirLockingThread(int thdNum, FileSystem fs, Path dir)
+ throws IOException {
+ this.thdNum = thdNum;
+ this.fs = fs;
+ this.dir = dir;
+ }
+
+ @Override
+ public void run() {
+ Thread.currentThread().setName("DirLockingThread-" + thdNum);
+ DirLock lock = null;
+ try {
+ do {
+ System.err.println("Trying lock " + getName());
+ lock = DirLock.tryLock(fs, dir);
+ System.err.println("Acquired lock " + getName());
+ if (lock == null) {
+ System.out.println("Retrying lock - " + getName());
+ }
+ } while (lock == null && !Thread.currentThread().isInterrupted());
+ cleanExit = true;
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ if (lock != null) {
+ lock.release();
+ System.err.println("Released lock " + getName());
+ }
+ } catch (IOException e) {
+ e.printStackTrace(System.err);
+ }
}
- } catch (IOException e) {
- e.printStackTrace(System.err);
- }
- }
- System.err.println("Thread exiting " + getName());
- } // run()
-
- } // class DirLockingThread
+ System.err.println("Thread exiting " + getName());
+ } // run()
+
+ } // class DirLockingThread
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestFileLock.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestFileLock.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestFileLock.java
index 725fa11..df131a4 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestFileLock.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestFileLock.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,388 +10,380 @@
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License 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 org.apache.storm.hdfs.spout;
-
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HdfsConfiguration;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.storm.hdfs.common.HdfsUtils;
import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
-
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.Rule;
public class TestFileLock {
- static MiniDFSCluster.Builder builder;
- static MiniDFSCluster hdfsCluster;
- static FileSystem fs;
- static String hdfsURI;
- static HdfsConfiguration conf = new HdfsConfiguration();
-
- private Path filesDir = new Path("/tmp/filesdir");
- private Path locksDir = new Path("/tmp/locskdir");
-
- @BeforeClass
- public static void setupClass() throws IOException {
- conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY,"5000");
- builder = new MiniDFSCluster.Builder(new Configuration());
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
- }
-
- @AfterClass
- public static void teardownClass() throws IOException {
- fs.close();
- hdfsCluster.shutdown();
- }
-
- @Before
- public void setUp() throws Exception {
- assert fs.mkdirs(filesDir) ;
- assert fs.mkdirs(locksDir) ;
- }
-
- @After
- public void tearDown() throws Exception {
- fs.delete(filesDir, true);
- fs.delete(locksDir, true);
- }
-
- @Test
- public void testBasicLocking() throws Exception {
- // create empty files in filesDir
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
- fs.create(file1).close();
- fs.create(file2).close(); // create empty file
-
- // acquire lock on file1 and verify if worked
- FileLock lock1a = FileLock.tryLock(fs, file1, locksDir, "spout1");
- Assert.assertNotNull(lock1a);
- Assert.assertTrue(fs.exists(lock1a.getLockFile()));
- Assert.assertEquals(lock1a.getLockFile().getParent(), locksDir); // verify lock file location
- Assert.assertEquals(lock1a.getLockFile().getName(), file1.getName()); // verify lock filename
-
- // acquire another lock on file1 and verify it failed
- FileLock lock1b = FileLock.tryLock(fs, file1, locksDir, "spout1");
- Assert.assertNull(lock1b);
-
- // release lock on file1 and check
- lock1a.release();
- Assert.assertFalse(fs.exists(lock1a.getLockFile()));
-
- // Retry locking and verify
- FileLock lock1c = FileLock.tryLock(fs, file1, locksDir, "spout1");
- Assert.assertNotNull(lock1c);
- Assert.assertTrue(fs.exists(lock1c.getLockFile()));
- Assert.assertEquals(lock1c.getLockFile().getParent(), locksDir); // verify lock file location
- Assert.assertEquals(lock1c.getLockFile().getName(), file1.getName()); // verify lock filename
-
- // try locking another file2 at the same time
- FileLock lock2a = FileLock.tryLock(fs, file2, locksDir, "spout1");
- Assert.assertNotNull(lock2a);
- Assert.assertTrue(fs.exists(lock2a.getLockFile()));
- Assert.assertEquals(lock2a.getLockFile().getParent(), locksDir); // verify lock file location
- Assert.assertEquals(lock2a.getLockFile().getName(), file2.getName()); // verify lock filename
-
- // release both locks
- lock2a.release();
- Assert.assertFalse(fs.exists(lock2a.getLockFile()));
- lock1c.release();
- Assert.assertFalse(fs.exists(lock1c.getLockFile()));
- }
-
- @Test
- public void testHeartbeat() throws Exception {
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- fs.create(file1).close();
-
- // acquire lock on file1
- FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
- Assert.assertNotNull(lock1);
- Assert.assertTrue(fs.exists(lock1.getLockFile()));
-
- ArrayList<String> lines = readTextFile(lock1.getLockFile());
- Assert.assertEquals("heartbeats appear to be missing", 1, lines.size());
-
- // hearbeat upon it
- lock1.heartbeat("1");
- lock1.heartbeat("2");
- lock1.heartbeat("3");
-
- lines = readTextFile(lock1.getLockFile());
- Assert.assertEquals("heartbeats appear to be missing", 4, lines.size());
-
- lock1.heartbeat("4");
- lock1.heartbeat("5");
- lock1.heartbeat("6");
-
- lines = readTextFile(lock1.getLockFile());
- Assert.assertEquals("heartbeats appear to be missing", 7, lines.size());
-
- lock1.release();
- lines = readTextFile(lock1.getLockFile());
- Assert.assertNull(lines);
- Assert.assertFalse(fs.exists(lock1.getLockFile()));
- }
-
- @Test
- public void testConcurrentLocking() throws IOException, InterruptedException {
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- fs.create(file1).close();
-
- FileLockingThread[] thds = startThreads(100, file1, locksDir);
- for (FileLockingThread thd : thds) {
- thd.join();
- if( !thd.cleanExit) {
- System.err.println(thd.getName() + " did not exit cleanly");
- }
- Assert.assertTrue(thd.cleanExit);
+ @Rule
+ public MiniDFSClusterRule dfsClusterRule = new MiniDFSClusterRule();
+
+ private FileSystem fs;
+ private HdfsConfiguration conf = new HdfsConfiguration();
+
+ private final Path filesDir = new Path("/tmp/filesdir");
+ private final Path locksDir = new Path("/tmp/locksdir");
+
+ @Before
+ public void setup() throws IOException {
+ conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY, "5000");
+ fs = dfsClusterRule.getDfscluster().getFileSystem();
+ assert fs.mkdirs(filesDir);
+ assert fs.mkdirs(locksDir);
}
- Path lockFile = new Path(locksDir + Path.SEPARATOR + file1.getName());
- Assert.assertFalse(fs.exists(lockFile));
- }
+ @After
+ public void teardown() throws IOException {
+ fs.delete(filesDir, true);
+ fs.delete(locksDir, true);
+ fs.close();
+ }
- private FileLockingThread[] startThreads(int thdCount, Path fileToLock, Path locksDir)
- throws IOException {
- FileLockingThread[] result = new FileLockingThread[thdCount];
- for (int i = 0; i < thdCount; i++) {
- result[i] = new FileLockingThread(i, fs, fileToLock, locksDir, "spout" + Integer.toString(i));
+ @Test
+ public void testBasicLocking() throws Exception {
+ // create empty files in filesDir
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
+ fs.create(file1).close();
+ fs.create(file2).close(); // create empty file
+
+ // acquire lock on file1 and verify if worked
+ FileLock lock1a = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ Assert.assertNotNull(lock1a);
+ Assert.assertTrue(fs.exists(lock1a.getLockFile()));
+ Assert.assertEquals(lock1a.getLockFile().getParent(), locksDir); // verify lock file location
+ Assert.assertEquals(lock1a.getLockFile().getName(), file1.getName()); // verify lock filename
+
+ // acquire another lock on file1 and verify it failed
+ FileLock lock1b = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ Assert.assertNull(lock1b);
+
+ // release lock on file1 and check
+ lock1a.release();
+ Assert.assertFalse(fs.exists(lock1a.getLockFile()));
+
+ // Retry locking and verify
+ FileLock lock1c = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ Assert.assertNotNull(lock1c);
+ Assert.assertTrue(fs.exists(lock1c.getLockFile()));
+ Assert.assertEquals(lock1c.getLockFile().getParent(), locksDir); // verify lock file location
+ Assert.assertEquals(lock1c.getLockFile().getName(), file1.getName()); // verify lock filename
+
+ // try locking another file2 at the same time
+ FileLock lock2a = FileLock.tryLock(fs, file2, locksDir, "spout1");
+ Assert.assertNotNull(lock2a);
+ Assert.assertTrue(fs.exists(lock2a.getLockFile()));
+ Assert.assertEquals(lock2a.getLockFile().getParent(), locksDir); // verify lock file location
+ Assert.assertEquals(lock2a.getLockFile().getName(), file2.getName()); // verify lock filename
+
+ // release both locks
+ lock2a.release();
+ Assert.assertFalse(fs.exists(lock2a.getLockFile()));
+ lock1c.release();
+ Assert.assertFalse(fs.exists(lock1c.getLockFile()));
}
- for (FileLockingThread thd : result) {
- thd.start();
+ @Test
+ public void testHeartbeat() throws Exception {
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ fs.create(file1).close();
+
+ // acquire lock on file1
+ FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ Assert.assertNotNull(lock1);
+ Assert.assertTrue(fs.exists(lock1.getLockFile()));
+
+ ArrayList<String> lines = readTextFile(lock1.getLockFile());
+ Assert.assertEquals("heartbeats appear to be missing", 1, lines.size());
+
+ // hearbeat upon it
+ lock1.heartbeat("1");
+ lock1.heartbeat("2");
+ lock1.heartbeat("3");
+
+ lines = readTextFile(lock1.getLockFile());
+ Assert.assertEquals("heartbeats appear to be missing", 4, lines.size());
+
+ lock1.heartbeat("4");
+ lock1.heartbeat("5");
+ lock1.heartbeat("6");
+
+ lines = readTextFile(lock1.getLockFile());
+ Assert.assertEquals("heartbeats appear to be missing", 7, lines.size());
+
+ lock1.release();
+ lines = readTextFile(lock1.getLockFile());
+ Assert.assertNull(lines);
+ Assert.assertFalse(fs.exists(lock1.getLockFile()));
}
- return result;
- }
-
-
- @Test
- public void testStaleLockDetection_SingleLock() throws Exception {
- final int LOCK_EXPIRY_SEC = 1;
- final int WAIT_MSEC = 1500;
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- fs.create(file1).close();
- FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
- try {
- // acquire lock on file1
- Assert.assertNotNull(lock1);
- Assert.assertTrue(fs.exists(lock1.getLockFile()));
- Thread.sleep(WAIT_MSEC); // wait for lock to expire
- HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
- Assert.assertNotNull(expired);
-
- // heartbeat, ensure its no longer stale and read back the heartbeat data
- lock1.heartbeat("1");
- expired = FileLock.locateOldestExpiredLock(fs, locksDir, 1);
- Assert.assertNull(expired);
-
- FileLock.LogEntry lastEntry = lock1.getLastLogEntry();
- Assert.assertNotNull(lastEntry);
- Assert.assertEquals("1", lastEntry.fileOffset);
-
- // wait and check for expiry again
- Thread.sleep(WAIT_MSEC);
- expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
- Assert.assertNotNull(expired);
- } finally {
- lock1.release();
- fs.delete(file1, false);
+
+ @Test
+ public void testConcurrentLocking() throws IOException, InterruptedException {
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ fs.create(file1).close();
+
+ FileLockingThread[] threads = null;
+ try {
+ threads = startThreads(100, file1, locksDir);
+ for (FileLockingThread thd : threads) {
+ thd.join(30_000);
+ Assert.assertTrue(thd.getName() + " did not exit cleanly", thd.cleanExit);
+ }
+
+ Path lockFile = new Path(locksDir + Path.SEPARATOR + file1.getName());
+ Assert.assertFalse(fs.exists(lockFile));
+ } finally {
+ if (threads != null) {
+ for (FileLockingThread thread : threads) {
+ thread.interrupt();
+ thread.join(30_000);
+ if (thread.isAlive()) {
+ throw new RuntimeException("Failed to stop threads within 30 seconds, threads may leak into other tests");
+ }
+ }
+ }
+ }
}
- }
-
- @Test
- public void testStaleLockDetection_MultipleLocks() throws Exception {
- final int LOCK_EXPIRY_SEC = 1;
- final int WAIT_MSEC = 1500;
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
- Path file3 = new Path(filesDir + Path.SEPARATOR + "file3");
-
- fs.create(file1).close();
- fs.create(file2).close();
- fs.create(file3).close();
-
- // 1) acquire locks on file1,file2,file3
- FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
- FileLock lock2 = FileLock.tryLock(fs, file2, locksDir, "spout2");
- FileLock lock3 = FileLock.tryLock(fs, file3, locksDir, "spout3");
- Assert.assertNotNull(lock1);
- Assert.assertNotNull(lock2);
- Assert.assertNotNull(lock3);
-
- try {
- HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
- Assert.assertNull(expired);
-
- // 2) wait for all 3 locks to expire then heart beat on 2 locks and verify stale lock
- Thread.sleep(WAIT_MSEC);
- lock1.heartbeat("1");
- lock2.heartbeat("1");
-
- expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
- Assert.assertNotNull(expired);
- Assert.assertEquals("spout3", expired.getValue().componentID);
- } finally {
- lock1.release();
- lock2.release();
- lock3.release();
- fs.delete(file1, false);
- fs.delete(file2, false);
- fs.delete(file3, false);
+
+ private FileLockingThread[] startThreads(int thdCount, Path fileToLock, Path locksDir)
+ throws IOException {
+ FileLockingThread[] result = new FileLockingThread[thdCount];
+ for (int i = 0; i < thdCount; i++) {
+ result[i] = new FileLockingThread(i, fs, fileToLock, locksDir, "spout" + Integer.toString(i));
+ }
+
+ for (FileLockingThread thd : result) {
+ thd.start();
+ }
+ return result;
}
- }
-
- @Test
- public void testLockRecovery() throws Exception {
- final int LOCK_EXPIRY_SEC = 1;
- final int WAIT_MSEC = LOCK_EXPIRY_SEC*1000 + 500;
- Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
- Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
- Path file3 = new Path(filesDir + Path.SEPARATOR + "file3");
-
- fs.create(file1).close();
- fs.create(file2).close();
- fs.create(file3).close();
-
- // 1) acquire locks on file1,file2,file3
- FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
- FileLock lock2 = FileLock.tryLock(fs, file2, locksDir, "spout2");
- FileLock lock3 = FileLock.tryLock(fs, file3, locksDir, "spout3");
- Assert.assertNotNull(lock1);
- Assert.assertNotNull(lock2);
- Assert.assertNotNull(lock3);
-
- try {
- HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
- Assert.assertNull(expired);
-
- // 1) Simulate lock file lease expiring and getting closed by HDFS
- closeUnderlyingLockFile(lock3);
-
- // 2) wait for all 3 locks to expire then heart beat on 2 locks
- Thread.sleep(WAIT_MSEC*2); // wait for locks to expire
- lock1.heartbeat("1");
- lock2.heartbeat("1");
-
- // 3) Take ownership of stale lock
- FileLock lock3b = FileLock.acquireOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC, "spout1");
- Assert.assertNotNull(lock3b);
- Assert.assertEquals("Expected lock3 file", Path.getPathWithoutSchemeAndAuthority(lock3b.getLockFile()), lock3.getLockFile());
- } finally {
- lock1.release();
- lock2.release();
- lock3.release();
- fs.delete(file1, false);
- fs.delete(file2, false);
- try {
- fs.delete(file3, false);
- } catch (Exception e) {
- e.printStackTrace();
- }
+
+ @Test
+ public void testStaleLockDetection_SingleLock() throws Exception {
+ final int LOCK_EXPIRY_SEC = 1;
+ final int WAIT_MSEC = 1500;
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ fs.create(file1).close();
+ FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ try {
+ // acquire lock on file1
+ Assert.assertNotNull(lock1);
+ Assert.assertTrue(fs.exists(lock1.getLockFile()));
+ Thread.sleep(WAIT_MSEC); // wait for lock to expire
+ HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
+ Assert.assertNotNull(expired);
+
+ // heartbeat, ensure its no longer stale and read back the heartbeat data
+ lock1.heartbeat("1");
+ expired = FileLock.locateOldestExpiredLock(fs, locksDir, 1);
+ Assert.assertNull(expired);
+
+ FileLock.LogEntry lastEntry = lock1.getLastLogEntry();
+ Assert.assertNotNull(lastEntry);
+ Assert.assertEquals("1", lastEntry.fileOffset);
+
+ // wait and check for expiry again
+ Thread.sleep(WAIT_MSEC);
+ expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
+ Assert.assertNotNull(expired);
+ } finally {
+ lock1.release();
+ fs.delete(file1, false);
+ }
}
- }
-
- public static void closeUnderlyingLockFile(FileLock lock) throws ReflectiveOperationException {
- Method m = FileLock.class.getDeclaredMethod("forceCloseLockFile");
- m.setAccessible(true);
- m.invoke(lock);
- }
-
- /** return null if file not found */
- private ArrayList<String> readTextFile(Path file) throws IOException {
- FSDataInputStream os = null;
- try {
- os = fs.open(file);
- if (os == null) {
- return null;
- }
- BufferedReader reader = new BufferedReader(new InputStreamReader(os));
- ArrayList<String> lines = new ArrayList<>();
- for (String line = reader.readLine(); line != null; line = reader.readLine()) {
- lines.add(line);
- }
- return lines;
- } catch( FileNotFoundException e) {
- return null;
- } finally {
- if(os!=null) {
- os.close();
- }
+
+ @Test
+ public void testStaleLockDetection_MultipleLocks() throws Exception {
+ final int LOCK_EXPIRY_SEC = 1;
+ final int WAIT_MSEC = 1500;
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
+ Path file3 = new Path(filesDir + Path.SEPARATOR + "file3");
+
+ fs.create(file1).close();
+ fs.create(file2).close();
+ fs.create(file3).close();
+
+ // 1) acquire locks on file1,file2,file3
+ FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ FileLock lock2 = FileLock.tryLock(fs, file2, locksDir, "spout2");
+ FileLock lock3 = FileLock.tryLock(fs, file3, locksDir, "spout3");
+ Assert.assertNotNull(lock1);
+ Assert.assertNotNull(lock2);
+ Assert.assertNotNull(lock3);
+
+ try {
+ HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
+ Assert.assertNull(expired);
+
+ // 2) wait for all 3 locks to expire then heart beat on 2 locks and verify stale lock
+ Thread.sleep(WAIT_MSEC);
+ lock1.heartbeat("1");
+ lock2.heartbeat("1");
+
+ expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
+ Assert.assertNotNull(expired);
+ Assert.assertEquals("spout3", expired.getValue().componentID);
+ } finally {
+ lock1.release();
+ lock2.release();
+ lock3.release();
+ fs.delete(file1, false);
+ fs.delete(file2, false);
+ fs.delete(file3, false);
+ }
}
- }
- class FileLockingThread extends Thread {
+ @Test
+ public void testLockRecovery() throws Exception {
+ final int LOCK_EXPIRY_SEC = 1;
+ final int WAIT_MSEC = LOCK_EXPIRY_SEC * 1000 + 500;
+ Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
+ Path file2 = new Path(filesDir + Path.SEPARATOR + "file2");
+ Path file3 = new Path(filesDir + Path.SEPARATOR + "file3");
+
+ fs.create(file1).close();
+ fs.create(file2).close();
+ fs.create(file3).close();
+
+ // 1) acquire locks on file1,file2,file3
+ FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
+ FileLock lock2 = FileLock.tryLock(fs, file2, locksDir, "spout2");
+ FileLock lock3 = FileLock.tryLock(fs, file3, locksDir, "spout3");
+ Assert.assertNotNull(lock1);
+ Assert.assertNotNull(lock2);
+ Assert.assertNotNull(lock3);
- private int thdNum;
- private final FileSystem fs;
- public boolean cleanExit = false;
- private Path fileToLock;
- private Path locksDir;
- private String spoutId;
+ try {
+ HdfsUtils.Pair<Path, FileLock.LogEntry> expired = FileLock.locateOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC);
+ Assert.assertNull(expired);
+
+ // 1) Simulate lock file lease expiring and getting closed by HDFS
+ closeUnderlyingLockFile(lock3);
+
+ // 2) wait for all 3 locks to expire then heart beat on 2 locks
+ Thread.sleep(WAIT_MSEC * 2); // wait for locks to expire
+ lock1.heartbeat("1");
+ lock2.heartbeat("1");
+
+ // 3) Take ownership of stale lock
+ FileLock lock3b = FileLock.acquireOldestExpiredLock(fs, locksDir, LOCK_EXPIRY_SEC, "spout1");
+ Assert.assertNotNull(lock3b);
+ Assert.assertEquals("Expected lock3 file", Path.getPathWithoutSchemeAndAuthority(lock3b.getLockFile()), lock3.getLockFile());
+ } finally {
+ lock1.release();
+ lock2.release();
+ lock3.release();
+ fs.delete(file1, false);
+ fs.delete(file2, false);
+ try {
+ fs.delete(file3, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
- public FileLockingThread(int thdNum, FileSystem fs, Path fileToLock, Path locksDir, String spoutId)
- throws IOException {
- this.thdNum = thdNum;
- this.fs = fs;
- this.fileToLock = fileToLock;
- this.locksDir = locksDir;
- this.spoutId = spoutId;
+ public static void closeUnderlyingLockFile(FileLock lock) throws ReflectiveOperationException {
+ Method m = FileLock.class.getDeclaredMethod("forceCloseLockFile");
+ m.setAccessible(true);
+ m.invoke(lock);
}
- @Override
- public void run() {
- Thread.currentThread().setName("FileLockingThread-" + thdNum);
- FileLock lock = null;
- try {
- do {
- System.err.println("Trying lock - " + getName());
- lock = FileLock.tryLock(fs, this.fileToLock, this.locksDir, spoutId);
- System.err.println("Acquired lock - " + getName());
- if(lock==null) {
- System.out.println("Retrying lock - " + getName());
- }
- } while (lock==null);
- cleanExit= true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally {
+ /**
+ * return null if file not found
+ */
+ private ArrayList<String> readTextFile(Path file) throws IOException {
+ FSDataInputStream os = null;
try {
- if(lock!=null) {
- lock.release();
- System.err.println("Released lock - " + getName());
- }
- } catch (IOException e) {
- e.printStackTrace(System.err);
+ os = fs.open(file);
+ if (os == null) {
+ return null;
+ }
+ BufferedReader reader = new BufferedReader(new InputStreamReader(os));
+ ArrayList<String> lines = new ArrayList<>();
+ for (String line = reader.readLine(); line != null; line = reader.readLine()) {
+ lines.add(line);
+ }
+ return lines;
+ } catch (FileNotFoundException e) {
+ return null;
+ } finally {
+ if (os != null) {
+ os.close();
+ }
+ }
+ }
+
+ class FileLockingThread extends Thread {
+
+ private int thdNum;
+ private final FileSystem fs;
+ public boolean cleanExit = false;
+ private Path fileToLock;
+ private Path locksDir;
+ private String spoutId;
+
+ public FileLockingThread(int thdNum, FileSystem fs, Path fileToLock, Path locksDir, String spoutId)
+ throws IOException {
+ this.thdNum = thdNum;
+ this.fs = fs;
+ this.fileToLock = fileToLock;
+ this.locksDir = locksDir;
+ this.spoutId = spoutId;
}
- }
- System.err.println("Thread exiting - " + getName());
- } // run()
- } // class FileLockingThread
+ @Override
+ public void run() {
+ Thread.currentThread().setName("FileLockingThread-" + thdNum);
+ FileLock lock = null;
+ try {
+ do {
+ System.err.println("Trying lock - " + getName());
+ lock = FileLock.tryLock(fs, this.fileToLock, this.locksDir, spoutId);
+ System.err.println("Acquired lock - " + getName());
+ if (lock == null) {
+ System.out.println("Retrying lock - " + getName());
+ }
+ } while (lock == null && !Thread.currentThread().isInterrupted());
+ cleanExit = true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ if (lock != null) {
+ lock.release();
+ System.err.println("Released lock - " + getName());
+ }
+ } catch (IOException e) {
+ e.printStackTrace(System.err);
+ }
+ }
+ System.err.println("Thread exiting - " + getName());
+ } // run()
+
+ } // class FileLockingThread
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSemantics.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSemantics.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSemantics.java
index 6628cc9..33432d9 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSemantics.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/spout/TestHdfsSemantics.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,196 +10,192 @@
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License 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 org.apache.storm.hdfs.spout;
-import org.apache.hadoop.conf.Configuration;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HdfsConfiguration;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
import org.apache.hadoop.ipc.RemoteException;
import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.Rule;
public class TestHdfsSemantics {
- static MiniDFSCluster.Builder builder;
- static MiniDFSCluster hdfsCluster;
- static FileSystem fs;
- static String hdfsURI;
- static HdfsConfiguration conf = new HdfsConfiguration();
-
- private Path dir = new Path("/tmp/filesdir");
-
- @BeforeClass
- public static void setupClass() throws IOException {
- conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY,"5000");
- builder = new MiniDFSCluster.Builder(new Configuration());
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
- }
-
- @AfterClass
- public static void teardownClass() throws IOException {
- fs.close();
- hdfsCluster.shutdown();
- }
-
- @Before
- public void setUp() throws Exception {
- assert fs.mkdirs(dir) ;
- }
-
- @After
- public void tearDown() throws Exception {
- fs.delete(dir, true);
- }
-
-
- @Test
- public void testDeleteSemantics() throws Exception {
- Path file = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
-// try {
- // 1) Delete absent file - should return false
- Assert.assertFalse(fs.exists(file));
- try {
- Assert.assertFalse(fs.delete(file, false));
- } catch (IOException e) {
- e.printStackTrace();
- }
+ @Rule
+ public MiniDFSClusterRule dfsClusterRule = new MiniDFSClusterRule();
- // 2) deleting open file - should return true
- fs.create(file, false);
- Assert.assertTrue(fs.delete(file, false));
-
- // 3) deleting closed file - should return true
- FSDataOutputStream os = fs.create(file, false);
- os.close();
- Assert.assertTrue(fs.exists(file));
- Assert.assertTrue(fs.delete(file, false));
- Assert.assertFalse(fs.exists(file));
- }
-
- @Test
- public void testConcurrentDeletion() throws Exception {
- Path file = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
- fs.create(file).close();
- // 1 concurrent deletion - only one thread should succeed
- FileDeletionThread[] thds = startThreads(10, file);
- int successCount=0;
- for (FileDeletionThread thd : thds) {
- thd.join();
- if( thd.succeeded)
- successCount++;
- if(thd.exception!=null)
- Assert.assertNotNull(thd.exception);
- }
- System.err.println(successCount);
- Assert.assertEquals(1, successCount);
-
- }
-
- @Test
- public void testAppendSemantics() throws Exception {
- //1 try to append to an open file
- Path file1 = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
- FSDataOutputStream os1 = fs.create(file1, false);
- try {
- fs.append(file1); // should fail
- Assert.assertTrue("Append did not throw an exception", false);
- } catch (RemoteException e) {
- // expecting AlreadyBeingCreatedException inside RemoteException
- Assert.assertEquals(AlreadyBeingCreatedException.class, e.unwrapRemoteException().getClass());
+ private FileSystem fs;
+ private final HdfsConfiguration conf = new HdfsConfiguration();
+
+ private final Path dir = new Path("/tmp/filesdir");
+
+ @Before
+ public void setup() throws IOException {
+ conf.set(CommonConfigurationKeys.IPC_PING_INTERVAL_KEY, "5000");
+ fs = dfsClusterRule.getDfscluster().getFileSystem();
+ assert fs.mkdirs(dir);
}
- //2 try to append to a closed file
- os1.close();
- FSDataOutputStream os2 = fs.append(file1); // should pass
- os2.close();
- }
-
- @Test
- public void testDoubleCreateSemantics() throws Exception {
- //1 create an already existing open file w/o override flag
- Path file1 = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
- FSDataOutputStream os1 = fs.create(file1, false);
- try {
- fs.create(file1, false); // should fail
- Assert.assertTrue("Create did not throw an exception", false);
- } catch (RemoteException e) {
- Assert.assertEquals(AlreadyBeingCreatedException.class, e.unwrapRemoteException().getClass());
+ @After
+ public void teardown() throws IOException {
+ fs.delete(dir, true);
+ fs.close();
}
- //2 close file and retry creation
- os1.close();
- try {
- fs.create(file1, false); // should still fail
- } catch (FileAlreadyExistsException e) {
- // expecting this exception
+
+ @Test
+ public void testDeleteSemantics() throws Exception {
+ Path file = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
+// try {
+ // 1) Delete absent file - should return false
+ Assert.assertFalse(fs.exists(file));
+ try {
+ Assert.assertFalse(fs.delete(file, false));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ // 2) deleting open file - should return true
+ fs.create(file, false);
+ Assert.assertTrue(fs.delete(file, false));
+
+ // 3) deleting closed file - should return true
+ FSDataOutputStream os = fs.create(file, false);
+ os.close();
+ Assert.assertTrue(fs.exists(file));
+ Assert.assertTrue(fs.delete(file, false));
+ Assert.assertFalse(fs.exists(file));
}
- //3 delete file and retry creation
- fs.delete(file1, false);
- FSDataOutputStream os2 = fs.create(file1, false); // should pass
- Assert.assertNotNull(os2);
- os2.close();
- }
+ @Test
+ public void testConcurrentDeletion() throws Exception {
+ Path file = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
+ fs.create(file).close();
+ // 1 concurrent deletion - only one thread should succeed
+ FileDeletionThread[] threads = null;
+ try {
+ threads = startThreads(10, file);
+ int successCount = 0;
+ for (FileDeletionThread thd : threads) {
+ thd.join(30_000);
+ if (thd.succeeded) {
+ successCount++;
+ }
+ if (thd.exception != null) {
+ Assert.assertNotNull(thd.exception);
+ }
+ }
+ System.err.println(successCount);
+ Assert.assertEquals(1, successCount);
+ } finally {
+ if (threads != null) {
+ for (FileDeletionThread thread : threads) {
+ thread.interrupt();
+ thread.join(30_000);
+ if (thread.isAlive()) {
+ throw new RuntimeException("Failed to stop threads within 30 seconds, threads may leak into other tests");
+ }
+ }
+ }
+ }
+ }
+ @Test
+ public void testAppendSemantics() throws Exception {
+ //1 try to append to an open file
+ Path file1 = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
+ try (FSDataOutputStream os1 = fs.create(file1, false)) {
+ fs.append(file1); // should fail
+ fail("Append did not throw an exception");
+ } catch (RemoteException e) {
+ // expecting AlreadyBeingCreatedException inside RemoteException
+ Assert.assertEquals(AlreadyBeingCreatedException.class, e.unwrapRemoteException().getClass());
+ }
+
+ //2 try to append to a closed file
+ try (FSDataOutputStream os2 = fs.append(file1)) {
+ assertNotNull(os2);
+ }
+ }
- private FileDeletionThread[] startThreads(int thdCount, Path file)
- throws IOException {
- FileDeletionThread[] result = new FileDeletionThread[thdCount];
- for (int i = 0; i < thdCount; i++) {
- result[i] = new FileDeletionThread(i, fs, file);
+ @Test
+ public void testDoubleCreateSemantics() throws Exception {
+ //1 create an already existing open file w/o override flag
+ Path file1 = new Path(dir.toString() + Path.SEPARATOR_CHAR + "file1");
+ try (FSDataOutputStream os1 = fs.create(file1, false)) {
+ fs.create(file1, false); // should fail
+ fail("Create did not throw an exception");
+ } catch (RemoteException e) {
+ Assert.assertEquals(AlreadyBeingCreatedException.class, e.unwrapRemoteException().getClass());
+ }
+ //2 close file and retry creation
+ try {
+ fs.create(file1, false); // should still fail
+ fail("Create did not throw an exception");
+ } catch (FileAlreadyExistsException e) {
+ // expecting this exception
+ }
+
+ //3 delete file and retry creation
+ fs.delete(file1, false);
+ try (FSDataOutputStream os2 = fs.create(file1, false)) {
+ Assert.assertNotNull(os2);
+ }
}
- for (FileDeletionThread thd : result) {
- thd.start();
+ private FileDeletionThread[] startThreads(int thdCount, Path file)
+ throws IOException {
+ FileDeletionThread[] result = new FileDeletionThread[thdCount];
+ for (int i = 0; i < thdCount; i++) {
+ result[i] = new FileDeletionThread(i, fs, file);
+ }
+
+ for (FileDeletionThread thd : result) {
+ thd.start();
+ }
+ return result;
}
- return result;
- }
- private static class FileDeletionThread extends Thread {
+ private static class FileDeletionThread extends Thread {
- private final int thdNum;
- private final FileSystem fs;
- private final Path file;
- public boolean succeeded;
- public Exception exception = null;
+ private final int thdNum;
+ private final FileSystem fs;
+ private final Path file;
+ public boolean succeeded;
+ public Exception exception = null;
- public FileDeletionThread(int thdNum, FileSystem fs, Path file)
+ public FileDeletionThread(int thdNum, FileSystem fs, Path file)
throws IOException {
- this.thdNum = thdNum;
- this.fs = fs;
- this.file = file;
- }
-
- @Override
- public void run() {
- Thread.currentThread().setName("FileDeletionThread-" + thdNum);
- try {
- succeeded = fs.delete(file, false);
- } catch (Exception e) {
- exception = e;
- }
- } // run()
-
- } // class FileLockingThread
+ this.thdNum = thdNum;
+ this.fs = fs;
+ this.file = file;
+ }
+
+ @Override
+ public void run() {
+ Thread.currentThread().setName("FileDeletionThread-" + thdNum);
+ try {
+ succeeded = fs.delete(file, false);
+ } catch (Exception e) {
+ exception = e;
+ }
+ } // run()
+
+ } // class FileLockingThread
}
[3/4] storm git commit: STORM-2810: Fix resource leaks in storm-hdfs
tests
Posted by sr...@apache.org.
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/BlobStoreTest.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/BlobStoreTest.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/BlobStoreTest.java
index 6e03bcf..f9374fe 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/BlobStoreTest.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/BlobStoreTest.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -33,10 +34,7 @@ import org.apache.storm.security.auth.NimbusPrincipal;
import org.apache.storm.security.auth.SingleUserPrincipal;
import org.apache.storm.utils.Utils;
import org.apache.commons.io.FileUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -63,469 +61,454 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.ClassRule;
+
public class BlobStoreTest {
- private static final Logger LOG = LoggerFactory.getLogger(BlobStoreTest.class);
- protected static MiniDFSCluster dfscluster = null;
- protected static Configuration hadoopConf = null;
- URI base;
- File baseFile;
- private static Map conf = new HashMap();
- public static final int READ = 0x01;
- public static final int WRITE = 0x02;
- public static final int ADMIN = 0x04;
-
- @Before
- public void init() {
- System.setProperty("test.build.data", "target/test/data");
- initializeConfigs();
- baseFile = new File("/tmp/blob-store-test-"+UUID.randomUUID());
- base = baseFile.toURI();
- }
-
- @After
- public void cleanup()
- throws IOException {
- FileUtils.deleteDirectory(baseFile);
- }
-
- @AfterClass
- public static void cleanupAfterClass() throws IOException {
- if (dfscluster != null) {
- dfscluster.shutdown();
+
+ @ClassRule
+ public static final MiniDFSClusterRule DFS_CLUSTER_RULE = new MiniDFSClusterRule();
+
+ private static final Logger LOG = LoggerFactory.getLogger(BlobStoreTest.class);
+ URI base;
+ File baseFile;
+ private static final Map CONF = new HashMap();
+ public static final int READ = 0x01;
+ public static final int WRITE = 0x02;
+ public static final int ADMIN = 0x04;
+
+ @Before
+ public void init() {
+ initializeConfigs();
+ baseFile = new File("/tmp/blob-store-test-" + UUID.randomUUID());
+ base = baseFile.toURI();
+ }
+
+ @After
+ public void cleanup()
+ throws IOException {
+ FileUtils.deleteDirectory(baseFile);
+ }
+
+ // Method which initializes nimbus admin
+ public static void initializeConfigs() {
+ CONF.put(Config.NIMBUS_ADMINS, "admin");
+ CONF.put(Config.NIMBUS_SUPERVISOR_USERS, "supervisor");
+ }
+
+ //Gets Nimbus Subject with NimbusPrincipal set on it
+ public static Subject getNimbusSubject() {
+ Subject nimbus = new Subject();
+ nimbus.getPrincipals().add(new NimbusPrincipal());
+ return nimbus;
+ }
+
+ // Overloading the assertStoreHasExactly method accomodate Subject in order to check for authorization
+ public static void assertStoreHasExactly(BlobStore store, Subject who, String... keys)
+ throws IOException, KeyNotFoundException, AuthorizationException {
+ Set<String> expected = new HashSet<>(Arrays.asList(keys));
+ Set<String> found = new HashSet<>();
+ Iterator<String> c = store.listKeys();
+ while (c.hasNext()) {
+ String keyName = c.next();
+ found.add(keyName);
+ }
+ Set<String> extra = new HashSet<>(found);
+ extra.removeAll(expected);
+ assertTrue("Found extra keys in the blob store " + extra, extra.isEmpty());
+ Set<String> missing = new HashSet<>(expected);
+ missing.removeAll(found);
+ assertTrue("Found keys missing from the blob store " + missing, missing.isEmpty());
+ }
+
+ public static void assertStoreHasExactly(BlobStore store, String... keys)
+ throws IOException, KeyNotFoundException, AuthorizationException {
+ assertStoreHasExactly(store, null, keys);
+ }
+
+ // Overloading the readInt method accomodate Subject in order to check for authorization (security turned on)
+ public static int readInt(BlobStore store, Subject who, String key) throws IOException, KeyNotFoundException, AuthorizationException {
+ try (InputStream in = store.getBlob(key, who)) {
+ return in.read();
+ }
+ }
+
+ public static int readInt(BlobStore store, String key)
+ throws IOException, KeyNotFoundException, AuthorizationException {
+ return readInt(store, null, key);
+ }
+
+ public static void readAssertEquals(BlobStore store, String key, int value)
+ throws IOException, KeyNotFoundException, AuthorizationException {
+ assertEquals(value, readInt(store, key));
}
- }
-
- // Method which initializes nimbus admin
- public static void initializeConfigs() {
- conf.put(Config.NIMBUS_ADMINS,"admin");
- conf.put(Config.NIMBUS_SUPERVISOR_USERS,"supervisor");
- }
-
- //Gets Nimbus Subject with NimbusPrincipal set on it
- public static Subject getNimbusSubject() {
- Subject nimbus = new Subject();
- nimbus.getPrincipals().add(new NimbusPrincipal());
- return nimbus;
- }
-
- // Overloading the assertStoreHasExactly method accomodate Subject in order to check for authorization
- public static void assertStoreHasExactly(BlobStore store, Subject who, String ... keys)
- throws IOException, KeyNotFoundException, AuthorizationException {
- Set<String> expected = new HashSet<String>(Arrays.asList(keys));
- Set<String> found = new HashSet<String>();
- Iterator<String> c = store.listKeys();
- while (c.hasNext()) {
- String keyName = c.next();
- found.add(keyName);
+
+ // Checks for assertion when we turn on security
+ public void readAssertEqualsWithAuth(BlobStore store, Subject who, String key, int value)
+ throws IOException, KeyNotFoundException, AuthorizationException {
+ assertEquals(value, readInt(store, who, key));
}
- Set<String> extra = new HashSet<String>(found);
- extra.removeAll(expected);
- assertTrue("Found extra keys in the blob store "+extra, extra.isEmpty());
- Set<String> missing = new HashSet<String>(expected);
- missing.removeAll(found);
- assertTrue("Found keys missing from the blob store "+missing, missing.isEmpty());
- }
-
- public static void assertStoreHasExactly(BlobStore store, String ... keys)
- throws IOException, KeyNotFoundException, AuthorizationException {
- assertStoreHasExactly(store, null, keys);
- }
-
- // Overloading the readInt method accomodate Subject in order to check for authorization (security turned on)
- public static int readInt(BlobStore store, Subject who, String key) throws IOException, KeyNotFoundException, AuthorizationException {
- InputStream in = store.getBlob(key, who);
- try {
- return in.read();
- } finally {
- in.close();
+
+ private AutoCloseableBlobStoreContainer initHdfs(String dirName)
+ throws Exception {
+ Map conf = new HashMap();
+ conf.put(Config.BLOBSTORE_DIR, dirName);
+ conf.put(Config.STORM_PRINCIPAL_TO_LOCAL_PLUGIN, "org.apache.storm.security.auth.DefaultPrincipalToLocal");
+ conf.put(Config.STORM_BLOBSTORE_REPLICATION_FACTOR, 3);
+ HdfsBlobStore store = new HdfsBlobStore();
+ store.prepareInternal(conf, null, DFS_CLUSTER_RULE.getDfscluster().getConfiguration(0));
+ return new AutoCloseableBlobStoreContainer(store);
}
- }
-
- public static int readInt(BlobStore store, String key)
- throws IOException, KeyNotFoundException, AuthorizationException {
- return readInt(store, null, key);
- }
-
- public static void readAssertEquals(BlobStore store, String key, int value)
- throws IOException, KeyNotFoundException, AuthorizationException {
- assertEquals(value, readInt(store, key));
- }
-
- // Checks for assertion when we turn on security
- public void readAssertEqualsWithAuth(BlobStore store, Subject who, String key, int value)
- throws IOException, KeyNotFoundException, AuthorizationException {
- assertEquals(value, readInt(store, who, key));
- }
-
- private HdfsBlobStore initHdfs(String dirName)
- throws Exception {
- if (hadoopConf == null) {
- hadoopConf = new Configuration();
+
+ private static class AutoCloseableBlobStoreContainer implements AutoCloseable {
+
+ private final HdfsBlobStore blobStore;
+
+ public AutoCloseableBlobStoreContainer(HdfsBlobStore blobStore) {
+ this.blobStore = blobStore;
+ }
+
+ @Override
+ public void close() throws Exception {
+ this.blobStore.shutdown();
+ }
+
}
- try {
- if (dfscluster == null) {
- dfscluster = new MiniDFSCluster.Builder(hadoopConf).numDataNodes(3).build();
- dfscluster.waitActive();
- }
- } catch (IOException e) {
- LOG.error("error creating MiniDFSCluster");
+
+ @Test
+ public void testHdfsReplication()
+ throws Exception {
+ try (AutoCloseableBlobStoreContainer container = initHdfs("/storm/blobstoreReplication")) {
+ testReplication("/storm/blobstoreReplication/test", container.blobStore);
+ }
}
- Map conf = new HashMap();
- conf.put(Config.BLOBSTORE_DIR, dirName);
- conf.put(Config.STORM_PRINCIPAL_TO_LOCAL_PLUGIN,"org.apache.storm.security.auth.DefaultPrincipalToLocal");
- conf.put(Config.STORM_BLOBSTORE_REPLICATION_FACTOR, 3);
- HdfsBlobStore store = new HdfsBlobStore();
- store.prepareInternal(conf, null, dfscluster.getConfiguration(0));
- return store;
- }
-
- @Test
- public void testHdfsReplication()
- throws Exception {
- BlobStore store = initHdfs("/storm/blobstoreReplication");
- testReplication("/storm/blobstoreReplication/test", store);
- }
-
- @Test
- public void testBasicHdfs()
- throws Exception {
- testBasic(initHdfs("/storm/blobstore1"));
- }
-
- @Test
- public void testMultipleHdfs()
- throws Exception {
- // use different blobstore dir so it doesn't conflict with other test
- testMultiple(initHdfs("/storm/blobstore2"));
- }
-
- @Test
- public void testHdfsWithAuth()
- throws Exception {
- // use different blobstore dir so it doesn't conflict with other tests
- testWithAuthentication(initHdfs("/storm/blobstore3"));
- }
-
- // Test for replication.
- public void testReplication(String path, BlobStore store)
- throws Exception {
- SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
- metadata.set_replication_factor(4);
- AtomicOutputStream out = store.createBlob("test", metadata, null);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", null), 4);
- store.deleteBlob("test", null);
-
- //Test for replication with NIMBUS as user
- Subject admin = getSubject("admin");
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- metadata.set_replication_factor(4);
- out = store.createBlob("test", metadata, admin);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", admin), 4);
- store.updateBlobReplication("test", 5, admin);
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", admin), 5);
- store.deleteBlob("test", admin);
-
- //Test for replication using SUPERVISOR access
- Subject supervisor = getSubject("supervisor");
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- metadata.set_replication_factor(4);
- out = store.createBlob("test", metadata, supervisor);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", supervisor), 4);
- store.updateBlobReplication("test", 5, supervisor);
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", supervisor), 5);
- store.deleteBlob("test", supervisor);
-
- //Test for a user having read or write or admin access to read replication for a blob
- String createSubject = "createSubject";
- String writeSubject = "writeSubject";
- String adminSubject = "adminSubject";
- Subject who = getSubject(createSubject);
- AccessControl writeAccess = new AccessControl(AccessControlType.USER, READ);
- AccessControl adminAccess = new AccessControl(AccessControlType.USER, ADMIN);
- writeAccess.set_name(writeSubject);
- adminAccess.set_name(adminSubject);
- List<AccessControl> acl = Arrays.asList(writeAccess, adminAccess);
- metadata = new SettableBlobMeta(acl);
- metadata.set_replication_factor(4);
- out = store.createBlob("test", metadata, who);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- who = getSubject(writeSubject);
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", who), 4);
-
- //Test for a user having WRITE or ADMIN privileges to change replication of a blob
- who = getSubject(adminSubject);
- store.updateBlobReplication("test", 5, who);
- assertEquals("Blobstore replication not matching", store.getBlobReplication("test", who), 5);
- store.deleteBlob("test", getSubject(createSubject));
- }
-
- public Subject getSubject(String name) {
- Subject subject = new Subject();
- SingleUserPrincipal user = new SingleUserPrincipal(name);
- subject.getPrincipals().add(user);
- return subject;
- }
-
- // Check for Blobstore with authentication
- public void testWithAuthentication(BlobStore store)
- throws Exception {
- //Test for Nimbus Admin
- Subject admin = getSubject("admin");
- assertStoreHasExactly(store);
- SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- AtomicOutputStream out = store.createBlob("test", metadata, admin);
- assertStoreHasExactly(store, "test");
- out.write(1);
- out.close();
- store.deleteBlob("test", admin);
-
- //Test for Supervisor Admin
- Subject supervisor = getSubject("supervisor");
- assertStoreHasExactly(store);
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- out = store.createBlob("test", metadata, supervisor);
- assertStoreHasExactly(store, "test");
- out.write(1);
- out.close();
- store.deleteBlob("test", supervisor);
-
- //Test for Nimbus itself as a user
- Subject nimbus = getNimbusSubject();
- assertStoreHasExactly(store);
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- out = store.createBlob("test", metadata, nimbus);
- assertStoreHasExactly(store, "test");
- out.write(1);
- out.close();
- store.deleteBlob("test", nimbus);
-
- // Test with a dummy test_subject for cases where subject !=null (security turned on)
- Subject who = getSubject("test_subject");
- assertStoreHasExactly(store);
-
- // Tests for case when subject != null (security turned on) and
- // acls for the blob are set to WORLD_EVERYTHING
- metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
- out = store.createBlob("test", metadata, who);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- // Testing whether acls are set to WORLD_EVERYTHING
- assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
- readAssertEqualsWithAuth(store, who, "test", 1);
-
- LOG.info("Deleting test");
- store.deleteBlob("test", who);
- assertStoreHasExactly(store);
-
- // Tests for case when subject != null (security turned on) and
- // acls are not set for the blob (DEFAULT)
- LOG.info("Creating test again");
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- out = store.createBlob("test", metadata, who);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test");
- // Testing whether acls are set to WORLD_EVERYTHING. Here the acl should not contain WORLD_EVERYTHING because
- // the subject is neither null nor empty. The ACL should however contain USER_EVERYTHING as user needs to have
- // complete access to the blob
- assertTrue("ACL does not contain WORLD_EVERYTHING", !metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
- readAssertEqualsWithAuth(store, who, "test", 2);
-
- LOG.info("Updating test");
- out = store.updateBlob("test", who);
- out.write(3);
- out.close();
- assertStoreHasExactly(store, "test");
- readAssertEqualsWithAuth(store, who, "test", 3);
-
- LOG.info("Updating test again");
- out = store.updateBlob("test", who);
- out.write(4);
- out.flush();
- LOG.info("SLEEPING");
- Thread.sleep(2);
- assertStoreHasExactly(store, "test");
- readAssertEqualsWithAuth(store, who, "test", 3);
-
- //Test for subject with no principals and acls set to WORLD_EVERYTHING
- who = new Subject();
- metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
- LOG.info("Creating test");
- out = store.createBlob("test-empty-subject-WE", metadata, who);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test-empty-subject-WE", "test");
- // Testing whether acls are set to WORLD_EVERYTHING
- assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
- readAssertEqualsWithAuth(store, who, "test-empty-subject-WE", 2);
-
- //Test for subject with no principals and acls set to DEFAULT
- who = new Subject();
- metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
- LOG.info("Creating other");
- out = store.createBlob("test-empty-subject-DEF", metadata, who);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test-empty-subject-DEF", "test", "test-empty-subject-WE");
- // Testing whether acls are set to WORLD_EVERYTHING
- assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
- readAssertEqualsWithAuth(store, who, "test-empty-subject-DEF", 2);
-
- if (store instanceof HdfsBlobStore) {
- ((HdfsBlobStore) store).fullCleanup(1);
- } else {
- fail("Error the blobstore is of unknowntype");
+
+ @Test
+ public void testBasicHdfs()
+ throws Exception {
+ try (AutoCloseableBlobStoreContainer container = initHdfs("/storm/blobstore1")) {
+ testBasic(container.blobStore);
+ }
}
- try {
- out.close();
- } catch (IOException e) {
- //This is likely to happen when we try to commit something that
- // was cleaned up. This is expected and acceptable.
+
+ @Test
+ public void testMultipleHdfs()
+ throws Exception {
+ // use different blobstore dir so it doesn't conflict with other test
+ try (AutoCloseableBlobStoreContainer container = initHdfs("/storm/blobstore2")) {
+ testMultiple(container.blobStore);
+ }
}
- }
-
- public void testBasic(BlobStore store)
- throws Exception {
- assertStoreHasExactly(store);
- LOG.info("Creating test");
- // Tests for case when subject == null (security turned off) and
- // acls for the blob are set to WORLD_EVERYTHING
- SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler
- .WORLD_EVERYTHING);
- AtomicOutputStream out = store.createBlob("test", metadata, null);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- // Testing whether acls are set to WORLD_EVERYTHING
- assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
- readAssertEquals(store, "test", 1);
-
- LOG.info("Deleting test");
- store.deleteBlob("test", null);
- assertStoreHasExactly(store);
-
- // The following tests are run for both hdfs and local store to test the
- // update blob interface
- metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
- LOG.info("Creating test again");
- out = store.createBlob("test", metadata, null);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test");
- readAssertEquals(store, "test", 2);
- LOG.info("Updating test");
- out = store.updateBlob("test", null);
- out.write(3);
- out.close();
- assertStoreHasExactly(store, "test");
- readAssertEquals(store, "test", 3);
-
- LOG.info("Updating test again");
- out = store.updateBlob("test", null);
- out.write(4);
- out.flush();
- LOG.info("SLEEPING");
- Thread.sleep(2);
-
- if (store instanceof HdfsBlobStore) {
- ((HdfsBlobStore) store).fullCleanup(1);
- } else {
- fail("Error the blobstore is of unknowntype");
+
+ @Test
+ public void testHdfsWithAuth()
+ throws Exception {
+ // use different blobstore dir so it doesn't conflict with other tests
+ try (AutoCloseableBlobStoreContainer container = initHdfs("/storm/blobstore3")) {
+ testWithAuthentication(container.blobStore);
+ }
}
- try {
- out.close();
- } catch (IOException e) {
- //This is likely to happen when we try to commit something that
- // was cleaned up. This is expected and acceptable.
+
+ // Test for replication.
+ public void testReplication(String path, BlobStore store)
+ throws Exception {
+ SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
+ metadata.set_replication_factor(4);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, null)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", null), 4);
+ store.deleteBlob("test", null);
+
+ //Test for replication with NIMBUS as user
+ Subject admin = getSubject("admin");
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ metadata.set_replication_factor(4);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, admin)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", admin), 4);
+ store.updateBlobReplication("test", 5, admin);
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", admin), 5);
+ store.deleteBlob("test", admin);
+
+ //Test for replication using SUPERVISOR access
+ Subject supervisor = getSubject("supervisor");
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ metadata.set_replication_factor(4);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, supervisor)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", supervisor), 4);
+ store.updateBlobReplication("test", 5, supervisor);
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", supervisor), 5);
+ store.deleteBlob("test", supervisor);
+
+ //Test for a user having read or write or admin access to read replication for a blob
+ String createSubject = "createSubject";
+ String writeSubject = "writeSubject";
+ String adminSubject = "adminSubject";
+ Subject who = getSubject(createSubject);
+ AccessControl writeAccess = new AccessControl(AccessControlType.USER, READ);
+ AccessControl adminAccess = new AccessControl(AccessControlType.USER, ADMIN);
+ writeAccess.set_name(writeSubject);
+ adminAccess.set_name(adminSubject);
+ List<AccessControl> acl = Arrays.asList(writeAccess, adminAccess);
+ metadata = new SettableBlobMeta(acl);
+ metadata.set_replication_factor(4);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, who)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ who = getSubject(writeSubject);
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", who), 4);
+
+ //Test for a user having WRITE or ADMIN privileges to change replication of a blob
+ who = getSubject(adminSubject);
+ store.updateBlobReplication("test", 5, who);
+ assertEquals("Blobstore replication not matching", store.getBlobReplication("test", who), 5);
+ store.deleteBlob("test", getSubject(createSubject));
}
- }
-
-
- public void testMultiple(BlobStore store)
- throws Exception {
- assertStoreHasExactly(store);
- LOG.info("Creating test");
- AtomicOutputStream out = store.createBlob("test", new SettableBlobMeta(BlobStoreAclHandler
- .WORLD_EVERYTHING), null);
- out.write(1);
- out.close();
- assertStoreHasExactly(store, "test");
- readAssertEquals(store, "test", 1);
-
- LOG.info("Creating other");
- out = store.createBlob("other", new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING),
- null);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test", "other");
- readAssertEquals(store, "test", 1);
- readAssertEquals(store, "other", 2);
-
- LOG.info("Updating other");
- out = store.updateBlob("other", null);
- out.write(5);
- out.close();
- assertStoreHasExactly(store, "test", "other");
- readAssertEquals(store, "test", 1);
- readAssertEquals(store, "other", 5);
-
- LOG.info("Deleting test");
- store.deleteBlob("test", null);
- assertStoreHasExactly(store, "other");
- readAssertEquals(store, "other", 5);
-
- LOG.info("Creating test again");
- out = store.createBlob("test", new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING),
- null);
- out.write(2);
- out.close();
- assertStoreHasExactly(store, "test", "other");
- readAssertEquals(store, "test", 2);
- readAssertEquals(store, "other", 5);
-
- LOG.info("Updating test");
- out = store.updateBlob("test", null);
- out.write(3);
- out.close();
- assertStoreHasExactly(store, "test", "other");
- readAssertEquals(store, "test", 3);
- readAssertEquals(store, "other", 5);
-
- LOG.info("Deleting other");
- store.deleteBlob("other", null);
- assertStoreHasExactly(store, "test");
- readAssertEquals(store, "test", 3);
-
- LOG.info("Updating test again");
- out = store.updateBlob("test", null);
- out.write(4);
- out.flush();
- LOG.info("SLEEPING");
- Thread.sleep(2);
-
- if (store instanceof HdfsBlobStore) {
- ((HdfsBlobStore) store).fullCleanup(1);
- } else {
- fail("Error the blobstore is of unknowntype");
- } assertStoreHasExactly(store, "test");
- readAssertEquals(store, "test", 3);
- try {
- out.close();
- } catch (IOException e) {
- //This is likely to happen when we try to commit something that
- // was cleaned up. This is expected and acceptable.
+
+ public Subject getSubject(String name) {
+ Subject subject = new Subject();
+ SingleUserPrincipal user = new SingleUserPrincipal(name);
+ subject.getPrincipals().add(user);
+ return subject;
+ }
+
+ // Check for Blobstore with authentication
+ public void testWithAuthentication(BlobStore store)
+ throws Exception {
+ //Test for Nimbus Admin
+ Subject admin = getSubject("admin");
+ assertStoreHasExactly(store);
+ SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, admin)) {
+ assertStoreHasExactly(store, "test");
+ out.write(1);
+ }
+ store.deleteBlob("test", admin);
+
+ //Test for Supervisor Admin
+ Subject supervisor = getSubject("supervisor");
+ assertStoreHasExactly(store);
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, supervisor)) {
+ assertStoreHasExactly(store, "test");
+ out.write(1);
+ }
+ store.deleteBlob("test", supervisor);
+
+ //Test for Nimbus itself as a user
+ Subject nimbus = getNimbusSubject();
+ assertStoreHasExactly(store);
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, nimbus)) {
+ assertStoreHasExactly(store, "test");
+ out.write(1);
+ }
+ store.deleteBlob("test", nimbus);
+
+ // Test with a dummy test_subject for cases where subject !=null (security turned on)
+ Subject who = getSubject("test_subject");
+ assertStoreHasExactly(store);
+
+ // Tests for case when subject != null (security turned on) and
+ // acls for the blob are set to WORLD_EVERYTHING
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, who)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ // Testing whether acls are set to WORLD_EVERYTHING
+ assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
+ readAssertEqualsWithAuth(store, who, "test", 1);
+
+ LOG.info("Deleting test");
+ store.deleteBlob("test", who);
+ assertStoreHasExactly(store);
+
+ // Tests for case when subject != null (security turned on) and
+ // acls are not set for the blob (DEFAULT)
+ LOG.info("Creating test again");
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, who)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test");
+ // Testing whether acls are set to WORLD_EVERYTHING. Here the acl should not contain WORLD_EVERYTHING because
+ // the subject is neither null nor empty. The ACL should however contain USER_EVERYTHING as user needs to have
+ // complete access to the blob
+ assertTrue("ACL does not contain WORLD_EVERYTHING", !metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
+ readAssertEqualsWithAuth(store, who, "test", 2);
+
+ LOG.info("Updating test");
+ try (AtomicOutputStream out = store.updateBlob("test", who)) {
+ out.write(3);
+ }
+ assertStoreHasExactly(store, "test");
+ readAssertEqualsWithAuth(store, who, "test", 3);
+
+ LOG.info("Updating test again");
+ try (AtomicOutputStream out = store.updateBlob("test", who)) {
+ out.write(4);
+ }
+ LOG.info("SLEEPING");
+ Thread.sleep(2);
+ assertStoreHasExactly(store, "test");
+ readAssertEqualsWithAuth(store, who, "test", 3);
+
+ //Test for subject with no principals and acls set to WORLD_EVERYTHING
+ who = new Subject();
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
+ LOG.info("Creating test");
+ try (AtomicOutputStream out = store.createBlob("test-empty-subject-WE", metadata, who)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test-empty-subject-WE", "test");
+ // Testing whether acls are set to WORLD_EVERYTHING
+ assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
+ readAssertEqualsWithAuth(store, who, "test-empty-subject-WE", 2);
+
+ //Test for subject with no principals and acls set to DEFAULT
+ who = new Subject();
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
+ LOG.info("Creating other");
+ try (AtomicOutputStream out = store.createBlob("test-empty-subject-DEF", metadata, who)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test-empty-subject-DEF", "test", "test-empty-subject-WE");
+ // Testing whether acls are set to WORLD_EVERYTHING
+ assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
+ readAssertEqualsWithAuth(store, who, "test-empty-subject-DEF", 2);
+
+ if (store instanceof HdfsBlobStore) {
+ ((HdfsBlobStore) store).fullCleanup(1);
+ } else {
+ fail("Error the blobstore is of unknowntype");
+ }
+ }
+
+ public void testBasic(BlobStore store)
+ throws Exception {
+ assertStoreHasExactly(store);
+ LOG.info("Creating test");
+ // Tests for case when subject == null (security turned off) and
+ // acls for the blob are set to WORLD_EVERYTHING
+ SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
+ try (AtomicOutputStream out = store.createBlob("test", metadata, null)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ // Testing whether acls are set to WORLD_EVERYTHING
+ assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
+ readAssertEquals(store, "test", 1);
+
+ LOG.info("Deleting test");
+ store.deleteBlob("test", null);
+ assertStoreHasExactly(store);
+
+ // The following tests are run for both hdfs and local store to test the
+ // update blob interface
+ metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
+ LOG.info("Creating test again");
+ try (AtomicOutputStream out = store.createBlob("test", metadata, null)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test");
+ readAssertEquals(store, "test", 2);
+ LOG.info("Updating test");
+ try (AtomicOutputStream out = store.updateBlob("test", null)) {
+ out.write(3);
+ }
+ assertStoreHasExactly(store, "test");
+ readAssertEquals(store, "test", 3);
+
+ LOG.info("Updating test again");
+ try (AtomicOutputStream out = store.updateBlob("test", null)) {
+ out.write(4);
+ }
+ LOG.info("SLEEPING");
+ Thread.sleep(2);
+
+ if (store instanceof HdfsBlobStore) {
+ ((HdfsBlobStore) store).fullCleanup(1);
+ } else {
+ fail("Error the blobstore is of unknowntype");
+ }
+ }
+
+ public void testMultiple(BlobStore store)
+ throws Exception {
+ assertStoreHasExactly(store);
+ LOG.info("Creating test");
+ try (AtomicOutputStream out = store.createBlob("test", new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING), null)) {
+ out.write(1);
+ }
+ assertStoreHasExactly(store, "test");
+ readAssertEquals(store, "test", 1);
+
+ LOG.info("Creating other");
+ try (AtomicOutputStream out = store.createBlob("other", new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING),
+ null)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test", "other");
+ readAssertEquals(store, "test", 1);
+ readAssertEquals(store, "other", 2);
+
+ LOG.info("Updating other");
+ try (AtomicOutputStream out = store.updateBlob("other", null)) {
+ out.write(5);
+ }
+ assertStoreHasExactly(store, "test", "other");
+ readAssertEquals(store, "test", 1);
+ readAssertEquals(store, "other", 5);
+
+ LOG.info("Deleting test");
+ store.deleteBlob("test", null);
+ assertStoreHasExactly(store, "other");
+ readAssertEquals(store, "other", 5);
+
+ LOG.info("Creating test again");
+ try (AtomicOutputStream out = store.createBlob("test", new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING),
+ null)) {
+ out.write(2);
+ }
+ assertStoreHasExactly(store, "test", "other");
+ readAssertEquals(store, "test", 2);
+ readAssertEquals(store, "other", 5);
+
+ LOG.info("Updating test");
+ try (AtomicOutputStream out = store.updateBlob("test", null)) {
+ out.write(3);
+ }
+ assertStoreHasExactly(store, "test", "other");
+ readAssertEquals(store, "test", 3);
+ readAssertEquals(store, "other", 5);
+
+ LOG.info("Deleting other");
+ store.deleteBlob("other", null);
+ assertStoreHasExactly(store, "test");
+ readAssertEquals(store, "test", 3);
+
+ LOG.info("Updating test again");
+ try (AtomicOutputStream out = store.updateBlob("test", null)) {
+ out.write(4);
+ }
+ LOG.info("SLEEPING");
+ Thread.sleep(2);
+
+ if (store instanceof HdfsBlobStore) {
+ ((HdfsBlobStore) store).fullCleanup(1);
+ } else {
+ fail("Error the blobstore is of unknowntype");
+ }
+ assertStoreHasExactly(store, "test");
+ readAssertEquals(store, "test", 3);
}
- }
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImplTest.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImplTest.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImplTest.java
index c49c44b..fd80631 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImplTest.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/blobstore/HdfsBlobStoreImplTest.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -23,9 +24,6 @@ import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hdfs.MiniDFSCluster;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,194 +37,190 @@ import java.util.Map;
import static org.junit.Assert.*;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.ClassRule;
+
public class HdfsBlobStoreImplTest {
+
+ @ClassRule
+ public static final MiniDFSClusterRule DFS_CLUSTER_RULE = new MiniDFSClusterRule();
+
private static final Logger LOG = LoggerFactory.getLogger(HdfsBlobStoreImplTest.class);
- protected static Configuration hadoopConf;
- protected static MiniDFSCluster dfscluster;
// key dir needs to be number 0 to number of buckets, choose one so we know where to look
private static String KEYDIR = "0";
private Path blobDir = new Path("/storm/blobstore1");
private Path fullKeyDir = new Path(blobDir, KEYDIR);
private String BLOBSTORE_DATA = "data";
- public class TestHdfsBlobStoreImpl extends HdfsBlobStoreImpl {
+ public class TestHdfsBlobStoreImpl extends HdfsBlobStoreImpl implements AutoCloseable {
public TestHdfsBlobStoreImpl(Path path, Map<String, Object> conf) throws IOException {
super(path, conf);
}
public TestHdfsBlobStoreImpl(Path path, Map<String, Object> conf,
- Configuration hconf) throws IOException {
+ Configuration hconf) throws IOException {
super(path, conf, hconf);
}
protected Path getKeyDir(String key) {
return new Path(new Path(blobDir, KEYDIR), key);
}
- }
-
- @BeforeClass
- public static void init() {
- System.setProperty("test.build.data", "target/test/data");
- if (hadoopConf == null) {
- hadoopConf = new Configuration();
- }
- try {
- if (dfscluster == null) {
- dfscluster = new MiniDFSCluster.Builder(hadoopConf).build();
- dfscluster.waitActive();
- }
- } catch (IOException e) {
- LOG.error("error creating MiniDFSCluster");
- }
- }
- @AfterClass
- public static void cleanup() throws IOException {
- if (dfscluster != null) {
- dfscluster.shutdown();
+ @Override
+ public void close() throws Exception {
+ this.shutdown();
}
}
// Be careful about adding additional tests as the dfscluster will be shared
-
@Test
public void testMultiple() throws Exception {
String testString = "testingblob";
String validKey = "validkeyBasic";
- FileSystem fs = dfscluster.getFileSystem();
+ //Will be closed automatically when shutting down the DFS cluster
+ FileSystem fs = DFS_CLUSTER_RULE.getDfscluster().getFileSystem();
Map conf = new HashMap();
- TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);
- // should have created blobDir
- assertTrue("BlobStore dir wasn't created", fs.exists(blobDir));
- assertEquals("BlobStore dir was created with wrong permissions",
+ try (TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, DFS_CLUSTER_RULE.getHadoopConf())) {
+ // should have created blobDir
+ assertTrue("BlobStore dir wasn't created", fs.exists(blobDir));
+ assertEquals("BlobStore dir was created with wrong permissions",
HdfsBlobStoreImpl.BLOBSTORE_DIR_PERMISSION, fs.getFileStatus(blobDir).getPermission());
- // test exist with non-existent key
- assertFalse("file exists but shouldn't", hbs.exists("bogus"));
-
- // test write
- BlobStoreFile pfile = hbs.write(validKey, false);
- // Adding metadata to avoid null pointer exception
- SettableBlobMeta meta = new SettableBlobMeta();
- meta.set_replication_factor(1);
- pfile.setMetadata(meta);
- OutputStream ios = pfile.getOutputStream();
- ios.write(testString.getBytes(Charset.forName("UTF-8")));
- ios.close();
-
- // test commit creates properly
- assertTrue("BlobStore key dir wasn't created", fs.exists(fullKeyDir));
- pfile.commit();
- Path dataFile = new Path(new Path(fullKeyDir, validKey), BLOBSTORE_DATA);
- assertTrue("blob data not committed", fs.exists(dataFile));
- assertEquals("BlobStore dir was created with wrong permissions",
+ // test exist with non-existent key
+ assertFalse("file exists but shouldn't", hbs.exists("bogus"));
+
+ // test write
+ BlobStoreFile pfile = hbs.write(validKey, false);
+ // Adding metadata to avoid null pointer exception
+ SettableBlobMeta meta = new SettableBlobMeta();
+ meta.set_replication_factor(1);
+ pfile.setMetadata(meta);
+ try (OutputStream ios = pfile.getOutputStream()) {
+ ios.write(testString.getBytes(StandardCharsets.UTF_8));
+ }
+
+ // test commit creates properly
+ assertTrue("BlobStore key dir wasn't created", fs.exists(fullKeyDir));
+ pfile.commit();
+ Path dataFile = new Path(new Path(fullKeyDir, validKey), BLOBSTORE_DATA);
+ assertTrue("blob data not committed", fs.exists(dataFile));
+ assertEquals("BlobStore dir was created with wrong permissions",
HdfsBlobStoreFile.BLOBSTORE_FILE_PERMISSION, fs.getFileStatus(dataFile).getPermission());
- assertTrue("key doesn't exist but should", hbs.exists(validKey));
-
- // test read
- BlobStoreFile readpFile = hbs.read(validKey);
- String readString = IOUtils.toString(readpFile.getInputStream(), "UTF-8");
- assertEquals("string read from blob doesn't match", testString, readString);
-
- // test listkeys
- Iterator<String> keys = hbs.listKeys();
- assertTrue("blob has one key", keys.hasNext());
- assertEquals("one key in blobstore", validKey, keys.next());
-
- // delete
- hbs.deleteKey(validKey);
- assertFalse("key not deleted", fs.exists(dataFile));
- assertFalse("key not deleted", hbs.exists(validKey));
-
- // Now do multiple
- String testString2 = "testingblob2";
- String validKey2= "validkey2";
-
- // test write
- pfile = hbs.write(validKey, false);
- pfile.setMetadata(meta);
- ios = pfile.getOutputStream();
- ios.write(testString.getBytes(Charset.forName("UTF-8")));
- ios.close();
-
- // test commit creates properly
- assertTrue("BlobStore key dir wasn't created", fs.exists(fullKeyDir));
- pfile.commit();
- assertTrue("blob data not committed", fs.exists(dataFile));
- assertEquals("BlobStore dir was created with wrong permissions",
+ assertTrue("key doesn't exist but should", hbs.exists(validKey));
+
+ // test read
+ BlobStoreFile readpFile = hbs.read(validKey);
+ try (InputStream inStream = readpFile.getInputStream()) {
+ String readString = IOUtils.toString(inStream, StandardCharsets.UTF_8);
+ assertEquals("string read from blob doesn't match", testString, readString);
+ }
+
+ // test listkeys
+ Iterator<String> keys = hbs.listKeys();
+ assertTrue("blob has one key", keys.hasNext());
+ assertEquals("one key in blobstore", validKey, keys.next());
+
+ // delete
+ hbs.deleteKey(validKey);
+ assertFalse("key not deleted", fs.exists(dataFile));
+ assertFalse("key not deleted", hbs.exists(validKey));
+
+ // Now do multiple
+ String testString2 = "testingblob2";
+ String validKey2 = "validkey2";
+
+ // test write
+ pfile = hbs.write(validKey, false);
+ pfile.setMetadata(meta);
+ try (OutputStream ios = pfile.getOutputStream()) {
+ ios.write(testString.getBytes(StandardCharsets.UTF_8));
+ }
+
+ // test commit creates properly
+ assertTrue("BlobStore key dir wasn't created", fs.exists(fullKeyDir));
+ pfile.commit();
+ assertTrue("blob data not committed", fs.exists(dataFile));
+ assertEquals("BlobStore dir was created with wrong permissions",
HdfsBlobStoreFile.BLOBSTORE_FILE_PERMISSION, fs.getFileStatus(dataFile).getPermission());
- assertTrue("key doesn't exist but should", hbs.exists(validKey));
-
- // test write again
- pfile = hbs.write(validKey2, false);
- pfile.setMetadata(meta);
- OutputStream ios2 = pfile.getOutputStream();
- ios2.write(testString2.getBytes(Charset.forName("UTF-8")));
- ios2.close();
-
- // test commit second creates properly
- pfile.commit();
- Path dataFile2 = new Path(new Path(fullKeyDir, validKey2), BLOBSTORE_DATA);
- assertTrue("blob data not committed", fs.exists(dataFile2));
- assertEquals("BlobStore dir was created with wrong permissions",
+ assertTrue("key doesn't exist but should", hbs.exists(validKey));
+
+ // test write again
+ pfile = hbs.write(validKey2, false);
+ pfile.setMetadata(meta);
+ try (OutputStream ios2 = pfile.getOutputStream()) {
+ ios2.write(testString2.getBytes(StandardCharsets.UTF_8));
+ }
+
+ // test commit second creates properly
+ pfile.commit();
+ Path dataFile2 = new Path(new Path(fullKeyDir, validKey2), BLOBSTORE_DATA);
+ assertTrue("blob data not committed", fs.exists(dataFile2));
+ assertEquals("BlobStore dir was created with wrong permissions",
HdfsBlobStoreFile.BLOBSTORE_FILE_PERMISSION, fs.getFileStatus(dataFile2).getPermission());
- assertTrue("key doesn't exist but should", hbs.exists(validKey2));
-
- // test listkeys
- keys = hbs.listKeys();
- int total = 0;
- boolean key1Found = false;
- boolean key2Found = false;
- while(keys.hasNext()) {
- total++;
- String key = keys.next();
- if (key.equals(validKey)) {
- key1Found = true;
- } else if (key.equals(validKey2)) {
- key2Found = true;
- } else {
- fail("Found key that wasn't expected: " + key);
+ assertTrue("key doesn't exist but should", hbs.exists(validKey2));
+
+ // test listkeys
+ keys = hbs.listKeys();
+ int total = 0;
+ boolean key1Found = false;
+ boolean key2Found = false;
+ while (keys.hasNext()) {
+ total++;
+ String key = keys.next();
+ if (key.equals(validKey)) {
+ key1Found = true;
+ } else if (key.equals(validKey2)) {
+ key2Found = true;
+ } else {
+ fail("Found key that wasn't expected: " + key);
+ }
}
+ assertEquals("number of keys is wrong", 2, total);
+ assertTrue("blobstore missing key1", key1Found);
+ assertTrue("blobstore missing key2", key2Found);
+
+ // test read
+ readpFile = hbs.read(validKey);
+ try (InputStream inStream = readpFile.getInputStream()) {
+ String readString = IOUtils.toString(inStream, StandardCharsets.UTF_8);
+ assertEquals("string read from blob doesn't match", testString, readString);
+ }
+
+ // test read
+ readpFile = hbs.read(validKey2);
+ try (InputStream inStream = readpFile.getInputStream()) {
+ String readString = IOUtils.toString(inStream, StandardCharsets.UTF_8);
+ assertEquals("string read from blob doesn't match", testString2, readString);
+ }
+
+ hbs.deleteKey(validKey);
+ assertFalse("key not deleted", hbs.exists(validKey));
+ hbs.deleteKey(validKey2);
+ assertFalse("key not deleted", hbs.exists(validKey2));
}
- assertEquals("number of keys is wrong", 2, total);
- assertTrue("blobstore missing key1", key1Found);
- assertTrue("blobstore missing key2", key2Found);
-
- // test read
- readpFile = hbs.read(validKey);
- readString = IOUtils.toString(readpFile.getInputStream(), "UTF-8");
- assertEquals("string read from blob doesn't match", testString, readString);
-
- // test read
- readpFile = hbs.read(validKey2);
- readString = IOUtils.toString(readpFile.getInputStream(), "UTF-8");
- assertEquals("string read from blob doesn't match", testString2, readString);
-
- hbs.deleteKey(validKey);
- assertFalse("key not deleted", hbs.exists(validKey));
- hbs.deleteKey(validKey2);
- assertFalse("key not deleted", hbs.exists(validKey2));
}
@Test
- public void testGetFileLength() throws IOException {
- FileSystem fs = dfscluster.getFileSystem();
- Map conf = new HashMap();
+ public void testGetFileLength() throws Exception {
+ Map<String, Object> conf = new HashMap<>();
String validKey = "validkeyBasic";
String testString = "testingblob";
- TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);
- BlobStoreFile pfile = hbs.write(validKey, false);
- // Adding metadata to avoid null pointer exception
- SettableBlobMeta meta = new SettableBlobMeta();
- meta.set_replication_factor(1);
- pfile.setMetadata(meta);
- OutputStream ios = pfile.getOutputStream();
- ios.write(testString.getBytes(Charset.forName("UTF-8")));
- ios.close();
- assertEquals(testString.getBytes(Charset.forName("UTF-8")).length, pfile.getFileLength());
+ try (TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, DFS_CLUSTER_RULE.getHadoopConf())) {
+ BlobStoreFile pfile = hbs.write(validKey, false);
+ // Adding metadata to avoid null pointer exception
+ SettableBlobMeta meta = new SettableBlobMeta();
+ meta.set_replication_factor(1);
+ pfile.setMetadata(meta);
+ try (OutputStream ios = pfile.getOutputStream()) {
+ ios.write(testString.getBytes(StandardCharsets.UTF_8));
+ }
+ assertEquals(testString.getBytes(StandardCharsets.UTF_8).length, pfile.getFileLength());
+ }
}
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/AvroGenericRecordBoltTest.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/AvroGenericRecordBoltTest.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/AvroGenericRecordBoltTest.java
index cd828da..0b08e1b 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/AvroGenericRecordBoltTest.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/AvroGenericRecordBoltTest.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -40,49 +41,71 @@ import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy;
import org.apache.storm.hdfs.bolt.sync.SyncPolicy;
import org.junit.Before;
import org.junit.After;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.Assert;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
-
+import org.apache.hadoop.hdfs.DistributedFileSystem;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule.Java7Supplier;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.runner.RunWith;
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
public class AvroGenericRecordBoltTest {
- private String hdfsURI;
+ @Rule
+ public MiniDFSClusterRule dfsClusterRule = new MiniDFSClusterRule(new Java7Supplier<Configuration>() {
+ @Override
+ public Configuration get() {
+ Configuration conf = new Configuration();
+ conf.set("fs.trash.interval", "10");
+ conf.setBoolean("dfs.permissions", true);
+ File baseDir = new File("./target/hdfs/").getAbsoluteFile();
+ FileUtil.fullyDelete(baseDir);
+ conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
+ return conf;
+ }
+ });
+ @Mock
+ private OutputCollector collector;
+ @Mock
+ private TopologyContext topologyContext;
+
private DistributedFileSystem fs;
- private MiniDFSCluster hdfsCluster;
+ private String hdfsURI;
private static final String testRoot = "/unittest";
- private static final Schema schema1;
- private static final Schema schema2;
- private static final Tuple tuple1;
- private static final Tuple tuple2;
- private static final String schemaV1 = "{\"type\":\"record\"," +
- "\"name\":\"myrecord\"," +
- "\"fields\":[{\"name\":\"foo1\",\"type\":\"string\"}," +
- "{ \"name\":\"int1\", \"type\":\"int\" }]}";
-
- private static final String schemaV2 = "{\"type\":\"record\"," +
- "\"name\":\"myrecord\"," +
- "\"fields\":[{\"name\":\"foo1\",\"type\":\"string\"}," +
- "{ \"name\":\"bar\", \"type\":\"string\", \"default\":\"baz\" }," +
- "{ \"name\":\"int1\", \"type\":\"int\" }]}";
-
- static {
-
+ private static Schema schema1;
+ private static Schema schema2;
+ private static Tuple tuple1;
+ private static Tuple tuple2;
+ private static final String schemaV1 = "{\"type\":\"record\","
+ + "\"name\":\"myrecord\","
+ + "\"fields\":[{\"name\":\"foo1\",\"type\":\"string\"},"
+ + "{ \"name\":\"int1\", \"type\":\"int\" }]}";
+
+ private static final String schemaV2 = "{\"type\":\"record\","
+ + "\"name\":\"myrecord\","
+ + "\"fields\":[{\"name\":\"foo1\",\"type\":\"string\"},"
+ + "{ \"name\":\"bar\", \"type\":\"string\", \"default\":\"baz\" },"
+ + "{ \"name\":\"int1\", \"type\":\"int\" }]}";
+
+ @BeforeClass
+ public static void setupClass() {
Schema.Parser parser = new Schema.Parser();
schema1 = parser.parse(schemaV1);
@@ -100,33 +123,19 @@ public class AvroGenericRecordBoltTest {
tuple2 = generateTestTuple(builder2.build());
}
- @Mock private OutputCollector collector;
- @Mock private TopologyContext topologyContext;
-
@Before
public void setup() throws Exception {
- MockitoAnnotations.initMocks(this);
- Configuration conf = new Configuration();
- conf.set("fs.trash.interval", "10");
- conf.setBoolean("dfs.permissions", true);
- File baseDir = new File("./target/hdfs/").getAbsoluteFile();
- FileUtil.fullyDelete(baseDir);
- conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
-
- MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
+ fs = dfsClusterRule.getDfscluster().getFileSystem();
hdfsURI = fs.getUri() + "/";
}
@After
public void shutDown() throws IOException {
fs.close();
- hdfsCluster.shutdown();
}
- @Test public void multipleTuplesOneFile() throws IOException
- {
+ @Test
+ public void multipleTuplesOneFile() throws IOException {
AvroGenericRecordBolt bolt = makeAvroBolt(hdfsURI, 1, 1f, schemaV1);
bolt.prepare(new Config(), topologyContext, collector);
@@ -139,8 +148,8 @@ public class AvroGenericRecordBoltTest {
verifyAllAvroFiles(testRoot);
}
- @Test public void multipleTuplesMutliplesFiles() throws IOException
- {
+ @Test
+ public void multipleTuplesMutliplesFiles() throws IOException {
AvroGenericRecordBolt bolt = makeAvroBolt(hdfsURI, 1, .0001f, schemaV1);
bolt.prepare(new Config(), topologyContext, collector);
@@ -153,8 +162,8 @@ public class AvroGenericRecordBoltTest {
verifyAllAvroFiles(testRoot);
}
- @Test public void forwardSchemaChangeWorks() throws IOException
- {
+ @Test
+ public void forwardSchemaChangeWorks() throws IOException {
AvroGenericRecordBolt bolt = makeAvroBolt(hdfsURI, 1, 1000f, schemaV1);
bolt.prepare(new Config(), topologyContext, collector);
@@ -167,8 +176,8 @@ public class AvroGenericRecordBoltTest {
verifyAllAvroFiles(testRoot);
}
- @Test public void backwardSchemaChangeWorks() throws IOException
- {
+ @Test
+ public void backwardSchemaChangeWorks() throws IOException {
AvroGenericRecordBolt bolt = makeAvroBolt(hdfsURI, 1, 1000f, schemaV2);
bolt.prepare(new Config(), topologyContext, collector);
@@ -180,8 +189,8 @@ public class AvroGenericRecordBoltTest {
verifyAllAvroFiles(testRoot);
}
- @Test public void schemaThrashing() throws IOException
- {
+ @Test
+ public void schemaThrashing() throws IOException {
AvroGenericRecordBolt bolt = makeAvroBolt(hdfsURI, 1, 1000f, schemaV2);
bolt.prepare(new Config(), topologyContext, collector);
@@ -206,19 +215,19 @@ public class AvroGenericRecordBoltTest {
FileNameFormat fieldsFileNameFormat = new DefaultFileNameFormat().withPath(testRoot);
FileRotationPolicy rotationPolicy =
- new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
+ new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
return new AvroGenericRecordBolt()
- .withFsUrl(nameNodeAddr)
- .withFileNameFormat(fieldsFileNameFormat)
- .withRotationPolicy(rotationPolicy)
- .withSyncPolicy(fieldsSyncPolicy);
+ .withFsUrl(nameNodeAddr)
+ .withFileNameFormat(fieldsFileNameFormat)
+ .withRotationPolicy(rotationPolicy)
+ .withSyncPolicy(fieldsSyncPolicy);
}
private static Tuple generateTestTuple(GenericRecord record) {
TopologyBuilder builder = new TopologyBuilder();
GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(),
- new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
+ new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
@Override
public Fields getComponentOutputFields(String componentId, String streamId) {
return new Fields("record");
@@ -250,24 +259,23 @@ public class AvroGenericRecordBoltTest {
return nonZero;
}
- private void fileIsGoodAvro (Path path) throws IOException {
+ private void fileIsGoodAvro(Path path) throws IOException {
DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
- FSDataInputStream in = fs.open(path, 0);
- FileOutputStream out = new FileOutputStream("target/FOO.avro");
-
- byte[] buffer = new byte[100];
- int bytesRead;
- while ((bytesRead = in.read(buffer)) > 0) {
- out.write(buffer, 0, bytesRead);
+ try (FSDataInputStream in = fs.open(path, 0); FileOutputStream out = new FileOutputStream("target/FOO.avro")) {
+ byte[] buffer = new byte[100];
+ int bytesRead;
+ while ((bytesRead = in.read(buffer)) > 0) {
+ out.write(buffer, 0, bytesRead);
+ }
}
- out.close();
java.io.File file = new File("target/FOO.avro");
- DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(file, datumReader);
- GenericRecord user = null;
- while (dataFileReader.hasNext()) {
- user = dataFileReader.next(user);
+ try (DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(file, datumReader)) {
+ GenericRecord user = null;
+ while (dataFileReader.hasNext()) {
+ user = dataFileReader.next(user);
+ }
}
file.delete();
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestHdfsBolt.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestHdfsBolt.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestHdfsBolt.java
index e8f0702..9386c9f 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestHdfsBolt.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestHdfsBolt.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -44,7 +45,7 @@ import org.junit.Assert;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+
import static org.mockito.Mockito.*;
import org.apache.hadoop.conf.Configuration;
@@ -59,40 +60,50 @@ import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+@RunWith(MockitoJUnitRunner.class)
public class TestHdfsBolt {
+ @Rule
+ public MiniDFSClusterRule dfsClusterRule = new MiniDFSClusterRule(new MiniDFSClusterRule.Java7Supplier<Configuration>() {
+ @Override
+ public Configuration get() {
+ Configuration conf = new Configuration();
+ conf.set("fs.trash.interval", "10");
+ conf.setBoolean("dfs.permissions", true);
+ File baseDir = new File("./target/hdfs/").getAbsoluteFile();
+ FileUtil.fullyDelete(baseDir);
+ conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
+ return conf;
+ }
+ });
+
private String hdfsURI;
private DistributedFileSystem fs;
- private MiniDFSCluster hdfsCluster;
private static final String testRoot = "/unittest";
Tuple tuple1 = generateTestTuple(1, "First Tuple", "SFO", "CA");
Tuple tuple2 = generateTestTuple(1, "Second Tuple", "SJO", "CA");
- @Mock private OutputCollector collector;
- @Mock private TopologyContext topologyContext;
- @Rule public ExpectedException thrown = ExpectedException.none();
+ @Mock
+ private OutputCollector collector;
+ @Mock
+ private TopologyContext topologyContext;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() throws Exception {
- MockitoAnnotations.initMocks(this);
- Configuration conf = new Configuration();
- conf.set("fs.trash.interval", "10");
- conf.setBoolean("dfs.permissions", true);
- File baseDir = new File("./target/hdfs/").getAbsoluteFile();
- FileUtil.fullyDelete(baseDir);
- conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
-
- MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
+ fs = dfsClusterRule.getDfscluster().getFileSystem();
+ hdfsURI = "hdfs://localhost:" + dfsClusterRule.getDfscluster().getNameNodePort() + "/";
}
@After
public void shutDown() throws IOException {
fs.close();
- hdfsCluster.shutdown();
}
@Test
@@ -134,8 +145,7 @@ public class TestHdfsBolt {
}
@Test
- public void testTwoTuplesOneFile() throws IOException
- {
+ public void testTwoTuplesOneFile() throws IOException {
HdfsBolt bolt = makeHdfsBolt(hdfsURI, 2, 10000f);
bolt.prepare(new Config(), topologyContext, collector);
bolt.execute(tuple1);
@@ -150,8 +160,7 @@ public class TestHdfsBolt {
}
@Test
- public void testFailedSync() throws IOException
- {
+ public void testFailedSync() throws IOException {
HdfsBolt bolt = makeHdfsBolt(hdfsURI, 2, 10000f);
bolt.prepare(new Config(), topologyContext, collector);
bolt.execute(tuple1);
@@ -167,27 +176,23 @@ public class TestHdfsBolt {
// One tuple and one rotation should yield one file with data
// The failed executions should not cause rotations and any new files
@Test
- public void testFailureFilecount() throws IOException, InterruptedException
- {
+ public void testFailureFilecount() throws IOException, InterruptedException {
HdfsBolt bolt = makeHdfsBolt(hdfsURI, 1, .000001f);
bolt.prepare(new Config(), topologyContext, collector);
bolt.execute(tuple1);
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
- try
- {
+ try {
bolt.execute(tuple2);
} catch (RuntimeException e) {
//
}
- try
- {
+ try {
bolt.execute(tuple2);
} catch (RuntimeException e) {
//
}
- try
- {
+ try {
bolt.execute(tuple2);
} catch (RuntimeException e) {
//
@@ -198,8 +203,7 @@ public class TestHdfsBolt {
}
@Test
- public void testTickTuples() throws IOException
- {
+ public void testTickTuples() throws IOException {
HdfsBolt bolt = makeHdfsBolt(hdfsURI, 10, 10000f);
bolt.prepare(new Config(), topologyContext, collector);
@@ -226,36 +230,28 @@ public class TestHdfsBolt {
SyncPolicy fieldsSyncPolicy = new CountSyncPolicy(countSync);
FileRotationPolicy fieldsRotationPolicy =
- new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
+ new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
FileNameFormat fieldsFileNameFormat = new DefaultFileNameFormat().withPath(testRoot);
return new HdfsBolt()
- .withFsUrl(nameNodeAddr)
- .withFileNameFormat(fieldsFileNameFormat)
- .withRecordFormat(fieldsFormat)
- .withRotationPolicy(fieldsRotationPolicy)
- .withSyncPolicy(fieldsSyncPolicy);
+ .withFsUrl(nameNodeAddr)
+ .withFileNameFormat(fieldsFileNameFormat)
+ .withRecordFormat(fieldsFormat)
+ .withRotationPolicy(fieldsRotationPolicy)
+ .withSyncPolicy(fieldsSyncPolicy);
}
- private Tuple generateTestTuple(Object id, Object msg,Object city,Object state) {
+ private Tuple generateTestTuple(Object id, Object msg, Object city, Object state) {
TopologyBuilder builder = new TopologyBuilder();
GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(),
- new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
+ new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
@Override
public Fields getComponentOutputFields(String componentId, String streamId) {
- return new Fields("id", "msg","city","state");
+ return new Fields("id", "msg", "city", "state");
}
};
- return new TupleImpl(topologyContext, new Values(id, msg,city,state), 1, "");
- }
-
- private void printFiles(String path) throws IOException {
- Path p = new Path(path);
- FileStatus[] fileStatuses = fs.listStatus(p);
- for (FileStatus file : fileStatuses) {
- System.out.println("@@@ " + file.getPath() + " [" + file.getLen() + "]");
- }
+ return new TupleImpl(topologyContext, new Values(id, msg, city, state), 1, "");
}
// Generally used to compare how files were actually written and compare to expectations based on total
@@ -264,9 +260,11 @@ public class TestHdfsBolt {
Path p = new Path(path);
int nonZero = 0;
- for (FileStatus file : fs.listStatus(p))
- if (file.getLen() > 0)
+ for (FileStatus file : fs.listStatus(p)) {
+ if (file.getLen() > 0) {
nonZero++;
+ }
+ }
return nonZero;
}
@@ -275,9 +273,11 @@ public class TestHdfsBolt {
Path p = new Path(path);
int zeroLength = 0;
- for (FileStatus file : fs.listStatus(p))
- if (file.getLen() == 0)
+ for (FileStatus file : fs.listStatus(p)) {
+ if (file.getLen() == 0) {
zeroLength++;
+ }
+ }
return zeroLength;
}
http://git-wip-us.apache.org/repos/asf/storm/blob/a0308efd/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestSequenceFileBolt.java
----------------------------------------------------------------------
diff --git a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestSequenceFileBolt.java b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestSequenceFileBolt.java
index 9913d9d..7fee578 100644
--- a/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestSequenceFileBolt.java
+++ b/external/storm-hdfs/src/test/java/org/apache/storm/hdfs/bolt/TestSequenceFileBolt.java
@@ -1,3 +1,4 @@
+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -17,8 +18,10 @@
*/
package org.apache.storm.hdfs.bolt;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
import org.apache.storm.Config;
-import org.apache.storm.Constants;
import org.apache.storm.task.GeneralTopologyContext;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
@@ -39,13 +42,10 @@ import org.junit.*;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import static org.mockito.Mockito.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
@@ -56,42 +56,51 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
+import org.apache.storm.hdfs.testing.MiniDFSClusterRule;
+import org.junit.runner.RunWith;
+import org.mockito.runners.MockitoJUnitRunner;
+@RunWith(MockitoJUnitRunner.class)
public class TestSequenceFileBolt {
private static final Logger LOG = LoggerFactory.getLogger(TestSequenceFileBolt.class);
+ @Rule
+ public MiniDFSClusterRule dfsClusterRule = new MiniDFSClusterRule(new MiniDFSClusterRule.Java7Supplier<Configuration>() {
+ @Override
+ public Configuration get() {
+ Configuration conf = new Configuration();
+ conf.set("fs.trash.interval", "10");
+ conf.setBoolean("dfs.permissions", true);
+ File baseDir = new File("./target/hdfs/").getAbsoluteFile();
+ FileUtil.fullyDelete(baseDir);
+ conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
+ return conf;
+ }
+ });
+
private String hdfsURI;
private DistributedFileSystem fs;
- private MiniDFSCluster hdfsCluster;
private static final String testRoot = "/unittest";
Tuple tuple1 = generateTestTuple(1l, "first tuple");
Tuple tuple2 = generateTestTuple(2l, "second tuple");
- @Mock private OutputCollector collector;
- @Mock private TopologyContext topologyContext;
- @Rule public ExpectedException thrown = ExpectedException.none();
+ @Mock
+ private OutputCollector collector;
+ @Mock
+ private TopologyContext topologyContext;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() throws Exception {
- MockitoAnnotations.initMocks(this);
- Configuration conf = new Configuration();
- conf.set("fs.trash.interval", "10");
- conf.setBoolean("dfs.permissions", true);
- File baseDir = new File("./target/hdfs/").getAbsoluteFile();
- FileUtil.fullyDelete(baseDir);
- conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
-
- MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
- hdfsCluster = builder.build();
- fs = hdfsCluster.getFileSystem();
- hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort() + "/";
+ fs = dfsClusterRule.getDfscluster().getFileSystem();
+ hdfsURI = "hdfs://localhost:" + dfsClusterRule.getDfscluster().getNameNodePort() + "/";
}
@After
public void shutDown() throws IOException {
fs.close();
- hdfsCluster.shutdown();
}
@Test
@@ -109,8 +118,7 @@ public class TestSequenceFileBolt {
}
@Test
- public void testTwoTuplesOneFile() throws IOException
- {
+ public void testTwoTuplesOneFile() throws IOException {
SequenceFileBolt bolt = makeSeqBolt(hdfsURI, 2, 10000f);
bolt.prepare(new Config(), topologyContext, collector);
bolt.execute(tuple1);
@@ -125,8 +133,7 @@ public class TestSequenceFileBolt {
}
@Test
- public void testFailedSync() throws IOException
- {
+ public void testFailedSync() throws IOException {
SequenceFileBolt bolt = makeSeqBolt(hdfsURI, 2, 10000f);
bolt.prepare(new Config(), topologyContext, collector);
bolt.execute(tuple1);
@@ -142,24 +149,24 @@ public class TestSequenceFileBolt {
SyncPolicy fieldsSyncPolicy = new CountSyncPolicy(countSync);
FileRotationPolicy fieldsRotationPolicy =
- new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
+ new FileSizeRotationPolicy(rotationSizeMB, FileSizeRotationPolicy.Units.MB);
FileNameFormat fieldsFileNameFormat = new DefaultFileNameFormat().withPath(testRoot);
SequenceFormat seqFormat = new DefaultSequenceFormat("key", "value");
return new SequenceFileBolt()
- .withFsUrl(nameNodeAddr)
- .withFileNameFormat(fieldsFileNameFormat)
- .withRotationPolicy(fieldsRotationPolicy)
- .withSequenceFormat(seqFormat)
- .withSyncPolicy(fieldsSyncPolicy);
+ .withFsUrl(nameNodeAddr)
+ .withFileNameFormat(fieldsFileNameFormat)
+ .withRotationPolicy(fieldsRotationPolicy)
+ .withSequenceFormat(seqFormat)
+ .withSyncPolicy(fieldsSyncPolicy);
}
private Tuple generateTestTuple(Long key, String value) {
TopologyBuilder builder = new TopologyBuilder();
GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(),
- new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
+ new Config(), new HashMap(), new HashMap(), new HashMap(), "") {
@Override
public Fields getComponentOutputFields(String componentId, String streamId) {
return new Fields("key", "value");