method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ExpressionParserFunctions { public static DateTime nowAmericaLosAngeles() { return nowInZone("America/Los_Angeles"); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer:
@Test public void nowAmericaLosAngeles() { DateTime now = ExpressionParserFunctions.nowAmericaLosAngeles(); assertThat(now.getZone(), is(DateTimeZone.forID("America/Los_Angeles"))); } |
### Question:
HousekeepingRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { Instant deletionCutoff = new Instant().minus(housekeeping.getExpiredPathDuration()); LOG.info("Housekeeping at instant {} has started", deletionCutoff); CompletionCode completionCode = CompletionCode.SUCCESS; try { housekeepingService.cleanUp(deletionCutoff); LOG.info("Housekeeping at instant {} has finished", deletionCutoff); } catch (Exception e) { completionCode = CompletionCode.FAILURE; LOG.error("Housekeeping at instant {} has failed", deletionCutoff, e); throw e; } finally { Map<String, Long> metricsMap = ImmutableMap .<String, Long>builder() .put("housekeeping", completionCode.getCode()) .build(); metricSender.send(metricsMap); } } @Autowired HousekeepingRunner(Housekeeping housekeeping, HousekeepingService housekeepingService, MetricSender metricSender); @Override void run(ApplicationArguments args); }### Answer:
@Test public void typical() throws Exception { ArgumentCaptor<Instant> instantCaptor = ArgumentCaptor.forClass(Instant.class); runner.run(null); verify(cleanUpPathService).cleanUp(instantCaptor.capture()); Instant twoDaysAgo = new Instant().minus(TWO_DAYS_DURATION.getMillis()); assertThat(instantCaptor.getValue().getMillis(), is(lessThanOrEqualTo(twoDaysAgo.getMillis()))); }
@Test(expected = IllegalStateException.class) public void rethrowException() throws Exception { doThrow(new IllegalStateException()).when(cleanUpPathService).cleanUp(any(Instant.class)); runner.run(null); } |
### Question:
ExpressionParserFunctions { public static String zeroPadLeft(int value, int width) { return zeroPadLeft(Integer.toString(value), width); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer:
@Test public void zeroPadLeftString() { assertThat(ExpressionParserFunctions.zeroPadLeft("A", 3), is("00A")); assertThat(ExpressionParserFunctions.zeroPadLeft("AAA", 3), is("AAA")); assertThat(ExpressionParserFunctions.zeroPadLeft("", 1), is("0")); }
@Test public void zeroPadLeftInt() { assertThat(ExpressionParserFunctions.zeroPadLeft(1, 3), is("001")); assertThat(ExpressionParserFunctions.zeroPadLeft(111, 3), is("111")); } |
### Question:
SpringExpressionParser { public String parse(String expressionString) { if (expressionString != null) { Expression expression = parser.parseExpression(expressionString, templateContext); expressionString = expression.getValue(evalContext).toString(); } return expressionString; } SpringExpressionParser(); SpringExpressionParser(Class<?>... functionHolders); String parse(String expressionString); }### Answer:
@Test public void literal() { assertThat(parser.parse("local_hour > 0"), is("local_hour > 0")); }
@Test public void empty() { assertThat(parser.parse(""), is("")); }
@Test public void blank() { assertThat(parser.parse(" "), is(" ")); }
@Test public void nullValue() { assertThat(parser.parse(null), is((Object) null)); }
@Test public void literalWithNowFunction() { assertThat(parser.parse("local_date > #{ #now().minusDays(30).toString('yyyy-MM-dd')}"), is("local_date > 2016-02-23")); }
@Test public void spaceBeforeRootContextReference() { assertThat(parser.parse("local_date >= '#{ #nowUtc().minusDays(2).toString(\"yyyy-MM-dd\") }'"), is("local_date >= '2016-03-22'")); } |
### Question:
HousekeepingCleanupLocationManager implements CleanupLocationManager { @Override public void scheduleLocations() throws CircusTrainException { try { List<URI> uris = new ArrayList<>(); for (CleanupLocation location : locations) { LOG.info("Scheduling old replica data for deletion for event {}: {}", eventId, location.path.toUri()); housekeepingListener .cleanUpLocation(eventId, location.pathEventId, location.path, location.replicaDatabase, location.replicaTable); uris.add(location.path.toUri()); } replicaCatalogListener.deprecatedReplicaLocations(uris); } finally { locations.clear(); } } HousekeepingCleanupLocationManager(
String eventId,
HousekeepingListener housekeepingListener,
ReplicaCatalogListener replicaCatalogListener,
String replicaDatabase,
String replicaTable); @Override void scheduleLocations(); @Override void addCleanupLocation(String pathEventId, Path location); }### Answer:
@Test public void scheduleLocations() throws Exception { HousekeepingCleanupLocationManager manager = new HousekeepingCleanupLocationManager(EVENT_ID, housekeepingListener, replicaCatalogListener, DATABASE, TABLE); String pathEventId = "pathEventId"; Path path = new Path("location1"); manager.addCleanupLocation(pathEventId, path); manager.scheduleLocations(); verify(housekeepingListener).cleanUpLocation(EVENT_ID, pathEventId, path, DATABASE, TABLE); List<URI> uris = Lists.newArrayList(path.toUri()); verify(replicaCatalogListener).deprecatedReplicaLocations(uris); } |
### Question:
RenameTableOperation { public void execute(CloseableMetaStoreClient client, Table from, Table to) throws Exception { LOG .info("Renaming table {}.{} to {}.{}", from.getDbName(), from.getTableName(), to.getDbName(), to.getTableName()); Table fromTable = client.getTable(from.getDbName(), from.getTableName()); Table toTable = client.getTable(to.getDbName(), to.getTableName()); String fromTableName = fromTable.getTableName(); String toTableName = toTable.getTableName(); String toDelete = toTableName + DELETE_ME; try { fromTable.setTableName(toTableName); toTable.setTableName(toDelete); client.alter_table(toTable.getDbName(), toTableName, toTable); client.alter_table(fromTable.getDbName(), fromTableName, fromTable); } finally { dropTableService.dropTable(client, toTable.getDbName(), toDelete); } } RenameTableOperation(DropTableService dropTableService); void execute(CloseableMetaStoreClient client, Table from, Table to); }### Answer:
@Test public void typicalRenameTable() throws Exception { Table toTableTemp = new Table(toTable); toTableTemp.setTableName(TO_TABLE_NAME_TEMP); operation.execute(client, fromTable, toTable); fromTable.setTableName(TO_TABLE_NAME); verify(client).alter_table(TO_DB_NAME, TO_TABLE_NAME, toTableTemp); verify(client).alter_table(FROM_DB_NAME, FROM_TABLE_NAME, fromTable); verify(dropTableService).dropTable(client, TO_DB_NAME, TO_TABLE_NAME_TEMP); }
@Test public void renameToTableException() throws Exception { Table toTableTemp = new Table(toTable); toTableTemp.setTableName(TO_TABLE_NAME_TEMP); TException toBeThrown = new TException(); doThrow(toBeThrown).when(client).alter_table(TO_DB_NAME, TO_TABLE_NAME, toTableTemp); try { operation.execute(client, fromTable, toTable); fail("Should throw exception."); } catch (Exception e) { verify(client).getTable(FROM_DB_NAME, FROM_TABLE_NAME); verify(client).getTable(TO_DB_NAME, TO_TABLE_NAME); fromTable.setTableName(TO_TABLE_NAME); verify(client).alter_table(TO_DB_NAME, TO_TABLE_NAME, toTableTemp); verify(dropTableService).dropTable(client, TO_DB_NAME, TO_TABLE_NAME_TEMP); verifyNoMoreInteractions(client); assertThat(e, is(toBeThrown)); } }
@Test public void renameFromTableException() throws Exception { Table toTableTemp = new Table(toTable); toTableTemp.setTableName(TO_TABLE_NAME_TEMP); TException toBeThrown = new TException(); doThrow(toBeThrown).when(client).alter_table(FROM_DB_NAME, FROM_TABLE_NAME, fromTable); try { operation.execute(client, fromTable, toTable); fail("Should throw exception."); } catch (Exception e) { verify(client).getTable(FROM_DB_NAME, FROM_TABLE_NAME); verify(client).getTable(TO_DB_NAME, TO_TABLE_NAME); fromTable.setTableName(TO_TABLE_NAME); verify(client).alter_table(TO_DB_NAME, TO_TABLE_NAME, toTableTemp); verify(client).alter_table(FROM_DB_NAME, FROM_TABLE_NAME, fromTable); verify(dropTableService).dropTable(client, TO_DB_NAME, TO_TABLE_NAME_TEMP); verifyNoMoreInteractions(client); assertThat(e, is(toBeThrown)); } } |
### Question:
HiveObjectUtils { public static String getParameter(Table table, String parameter) { return getParameter(table.getParameters(), table.getSd().getSerdeInfo().getParameters(), parameter); } private HiveObjectUtils(); static String getParameter(Table table, String parameter); static String getParameter(Partition partition, String parameter); static Table updateSerDeUrl(Table table, String parameter, String url); static Partition updateSerDeUrl(Partition partition, String parameter, String url); }### Answer:
@Test public void getParameterFromTablesTableProperties() { Table table = newTable(); table.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); assertThat(HiveObjectUtils.getParameter(table, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromTablesSerDeProperties() { Table table = newTable(); table.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); assertThat(HiveObjectUtils.getParameter(table, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromTableWhichIsntSetReturnsNull() { Table table = newTable(); assertThat(HiveObjectUtils.getParameter(table, AVRO_SCHEMA_URL_PARAMETER), is(nullValue())); }
@Test public void getParameterFromTablePropertiesWhenSerDePropertiesAreAlsoSetInTable() { Table table = newTable(); table.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); table.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "foo"); assertThat(HiveObjectUtils.getParameter(table, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromPartitionsTableProperties() { Partition partition = newPartition(); partition.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); assertThat(HiveObjectUtils.getParameter(partition, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromPartitionsSerDeProperties() { Partition partition = newPartition(); partition.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); assertThat(HiveObjectUtils.getParameter(partition, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromTablePropertiesWhenSerDePropertiesAreAlsoSetInPartition() { Partition partition = newPartition(); partition.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); partition.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "foo"); assertThat(HiveObjectUtils.getParameter(partition, AVRO_SCHEMA_URL_PARAMETER), is("test")); }
@Test public void getParameterFromPartitionWhichIsntSetReturnsNull() { Partition partition = newPartition(); assertTrue(HiveObjectUtils.getParameter(partition, AVRO_SCHEMA_URL_PARAMETER) == null); } |
### Question:
CleanupLocationManagerFactory { public static CleanupLocationManager newInstance(String eventId, HousekeepingListener housekeepingListener, ReplicaCatalogListener replicaCatalogListener, TableReplication tableReplication) { if (tableReplication.getReplicationMode() == ReplicationMode.FULL && tableReplication.getOrphanedDataStrategy() == OrphanedDataStrategy.HOUSEKEEPING) { return new HousekeepingCleanupLocationManager(eventId, housekeepingListener, replicaCatalogListener, tableReplication.getReplicaDatabaseName(), tableReplication.getReplicaTableName()); } else { return CleanupLocationManager.NULL_CLEANUP_LOCATION_MANAGER; } } static CleanupLocationManager newInstance(String eventId, HousekeepingListener housekeepingListener,
ReplicaCatalogListener replicaCatalogListener, TableReplication tableReplication); }### Answer:
@Test public void typicalHousekeepingCleanupLocationManager() { ReplicaTable table = new ReplicaTable(); table.setDatabaseName("database"); table.setTableName("table"); TableReplication tableReplication = new TableReplication(); tableReplication.setReplicaTable(table); tableReplication.setReplicationMode(ReplicationMode.FULL); tableReplication.setOrphanedDataStrategy(OrphanedDataStrategy.HOUSEKEEPING); CleanupLocationManager cleanupLocationManager = CleanupLocationManagerFactory.newInstance(eventId, housekeepingListener, replicaCatalogListener, tableReplication); assertThat(cleanupLocationManager, instanceOf(HousekeepingCleanupLocationManager.class)); }
@Test public void notHousekeepingNullCleanupLocationManager() { TableReplication tableReplication = new TableReplication(); tableReplication.setReplicationMode(ReplicationMode.FULL); tableReplication.setOrphanedDataStrategy(OrphanedDataStrategy.NONE); CleanupLocationManager cleanupLocationManager = CleanupLocationManagerFactory.newInstance(eventId, housekeepingListener, replicaCatalogListener, tableReplication); assertThat(cleanupLocationManager, instanceOf(CleanupLocationManager.NULL_CLEANUP_LOCATION_MANAGER.getClass())); }
@Test public void metatdataMirrorNullCleanupLocationManager() { TableReplication tableReplication = new TableReplication(); tableReplication.setReplicationMode(ReplicationMode.METADATA_MIRROR); tableReplication.setOrphanedDataStrategy(OrphanedDataStrategy.HOUSEKEEPING); CleanupLocationManager cleanupLocationManager = CleanupLocationManagerFactory.newInstance(eventId, housekeepingListener, replicaCatalogListener, tableReplication); assertThat(cleanupLocationManager, instanceOf(CleanupLocationManager.NULL_CLEANUP_LOCATION_MANAGER.getClass())); }
@Test public void metatdataUpdateNullCleanupLocationManager() { TableReplication tableReplication = new TableReplication(); tableReplication.setReplicationMode(ReplicationMode.METADATA_UPDATE); tableReplication.setOrphanedDataStrategy(OrphanedDataStrategy.HOUSEKEEPING); CleanupLocationManager cleanupLocationManager = CleanupLocationManagerFactory.newInstance(eventId, housekeepingListener, replicaCatalogListener, tableReplication); assertThat(cleanupLocationManager, instanceOf(CleanupLocationManager.NULL_CLEANUP_LOCATION_MANAGER.getClass())); } |
### Question:
DestructiveReplica { public boolean tableIsUnderCircusTrainControl() throws TException { try (CloseableMetaStoreClient client = replicaMetaStoreClientSupplier.get()) { if (!client.tableExists(databaseName, tableName)) { return true; } String sourceTableParameterValue = client .getTable(databaseName, tableName) .getParameters() .get(CircusTrainTableParameter.SOURCE_TABLE.parameterName()); if (sourceTableParameterValue != null) { String qualifiedName = tableReplication.getSourceTable().getQualifiedName(); return qualifiedName.equals(sourceTableParameterValue); } } return false; } DestructiveReplica(
Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier,
CleanupLocationManager cleanupLocationManager,
TableReplication tableReplication); boolean tableIsUnderCircusTrainControl(); void dropDeletedPartitions(final List<String> sourcePartitionNames); void dropTable(); }### Answer:
@Test public void tableIsUnderCircusTrainControl() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); assertThat(replica.tableIsUnderCircusTrainControl(), is(true)); verify(client).close(); }
@Test public void tableIsUnderCircusTrainControlTableDoesNotExist() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(false); assertThat(replica.tableIsUnderCircusTrainControl(), is(true)); verify(client).close(); }
@Test public void tableIsUnderCircusTrainControlParameterDoesNotMatch() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); table.putToParameters(CircusTrainTableParameter.SOURCE_TABLE.parameterName(), "different.table"); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); assertThat(replica.tableIsUnderCircusTrainControl(), is(false)); verify(client).close(); }
@Test public void tableIsUnderCircusTrainControlParameterIsNull() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); Map<String, String> parameters = new HashMap<>(); table.setParameters(parameters); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); assertThat(replica.tableIsUnderCircusTrainControl(), is(false)); verify(client).close(); } |
### Question:
DestructiveReplica { public void dropDeletedPartitions(final List<String> sourcePartitionNames) throws TException { try (CloseableMetaStoreClient client = replicaMetaStoreClientSupplier.get()) { if (!client.tableExists(databaseName, tableName)) { return; } dropAndDeletePartitions(client, new Predicate<String>() { @Override public boolean apply(String partitionName) { return !sourcePartitionNames.contains(partitionName); } }); } finally { cleanupLocationManager.scheduleLocations(); } } DestructiveReplica(
Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier,
CleanupLocationManager cleanupLocationManager,
TableReplication tableReplication); boolean tableIsUnderCircusTrainControl(); void dropDeletedPartitions(final List<String> sourcePartitionNames); void dropTable(); }### Answer:
@Test public void dropDeletedPartitions() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); Path location1 = new Path("loc1"); Partition replicaPartition1 = newPartition("value1", location1); Path location2 = new Path("loc2"); Partition replicaPartition2 = newPartition("value2", location2); List<Partition> replicaPartitions = Lists.newArrayList(replicaPartition1, replicaPartition2); mockPartitionIterator(replicaPartitions); List<String> sourcePartitionNames = Lists.newArrayList(); replica.dropDeletedPartitions(sourcePartitionNames); verify(client).dropPartition(DATABASE, REPLICA_TABLE, "part1=value1", false); verify(client).dropPartition(DATABASE, REPLICA_TABLE, "part1=value2", false); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, location1); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, location2); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); }
@Test public void dropDeletedPartitionsTableDoesNotExist() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(false); replica.dropDeletedPartitions(Lists.<String> newArrayList()); verify(client, never()).dropPartition(eq(DATABASE), eq(REPLICA_TABLE), anyString(), anyBoolean()); verify(cleanupLocationManager, never()).addCleanupLocation(anyString(), any(Path.class)); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); }
@Test public void dropDeletedPartitionsNothingToDrop() throws Exception { when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); Partition replicaPartition = new Partition(); replicaPartition.setValues(Lists.newArrayList("value1")); List<Partition> replicaPartitions = Lists.newArrayList(replicaPartition); mockPartitionIterator(replicaPartitions); List<String> sourcePartitionNames = Lists.newArrayList("part1=value1"); replica.dropDeletedPartitions(sourcePartitionNames); verify(client, never()).dropPartition(DATABASE, REPLICA_TABLE, "part1=value1", false); verify(cleanupLocationManager, never()).addCleanupLocation(anyString(), any(Path.class)); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); }
@Test public void dropDeletedPartitionsUnpartitionedTable() throws Exception { table.setPartitionKeys(null); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); List<String> sourcePartitionNames = Lists.newArrayList(); replica.dropDeletedPartitions(sourcePartitionNames); verify(client, never()).dropPartition(eq(DATABASE), eq(REPLICA_TABLE), anyString(), eq(false)); verify(cleanupLocationManager, never()).addCleanupLocation(anyString(), any(Path.class)); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); } |
### Question:
DestructiveReplica { public void dropTable() throws TException { try { try (CloseableMetaStoreClient client = replicaMetaStoreClientSupplier.get()) { if (!client.tableExists(databaseName, tableName)) { return; } dropAndDeletePartitions(client, Predicates.<String> alwaysTrue()); Table table = client.getTable(databaseName, tableName); log.info("Dropping replica table: " + databaseName + "." + tableName); client.dropTable(databaseName, tableName, DELETE_DATA, IGNORE_UNKNOWN); Path oldLocation = locationAsPath(table); String oldEventId = table.getParameters().get(REPLICATION_EVENT.parameterName()); cleanupLocationManager.addCleanupLocation(oldEventId, oldLocation); } } finally { cleanupLocationManager.scheduleLocations(); } } DestructiveReplica(
Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier,
CleanupLocationManager cleanupLocationManager,
TableReplication tableReplication); boolean tableIsUnderCircusTrainControl(); void dropDeletedPartitions(final List<String> sourcePartitionNames); void dropTable(); }### Answer:
@Test public void dropTablePartitioned() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); Path location1 = new Path("loc1"); Partition replicaPartition1 = newPartition("value1", location1); Path location2 = new Path("loc2"); Partition replicaPartition2 = newPartition("value2", location2); List<Partition> replicaPartitions = Lists.newArrayList(replicaPartition1, replicaPartition2); mockPartitionIterator(replicaPartitions); replica.dropTable(); verify(client).dropPartition(DATABASE, REPLICA_TABLE, "part1=value1", false); verify(client).dropPartition(DATABASE, REPLICA_TABLE, "part1=value2", false); verify(client).dropTable(DATABASE, REPLICA_TABLE, false, true); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, location1); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, location2); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, tableLocation); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); }
@Test public void dropTableButTableDoesNotExist() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(false); List<Partition> replicaPartitions = Lists.newArrayList(); mockPartitionIterator(replicaPartitions); replica.dropTable(); verify(client, never()).dropPartition(eq(DATABASE), eq(REPLICA_TABLE), anyString(), anyBoolean()); verify(client, never()).dropTable(eq(DATABASE), eq(REPLICA_TABLE), anyBoolean(), anyBoolean()); verify(cleanupLocationManager, never()).addCleanupLocation(anyString(), any(Path.class)); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); }
@Test public void dropTableUnpartitioned() throws Exception { when(client.tableExists(DATABASE, REPLICA_TABLE)).thenReturn(true); table.setPartitionKeys(null); when(client.getTable(DATABASE, REPLICA_TABLE)).thenReturn(table); replica.dropTable(); verify(client).dropTable(DATABASE, REPLICA_TABLE, false, true); verify(cleanupLocationManager).addCleanupLocation(EVENT_ID, tableLocation); verify(client).close(); verify(cleanupLocationManager).scheduleLocations(); } |
### Question:
ReplicaTableFactoryProvider { public ReplicaTableFactory newInstance(TableReplication tableReplication) { if (tableReplication.getSourceTable().isGeneratePartitionFilter()) { return new AddCheckSumReplicaTableFactory(sourceHiveConf, checksumFunction, tableTransformation, partitionTransformation, columnStatisticsTransformation); } return new ReplicaTableFactory(sourceHiveConf, tableTransformation, partitionTransformation, columnStatisticsTransformation); } @Autowired ReplicaTableFactoryProvider(
@Value("#{sourceHiveConf}") HiveConf sourceHiveConf,
@Value("#{checksumFunction}") Function<Path, String> checksumFunction,
TableTransformation tableTransformation,
PartitionTransformation partitionTransformation,
ColumnStatisticsTransformation columnStatisticsTransformation); ReplicaTableFactory newInstance(TableReplication tableReplication); }### Answer:
@Test public void newInstanceReturnsReplicaTableFactory() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(false); ReplicaTableFactory factory = picker.newInstance(tableReplication); assertThat(factory, instanceOf(ReplicaTableFactory.class)); assertThat(factory, not(instanceOf(AddCheckSumReplicaTableFactory.class))); }
@Test public void newInstanceReturnsAddChecksumReplicaTableFactory() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(true); ReplicaTableFactory factory = picker.newInstance(tableReplication); assertThat(factory, instanceOf(AddCheckSumReplicaTableFactory.class)); } |
### Question:
AddCheckSumReplicaTableFactory extends ReplicaTableFactory { @Override Partition newReplicaPartition( String eventId, Table sourceTable, Partition sourcePartition, String replicaDatabaseName, String replicaTableName, Path replicaPartitionLocation, ReplicationMode replicationMode) { Partition replica = super.newReplicaPartition(eventId, sourceTable, sourcePartition, replicaDatabaseName, replicaTableName, replicaPartitionLocation, replicationMode); String checksum = checksumFunction.apply(locationAsPath(sourcePartition)); replica.putToParameters(PARTITION_CHECKSUM.parameterName(), checksum); return replica; } AddCheckSumReplicaTableFactory(
HiveConf sourceHiveConf,
Function<Path, String> checksumFunction,
TableTransformation tableTransformation,
PartitionTransformation partitionTransformation,
ColumnStatisticsTransformation columnStatisticsTransformation); }### Answer:
@Test public void newReplicaPartition() throws Exception { Path sourceTableLocationPath = new Path(sourcePartitionFile.toURI().toString()); when(checksumFunction.apply(sourceTableLocationPath)).thenReturn("checksum"); Partition partition = factory.newReplicaPartition("eventId", sourceTable, sourcePartition, "replicaDatabase", "replicaTable", replicaPartitionLocation, FULL); assertThat(partition.getParameters().get(PARTITION_CHECKSUM.parameterName()), is("checksum")); } |
### Question:
MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() throws CircusTrainException { return sourceLocationManager.getTableLocation(); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test public void unpartitionedTableLocation() throws Exception { when(sourceLocationManager.getTableLocation()).thenReturn(TABLE_LOCATION); MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); assertThat(replicaLocationManager.getTableLocation(), is(TABLE_LOCATION)); }
@Test public void unpartitionedTableEmptyLocation() throws Exception { when(sourceLocationManager.getTableLocation()).thenReturn(null); MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); assertThat(replicaLocationManager.getTableLocation(), is(nullValue())); } |
### Question:
MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() throws CircusTrainException { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } return getTableLocation(); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionBaseTableLocation() throws Exception { MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); replicaLocationManager.getPartitionBaseLocation(); } |
### Question:
MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } if (!LocationUtils.hasLocation(sourcePartition)) { return null; } return new Path(sourcePartition.getSd().getLocation()); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionLocation() throws Exception { MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); replicaLocationManager.getPartitionLocation(sourcePartition); } |
### Question:
S3S3CopierOptions { public Long getMultipartCopyPartSize() { return MapUtils.getLong(copierOptions, Keys.MULTIPART_COPY_PART_SIZE.keyName(), null); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer:
@Test public void getMultipartCopyPartSize() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.MULTIPART_COPY_PART_SIZE.keyName(), 128L); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMultipartCopyPartSize(), is(128L)); }
@Test public void getMultipartCopyPartSizeDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getMultipartCopyPartSize()); } |
### Question:
HiveObjectUtils { public static Table updateSerDeUrl(Table table, String parameter, String url) { updateSerDeUrl(table.getParameters(), table.getSd().getSerdeInfo().getParameters(), parameter, url); return table; } private HiveObjectUtils(); static String getParameter(Table table, String parameter); static String getParameter(Partition partition, String parameter); static Table updateSerDeUrl(Table table, String parameter, String url); static Partition updateSerDeUrl(Partition partition, String parameter, String url); }### Answer:
@Test public void updateUrlInTable() { Table table = newTable(); table.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); table.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); HiveObjectUtils.updateSerDeUrl(table, AVRO_SCHEMA_URL_PARAMETER, "updatedUrl"); assertThat(table.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is("updatedUrl")); assertThat(table.getSd().getSerdeInfo().getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(nullValue())); }
@Test public void updateUrlInPartition() { Partition partition = newPartition(); partition.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); partition.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); HiveObjectUtils.updateSerDeUrl(partition, AVRO_SCHEMA_URL_PARAMETER, "updatedUrl"); assertThat(partition.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is("updatedUrl")); assertThat(partition.getSd().getSerdeInfo().getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(nullValue())); } |
### Question:
FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() { Path replicaDataLocation = new Path(tablePath); if (tableType == UNPARTITIONED) { replicaDataLocation = new Path(replicaDataLocation, eventId); } LOG.debug("Generated table data destination path: {}", replicaDataLocation.toUri()); replicaCatalogListener.resolvedReplicaLocation(replicaDataLocation.toUri()); return replicaDataLocation; } FullReplicationReplicaLocationManager(
SourceLocationManager sourceLocationManager,
String tablePath,
String eventId,
TableType tableType,
CleanupLocationManager cleanupLocationManager,
ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test public void getTableOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getTableLocation(); assertThat(path, is(new Path(TABLE_PATH, new Path(EVENT_ID)))); }
@Test public void getTableOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getTableLocation(); assertThat(path, is(new Path(TABLE_PATH))); } |
### Question:
FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } Path partitionBasePath = new Path(getTableLocation(), eventId); LOG.debug("Generated partition data destination base path: {}", partitionBasePath.toUri()); return partitionBasePath; } FullReplicationReplicaLocationManager(
SourceLocationManager sourceLocationManager,
String tablePath,
String eventId,
TableType tableType,
CleanupLocationManager cleanupLocationManager,
ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getPartitionBaseOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); manager.getPartitionBaseLocation(); }
@Test public void getPartitionBaseOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getPartitionBaseLocation(); assertThat(path, is(new Path(TABLE_PATH, new Path(EVENT_ID)))); } |
### Question:
FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } Path partitionSubPath = sourceLocationManager.getPartitionSubPath(locationAsPath(sourcePartition)); Path replicaPartitionLocation = new Path(getPartitionBaseLocation(), partitionSubPath); return replicaPartitionLocation; } FullReplicationReplicaLocationManager(
SourceLocationManager sourceLocationManager,
String tablePath,
String eventId,
TableType tableType,
CleanupLocationManager cleanupLocationManager,
ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getPartitionLocationOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); manager.getPartitionLocation(sourcePartition); }
@Test public void getPartitionLocationOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); when(sourcePartition.getSd()).thenReturn(sd); String partitionLocation = TABLE_PATH + "/" + EVENT_ID + "/partitionKey1=value"; when(sd.getLocation()).thenReturn(partitionLocation); when(sourceLocationManager.getPartitionSubPath(new Path(partitionLocation))) .thenReturn(new Path("partitionKey1=value")); Path path = manager.getPartitionLocation(sourcePartition); assertThat(path, is(new Path(partitionLocation))); } |
### Question:
MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() { return new Path(tablePath); } MetadataUpdateReplicaLocationManager(
CloseableMetaStoreClient replicaMetastoreClient,
TableType tableType,
String tablePath,
String replicaDatabaseName,
String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test public void unpartitionedTableLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); assertThat(replicaLocationManager.getTableLocation(), is(tableLocationPath)); } |
### Question:
MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } return getTableLocation(); } MetadataUpdateReplicaLocationManager(
CloseableMetaStoreClient replicaMetastoreClient,
TableType tableType,
String tablePath,
String replicaDatabaseName,
String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionBaseTableLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); replicaLocationManager.getPartitionBaseLocation(); } |
### Question:
MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } try { Partition partition = replicaMetastoreClient.getPartition(replicaDatabaseName, replicaTableName, sourcePartition.getValues()); return new Path(partition.getSd().getLocation()); } catch (TException e) { throw new CircusTrainException("Partition should exist on replica but doesn't", e); } } MetadataUpdateReplicaLocationManager(
CloseableMetaStoreClient replicaMetastoreClient,
TableType tableType,
String tablePath,
String replicaDatabaseName,
String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); replicaLocationManager.getPartitionLocation(sourcePartition); } |
### Question:
ReplicaFactory implements HiveEndpointFactory<Replica> { @Override public Replica newInstance(TableReplication tableReplication) { ReplicaTableFactory replicaTableFactory = replicaTableFactoryPicker.newInstance(tableReplication); DropTableService dropTableService = new DropTableService(); AlterTableService alterTableService = new AlterTableService(dropTableService, new CopyPartitionsOperation(), new RenameTableOperation(dropTableService)); return new Replica(replicaCatalog, replicaHiveConf, replicaMetaStoreClientSupplier, replicaTableFactory, housekeepingListener, replicaCatalogListener, tableReplication, alterTableService); } @Autowired ReplicaFactory(
ReplicaCatalog replicaCatalog,
@Value("#{replicaHiveConf}") HiveConf replicaHiveConf,
Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier,
HousekeepingListener housekeepingListener,
ReplicaCatalogListener replicaCatalogListener,
ReplicaTableFactoryProvider replicaTableFactoryProvider); @Override Replica newInstance(TableReplication tableReplication); }### Answer:
@Test public void defaultReplicaTableFactory() throws Exception { Replica replica = replicaFactory.newInstance(tableReplication); assertNotNull(replica); verify(replicaTableFactoryPicker).newInstance(tableReplication); } |
### Question:
SourceFactory implements HiveEndpointFactory<Source> { @Override public Source newInstance(TableReplication tableReplication) { boolean snapshotsDisabled = true; if (tableReplication.getReplicationMode() == ReplicationMode.FULL) { snapshotsDisabled = sourceCatalog.isDisableSnapshots(); } return new Source(sourceCatalog, sourceHiveConf, sourceMetaStoreClientSupplier, sourceCatalogListener, snapshotsDisabled, tableReplication.getSourceTable().getTableLocation()); } @Autowired SourceFactory(
SourceCatalog sourceCatalog,
@Value("#{sourceHiveConf}") HiveConf sourceHiveConf,
@Value("#{sourceMetaStoreClientSupplier}") Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier,
SourceCatalogListener sourceCatalogListener); @Override Source newInstance(TableReplication tableReplication); }### Answer:
@Test public void newInstanceFullReplicationMode() throws Exception { when(tableReplication.getReplicationMode()).thenReturn(ReplicationMode.FULL); when(sourceCatalog.isDisableSnapshots()).thenReturn(false); SourceFactory sourceFactory = new SourceFactory(sourceCatalog, sourceHiveConf, sourceMetaStoreClientSupplier, sourceCatalogListener); Source source = sourceFactory.newInstance(tableReplication); assertFalse(source.isSnapshotsDisabled()); }
@Test public void newInstanceMetadataMirrorReplicationModeOverridesDisabledSnapshots() throws Exception { when(tableReplication.getReplicationMode()).thenReturn(ReplicationMode.METADATA_MIRROR); when(sourceCatalog.isDisableSnapshots()).thenReturn(false); SourceFactory sourceFactory = new SourceFactory(sourceCatalog, sourceHiveConf, sourceMetaStoreClientSupplier, sourceCatalogListener); Source source = sourceFactory.newInstance(tableReplication); assertTrue(source.isSnapshotsDisabled()); }
@Test public void newInstanceMetadataUpdateReplicationModeOverridesDisabledSnapshots() throws Exception { when(tableReplication.getReplicationMode()).thenReturn(ReplicationMode.METADATA_UPDATE); when(sourceCatalog.isDisableSnapshots()).thenReturn(false); SourceFactory sourceFactory = new SourceFactory(sourceCatalog, sourceHiveConf, sourceMetaStoreClientSupplier, sourceCatalogListener); Source source = sourceFactory.newInstance(tableReplication); assertTrue(source.isSnapshotsDisabled()); } |
### Question:
ViewLocationManager implements SourceLocationManager { @Override public Path getTableLocation() { return null; } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void nullTableLocation() { assertThat(locationManager.getTableLocation(), is(nullValue())); } |
### Question:
ViewLocationManager implements SourceLocationManager { @Override public List<Path> getPartitionLocations() { return Collections.emptyList(); } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void emptyPartitionLocations() { assertThat(locationManager.getPartitionLocations(), is(not(nullValue()))); } |
### Question:
ViewLocationManager implements SourceLocationManager { @Override public Path getPartitionSubPath(Path partitionLocation) { return null; } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void nullPartitionSubPath() { assertThat(locationManager.getPartitionSubPath(new Path("whatever")), is(nullValue())); } |
### Question:
FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public List<Path> getPartitionLocations() throws CircusTrainException { List<Path> result = new ArrayList<>(); List<Path> paths = sourceLocationManager.getPartitionLocations(); FileSystem fileSystem = null; for (Path path : paths) { try { if (fileSystem == null) { fileSystem = path.getFileSystem(hiveConf); } if (fileSystem.exists(path)) { result.add(path); } else { LOG .warn("Source path '{}' does not exist skipping it for replication." + " WARNING: this means there is a partition in Hive that does not have a corresponding folder in" + " source file store, check your table and data.", path); } } catch (IOException e) { LOG.warn("Exception while checking path, skipping path '{}', error {}", path, e); } } return result; } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void getPartitionLocations() { List<Path> paths = Lists.newArrayList(path, missingPath); when(sourceLocationManager.getPartitionLocations()).thenReturn(paths); List<Path> filteredPaths = filterMissingPartitionsLocationManager.getPartitionLocations(); List<Path> expected = Lists.newArrayList(path); assertThat(filteredPaths, is(expected)); }
@Test public void getPartitionLocationsExceptionThrowingPathIsSkipped() { List<Path> paths = Lists.newArrayList(path, exceptionThrowingPath); when(sourceLocationManager.getPartitionLocations()).thenReturn(paths); List<Path> filteredPaths = filterMissingPartitionsLocationManager.getPartitionLocations(); List<Path> expected = Lists.newArrayList(path); assertThat(filteredPaths, is(expected)); } |
### Question:
FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public Path getTableLocation() throws CircusTrainException { return sourceLocationManager.getTableLocation(); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void getTableLocation() { filterMissingPartitionsLocationManager.getTableLocation(); verify(sourceLocationManager).getTableLocation(); } |
### Question:
FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public void cleanUpLocations() throws CircusTrainException { sourceLocationManager.cleanUpLocations(); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void cleanUpLocations() { filterMissingPartitionsLocationManager.cleanUpLocations(); verify(sourceLocationManager).cleanUpLocations(); } |
### Question:
FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public Path getPartitionSubPath(Path partitionLocation) { return sourceLocationManager.getPartitionSubPath(partitionLocation); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void getPartitionSubPath() { Path partitionLocation = new Path("/tmp"); filterMissingPartitionsLocationManager.getPartitionSubPath(partitionLocation); verify(sourceLocationManager).getPartitionSubPath(partitionLocation); } |
### Question:
Source extends HiveEndpoint { @Override public TableAndStatistics getTableAndStatistics(String database, String table) { TableAndStatistics sourceTable = super.getTableAndStatistics(database, table); sourceCatalogListener.resolvedMetaStoreSourceTable(EventUtils.toEventTable(sourceTable.getTable())); return sourceTable; } Source(
SourceCatalog sourceCatalog,
HiveConf sourceHiveConf,
Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier,
SourceCatalogListener sourceCatalogListener,
boolean snapshotsDisabled,
String sourceTableLocation); @Override TableAndStatistics getTableAndStatistics(String database, String table); @Override PartitionsAndStatistics getPartitions(Table sourceTable, String partitionPredicate, int maxPartitions); SourceLocationManager getLocationManager(Table table, String eventId); SourceLocationManager getLocationManager(
Table table,
List<Partition> partitions,
String eventId,
Map<String, Object> copierOptions); @Override TableAndStatistics getTableAndStatistics(TableReplication tableReplication); }### Answer:
@Test public void getTable() throws Exception { when(metaStoreClient.getTable(DATABASE, TABLE)).thenReturn(table); when(metaStoreClient.getTableColumnStatistics(DATABASE, TABLE, COLUMN_NAMES)).thenReturn(columnStatisticsObjs); TableAndStatistics sourceTable = source.getTableAndStatistics(DATABASE, TABLE); assertThat(sourceTable.getTable(), is(table)); assertThat(sourceTable.getStatistics(), is(columnStatistics)); }
@Test public void getTableNoStats() throws Exception { when(metaStoreClient.getTable(DATABASE, TABLE)).thenReturn(table); when(metaStoreClient.getTableColumnStatistics(DATABASE, TABLE, COLUMN_NAMES)) .thenReturn(Collections.<ColumnStatisticsObj> emptyList()); TableAndStatistics sourceTable = source.getTableAndStatistics(DATABASE, TABLE); assertThat(sourceTable.getTable(), is(table)); assertThat(sourceTable.getStatistics(), is(nullValue())); } |
### Question:
Source extends HiveEndpoint { @Override public PartitionsAndStatistics getPartitions(Table sourceTable, String partitionPredicate, int maxPartitions) throws TException { PartitionsAndStatistics sourcePartitions = super.getPartitions(sourceTable, partitionPredicate, maxPartitions); sourceCatalogListener .resolvedSourcePartitions(EventUtils.toEventPartitions(sourceTable, sourcePartitions.getPartitions())); return sourcePartitions; } Source(
SourceCatalog sourceCatalog,
HiveConf sourceHiveConf,
Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier,
SourceCatalogListener sourceCatalogListener,
boolean snapshotsDisabled,
String sourceTableLocation); @Override TableAndStatistics getTableAndStatistics(String database, String table); @Override PartitionsAndStatistics getPartitions(Table sourceTable, String partitionPredicate, int maxPartitions); SourceLocationManager getLocationManager(Table table, String eventId); SourceLocationManager getLocationManager(
Table table,
List<Partition> partitions,
String eventId,
Map<String, Object> copierOptions); @Override TableAndStatistics getTableAndStatistics(TableReplication tableReplication); }### Answer:
@Test public void getPartitions() throws Exception { when(metaStoreClient.listPartitionsByFilter(DATABASE, TABLE, PARTITION_PREDICATE, (short) MAX_PARTITIONS)) .thenReturn(partitions); when(metaStoreClient.getPartitionColumnStatistics(DATABASE, TABLE, PARTITION_NAMES, COLUMN_NAMES)) .thenReturn(partitionStatsMap); PartitionsAndStatistics partitionsAndStatistics = source.getPartitions(table, PARTITION_PREDICATE, MAX_PARTITIONS); assertThat(partitionsAndStatistics.getPartitions(), is(partitions)); assertThat(partitionsAndStatistics.getStatisticsForPartition(partition), is(partitionColumnStatistics)); }
@Test public void getPartitionsNoStats() throws Exception { when(metaStoreClient.listPartitionsByFilter(DATABASE, TABLE, PARTITION_PREDICATE, (short) MAX_PARTITIONS)) .thenReturn(partitions); when(metaStoreClient.getPartitionColumnStatistics(DATABASE, TABLE, PARTITION_NAMES, COLUMN_NAMES)) .thenReturn(Collections.<String, List<ColumnStatisticsObj>> emptyMap()); PartitionsAndStatistics partitionsAndStatistics = source.getPartitions(table, PARTITION_PREDICATE, MAX_PARTITIONS); assertThat(partitionsAndStatistics.getPartitions(), is(partitions)); assertThat(partitionsAndStatistics.getStatisticsForPartition(partition), is(nullValue())); } |
### Question:
HdfsSnapshotLocationManager implements SourceLocationManager { @Override public Path getTableLocation() { LOG.debug("Copying source data from: {}", copyBasePath.toString()); sourceCatalogListener.resolvedSourceLocation(copyBasePath.toUri()); return copyBasePath; } HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
FileSystemFactory fileSystemFactory,
SourceCatalogListener sourceCatalogListener); @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void getTableLocationUnpartitionedTableSnapshotsDisabled() throws Exception { HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, true, sourceCatalogListener); Path tableLocation = manager.getTableLocation(); assertThat(tableLocation, is(new Path(TABLE_LOCATION))); }
@Test public void getTableLocationPartitionedTableSnapshotsDisabled() throws Exception { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation(TABLE_LOCATION + "/partition1"); partition1.setSd(sd); sd = new StorageDescriptor(); sd.setLocation(TABLE_LOCATION + "/partition2"); partition2.setSd(sd); HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, partitions, true, null, sourceCatalogListener); Path tableLocation = manager.getTableLocation(); assertThat(tableLocation, is(new Path(TABLE_LOCATION))); }
@Test public void getTableLocationPartitionedTableSnapshotsDisabledWithOverride() throws Exception { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation(PARTITION_BASE_LOCATION + "/partition1"); partition1.setSd(sd); sd = new StorageDescriptor(); sd.setLocation(PARTITION_BASE_LOCATION + "/partition2"); partition2.setSd(sd); HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, partitions, true, PARTITION_BASE_LOCATION, sourceCatalogListener); Path tableLocation = manager.getTableLocation(); assertThat(tableLocation, is(new Path(PARTITION_BASE_LOCATION))); } |
### Question:
HdfsSnapshotLocationManager implements SourceLocationManager { static List<Path> calculateSubPaths( List<Partition> sourcePartitions, String sourceDataLocation, String copyBaseLocation) { List<Path> paths = new ArrayList<>(sourcePartitions.size()); for (Partition partition : sourcePartitions) { String partitionLocation = partition.getSd().getLocation(); String partitionBranch = partitionLocation.replace(sourceDataLocation, ""); while (partitionBranch.startsWith("/")) { partitionBranch = partitionBranch.substring(1); } Path copyPartitionPath = new Path(copyBaseLocation, partitionBranch); paths.add(copyPartitionPath); LOG.debug("Added sub-path {}.", copyPartitionPath.toString()); } return paths; } HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
FileSystemFactory fileSystemFactory,
SourceCatalogListener sourceCatalogListener); @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void calculateSubPaths() { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation("/a/partition1"); partition1.setSd(sd); List<Path> subPaths = HdfsSnapshotLocationManager.calculateSubPaths(Collections.singletonList(partition1), "/a", "/b"); assertThat(subPaths.get(0).toString(), is("/b/partition1")); }
@Test public void calculateSubPathsFullUri() { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation("/a/partition1"); partition1.setSd(sd); List<Path> subPaths = HdfsSnapshotLocationManager.calculateSubPaths(Collections.singletonList(partition1), "/a", "hdfs: assertThat(subPaths.get(0).toString(), is("hdfs: }
@Test public void calculateSubPathsUriEncodedPathAndPartition() { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation("hdfs: partition1.setSd(sd); List<Path> subPaths = HdfsSnapshotLocationManager.calculateSubPaths(Collections.singletonList(partition1), "hdfs: assertThat(subPaths.get(0).toString(), is("/b%25c/partition1=url%25encoded.%3A")); }
@Test public void calculateSubPathsTrailingSlash() { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation("/a/partition1"); partition1.setSd(sd); List<Path> subPaths = HdfsSnapshotLocationManager.calculateSubPaths(Collections.singletonList(partition1), "/a/", "/b"); assertThat(subPaths.get(0).toString(), is("/b/partition1")); } |
### Question:
HdfsSnapshotLocationManager implements SourceLocationManager { @Override public Path getPartitionSubPath(Path partitionLocation) { String sourceDataPathString = sourceDataPath.toString(); String partitionLocationString = partitionLocation.toString(); if (!partitionLocationString.startsWith(sourceDataPathString)) { throw new CircusTrainException("Partition path '" + partitionLocationString + "' does not seem to belong to data source path '" + sourceDataPathString + "'"); } String subPath = partitionLocationString.replace(sourceDataPathString, ""); if (subPath.charAt(0) == '/') { subPath = subPath.substring(1); } return new Path(subPath); } HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
SourceCatalogListener sourceCatalogListener); HdfsSnapshotLocationManager(
HiveConf sourceHiveConf,
String eventId,
Table sourceTable,
List<Partition> sourcePartitions,
boolean snapshotsDisabled,
String tableBasePath,
FileSystemFactory fileSystemFactory,
SourceCatalogListener sourceCatalogListener); @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer:
@Test public void partitionSubPath() throws Exception { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation(PARTITION_BASE_LOCATION + "/partition1"); partition1.setSd(sd); HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, Arrays.asList(partition1), false, PARTITION_BASE_LOCATION, fileSystemFactory, sourceCatalogListener); assertThat(manager.getPartitionSubPath(new Path(partition1.getSd().getLocation())), is(new Path("partition1"))); }
@Test public void partitionSubPathUriEncoded() throws Exception { Path path = new Path(PARTITION_BASE_LOCATION + "/partition%251"); StorageDescriptor sd = new StorageDescriptor(); sd.setLocation(path.toUri().getPath()); partition1.setSd(sd); HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, Arrays.asList(partition1), false, PARTITION_BASE_LOCATION, fileSystemFactory, sourceCatalogListener); assertThat(manager.getPartitionSubPath(path), is(new Path("partition%251"))); }
@Test(expected = CircusTrainException.class) public void invalidPartitionSubPath() throws Exception { StorageDescriptor sd = new StorageDescriptor(); sd.setLocation("anotherBaseLocation" + "/partition1"); partition1.setSd(sd); HdfsSnapshotLocationManager manager = new HdfsSnapshotLocationManager(hiveConf, EVENT_ID, sourceTable, Arrays.asList(partition1), false, PARTITION_BASE_LOCATION, fileSystemFactory, sourceCatalogListener); manager.getPartitionSubPath(new Path(partition1.getSd().getLocation())); } |
### Question:
DestructiveSource { public boolean tableExists() throws TException { try (CloseableMetaStoreClient client = sourceMetaStoreClientSupplier.get()) { return client.tableExists(databaseName, tableName); } } DestructiveSource(
Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier,
TableReplication tableReplication); boolean tableExists(); List<String> getPartitionNames(); }### Answer:
@Test public void tableExists() throws Exception { when(client.tableExists(DATABASE, TABLE)).thenReturn(true); DestructiveSource source = new DestructiveSource(sourceMetaStoreClientSupplier, tableReplication); assertThat(source.tableExists(), is(true)); verify(client).close(); } |
### Question:
AvroStringUtils { public static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation) { checkArgument(isNotBlank(pathToDestinationFolder), "There must be a pathToDestinationFolder provided"); checkArgument(isNotBlank(eventId), "There must be a eventId provided"); pathToDestinationFolder = appendForwardSlashIfNotPresent(pathToDestinationFolder); eventId = appendForwardSlashIfNotPresent(eventId); if (tableLocation != null && pathToDestinationFolder.equals(appendForwardSlashIfNotPresent(tableLocation))) { return pathToDestinationFolder + eventId + ".schema"; } return pathToDestinationFolder + eventId; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer:
@Test public void avroDestinationTest() { assertThat(avroDestination("file: assertThat(avroDestination("file: }
@Test public void avroDestinationIsSameAsReplicaLocationTest() { assertThat(avroDestination("file: assertThat(avroDestination("file: }
@Test public void avroDestinationIsHiddenFolder() { String[] folders = avroDestination("dummy/url/", "123", "dummy/url").split("/"); assertThat(folders[folders.length - 1], startsWith(".")); }
@Test(expected = IllegalArgumentException.class) public void nullDestinationFolderParamTest() { avroDestination(null, "123", "location"); }
@Test(expected = IllegalArgumentException.class) public void emptyDestinationFolderParamTest() { avroDestination("", "123", "location"); }
@Test(expected = IllegalArgumentException.class) public void nullEventIdParamTest() { avroDestination("test", null, "location"); }
@Test(expected = IllegalArgumentException.class) public void emptyEventIdParamTest() { avroDestination("", null, "location"); } |
### Question:
DestructiveSource { public List<String> getPartitionNames() throws TException { try (CloseableMetaStoreClient client = sourceMetaStoreClientSupplier.get()) { return client.listPartitionNames(databaseName, tableName, ALL); } } DestructiveSource(
Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier,
TableReplication tableReplication); boolean tableExists(); List<String> getPartitionNames(); }### Answer:
@Test public void getPartitionNames() throws Exception { List<String> expectedPartitionNames = Lists.newArrayList("partition1=value1"); when(client.listPartitionNames(DATABASE, TABLE, (short) -1)).thenReturn(expectedPartitionNames); DestructiveSource source = new DestructiveSource(sourceMetaStoreClientSupplier, tableReplication); assertThat(source.getPartitionNames(), is(expectedPartitionNames)); verify(client).close(); } |
### Question:
DiffGeneratedPartitionPredicate implements PartitionPredicate { @Override public String getPartitionPredicate() { if (!generated) { partitionPredicate = generate(); generated = true; } return partitionPredicate; } DiffGeneratedPartitionPredicate(
@Nonnull HiveEndpoint source,
@Nonnull HiveEndpoint replica,
TableReplication tableReplication,
Function<Path, String> checksumFunction); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer:
@Test public void autogeneratePredicate() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicate(), is("(p1='value11' AND p2='value22') OR (p1='value1' AND p2='value2')")); }
@Test public void autogeneratePredicateReplicaTableDoesNotExist() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenThrow(new CircusTrainException("Table does not exist!")); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicate(), is("(p1='value11' AND p2='value22') OR (p1='value1' AND p2='value2')")); } |
### Question:
DiffGeneratedPartitionPredicate implements PartitionPredicate { @Override public short getPartitionPredicateLimit() { if (Strings.isNullOrEmpty(getPartitionPredicate())) { return 0; } return partitionLimit; } DiffGeneratedPartitionPredicate(
@Nonnull HiveEndpoint source,
@Nonnull HiveEndpoint replica,
TableReplication tableReplication,
Function<Path, String> checksumFunction); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer:
@Test public void partitionPredicateLimit() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) 10)); }
@Test public void noPartitionPredicateLimitSetDefaultsToMinus1() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn(null); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) -1)); }
@Test public void partitionPredicateLimitOverriddenToZeroWhenNoDiffs() throws Exception { when(sourceTableAndStats.getTable()).thenReturn(table2); when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) 0)); } |
### Question:
Locomotive implements ApplicationRunner, ExitCodeGenerator { @VisibleForTesting String getReplicationSummary(TableReplication tableReplication) { return String.format("%s:%s to %s:%s", sourceCatalog.getName(), tableReplication.getSourceTable().getQualifiedName(), replicaCatalog.getName(), tableReplication.getQualifiedReplicaName()); } @Autowired Locomotive(
SourceCatalog sourceCatalog,
ReplicaCatalog replicaCatalog,
Security security,
TableReplications tableReplications,
ReplicationFactory replicationFactory,
MetricSender metricSender,
LocomotiveListener locomotiveListener,
TableReplicationListener tableReplicationListener); @Override void run(ApplicationArguments args); @Override int getExitCode(); }### Answer:
@Test public void getReplicationSummary() { assertThat(locomotive.getReplicationSummary(tableReplication1), is("source-catalog:source-database.source-table to replica-catalog:replica-database.replica-table1")); } |
### Question:
MetricsListener implements TableReplicationListener, CopierListener { @Override public void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t) { sendMetrics(CompletionCode.FAILURE, tableReplication.getQualifiedReplicaName(), Metrics.NULL_VALUE); } @Autowired MetricsListener(
MetricSender metricSender,
ScheduledReporterFactory runningMetricsReporterFactory,
@Value("${metrics-reporter.period:1}") long metricsReporterPeriod,
@Value("${metrics-reporter.time-unit:MINUTES}") TimeUnit metricsReporterTimeUnit); @Override void tableReplicationStart(EventTableReplication tableReplication, String eventId); @Override void tableReplicationSuccess(EventTableReplication tableReplication, String eventId); @Override void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t); @Override void copierEnd(Metrics metrics); @Override void copierStart(String copierImplementation); }### Answer:
@Test public void failureWithoutStartOrSuccessDoesntThrowException() { Throwable throwable = new Throwable("Test"); listener.tableReplicationFailure(tableReplication, "event-id", throwable); verify(metricSender).send(metricsCaptor.capture()); Map<String, Long> metrics = metricsCaptor.getValue(); assertThat(metrics.size(), is(3)); assertThat(metrics.get("target.replication_time"), is(-1L)); assertThat(metrics.get("target.completion_code"), is(-1L)); assertThat(metrics.get("target.bytes_replicated"), is(0L)); } |
### Question:
LoggingListener implements TableReplicationListener, LocomotiveListener, SourceCatalogListener,
ReplicaCatalogListener, CopierListener { @Override public void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t) { if (sourceCatalog != null && replicaCatalog != null) { LOG .error("[{}] Failed to replicate '{}:{}' to '{}:{}' with error '{}'", eventId, sourceCatalog.getName(), tableReplication.getSourceTable().getQualifiedName(), replicaCatalog.getName(), tableReplication.getQualifiedReplicaName(), t.getMessage()); } } @Override void tableReplicationStart(EventTableReplication tableReplication, String eventId); @Override void tableReplicationSuccess(EventTableReplication tableReplication, String eventId); @Override void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t); @Override void circusTrainStartUp(String[] args, EventSourceCatalog sourceCatalog, EventReplicaCatalog replicaCatalog); @Override void resolvedMetaStoreSourceTable(EventTable table); @Override void partitionsToCreate(EventPartitions partitions); @Override void partitionsToAlter(EventPartitions partitions); @Override void copierEnd(Metrics metrics); @Override void circusTrainShutDown(CompletionCode completionCode, Map<String, Long> metrics); @Override void resolvedSourcePartitions(EventPartitions partitions); @Override void resolvedSourceLocation(URI location); @Override void resolvedReplicaLocation(URI location); @Override void existingReplicaPartitions(EventPartitions partitions); @Override void deprecatedReplicaLocations(List<URI> locations); @Override void copierStart(String copierImplementation); }### Answer:
@Test public void failureWithoutStartOrSuccessDoesntThrowException() { Throwable throwable = new Throwable("Test"); listener.tableReplicationFailure(tableReplication, "event-id", throwable); } |
### Question:
EventUtils { public static EventPartitions toEventPartitions(Table table, List<Partition> partitions) { LinkedHashMap<String, String> partitionKeyTypes = new LinkedHashMap<>(); List<FieldSchema> partitionKeys = table.getPartitionKeys(); for (FieldSchema partitionKey : partitionKeys) { partitionKeyTypes.put(partitionKey.getName(), partitionKey.getType()); } EventPartitions eventPartitions = new EventPartitions(partitionKeyTypes); if (partitions != null) { for (Partition partition : partitions) { eventPartitions.add(new EventPartition(partition.getValues(), LocationUtils.hasLocation(partition) ? LocationUtils.locationAsUri(partition) : null)); } } return eventPartitions; } private EventUtils(); static List<URI> toUris(List<Path> paths); static EventPartitions toEventPartitions(Table table, List<Partition> partitions); static EventTable toEventTable(Table sourceTable); static EventSourceCatalog toEventSourceCatalog(SourceCatalog sourceCatalog); static EventReplicaCatalog toEventReplicaCatalog(ReplicaCatalog replicaCatalog, Security security); static EventTableReplication toEventTableReplication(TableReplication tableReplication); static final String EVENT_ID_UNAVAILABLE; }### Answer:
@Test public void toNullEventPartitions() { EventPartitions eventPartitions = EventUtils.toEventPartitions(table, null); assertThat(eventPartitions.getEventPartitions().size(), is(0)); }
@Test public void toEmptyEventPartitions() { EventPartitions eventPartitions = EventUtils.toEventPartitions(table, Collections.<Partition> emptyList()); List<EventPartition> partitions = eventPartitions.getEventPartitions(); assertThat(partitions, is(not(nullValue()))); assertThat(partitions.size(), is(0)); assertPartitionKeyTypes(eventPartitions.getPartitionKeyTypes()); }
@Test public void toEventPartitions() { when(partitionStorageDescriptor.getLocation()).thenReturn("location"); EventPartitions eventPartitions = EventUtils.toEventPartitions(table, ImmutableList.of(partition)); List<EventPartition> partitions = eventPartitions.getEventPartitions(); assertThat(partitions, is(not(nullValue()))); assertThat(partitions.size(), is(1)); assertThat(partitions.get(0).getValues(), is(PARTITION_VALUES)); assertThat(partitions.get(0).getLocation(), is(URI.create("location"))); assertPartitionKeyTypes(eventPartitions.getPartitionKeyTypes()); }
@Test public void toEventPartitionsWithNullLocation() { EventPartitions eventPartitions = EventUtils.toEventPartitions(table, ImmutableList.of(partition)); List<EventPartition> partitions = eventPartitions.getEventPartitions(); assertThat(partitions, is(not(nullValue()))); assertThat(partitions.size(), is(1)); assertThat(partitions.get(0).getValues(), is(PARTITION_VALUES)); assertThat(partitions.get(0).getLocation(), is(nullValue())); } |
### Question:
EventUtils { public static EventTable toEventTable(Table sourceTable) { if (sourceTable == null) { return null; } return new EventTable(FieldSchemaUtils.getFieldNames(sourceTable.getPartitionKeys()), LocationUtils.hasLocation(sourceTable) ? LocationUtils.locationAsUri(sourceTable) : null); } private EventUtils(); static List<URI> toUris(List<Path> paths); static EventPartitions toEventPartitions(Table table, List<Partition> partitions); static EventTable toEventTable(Table sourceTable); static EventSourceCatalog toEventSourceCatalog(SourceCatalog sourceCatalog); static EventReplicaCatalog toEventReplicaCatalog(ReplicaCatalog replicaCatalog, Security security); static EventTableReplication toEventTableReplication(TableReplication tableReplication); static final String EVENT_ID_UNAVAILABLE; }### Answer:
@Test public void toNullEventTable() { assertThat(EventUtils.toEventTable(null), is(nullValue())); }
@Test public void toEventTable() { when(tableStorageDescriptor.getLocation()).thenReturn("location"); EventTable eventTable = EventUtils.toEventTable(table); assertThat(eventTable, is(not(nullValue()))); assertThat(eventTable.getPartitionKeys(), is(PARTITION_KEY_NAMES)); assertThat(eventTable.getLocation(), is(URI.create("location"))); }
@Test public void toEventTableWithNullLocation() { EventTable eventTable = EventUtils.toEventTable(table); assertThat(eventTable, is(not(nullValue()))); assertThat(eventTable.getPartitionKeys(), is(PARTITION_KEY_NAMES)); assertThat(eventTable.getLocation(), is(nullValue())); } |
### Question:
ListenerConfig { public int getQueueSize() { return queueSize; } void setQueueSize(int queueSize); String getStartTopic(); void setStartTopic(String startTopic); String getSuccessTopic(); void setSuccessTopic(String successTopic); String getFailTopic(); void setFailTopic(String failTopic); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); String getSubject(); void setSubject(String subject); int getQueueSize(); String getTopic(); void setTopic(String topic); String getRegion(); void setRegion(String region); }### Answer:
@Test public void defaultQueueSize() { assertThat(config.getQueueSize(), is(100)); } |
### Question:
SnsMessage { public void clearModifiedPartitions() { if (modifiedPartitions != null) { modifiedPartitions.clear(); } } SnsMessage(
SnsMessageType type,
Map<String, String> headers,
String startTime,
String endTime,
String eventId,
String sourceCatalog,
String replicaCatalog,
String replicaMetastoreUris,
String sourceTable,
String replicaTable,
String replicaTableLocation,
LinkedHashMap<String, String> partitionKeys,
List<List<String>> modifiedPartitions,
Long bytesReplicated,
String errorMessage); String getProtocolVersion(); SnsMessageType getType(); Map<String, String> getHeaders(); String getStartTime(); String getEndTime(); String getEventId(); String getSourceCatalog(); String getReplicaCatalog(); String getSourceTable(); String getReplicaTable(); String getReplicaTableLocation(); String getReplicaMetastoreUris(); LinkedHashMap<String, String> getPartitionKeys(); List<List<String>> getModifiedPartitions(); void clearModifiedPartitions(); Long getBytesReplicated(); String getErrorMessage(); Boolean isMessageTruncated(); void setMessageTruncated(Boolean truncated); }### Answer:
@Test public void clearNullPartitions() throws JsonProcessingException { SnsMessage message = new SnsMessage(null, null, null, null, null, null, null, null, null, null, null, null, null, 0L, null); message.clearModifiedPartitions(); } |
### Question:
SnsConfiguration { @Bean AWSCredentialsProvider awsCredentialsProvider( @Qualifier("replicaHiveConf") org.apache.hadoop.conf.Configuration conf) { return new AWSCredentialsProviderChain(new BasicAuth(conf), InstanceProfileCredentialsProvider.getInstance()); } }### Answer:
@Test public void credentials() throws IOException { when(conf.getPassword("access.key")).thenReturn("accessKey".toCharArray()); when(conf.getPassword("secret.key")).thenReturn("secretKey".toCharArray()); AWSCredentialsProvider credentialsProvider = configuration.awsCredentialsProvider(conf); AWSCredentials awsCredentials = credentialsProvider.getCredentials(); assertThat(awsCredentials.getAWSAccessKeyId(), is("accessKey")); assertThat(awsCredentials.getAWSSecretKey(), is("secretKey")); } |
### Question:
SnsConfiguration { @Bean AmazonSNSAsync amazonSNS(ListenerConfig config, AWSCredentialsProvider awsCredentialsProvider) { return AmazonSNSAsyncClient.asyncBuilder() .withCredentials(awsCredentialsProvider) .withRegion(config.getRegion()) .build(); } }### Answer:
@Test public void snsClient() { AWSCredentialsProvider credentialsProvider = mock(AWSCredentialsProvider.class); when(credentialsProvider.getCredentials()).thenReturn(new BasicAWSCredentials("accessKey", "secretKey")); ListenerConfig config = new ListenerConfig(); config.setRegion("eu-west-1"); AmazonSNS sns = configuration.amazonSNS(config, credentialsProvider); assertThat(sns, is(not(nullValue()))); } |
### Question:
SnsListener implements LocomotiveListener, SourceCatalogListener, ReplicaCatalogListener,
TableReplicationListener, CopierListener { @VisibleForTesting static List<List<String>> getModifiedPartitions( List<EventPartition> partitionsToAlter, List<EventPartition> partitionsToCreate) { if (partitionsToAlter == null && partitionsToCreate == null) { return null; } List<List<String>> partitionValues = new ArrayList<>(); for (List<EventPartition> partitions : Arrays.asList(partitionsToAlter, partitionsToCreate)) { if (partitions != null) { for (EventPartition partition : partitions) { partitionValues.add(partition.getValues()); } } } return partitionValues; } @Autowired SnsListener(AmazonSNSAsync sns, ListenerConfig config); SnsListener(AmazonSNSAsync sns, ListenerConfig config, Clock clock); @Override void circusTrainStartUp(String[] args, EventSourceCatalog sourceCatalog, EventReplicaCatalog replicaCatalog); @Override void copierEnd(Metrics metrics); @Override void tableReplicationStart(EventTableReplication tableReplication, String eventId); @Override void tableReplicationSuccess(EventTableReplication tableReplication, String eventId); @Override void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t); @Override void partitionsToCreate(EventPartitions eventPartitions); @Override void partitionsToAlter(EventPartitions eventPartitions); @PreDestroy void flush(); @Override void copierStart(String copierImplementation); @Override void resolvedReplicaLocation(URI location); @Override void existingReplicaPartitions(EventPartitions eventPartitions); @Override void deprecatedReplicaLocations(List<URI> locations); @Override void resolvedMetaStoreSourceTable(EventTable table); @Override void resolvedSourcePartitions(EventPartitions eventPartitions); @Override void resolvedSourceLocation(URI location); @Override void circusTrainShutDown(CompletionCode completionCode, Map<String, Long> metrics); }### Answer:
@Test public void getModifiedPartitionsTypical() throws URISyntaxException { List<EventPartition> created = Arrays.asList(new EventPartition(Arrays.asList("a"), new URI("location_a"))); List<EventPartition> altered = Arrays.asList(new EventPartition(Arrays.asList("b"), new URI("location_b"))); List<List<String>> partitions = SnsListener.getModifiedPartitions(created, altered); assertThat(partitions.size(), is(2)); assertThat(partitions.get(0), is(Arrays.asList("a"))); assertThat(partitions.get(1), is(Arrays.asList("b"))); }
@Test public void getModifiedPartitionsOneOnly() throws URISyntaxException { List<EventPartition> created = Arrays .asList(new EventPartition(Arrays.asList("a"), new URI("location_a")), new EventPartition(Arrays.asList("b"), new URI("location_b"))); List<List<String>> partitions = SnsListener.getModifiedPartitions(created, null); assertThat(partitions.size(), is(2)); assertThat(partitions.get(0), is(Arrays.asList("a"))); assertThat(partitions.get(1), is(Arrays.asList("b"))); }
@Test public void getModifiedPartitionsBothNull() throws URISyntaxException { List<List<String>> partitions = SnsListener.getModifiedPartitions(null, null); assertThat(partitions, is(nullValue())); } |
### Question:
S3Schemes { public static boolean isS3Scheme(String scheme) { return S3_SCHEMES.contains(Strings.nullToEmpty(scheme).toLowerCase(Locale.ROOT)); } private S3Schemes(); static boolean isS3Scheme(String scheme); }### Answer:
@Test public void isS3Scheme() { assertTrue(S3Schemes.isS3Scheme("s3")); assertTrue(S3Schemes.isS3Scheme("S3")); assertTrue(S3Schemes.isS3Scheme("s3a")); assertTrue(S3Schemes.isS3Scheme("S3A")); assertTrue(S3Schemes.isS3Scheme("s3n")); assertTrue(S3Schemes.isS3Scheme("S3N")); }
@Test public void isNotS3Scheme() { assertFalse(S3Schemes.isS3Scheme(null)); assertFalse(S3Schemes.isS3Scheme("")); assertFalse(S3Schemes.isS3Scheme("file")); assertFalse(S3Schemes.isS3Scheme("s321")); assertFalse(S3Schemes.isS3Scheme("sss")); } |
### Question:
AWSBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (CommonBeans.BEAN_BASE_CONF.equals(beanName)) { Configuration baseConf = (Configuration) bean; bindS3AFileSystem.bindFileSystem(baseConf); if (baseConf.get(CREDENTIAL_PROVIDER_PATH) != null) { s3CredentialsUtils.setS3Credentials(baseConf); } return baseConf; } return bean; } @Autowired AWSBeanPostProcessor(BindS3AFileSystem bindS3AFileSystem, S3CredentialsUtils s3CredentialsUtils); @Override Object postProcessBeforeInitialization(Object bean, String beanName); @Override Object postProcessAfterInitialization(Object bean, String beanName); }### Answer:
@Test public void baseConfBindFileSystem() throws Exception { Configuration conf = new Configuration(); Object result = postProcessor.postProcessAfterInitialization(conf, "baseConf"); Configuration resultConf = (Configuration) result; assertThat(resultConf, is(conf)); verify(bindS3AFileSystem).bindFileSystem(conf); verifyZeroInteractions(s3CredentialsUtils); }
@Test public void baseConfs3Credentials() throws Exception { Configuration conf = new Configuration(); conf.set(CREDENTIAL_PROVIDER_PATH, "path"); Object result = postProcessor.postProcessAfterInitialization(conf, "baseConf"); Configuration resultConf = (Configuration) result; assertThat(resultConf, is(conf)); verify(bindS3AFileSystem).bindFileSystem(conf); verify(s3CredentialsUtils).setS3Credentials(conf); }
@Test public void postProcessAfterInitializationReturnsBean() throws Exception { Object bean = new Object(); Object result = postProcessor.postProcessAfterInitialization(bean, "bean"); assertThat(result, is(bean)); } |
### Question:
AWSBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Autowired AWSBeanPostProcessor(BindS3AFileSystem bindS3AFileSystem, S3CredentialsUtils s3CredentialsUtils); @Override Object postProcessBeforeInitialization(Object bean, String beanName); @Override Object postProcessAfterInitialization(Object bean, String beanName); }### Answer:
@Test public void postProcessBeforeInitializationReturnsBean() throws Exception { Object bean = new Object(); Object result = postProcessor.postProcessBeforeInitialization(bean, "bean"); assertThat(result, is(bean)); } |
### Question:
AssumeRoleCredentialProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (this.credentialsProvider == null) { initializeCredentialProvider(); } return this.credentialsProvider.getCredentials(); } AssumeRoleCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); static final String ASSUME_ROLE_PROPERTY_NAME; static final String ASSUME_ROLE_SESSION_DURATION_SECONDS_PROPERTY_NAME; }### Answer:
@Test(expected = NullPointerException.class) public void getCredentialsThrowsNullPointerException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(null); provider.getCredentials(); }
@Test(expected = IllegalArgumentException.class) public void getCredentialsThrowsIllegalArgumentException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(new Configuration()); provider.getCredentials(); } |
### Question:
AssumeRoleCredentialProvider implements AWSCredentialsProvider { @Override public void refresh() { if (this.credentialsProvider == null) { initializeCredentialProvider(); } this.credentialsProvider.refresh(); } AssumeRoleCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); static final String ASSUME_ROLE_PROPERTY_NAME; static final String ASSUME_ROLE_SESSION_DURATION_SECONDS_PROPERTY_NAME; }### Answer:
@Test(expected = NullPointerException.class) public void refreshThrowsNullPointerException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(null); provider.refresh(); }
@Test(expected = IllegalArgumentException.class) public void refreshThrowsIllegalArgumentException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(new Configuration()); provider.refresh(); } |
### Question:
AWSCredentialUtils { static String getKey(Configuration conf, String keyType) { checkNotNull(conf, "conf cannot be null"); checkNotNull(keyType, "KeyType cannot be null"); try { char[] key = conf.getPassword(keyType); if (key == null) { throw new IllegalStateException(format("Unable to get value of '%s'", keyType)); } return new String(key); } catch (IOException e) { throw new RuntimeException(format("Error getting key for '%s' from credential provider", keyType), e); } } private AWSCredentialUtils(); static Configuration configureCredentialProvider(String credentialProviderPath); static Configuration configureCredentialProvider(String credentialProviderPath, Configuration conf); }### Answer:
@Test public void getAccessKeyFromConfTest() throws Exception { Configuration conf = new Configuration(); conf.set(AWSConstants.ACCESS_KEY, "access"); conf.set(AWSConstants.SECRET_KEY, "secret"); String access = AWSCredentialUtils.getKey(conf, AWSConstants.ACCESS_KEY); assertThat(access, is("access")); }
@Test public void getSecretKeyFromConfTest() throws Exception { Configuration conf = new Configuration(); conf.set(AWSConstants.ACCESS_KEY, "access"); conf.set(AWSConstants.SECRET_KEY, "secret"); String secret = AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); assertThat(secret, is("secret")); }
@Test(expected = IllegalStateException.class) public void getKeyFromConfWhichIsntSetThrowsExceptionTest() throws Exception { Configuration conf = new Configuration(); AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); }
@Test(expected = RuntimeException.class) public void getKeyThrowsRuntimeExceptionTest() throws Exception { Configuration conf = mock(Configuration.class); when(conf.getPassword(anyString())).thenThrow(new IOException()); AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); } |
### Question:
AmazonS3URIs { public static AmazonS3URI toAmazonS3URI(URI uri) { if (FS_PROTOCOL_S3.equalsIgnoreCase(uri.getScheme())) { return new AmazonS3URI(uri); } else if (S3Schemes.isS3Scheme(uri.getScheme())) { try { return new AmazonS3URI(new URI(FS_PROTOCOL_S3, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { } } return new AmazonS3URI(uri); } private AmazonS3URIs(); static AmazonS3URI toAmazonS3URI(URI uri); }### Answer:
@Test public void toAmazonS3URISchemeIsS3() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("s3: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test public void toAmazonS3URISchemeIsS3Uppercase() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("S3: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test public void toAmazonS3URISchemeIsS3a() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("s3a: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test public void toAmazonS3URISchemeIsS3aUppercase() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("S3A: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test public void toAmazonS3URISchemeIsS3n() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("s3n: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test public void toAmazonS3URISchemeIsS3nUppercase() throws Exception { AmazonS3URI result = AmazonS3URIs.toAmazonS3URI(new URI("S3N: AmazonS3URI expected = new AmazonS3URI("s3: assertThat(result, is(expected)); }
@Test(expected = IllegalArgumentException.class) public void toAmazonS3URISchemeIsInvalidS3Scheme() throws Exception { AmazonS3URIs.toAmazonS3URI(new URI("s321: }
@Test(expected = IllegalArgumentException.class) public void toAmazonS3URISchemeIsNonAmazon() throws Exception { AmazonS3URIs.toAmazonS3URI(new URI("file: }
@Test(expected = IllegalArgumentException.class) public void toAmazonS3URISchemeIsNullScheme() throws Exception { AmazonS3URIs.toAmazonS3URI(new URI("/a/b")); } |
### Question:
JceksAWSCredentialProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (credentials == null) { refresh(); } return credentials; } JceksAWSCredentialProvider(String credentialProviderPath); JceksAWSCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); }### Answer:
@Test public void credentialsFromFile() throws IOException { String jceksPath = "jceks: JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(jceksPath); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("access")); assertThat(credentials.getAWSSecretKey(), is("secret")); }
@Test public void credentialsFromConf() throws IOException { when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray()); when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray()); JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(conf); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("accessKey")); assertThat(credentials.getAWSSecretKey(), is("secretKey")); }
@Test(expected = IllegalStateException.class) public void secretKeyNotSetInConfThrowsException() throws Exception { when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray()); new JceksAWSCredentialProvider(conf).getCredentials(); }
@Test(expected = IllegalStateException.class) public void accessKeyNotSetInConfThrowsException() throws Exception { when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray()); new JceksAWSCredentialProvider(conf).getCredentials(); } |
### Question:
ReplicaCatalog implements TunnelMetastoreCatalog { public void setName(String name) { this.name = name; } @Override String getName(); void setName(String name); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); }### Answer:
@Test public void nullName() { replicaCatalog.setName(null); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyName() { replicaCatalog.setName(""); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankName() { replicaCatalog.setName(" "); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); } |
### Question:
ReplicaCatalog implements TunnelMetastoreCatalog { public void setHiveMetastoreUris(String hiveMetastoreUris) { this.hiveMetastoreUris = hiveMetastoreUris; } @Override String getName(); void setName(String name); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); }### Answer:
@Test public void nullHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(null); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(""); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(" "); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); } |
### Question:
AvroStringUtils { @VisibleForTesting static String appendForwardSlashIfNotPresent(String path) { checkArgument(isNotBlank(path), "There must be a path provided"); if (path.charAt(path.length() - 1) == '/') { return path; } return path + "/"; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer:
@Test public void appendForwardSlashWhenNoneIsPresent() { assertThat(appendForwardSlashIfNotPresent("test"), is("test/")); }
@Test public void doesntAppendSecondForwardSlashWhenOneIsPresent() { assertThat(appendForwardSlashIfNotPresent("test/"), is("test/")); }
@Test(expected = IllegalArgumentException.class) public void nullArgParamTest() { appendForwardSlashIfNotPresent(null); }
@Test(expected = IllegalArgumentException.class) public void emptyArgParamTest() { appendForwardSlashIfNotPresent(""); } |
### Question:
TableReplication { public String getQualifiedReplicaName() { return getReplicaDatabaseName() + "." + getReplicaTableName(); } SourceTable getSourceTable(); void setSourceTable(SourceTable sourceTable); ReplicaTable getReplicaTable(); void setReplicaTable(ReplicaTable replicaTable); Map<String, Object> getCopierOptions(); Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions); static Map<String, Object> getMergedCopierOptions(
Map<String, Object> baseCopierOptions,
Map<String, Object> overrideCopierOptions); void setCopierOptions(Map<String, Object> copierOptions); Map<String, Object> getTransformOptions(); void setTransformOptions(Map<String, Object> transformOptions); String getReplicaDatabaseName(); String getReplicaTableName(); String getQualifiedReplicaName(); short getPartitionIteratorBatchSize(); void setPartitionIteratorBatchSize(short partitionIteratorBatchSize); short getPartitionFetcherBufferSize(); void setPartitionFetcherBufferSize(short partitionFetcherBufferSize); ReplicationMode getReplicationMode(); void setReplicationMode(ReplicationMode replicationMode); Map<String, String> getTableMappings(); void setTableMappings(Map<String, String> tableMappings); ReplicationStrategy getReplicationStrategy(); void setReplicationStrategy(ReplicationStrategy replicationStrategy); OrphanedDataStrategy getOrphanedDataStrategy(); void setOrphanedDataStrategy(OrphanedDataStrategy orphanedDataStrategy); }### Answer:
@Test public void getQualifiedReplicaName() { assertThat(tableReplication.getQualifiedReplicaName(), is("replica-database.replica-table")); }
@Test public void getQualifiedReplicaNameUseSourceDatabase() { replicaTable.setDatabaseName(null); assertThat(tableReplication.getQualifiedReplicaName(), is("source-database.replica-table")); }
@Test public void getQualifiedReplicaNameUseSourceTable() { replicaTable.setTableName(null); assertThat(tableReplication.getQualifiedReplicaName(), is("replica-database.source-table")); } |
### Question:
TableReplication { public Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions) { return getMergedCopierOptions(baseCopierOptions, getCopierOptions()); } SourceTable getSourceTable(); void setSourceTable(SourceTable sourceTable); ReplicaTable getReplicaTable(); void setReplicaTable(ReplicaTable replicaTable); Map<String, Object> getCopierOptions(); Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions); static Map<String, Object> getMergedCopierOptions(
Map<String, Object> baseCopierOptions,
Map<String, Object> overrideCopierOptions); void setCopierOptions(Map<String, Object> copierOptions); Map<String, Object> getTransformOptions(); void setTransformOptions(Map<String, Object> transformOptions); String getReplicaDatabaseName(); String getReplicaTableName(); String getQualifiedReplicaName(); short getPartitionIteratorBatchSize(); void setPartitionIteratorBatchSize(short partitionIteratorBatchSize); short getPartitionFetcherBufferSize(); void setPartitionFetcherBufferSize(short partitionFetcherBufferSize); ReplicationMode getReplicationMode(); void setReplicationMode(ReplicationMode replicationMode); Map<String, String> getTableMappings(); void setTableMappings(Map<String, String> tableMappings); ReplicationStrategy getReplicationStrategy(); void setReplicationStrategy(ReplicationStrategy replicationStrategy); OrphanedDataStrategy getOrphanedDataStrategy(); void setOrphanedDataStrategy(OrphanedDataStrategy orphanedDataStrategy); }### Answer:
@Test public void mergeNullOptions() { Map<String, Object> mergedCopierOptions = tableReplication.getMergedCopierOptions(null); assertThat(mergedCopierOptions, is(not(nullValue()))); assertThat(mergedCopierOptions.isEmpty(), is(true)); } |
### Question:
SourceCatalog implements TunnelMetastoreCatalog { public void setName(String name) { this.name = name; } @Override String getName(); void setName(String name); boolean isDisableSnapshots(); void setDisableSnapshots(boolean disableSnapshots); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); }### Answer:
@Test public void nullName() { sourceCatalog.setName(null); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyName() { sourceCatalog.setName(""); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankName() { sourceCatalog.setName(" "); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void nullDatabaseName() { sourceTable.setDatabaseName(null); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void emptyDatabaseName() { sourceTable.setDatabaseName(""); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void blankDatabaseName() { sourceTable.setDatabaseName(" "); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setTableName(String tableName) { this.tableName = tableName; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void nullTableName() { sourceTable.setTableName(null); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void emptyTableName() { sourceTable.setTableName(""); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setPartitionLimit(Short partitionLimit) { this.partitionLimit = partitionLimit; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void partitionLimitTooLow() { sourceTable.setPartitionLimit((short) 0); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public String getQualifiedName() { return databaseName.toLowerCase(Locale.ROOT) + "." + tableName.toLowerCase(Locale.ROOT); } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void qualifiedTableName() { assertThat(sourceTable.getQualifiedName(), is("databasename.tablename")); } |
### Question:
AvroStringUtils { public static boolean argsPresent(String... args) { for (String arg : args) { if (isBlank(arg)) { return false; } } return true; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer:
@Test public void argsPresentTest() { assertTrue(argsPresent("test", "strings", "are", "present")); }
@Test public void argsPresentShouldFailWithNullStringTest() { assertFalse(argsPresent("test", "strings", null, "present")); }
@Test public void argsPresentShouldFailWithEmptyStringTest() { assertFalse(argsPresent("test", "strings", "", "present")); } |
### Question:
S3S3CopierOptions { public URI getS3Endpoint() { return s3Endpoint(Keys.S3_ENDPOINT_URI.keyName()); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer:
@Test public void getS3Endpoint() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.S3_ENDPOINT_URI.keyName(), "http: S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getS3Endpoint(), is(URI.create("http: }
@Test public void getS3EndpointDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getS3Endpoint()); } |
### Question:
S3MapReduceCpCopierFactory implements CopierFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return !S3Schemes.isS3Scheme(sourceScheme) && S3Schemes.isS3Scheme(replicaScheme); } @Autowired S3MapReduceCpCopierFactory(@Value("#{sourceHiveConf}") Configuration conf, MetricRegistry runningMetricsRegistry); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); @Override Copier newInstance(CopierContext copierContext); @Override Copier newInstance(
String eventId,
Path sourceBaseLocation,
Path replicaLocation,
Map<String, Object> copierOptions); @Override Copier newInstance(
String eventId,
Path sourceBaseLocation,
List<Path> sourceSubLocations,
Path replicaLocation,
Map<String, Object> copierOptions); }### Answer:
@Test public void supportsSchemes() throws Exception { S3MapReduceCpCopierFactory factory = new S3MapReduceCpCopierFactory(conf, runningMetricsRegistry); assertTrue(factory.supportsSchemes("hdfs", "s3")); assertTrue(factory.supportsSchemes("hdfs", "s3a")); assertTrue(factory.supportsSchemes("hdfs", "s3n")); assertTrue(factory.supportsSchemes("file", "s3")); assertTrue(factory.supportsSchemes("whatever", "s3")); }
@Test public void doesNotsupportsSchemes() throws Exception { S3MapReduceCpCopierFactory factory = new S3MapReduceCpCopierFactory(conf, runningMetricsRegistry); assertFalse(factory.supportsSchemes("hdfs", "hdfs")); assertFalse(factory.supportsSchemes("s3", "s3")); assertFalse(factory.supportsSchemes("s3", "hdfs")); assertFalse(factory.supportsSchemes("hdfs", "s321")); } |
### Question:
FileSystemPathResolver { public Path resolveScheme(Path path) { try { URI uri = path.toUri(); if (isEmpty(uri.getScheme())) { String scheme = FileSystem.get(configuration).getScheme(); Path result = new Path(new URI(scheme, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()).toString()); LOG.info("Added scheme {} to path {}. Resulting path is {}", scheme, path, result); return result; } } catch (URISyntaxException | IOException e) { throw new CircusTrainException(e); } return path; } FileSystemPathResolver(Configuration configuration); Path resolveScheme(Path path); Path resolveNameServices(Path path); }### Answer:
@Test public void resolveSchemeDoesntChangeSchemeForPathWithScheme() { Path expected = new Path("s3:/etl/test/avsc/schema.avsc"); Path result = resolver.resolveScheme(expected); assertThat(result, is(expected)); }
@Test public void resolveSchemeDoesntChangeSchemeForFullyQualifiedPathWithScheme() { Path expected = new Path("s3: Path result = resolver.resolveScheme(expected); assertThat(result, is(expected)); }
@Test public void resolveSchemeSetsSchemeIfSchemeIsntPresent() { Path input = new Path("/etl/test/avsc/schema.avsc"); Path result = resolver.resolveScheme(input); Path expected = new Path("file:/etl/test/avsc/schema.avsc"); assertThat(result, is(expected)); } |
### Question:
FileSystemPathResolver { public Path resolveNameServices(Path path) { URI uri = path.toUri(); if (HDFS_SCHEME.equalsIgnoreCase(uri.getScheme())) { String nameService = configuration.get(DFSConfigKeys.DFS_NAMESERVICES); if (isNotBlank(nameService)) { String scheme = uri.getScheme(); String url = uri.getPath(); final String original = path.toString(); if (isBlank(scheme)) { url = String.format("/%s%s", nameService, path); path = new Path(url); } else { path = new Path(scheme, nameService, url); } LOG.info("Added nameservice to path. {} became {}", original, path); } } return path; } FileSystemPathResolver(Configuration configuration); Path resolveScheme(Path path); Path resolveNameServices(Path path); }### Answer:
@Test public void resolveNameServiceAddsAuthorityToPathWithScheme() { setDfsPaths("hdp-ha"); Path input = new Path("hdfs:/etl/test/avsc/schema.avsc"); Path result = resolver.resolveNameServices(input); Path expected = new Path("hdfs: assertThat(result, is(expected)); }
@Test public void resolveNameServiceS3() { setDfsPaths("hdp-ha"); Path input = new Path("s3: Path result = resolver.resolveNameServices(input); assertThat(result, is(input)); }
@Test public void resolveNameServicesAddsAuthorityToFullyQualifiedPathWithScheme() { setDfsPaths("hdp-ha"); Path input = new Path("hdfs: Path result = resolver.resolveNameServices(input); Path expected = new Path("hdfs: assertThat(result, is(expected)); }
@Test public void resolveNameServicesAddsAuthorityToPathWithoutScheme() { setDfsPaths("foo"); Path input = new Path("/etl/test/avsc/schema.avsc"); Path result = resolver.resolveNameServices(input); Path expected = new Path("/etl/test/avsc/schema.avsc"); assertThat(result, is(expected)); }
@Test public void resolveNameServicesWithEmptyDfsNameservicesConfiguredReturnsOriginalPathFromFullyQualifiedPathWithScheme() { setDfsPaths(""); Path expected = new Path("hdfs: Path result = resolver.resolveNameServices(expected); assertThat(result, is(expected)); }
@Test public void resolveNameServicesWithEmptyDfsNameservicesConfiguredReturnsOriginalPathFromPathWithScheme() { setDfsPaths(""); Path expected = new Path("hdfs:/etl/test/avsc/schema.avsc"); Path result = resolver.resolveNameServices(expected); assertThat(result, is(expected)); }
@Test public void resolveNameServicesWithoutDfsNameservicesConfiguredReturnsOriginalPathFromFullyQualifiedPathWithScheme() { Path expected = new Path("hdfs: Path result = resolver.resolveNameServices(expected); assertThat(result, is(expected)); }
@Test public void resolveNameServicesWithoutDfsNameservicesConfiguredReturnsOriginalPathFromPathWithScheme() { Path expected = new Path("hdfs:/etl/test/avsc/schema.avsc"); Path result = resolver.resolveNameServices(expected); assertThat(result, is(expected)); }
@Test public void resolveNameServicesWithoutDfsNameservicesReturnsOriginalPathWithoutScheme() { Path expected = new Path("/etl/test/avsc/schema.avsc"); Path result = resolver.resolveNameServices(expected); assertThat(result, is(expected)); } |
### Question:
SchemaCopier { public Path copy(String source, String destination, EventTableReplication eventTableReplication, String eventId) { checkNotNull(source, "source cannot be null"); checkNotNull(destination, "destinationFolder cannot be null"); FileSystemPathResolver sourceFileSystemPathResolver = new FileSystemPathResolver(sourceHiveConf); Path sourceLocation = new Path(source); sourceLocation = sourceFileSystemPathResolver.resolveScheme(sourceLocation); sourceLocation = sourceFileSystemPathResolver.resolveNameServices(sourceLocation); Path destinationSchemaFile = new Path(destination, sourceLocation.getName()); Map<String, Object> mergedCopierOptions = new HashMap<>(TableReplication .getMergedCopierOptions(globalCopierOptions.getCopierOptions(), eventTableReplication.getCopierOptions())); mergedCopierOptions.put(CopierOptions.COPY_DESTINATION_IS_FILE, "true"); CopierFactory copierFactory = copierFactoryManager .getCopierFactory(sourceLocation, destinationSchemaFile, mergedCopierOptions); LOG.info("Replicating Avro schema from '{}' to '{}'", sourceLocation, destinationSchemaFile); CopierContext copierContext = new CopierContext(eventId, sourceLocation, destinationSchemaFile, mergedCopierOptions); Copier copier = copierFactory.newInstance(copierContext); Metrics metrics = copier.copy(); LOG .info("Avro schema '{} bytes' has been copied from '{}' to '{}'", metrics.getBytesReplicated(), sourceLocation, destinationSchemaFile); return destinationSchemaFile; } @Autowired SchemaCopier(
Configuration sourceHiveConf,
CopierFactoryManager copierFactoryManager,
CopierOptions globalCopierOptions); Path copy(String source, String destination, EventTableReplication eventTableReplication, String eventId); }### Answer:
@Test public void copiedToCorrectDestination() throws IOException { Path source = new Path(temporaryFolder.newFile("test.txt").toURI()); File destination = temporaryFolder.newFolder(); Path targetFile = new Path(destination.toString(), "test.txt"); Map<String, Object> copierOptionsMap = new HashMap<>(); copierOptionsMap.put(CopierOptions.COPY_DESTINATION_IS_FILE, "true"); when(copierFactoryManager.getCopierFactory(eq(source), eq(targetFile), eq(copierOptionsMap))) .thenReturn(copierFactory); when(copierFactory.newInstance(any(CopierContext.class))).thenReturn(copier); when(copier.copy()).thenReturn(metrics); when(metrics.getBytesReplicated()).thenReturn(123L); Path result = schemaCopier.copy(source.toString(), destination.toString(), eventTableReplication, eventId); assertThat(result, is(targetFile)); }
@Test(expected = NullPointerException.class) public void copyWithNullSourceParamThrowsException() throws IOException { File destination = temporaryFolder.newFolder(); schemaCopier.copy(null, destination.toString(), eventTableReplication, eventId); }
@Test(expected = IllegalArgumentException.class) public void copyWithEmptySourceParamThrowsException() throws IOException { File destination = temporaryFolder.newFolder(); schemaCopier.copy("", destination.toString(), eventTableReplication, eventId); }
@Test(expected = NullPointerException.class) public void copyWithNullDestinationParamThrowsException() throws IOException { File source = temporaryFolder.newFile("test.txt"); schemaCopier.copy(source.toString(), null, eventTableReplication, eventId); }
@Test(expected = IllegalArgumentException.class) public void copyWithEmptyDestinationParamThrowsException() throws IOException { File source = temporaryFolder.newFile("test.txt"); schemaCopier.copy(source.toString(), "", eventTableReplication, eventId); } |
### Question:
S3S3CopierOptions { public Boolean isS3ServerSideEncryption() { return MapUtils.getBoolean(copierOptions, Keys.S3_SERVER_SIDE_ENCRYPTION.keyName(), false); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer:
@Test public void setS3ServerSideEncryption() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.S3_SERVER_SIDE_ENCRYPTION.keyName(), "true"); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.isS3ServerSideEncryption(), is(true)); }
@Test public void defaultS3ServerSideEncryption() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.isS3ServerSideEncryption(), is(false)); } |
### Question:
CheckpointStatsTracker { public CheckpointCoordinatorConfiguration getJobCheckpointingConfiguration() { return jobCheckpointingConfiguration; } CheckpointStatsTracker(
int numRememberedCheckpoints,
List<ExecutionJobVertex> jobVertices,
CheckpointCoordinatorConfiguration jobCheckpointingConfiguration,
MetricGroup metricGroup); CheckpointCoordinatorConfiguration getJobCheckpointingConfiguration(); CheckpointStatsSnapshot createSnapshot(); }### Answer:
@Test public void testGetSnapshottingSettings() throws Exception { ExecutionJobVertex jobVertex = mock(ExecutionJobVertex.class); when(jobVertex.getJobVertexId()).thenReturn(new JobVertexID()); when(jobVertex.getParallelism()).thenReturn(1); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), new CheckpointCoordinatorConfiguration( 181238123L, 19191992L, 191929L, 123, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, false ), null); CheckpointStatsTracker tracker = new CheckpointStatsTracker( 0, Collections.singletonList(jobVertex), snapshottingSettings.getCheckpointCoordinatorConfiguration(), new UnregisteredMetricsGroup()); assertEquals(snapshottingSettings.getCheckpointCoordinatorConfiguration(), tracker.getJobCheckpointingConfiguration()); }
@Test public void testGetSnapshottingSettings() throws Exception { ExecutionJobVertex jobVertex = mock(ExecutionJobVertex.class); when(jobVertex.getJobVertexId()).thenReturn(new JobVertexID()); when(jobVertex.getParallelism()).thenReturn(1); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), new CheckpointCoordinatorConfiguration( 181238123L, 19191992L, 191929L, 123, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, false, false, 0 ), null); CheckpointStatsTracker tracker = new CheckpointStatsTracker( 0, Collections.singletonList(jobVertex), snapshottingSettings.getCheckpointCoordinatorConfiguration(), new UnregisteredMetricsGroup()); assertEquals(snapshottingSettings.getCheckpointCoordinatorConfiguration(), tracker.getJobCheckpointingConfiguration()); }
@Test public void testGetSnapshottingSettings() throws Exception { ExecutionJobVertex jobVertex = mock(ExecutionJobVertex.class); when(jobVertex.getJobVertexId()).thenReturn(new JobVertexID()); when(jobVertex.getParallelism()).thenReturn(1); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), Collections.singletonList(new JobVertexID()), new CheckpointCoordinatorConfiguration( 181238123L, 19191992L, 191929L, 123, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, false, false, false, 0 ), null); CheckpointStatsTracker tracker = new CheckpointStatsTracker( 0, Collections.singletonList(jobVertex), snapshottingSettings.getCheckpointCoordinatorConfiguration(), new UnregisteredMetricsGroup()); assertEquals(snapshottingSettings.getCheckpointCoordinatorConfiguration(), tracker.getJobCheckpointingConfiguration()); } |
### Question:
PendingCheckpointStats extends AbstractCheckpointStats { CompletedCheckpointStats.DiscardCallback reportCompletedCheckpoint(String externalPointer) { CompletedCheckpointStats completed = new CompletedCheckpointStats( checkpointId, triggerTimestamp, props, numberOfSubtasks, new HashMap<>(taskStats), currentNumAcknowledgedSubtasks, currentStateSize, currentAlignmentBuffered, latestAcknowledgedSubtask, externalPointer); trackerCallback.reportCompletedCheckpoint(completed); return completed.getDiscardCallback(); } PendingCheckpointStats(
long checkpointId,
long triggerTimestamp,
CheckpointProperties props,
int totalSubtaskCount,
Map<JobVertexID, TaskStateStats> taskStats,
CheckpointStatsTracker.PendingCheckpointStatsCallback trackerCallback); @Override CheckpointStatsStatus getStatus(); @Override int getNumberOfAcknowledgedSubtasks(); @Override long getStateSize(); @Override long getAlignmentBuffered(); @Override SubtaskStateStats getLatestAcknowledgedSubtaskStats(); @Override String toString(); }### Answer:
@Test public void testReportCompletedCheckpoint() throws Exception { TaskStateStats task1 = new TaskStateStats(new JobVertexID(), 3); TaskStateStats task2 = new TaskStateStats(new JobVertexID(), 4); HashMap<JobVertexID, TaskStateStats> taskStats = new HashMap<>(); taskStats.put(task1.getJobVertexId(), task1); taskStats.put(task2.getJobVertexId(), task2); CheckpointStatsTracker.PendingCheckpointStatsCallback callback = mock( CheckpointStatsTracker.PendingCheckpointStatsCallback.class); PendingCheckpointStats pending = new PendingCheckpointStats( 0, 1, CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), task1.getNumberOfSubtasks() + task2.getNumberOfSubtasks(), taskStats, callback); for (int i = 0; i < task1.getNumberOfSubtasks(); i++) { pending.reportSubtaskStats(task1.getJobVertexId(), createSubtaskStats(i)); } for (int i = 0; i < task2.getNumberOfSubtasks(); i++) { pending.reportSubtaskStats(task2.getJobVertexId(), createSubtaskStats(i)); } String externalPath = "asdjkasdjkasd"; CompletedCheckpointStats.DiscardCallback discardCallback = pending.reportCompletedCheckpoint(externalPath); ArgumentCaptor<CompletedCheckpointStats> args = ArgumentCaptor.forClass(CompletedCheckpointStats.class); verify(callback).reportCompletedCheckpoint(args.capture()); CompletedCheckpointStats completed = args.getValue(); assertNotNull(completed); assertEquals(CheckpointStatsStatus.COMPLETED, completed.getStatus()); assertFalse(completed.isDiscarded()); discardCallback.notifyDiscardedCheckpoint(); assertTrue(completed.isDiscarded()); assertEquals(externalPath, completed.getExternalPath()); assertEquals(pending.getCheckpointId(), completed.getCheckpointId()); assertEquals(pending.getNumberOfAcknowledgedSubtasks(), completed.getNumberOfAcknowledgedSubtasks()); assertEquals(pending.getLatestAcknowledgedSubtaskStats(), completed.getLatestAcknowledgedSubtaskStats()); assertEquals(pending.getLatestAckTimestamp(), completed.getLatestAckTimestamp()); assertEquals(pending.getEndToEndDuration(), completed.getEndToEndDuration()); assertEquals(pending.getStateSize(), completed.getStateSize()); assertEquals(pending.getAlignmentBuffered(), completed.getAlignmentBuffered()); assertEquals(task1, completed.getTaskStateStats(task1.getJobVertexId())); assertEquals(task2, completed.getTaskStateStats(task2.getJobVertexId())); } |
### Question:
PendingCheckpointStats extends AbstractCheckpointStats { void reportFailedCheckpoint(long failureTimestamp, @Nullable Throwable cause) { FailedCheckpointStats failed = new FailedCheckpointStats( checkpointId, triggerTimestamp, props, numberOfSubtasks, new HashMap<>(taskStats), currentNumAcknowledgedSubtasks, currentStateSize, currentAlignmentBuffered, failureTimestamp, latestAcknowledgedSubtask, cause); trackerCallback.reportFailedCheckpoint(failed); } PendingCheckpointStats(
long checkpointId,
long triggerTimestamp,
CheckpointProperties props,
int totalSubtaskCount,
Map<JobVertexID, TaskStateStats> taskStats,
CheckpointStatsTracker.PendingCheckpointStatsCallback trackerCallback); @Override CheckpointStatsStatus getStatus(); @Override int getNumberOfAcknowledgedSubtasks(); @Override long getStateSize(); @Override long getAlignmentBuffered(); @Override SubtaskStateStats getLatestAcknowledgedSubtaskStats(); @Override String toString(); }### Answer:
@Test public void testReportFailedCheckpoint() throws Exception { TaskStateStats task1 = new TaskStateStats(new JobVertexID(), 3); TaskStateStats task2 = new TaskStateStats(new JobVertexID(), 4); HashMap<JobVertexID, TaskStateStats> taskStats = new HashMap<>(); taskStats.put(task1.getJobVertexId(), task1); taskStats.put(task2.getJobVertexId(), task2); CheckpointStatsTracker.PendingCheckpointStatsCallback callback = mock( CheckpointStatsTracker.PendingCheckpointStatsCallback.class); long triggerTimestamp = 123123; PendingCheckpointStats pending = new PendingCheckpointStats( 0, triggerTimestamp, CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), task1.getNumberOfSubtasks() + task2.getNumberOfSubtasks(), taskStats, callback); for (int i = 0; i < task1.getNumberOfSubtasks(); i++) { pending.reportSubtaskStats(task1.getJobVertexId(), createSubtaskStats(i)); } for (int i = 0; i < task2.getNumberOfSubtasks(); i++) { pending.reportSubtaskStats(task2.getJobVertexId(), createSubtaskStats(i)); } Exception cause = new Exception("test exception"); long failureTimestamp = 112211137; pending.reportFailedCheckpoint(failureTimestamp, cause); ArgumentCaptor<FailedCheckpointStats> args = ArgumentCaptor.forClass(FailedCheckpointStats.class); verify(callback).reportFailedCheckpoint(args.capture()); FailedCheckpointStats failed = args.getValue(); assertNotNull(failed); assertEquals(CheckpointStatsStatus.FAILED, failed.getStatus()); assertEquals(failureTimestamp, failed.getFailureTimestamp()); assertEquals(cause.getMessage(), failed.getFailureMessage()); assertEquals(pending.getCheckpointId(), failed.getCheckpointId()); assertEquals(pending.getNumberOfAcknowledgedSubtasks(), failed.getNumberOfAcknowledgedSubtasks()); assertEquals(pending.getLatestAcknowledgedSubtaskStats(), failed.getLatestAcknowledgedSubtaskStats()); assertEquals(pending.getLatestAckTimestamp(), failed.getLatestAckTimestamp()); assertEquals(failureTimestamp - triggerTimestamp, failed.getEndToEndDuration()); assertEquals(pending.getStateSize(), failed.getStateSize()); assertEquals(pending.getAlignmentBuffered(), failed.getAlignmentBuffered()); assertEquals(task1, failed.getTaskStateStats(task1.getJobVertexId())); assertEquals(task2, failed.getTaskStateStats(task2.getJobVertexId())); } |
### Question:
CheckpointProperties implements Serializable { @VisibleForTesting CheckpointProperties( boolean forced, CheckpointType checkpointType, boolean discardSubsumed, boolean discardFinished, boolean discardCancelled, boolean discardFailed, boolean discardSuspended) { this.forced = forced; this.checkpointType = checkNotNull(checkpointType); this.discardSubsumed = discardSubsumed; this.discardFinished = discardFinished; this.discardCancelled = discardCancelled; this.discardFailed = discardFailed; this.discardSuspended = discardSuspended; } @VisibleForTesting CheckpointProperties(
boolean forced,
CheckpointType checkpointType,
boolean discardSubsumed,
boolean discardFinished,
boolean discardCancelled,
boolean discardFailed,
boolean discardSuspended); CheckpointType getCheckpointType(); boolean isSavepoint(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static CheckpointProperties forSavepoint(); static CheckpointProperties forCheckpoint(CheckpointRetentionPolicy policy); }### Answer:
@Test public void testCheckpointProperties() { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_FAILURE); assertFalse(props.forceCheckpoint()); assertTrue(props.discardOnSubsumed()); assertTrue(props.discardOnJobFinished()); assertTrue(props.discardOnJobCancelled()); assertFalse(props.discardOnJobFailed()); assertTrue(props.discardOnJobSuspended()); props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_CANCELLATION); assertFalse(props.forceCheckpoint()); assertTrue(props.discardOnSubsumed()); assertTrue(props.discardOnJobFinished()); assertFalse(props.discardOnJobCancelled()); assertFalse(props.discardOnJobFailed()); assertFalse(props.discardOnJobSuspended()); } |
### Question:
CheckpointProperties implements Serializable { public boolean isSavepoint() { return checkpointType == CheckpointType.SAVEPOINT; } @VisibleForTesting CheckpointProperties(
boolean forced,
CheckpointType checkpointType,
boolean discardSubsumed,
boolean discardFinished,
boolean discardCancelled,
boolean discardFailed,
boolean discardSuspended); CheckpointType getCheckpointType(); boolean isSavepoint(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static CheckpointProperties forSavepoint(); static CheckpointProperties forCheckpoint(CheckpointRetentionPolicy policy); }### Answer:
@Test public void testIsSavepoint() throws Exception { { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_FAILURE); assertFalse(props.isSavepoint()); } { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_CANCELLATION); assertFalse(props.isSavepoint()); } { CheckpointProperties props = CheckpointProperties.forSavepoint(); assertTrue(props.isSavepoint()); CheckpointProperties deserializedCheckpointProperties = InstantiationUtil.deserializeObject( InstantiationUtil.serializeObject(props), getClass().getClassLoader()); assertTrue(deserializedCheckpointProperties.isSavepoint()); } } |
### Question:
StateObjectCollection implements Collection<T>, StateObject { public boolean hasState() { for (StateObject state : stateObjects) { if (state != null) { return true; } } return false; } StateObjectCollection(); StateObjectCollection(Collection<T> stateObjects); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean removeIf(Predicate<? super T> filter); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override void discardState(); @Override long getStateSize(); boolean hasState(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static StateObjectCollection<T> empty(); static StateObjectCollection<T> singleton(T stateObject); }### Answer:
@Test public void testHasState() { StateObjectCollection<StateObject> stateObjects = new StateObjectCollection<>(new ArrayList<>()); Assert.assertFalse(stateObjects.hasState()); stateObjects = new StateObjectCollection<>(Collections.singletonList(null)); Assert.assertFalse(stateObjects.hasState()); stateObjects = new StateObjectCollection<>(Collections.singletonList(mock(StateObject.class))); Assert.assertTrue(stateObjects.hasState()); } |
### Question:
CheckpointCoordinator { public CompletableFuture<CompletedCheckpoint> triggerSavepoint( long timestamp, @Nullable String targetLocation) { CheckpointProperties props = CheckpointProperties.forSavepoint(); CheckpointTriggerResult triggerResult = triggerCheckpoint( timestamp, props, targetLocation, false); if (triggerResult.isSuccess()) { return triggerResult.getPendingCheckpoint().getCompletionFuture(); } else { Throwable cause = new CheckpointTriggerException("Failed to trigger savepoint.", triggerResult.getFailureReason()); return FutureUtils.completedExceptionally(cause); } } CheckpointCoordinator(
JobID job,
long baseInterval,
long checkpointTimeout,
long minPauseBetweenCheckpoints,
int maxConcurrentCheckpointAttempts,
CheckpointRetentionPolicy retentionPolicy,
ExecutionVertex[] tasksToTrigger,
ExecutionVertex[] tasksToWaitFor,
ExecutionVertex[] tasksToCommitTo,
CheckpointIDCounter checkpointIDCounter,
CompletedCheckpointStore completedCheckpointStore,
StateBackend checkpointStateBackend,
Executor executor,
SharedStateRegistryFactory sharedStateRegistryFactory); boolean addMasterHook(MasterTriggerRestoreHook<?> hook); int getNumberOfRegisteredMasterHooks(); void setCheckpointStatsTracker(@Nullable CheckpointStatsTracker statsTracker); void shutdown(JobStatus jobStatus); boolean isShutdown(); CompletableFuture<CompletedCheckpoint> triggerSavepoint(
long timestamp,
@Nullable String targetLocation); boolean triggerCheckpoint(long timestamp, boolean isPeriodic); @VisibleForTesting CheckpointTriggerResult triggerCheckpoint(
long timestamp,
CheckpointProperties props,
@Nullable String externalSavepointLocation,
boolean isPeriodic); void receiveDeclineMessage(DeclineCheckpoint message); boolean receiveAcknowledgeMessage(AcknowledgeCheckpoint message); void failUnacknowledgedPendingCheckpointsFor(ExecutionAttemptID executionAttemptId, Throwable cause); boolean restoreLatestCheckpointedState(
Map<JobVertexID, ExecutionJobVertex> tasks,
boolean errorIfNoCheckpoint,
boolean allowNonRestoredState); boolean restoreSavepoint(
String savepointPointer,
boolean allowNonRestored,
Map<JobVertexID, ExecutionJobVertex> tasks,
ClassLoader userClassLoader); int getNumberOfPendingCheckpoints(); int getNumberOfRetainedSuccessfulCheckpoints(); Map<Long, PendingCheckpoint> getPendingCheckpoints(); List<CompletedCheckpoint> getSuccessfulCheckpoints(); CheckpointStorage getCheckpointStorage(); CompletedCheckpointStore getCheckpointStore(); CheckpointIDCounter getCheckpointIdCounter(); long getCheckpointTimeout(); boolean isPeriodicCheckpointingConfigured(); void startCheckpointScheduler(); void stopCheckpointScheduler(); JobStatusListener createActivatorDeactivator(); }### Answer:
@Test public void testMinDelayBetweenSavepoints() throws Exception { JobID jobId = new JobID(); final ExecutionAttemptID attemptID1 = new ExecutionAttemptID(); ExecutionVertex vertex1 = mockExecutionVertex(attemptID1); CheckpointCoordinator coord = new CheckpointCoordinator( jobId, 100000, 200000, 100000000L, 1, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, new ExecutionVertex[] { vertex1 }, new ExecutionVertex[] { vertex1 }, new ExecutionVertex[] { vertex1 }, new StandaloneCheckpointIDCounter(), new StandaloneCompletedCheckpointStore(2), new MemoryStateBackend(), Executors.directExecutor(), SharedStateRegistry.DEFAULT_FACTORY); String savepointDir = tmpFolder.newFolder().getAbsolutePath(); CompletableFuture<CompletedCheckpoint> savepoint0 = coord.triggerSavepoint(0, savepointDir); assertFalse("Did not trigger savepoint", savepoint0.isDone()); CompletableFuture<CompletedCheckpoint> savepoint1 = coord.triggerSavepoint(1, savepointDir); assertFalse("Did not trigger savepoint", savepoint1.isDone()); } |
### Question:
CheckpointCoordinator { public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) { return triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic).isSuccess(); } CheckpointCoordinator(
JobID job,
long baseInterval,
long checkpointTimeout,
long minPauseBetweenCheckpoints,
int maxConcurrentCheckpointAttempts,
CheckpointRetentionPolicy retentionPolicy,
ExecutionVertex[] tasksToTrigger,
ExecutionVertex[] tasksToWaitFor,
ExecutionVertex[] tasksToCommitTo,
CheckpointIDCounter checkpointIDCounter,
CompletedCheckpointStore completedCheckpointStore,
StateBackend checkpointStateBackend,
Executor executor,
SharedStateRegistryFactory sharedStateRegistryFactory); boolean addMasterHook(MasterTriggerRestoreHook<?> hook); int getNumberOfRegisteredMasterHooks(); void setCheckpointStatsTracker(@Nullable CheckpointStatsTracker statsTracker); void shutdown(JobStatus jobStatus); boolean isShutdown(); CompletableFuture<CompletedCheckpoint> triggerSavepoint(
long timestamp,
@Nullable String targetLocation); boolean triggerCheckpoint(long timestamp, boolean isPeriodic); @VisibleForTesting CheckpointTriggerResult triggerCheckpoint(
long timestamp,
CheckpointProperties props,
@Nullable String externalSavepointLocation,
boolean isPeriodic); void receiveDeclineMessage(DeclineCheckpoint message); boolean receiveAcknowledgeMessage(AcknowledgeCheckpoint message); void failUnacknowledgedPendingCheckpointsFor(ExecutionAttemptID executionAttemptId, Throwable cause); boolean restoreLatestCheckpointedState(
Map<JobVertexID, ExecutionJobVertex> tasks,
boolean errorIfNoCheckpoint,
boolean allowNonRestoredState); boolean restoreSavepoint(
String savepointPointer,
boolean allowNonRestored,
Map<JobVertexID, ExecutionJobVertex> tasks,
ClassLoader userClassLoader); int getNumberOfPendingCheckpoints(); int getNumberOfRetainedSuccessfulCheckpoints(); Map<Long, PendingCheckpoint> getPendingCheckpoints(); List<CompletedCheckpoint> getSuccessfulCheckpoints(); CheckpointStorage getCheckpointStorage(); CompletedCheckpointStore getCheckpointStore(); CheckpointIDCounter getCheckpointIdCounter(); long getCheckpointTimeout(); boolean isPeriodicCheckpointingConfigured(); void startCheckpointScheduler(); void stopCheckpointScheduler(); JobStatusListener createActivatorDeactivator(); }### Answer:
@Test public void testStopPeriodicScheduler() throws Exception { final ExecutionAttemptID attemptID1 = new ExecutionAttemptID(); ExecutionVertex vertex1 = mockExecutionVertex(attemptID1); CheckpointCoordinator coord = new CheckpointCoordinator( new JobID(), 600000, 600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, new ExecutionVertex[] { vertex1 }, new ExecutionVertex[] { vertex1 }, new ExecutionVertex[] { vertex1 }, new StandaloneCheckpointIDCounter(), new StandaloneCompletedCheckpointStore(1), new MemoryStateBackend(), Executors.directExecutor(), SharedStateRegistry.DEFAULT_FACTORY); CheckpointTriggerResult triggerResult = coord.triggerCheckpoint( System.currentTimeMillis(), CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), null, true); assertTrue(triggerResult.isFailure()); assertEquals(CheckpointDeclineReason.PERIODIC_SCHEDULER_SHUTDOWN, triggerResult.getFailureReason()); triggerResult = coord.triggerCheckpoint( System.currentTimeMillis(), CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), null, false); assertFalse(triggerResult.isFailure()); } |
### Question:
FailedCheckpointStats extends AbstractCheckpointStats { @Override public long getEndToEndDuration() { return Math.max(0, failureTimestamp - triggerTimestamp); } FailedCheckpointStats(
long checkpointId,
long triggerTimestamp,
CheckpointProperties props,
int totalSubtaskCount,
Map<JobVertexID, TaskStateStats> taskStats,
int numAcknowledgedSubtasks,
long stateSize,
long alignmentBuffered,
long failureTimestamp,
@Nullable SubtaskStateStats latestAcknowledgedSubtask,
@Nullable Throwable cause); @Override CheckpointStatsStatus getStatus(); @Override int getNumberOfAcknowledgedSubtasks(); @Override long getStateSize(); @Override long getAlignmentBuffered(); @Override @Nullable SubtaskStateStats getLatestAcknowledgedSubtaskStats(); @Override long getEndToEndDuration(); long getFailureTimestamp(); @Nullable String getFailureMessage(); }### Answer:
@Test public void testEndToEndDuration() throws Exception { long duration = 123912931293L; long triggerTimestamp = 10123; long failureTimestamp = triggerTimestamp + duration; Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>(); JobVertexID jobVertexId = new JobVertexID(); taskStats.put(jobVertexId, new TaskStateStats(jobVertexId, 1)); FailedCheckpointStats failed = new FailedCheckpointStats( 0, triggerTimestamp, CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), 1, taskStats, 0, 0, 0, failureTimestamp, null, null); assertEquals(duration, failed.getEndToEndDuration()); } |
### Question:
JobResult implements Serializable { public boolean isSuccess() { return serializedThrowable == null; } private JobResult(
final JobID jobId,
final Map<String, SerializedValue<OptionalFailure<Object>>> accumulatorResults,
final long netRuntime,
@Nullable final SerializedThrowable serializedThrowable); boolean isSuccess(); JobID getJobId(); Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorResults(); long getNetRuntime(); Optional<SerializedThrowable> getSerializedThrowable(); JobExecutionResult toJobExecutionResult(ClassLoader classLoader); static JobResult createFrom(AccessExecutionGraph accessExecutionGraph); }### Answer:
@Test public void testIsNotSuccess() throws Exception { final JobResult jobResult = new JobResult.Builder() .jobId(new JobID()) .serializedThrowable(new SerializedThrowable(new RuntimeException())) .netRuntime(Long.MAX_VALUE) .build(); assertThat(jobResult.isSuccess(), equalTo(false)); }
@Test public void testIsSuccess() throws Exception { final JobResult jobResult = new JobResult.Builder() .jobId(new JobID()) .netRuntime(Long.MAX_VALUE) .build(); assertThat(jobResult.isSuccess(), equalTo(true)); } |
### Question:
SlotSharingManager { MultiTaskSlot createRootSlot( SlotRequestId slotRequestId, CompletableFuture<? extends SlotContext> slotContextFuture, SlotRequestId allocatedSlotRequestId) { final MultiTaskSlot rootMultiTaskSlot = new MultiTaskSlot( slotRequestId, slotContextFuture, allocatedSlotRequestId); allTaskSlots.put(slotRequestId, rootMultiTaskSlot); synchronized (lock) { unresolvedRootSlots.put(slotRequestId, rootMultiTaskSlot); } slotContextFuture.whenComplete( (SlotContext slotContext, Throwable throwable) -> { if (slotContext != null) { synchronized (lock) { final MultiTaskSlot resolvedRootNode = unresolvedRootSlots.remove(slotRequestId); if (resolvedRootNode != null) { final Set<MultiTaskSlot> innerCollection = resolvedRootSlots.computeIfAbsent( slotContext.getTaskManagerLocation(), taskManagerLocation -> new HashSet<>(4)); innerCollection.add(resolvedRootNode); } } } else { rootMultiTaskSlot.release(throwable); } }); return rootMultiTaskSlot; } SlotSharingManager(
SlotSharingGroupId slotSharingGroupId,
AllocatedSlotActions allocatedSlotActions,
SlotOwner slotOwner); boolean isEmpty(); boolean contains(SlotRequestId slotRequestId); @Override String toString(); @VisibleForTesting Collection<MultiTaskSlot> getResolvedRootSlots(); }### Answer:
@Test public void testSlotContextFutureCompletion() throws Exception { final TestingAllocatedSlotActions allocatedSlotActions = new TestingAllocatedSlotActions(); final SlotSharingManager slotSharingManager = new SlotSharingManager( SLOT_SHARING_GROUP_ID, allocatedSlotActions, SLOT_OWNER); final SlotContext slotContext = new SimpleSlotContext( new AllocationID(), new LocalTaskManagerLocation(), 0, new SimpleAckingTaskManagerGateway()); CompletableFuture<SlotContext> slotContextFuture = new CompletableFuture<>(); SlotSharingManager.MultiTaskSlot rootSlot = slotSharingManager.createRootSlot( new SlotRequestId(), slotContextFuture, new SlotRequestId()); Locality locality1 = Locality.LOCAL; SlotSharingManager.SingleTaskSlot singleTaskSlot1 = rootSlot.allocateSingleTaskSlot( new SlotRequestId(), new AbstractID(), locality1); Locality locality2 = Locality.HOST_LOCAL; SlotSharingManager.SingleTaskSlot singleTaskSlot2 = rootSlot.allocateSingleTaskSlot( new SlotRequestId(), new AbstractID(), locality2); CompletableFuture<LogicalSlot> logicalSlotFuture1 = singleTaskSlot1.getLogicalSlotFuture(); CompletableFuture<LogicalSlot> logicalSlotFuture2 = singleTaskSlot2.getLogicalSlotFuture(); assertFalse(logicalSlotFuture1.isDone()); assertFalse(logicalSlotFuture2.isDone()); slotContextFuture.complete(slotContext); assertTrue(logicalSlotFuture1.isDone()); assertTrue(logicalSlotFuture2.isDone()); final LogicalSlot logicalSlot1 = logicalSlotFuture1.get(); final LogicalSlot logicalSlot2 = logicalSlotFuture2.get(); assertEquals(logicalSlot1.getAllocationId(), slotContext.getAllocationId()); assertEquals(logicalSlot2.getAllocationId(), slotContext.getAllocationId()); assertEquals(locality1, logicalSlot1.getLocality()); assertEquals(locality2, logicalSlot2.getLocality()); Locality locality3 = Locality.NON_LOCAL; SlotSharingManager.SingleTaskSlot singleTaskSlot3 = rootSlot.allocateSingleTaskSlot( new SlotRequestId(), new AbstractID(), locality3); CompletableFuture<LogicalSlot> logicalSlotFuture3 = singleTaskSlot3.getLogicalSlotFuture(); assertTrue(logicalSlotFuture3.isDone()); LogicalSlot logicalSlot3 = logicalSlotFuture3.get(); assertEquals(locality3, logicalSlot3.getLocality()); assertEquals(slotContext.getAllocationId(), logicalSlot3.getAllocationId()); } |
### Question:
JobManagerRunner implements LeaderContender, OnCompletionActions, AutoCloseableAsync { @Override public void jobFinishedByOther() { resultFuture.completeExceptionally(new JobNotFinishedException(jobGraph.getJobID())); } JobManagerRunner(
final ResourceID resourceId,
final JobGraph jobGraph,
final Configuration configuration,
final RpcService rpcService,
final HighAvailabilityServices haServices,
final HeartbeatServices heartbeatServices,
final BlobServer blobServer,
final JobManagerSharedServices jobManagerSharedServices,
final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
final FatalErrorHandler fatalErrorHandler); CompletableFuture<JobMasterGateway> getLeaderGatewayFuture(); JobGraph getJobGraph(); CompletableFuture<ArchivedExecutionGraph> getResultFuture(); void start(); @Override CompletableFuture<Void> closeAsync(); @Override void jobReachedGloballyTerminalState(ArchivedExecutionGraph executionGraph); @Override void jobFinishedByOther(); @Override void jobMasterFailed(Throwable cause); @Override void grantLeadership(final UUID leaderSessionID); @Override void revokeLeadership(); @Override String getAddress(); @Override void handleError(Exception exception); }### Answer:
@Test public void testJobFinishedByOther() throws Exception { final JobManagerRunner jobManagerRunner = createJobManagerRunner(); try { jobManagerRunner.start(); final CompletableFuture<ArchivedExecutionGraph> resultFuture = jobManagerRunner.getResultFuture(); assertThat(resultFuture.isDone(), is(false)); jobManagerRunner.jobFinishedByOther(); try { resultFuture.get(); fail("Should have failed."); } catch (ExecutionException ee) { assertThat(ExceptionUtils.stripExecutionException(ee), instanceOf(JobNotFinishedException.class)); } } finally { jobManagerRunner.close(); } } |
### Question:
JobManagerRunner implements LeaderContender, OnCompletionActions, AutoCloseableAsync { public void start() throws Exception { try { leaderElectionService.start(this); } catch (Exception e) { log.error("Could not start the JobManager because the leader election service did not start.", e); throw new Exception("Could not start the leader election service.", e); } } JobManagerRunner(
final ResourceID resourceId,
final JobGraph jobGraph,
final Configuration configuration,
final RpcService rpcService,
final HighAvailabilityServices haServices,
final HeartbeatServices heartbeatServices,
final BlobServer blobServer,
final JobManagerSharedServices jobManagerSharedServices,
final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
final FatalErrorHandler fatalErrorHandler); CompletableFuture<JobMasterGateway> getLeaderGatewayFuture(); JobGraph getJobGraph(); CompletableFuture<ArchivedExecutionGraph> getResultFuture(); void start(); @Override CompletableFuture<Void> closeAsync(); @Override void jobReachedGloballyTerminalState(ArchivedExecutionGraph executionGraph); @Override void jobFinishedByOther(); @Override void jobMasterFailed(Throwable cause); @Override void grantLeadership(final UUID leaderSessionID); @Override void revokeLeadership(); @Override String getAddress(); @Override void handleError(Exception exception); }### Answer:
@Test public void testLibraryCacheManagerRegistration() throws Exception { final JobManagerRunner jobManagerRunner = createJobManagerRunner(); try { jobManagerRunner.start(); final LibraryCacheManager libraryCacheManager = jobManagerSharedServices.getLibraryCacheManager(); final JobID jobID = jobGraph.getJobID(); assertThat(libraryCacheManager.hasClassLoader(jobID), is(true)); jobManagerRunner.close(); assertThat(libraryCacheManager.hasClassLoader(jobID), is(false)); } finally { jobManagerRunner.close(); } } |
### Question:
ImmutableListState extends ImmutableState implements ListState<V> { @Override public void update(List<V> values) throws Exception { throw MODIFICATION_ATTEMPT_ERROR; } private ImmutableListState(final List<V> state); @Override Iterable<V> get(); @Override void add(V value); @Override void clear(); static ImmutableListState<V> createState(
final ListStateDescriptor<V> stateDescriptor,
final byte[] serializedState); @Override void update(List<V> values); @Override void addAll(List<V> values); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testUpdate() { List<Long> list = getStateContents(); assertEquals(1L, list.size()); long element = list.get(0); assertEquals(42L, element); listState.add(54L); } |
### Question:
ImmutableListState extends ImmutableState implements ListState<V> { @Override public void clear() { throw MODIFICATION_ATTEMPT_ERROR; } private ImmutableListState(final List<V> state); @Override Iterable<V> get(); @Override void add(V value); @Override void clear(); static ImmutableListState<V> createState(
final ListStateDescriptor<V> stateDescriptor,
final byte[] serializedState); @Override void update(List<V> values); @Override void addAll(List<V> values); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testClear() { List<Long> list = getStateContents(); assertEquals(1L, list.size()); long element = list.get(0); assertEquals(42L, element); listState.clear(); } |
### Question:
RestClusterClient extends ClusterClient<T> implements NewClusterClient { @Override public CompletableFuture<Collection<JobStatusMessage>> listJobs() throws Exception { return sendRequest(JobsOverviewHeaders.getInstance()) .thenApply( (multipleJobsDetails) -> multipleJobsDetails .getJobs() .stream() .map(detail -> new JobStatusMessage( detail.getJobId(), detail.getJobName(), detail.getStatus(), detail.getStartTime())) .collect(Collectors.toList())); } RestClusterClient(Configuration config, T clusterId); RestClusterClient(
Configuration config,
T clusterId,
LeaderRetrievalService webMonitorRetrievalService); @VisibleForTesting RestClusterClient(
Configuration configuration,
@Nullable RestClient restClient,
T clusterId,
WaitStrategy waitStrategy,
@Nullable LeaderRetrievalService webMonitorRetrievalService); @Override void shutdown(); @Override JobSubmissionResult submitJob(JobGraph jobGraph, ClassLoader classLoader); @Override CompletableFuture<JobStatus> getJobStatus(JobID jobId); @Override CompletableFuture<JobResult> requestJobResult(@Nonnull JobID jobId); @Override CompletableFuture<JobSubmissionResult> submitJob(@Nonnull JobGraph jobGraph); @Override void stop(JobID jobID); @Override void cancel(JobID jobID); @Override String cancelWithSavepoint(JobID jobId, @Nullable String savepointDirectory); @Override CompletableFuture<String> triggerSavepoint(
final JobID jobId,
final @Nullable String savepointDirectory); @Override Map<String, OptionalFailure<Object>> getAccumulators(final JobID jobID, ClassLoader loader); @Override CompletableFuture<Collection<JobStatusMessage>> listJobs(); @Override T getClusterId(); @Override LeaderConnectionInfo getClusterConnectionInfo(); @Override CompletableFuture<Acknowledge> rescaleJob(JobID jobId, int newParallelism); @Override CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath); @Override void shutDownCluster(); @Override boolean hasUserJarsInClassPath(List<URL> userJarFiles); @Override void waitForClusterToBeReady(); @Override String getWebInterfaceURL(); @Override GetClusterStatusResponse getClusterStatus(); @Override List<String> getNewMessages(); @Override int getMaxSlots(); }### Answer:
@Test public void testListJobs() throws Exception { try (TestRestServerEndpoint ignored = createRestServerEndpoint(new TestListJobsHandler())) { { CompletableFuture<Collection<JobStatusMessage>> jobDetailsFuture = restClusterClient.listJobs(); Collection<JobStatusMessage> jobDetails = jobDetailsFuture.get(); Iterator<JobStatusMessage> jobDetailsIterator = jobDetails.iterator(); JobStatusMessage job1 = jobDetailsIterator.next(); JobStatusMessage job2 = jobDetailsIterator.next(); Assert.assertNotEquals("The job status should not be equal.", job1.getJobState(), job2.getJobState()); } } } |
### Question:
RestClusterClient extends ClusterClient<T> implements NewClusterClient { @Override public Map<String, OptionalFailure<Object>> getAccumulators(final JobID jobID, ClassLoader loader) throws Exception { final JobAccumulatorsHeaders accumulatorsHeaders = JobAccumulatorsHeaders.getInstance(); final JobAccumulatorsMessageParameters accMsgParams = accumulatorsHeaders.getUnresolvedMessageParameters(); accMsgParams.jobPathParameter.resolve(jobID); accMsgParams.includeSerializedAccumulatorsParameter.resolve(Collections.singletonList(true)); CompletableFuture<JobAccumulatorsInfo> responseFuture = sendRequest( accumulatorsHeaders, accMsgParams ); Map<String, OptionalFailure<Object>> result = Collections.emptyMap(); try { result = responseFuture.thenApply((JobAccumulatorsInfo accumulatorsInfo) -> { try { return AccumulatorHelper.deserializeAccumulators( accumulatorsInfo.getSerializedUserAccumulators(), loader); } catch (Exception e) { throw new CompletionException( new FlinkException( String.format("Deserialization of accumulators for job %s failed.", jobID), e)); } }).get(timeout.toMillis(), TimeUnit.MILLISECONDS); } catch (ExecutionException ee) { ExceptionUtils.rethrowException(ExceptionUtils.stripExecutionException(ee)); } return result; } RestClusterClient(Configuration config, T clusterId); RestClusterClient(
Configuration config,
T clusterId,
LeaderRetrievalService webMonitorRetrievalService); @VisibleForTesting RestClusterClient(
Configuration configuration,
@Nullable RestClient restClient,
T clusterId,
WaitStrategy waitStrategy,
@Nullable LeaderRetrievalService webMonitorRetrievalService); @Override void shutdown(); @Override JobSubmissionResult submitJob(JobGraph jobGraph, ClassLoader classLoader); @Override CompletableFuture<JobStatus> getJobStatus(JobID jobId); @Override CompletableFuture<JobResult> requestJobResult(@Nonnull JobID jobId); @Override CompletableFuture<JobSubmissionResult> submitJob(@Nonnull JobGraph jobGraph); @Override void stop(JobID jobID); @Override void cancel(JobID jobID); @Override String cancelWithSavepoint(JobID jobId, @Nullable String savepointDirectory); @Override CompletableFuture<String> triggerSavepoint(
final JobID jobId,
final @Nullable String savepointDirectory); @Override Map<String, OptionalFailure<Object>> getAccumulators(final JobID jobID, ClassLoader loader); @Override CompletableFuture<Collection<JobStatusMessage>> listJobs(); @Override T getClusterId(); @Override LeaderConnectionInfo getClusterConnectionInfo(); @Override CompletableFuture<Acknowledge> rescaleJob(JobID jobId, int newParallelism); @Override CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath); @Override void shutDownCluster(); @Override boolean hasUserJarsInClassPath(List<URL> userJarFiles); @Override void waitForClusterToBeReady(); @Override String getWebInterfaceURL(); @Override GetClusterStatusResponse getClusterStatus(); @Override List<String> getNewMessages(); @Override int getMaxSlots(); }### Answer:
@Test public void testGetAccumulators() throws Exception { TestAccumulatorHandler accumulatorHandler = new TestAccumulatorHandler(); try (TestRestServerEndpoint ignored = createRestServerEndpoint(accumulatorHandler)){ JobID id = new JobID(); { Map<String, OptionalFailure<Object>> accumulators = restClusterClient.getAccumulators(id); assertNotNull(accumulators); assertEquals(1, accumulators.size()); assertEquals(true, accumulators.containsKey("testKey")); assertEquals("testValue", accumulators.get("testKey").get().toString()); } } } |
### Question:
ExponentialWaitStrategy implements WaitStrategy { @Override public long sleepTime(final long attempt) { checkArgument(attempt >= 0, "attempt must not be negative (%d)", attempt); final long exponentialSleepTime = initialWait * Math.round(Math.pow(2, attempt)); return exponentialSleepTime >= 0 && exponentialSleepTime < maxWait ? exponentialSleepTime : maxWait; } ExponentialWaitStrategy(final long initialWait, final long maxWait); @Override long sleepTime(final long attempt); }### Answer:
@Test public void testMaxSleepTime() { final long sleepTime = new ExponentialWaitStrategy(1, 1).sleepTime(100); assertThat(sleepTime, equalTo(1L)); }
@Test public void testExponentialGrowth() { final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, 1000); assertThat(exponentialWaitStrategy.sleepTime(3) / exponentialWaitStrategy.sleepTime(2), equalTo(2L)); }
@Test public void testMaxAttempts() { final long maxWait = 1000; final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, maxWait); assertThat(exponentialWaitStrategy.sleepTime(Long.MAX_VALUE), equalTo(maxWait)); }
@Test public void test64Attempts() { final long maxWait = 1000; final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, maxWait); assertThat(exponentialWaitStrategy.sleepTime(64), equalTo(maxWait)); } |
### Question:
ClusterClient { public void shutdown() throws Exception { synchronized (this) { actorSystemLoader.shutdown(); if (!sharedHaServices && highAvailabilityServices != null) { highAvailabilityServices.close(); } } } ClusterClient(Configuration flinkConfig); ClusterClient(Configuration flinkConfig, HighAvailabilityServices highAvailabilityServices, boolean sharedHaServices); void shutdown(); void setPrintStatusDuringExecution(boolean print); boolean getPrintStatusDuringExecution(); LeaderConnectionInfo getClusterConnectionInfo(); static String getOptimizedPlanAsJson(Optimizer compiler, PackagedProgram prog, int parallelism); static FlinkPlan getOptimizedPlan(Optimizer compiler, PackagedProgram prog, int parallelism); static OptimizedPlan getOptimizedPlan(Optimizer compiler, Plan p, int parallelism); JobSubmissionResult run(PackagedProgram prog, int parallelism); JobSubmissionResult run(JobWithJars program, int parallelism); JobSubmissionResult run(JobWithJars jobWithJars, int parallelism, SavepointRestoreSettings savepointSettings); JobSubmissionResult run(
FlinkPlan compiledPlan, List<URL> libraries, List<URL> classpaths, ClassLoader classLoader); JobSubmissionResult run(FlinkPlan compiledPlan,
List<URL> libraries, List<URL> classpaths, ClassLoader classLoader, SavepointRestoreSettings savepointSettings); JobExecutionResult run(JobGraph jobGraph, ClassLoader classLoader); JobSubmissionResult runDetached(JobGraph jobGraph, ClassLoader classLoader); JobExecutionResult retrieveJob(JobID jobID); JobListeningContext connectToJob(JobID jobID); CompletableFuture<JobStatus> getJobStatus(JobID jobId); void cancel(JobID jobId); String cancelWithSavepoint(JobID jobId, @Nullable String savepointDirectory); void stop(final JobID jobId); CompletableFuture<String> triggerSavepoint(JobID jobId, @Nullable String savepointDirectory); CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath); CompletableFuture<Collection<JobStatusMessage>> listJobs(); Map<String, OptionalFailure<Object>> getAccumulators(JobID jobID); Map<String, OptionalFailure<Object>> getAccumulators(JobID jobID, ClassLoader loader); void endSession(JobID jobId); void endSessions(List<JobID> jobIds); static JobGraph getJobGraph(Configuration flinkConfig, PackagedProgram prog, FlinkPlan optPlan, SavepointRestoreSettings savepointSettings); static JobGraph getJobGraph(Configuration flinkConfig, FlinkPlan optPlan, List<URL> jarFiles, List<URL> classpaths, SavepointRestoreSettings savepointSettings); ActorGateway getJobManagerGateway(); abstract void waitForClusterToBeReady(); abstract String getWebInterfaceURL(); abstract GetClusterStatusResponse getClusterStatus(); abstract List<String> getNewMessages(); abstract T getClusterId(); void setDetached(boolean isDetached); boolean isDetached(); Configuration getFlinkConfiguration(); abstract int getMaxSlots(); abstract boolean hasUserJarsInClassPath(List<URL> userJarFiles); abstract JobSubmissionResult submitJob(JobGraph jobGraph, ClassLoader classLoader); CompletableFuture<Acknowledge> rescaleJob(JobID jobId, int newParallelism); void shutDownCluster(); static final int MAX_SLOTS_UNKNOWN; }### Answer:
@Test public void testClusterClientShutdown() throws Exception { Configuration config = new Configuration(); HighAvailabilityServices highAvailabilityServices = mock(HighAvailabilityServices.class); StandaloneClusterClient clusterClient = new StandaloneClusterClient(config, highAvailabilityServices, false); clusterClient.shutdown(); verify(highAvailabilityServices, never()).closeAndCleanupAllData(); verify(highAvailabilityServices).close(); } |
### Question:
PackagedProgram { public String getPreviewPlan() throws ProgramInvocationException { Thread.currentThread().setContextClassLoader(this.getUserCodeClassLoader()); List<DataSinkNode> previewPlan; if (isUsingProgramEntryPoint()) { previewPlan = Optimizer.createPreOptimizedPlan(getPlan()); } else if (isUsingInteractiveMode()) { PreviewPlanEnvironment env = new PreviewPlanEnvironment(); env.setAsContext(); try { invokeInteractiveModeForExecution(); } catch (ProgramInvocationException e) { throw e; } catch (Throwable t) { if (env.previewPlan != null) { previewPlan = env.previewPlan; } else if (env.preview != null) { return env.preview; } else { throw new ProgramInvocationException("The program caused an error: ", t); } } finally { env.unsetAsContext(); } if (env.previewPlan != null) { previewPlan = env.previewPlan; } else { throw new ProgramInvocationException( "The program plan could not be fetched. The program silently swallowed the control flow exceptions."); } } else { throw new RuntimeException(); } PlanJSONDumpGenerator jsonGen = new PlanJSONDumpGenerator(); StringWriter string = new StringWriter(1024); try (PrintWriter pw = new PrintWriter(string)) { jsonGen.dumpPactPlanAsJSON(previewPlan, pw); } return string.toString(); } PackagedProgram(File jarFile, String... args); PackagedProgram(File jarFile, List<URL> classpaths, String... args); PackagedProgram(File jarFile, @Nullable String entryPointClassName, String... args); PackagedProgram(File jarFile, List<URL> classpaths, @Nullable String entryPointClassName, String... args); PackagedProgram(Class<?> entryPointClass, String... args); void setSavepointRestoreSettings(SavepointRestoreSettings savepointSettings); SavepointRestoreSettings getSavepointSettings(); String[] getArguments(); String getMainClassName(); boolean isUsingInteractiveMode(); boolean isUsingProgramEntryPoint(); JobWithJars getPlanWithoutJars(); JobWithJars getPlanWithJars(); String getPreviewPlan(); @Nullable String getDescription(); void invokeInteractiveModeForExecution(); List<URL> getClasspaths(); ClassLoader getUserCodeClassLoader(); List<URL> getAllLibraries(); void deleteExtractedLibraries(); static List<File> extractContainedLibraries(URL jarFile); static void deleteExtractedLibraries(List<File> tempLibraries); static final String MANIFEST_ATTRIBUTE_ASSEMBLER_CLASS; static final String MANIFEST_ATTRIBUTE_MAIN_CLASS; }### Answer:
@Test public void testGetPreviewPlan() { try { PackagedProgram prog = new PackagedProgram(new File(CliFrontendTestUtils.getTestJarPath())); final PrintStream out = System.out; final PrintStream err = System.err; try { System.setOut(new PrintStream(new NullOutputStream())); System.setErr(new PrintStream(new NullOutputStream())); Assert.assertNotNull(prog.getPreviewPlan()); } finally { System.setOut(out); System.setErr(err); } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); Assert.fail("Test is erroneous: " + e.getMessage()); } } |
### Question:
MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { @Override protected void initialize() throws ResourceManagerException { try { this.workerStore = mesosServices.createMesosWorkerStore(flinkConfig, getRpcService().getExecutor()); workerStore.start(); } catch (Exception e) { throw new ResourceManagerException("Unable to initialize the worker store.", e); } Protos.FrameworkInfo.Builder frameworkInfo = mesosConfig.frameworkInfo() .clone() .setCheckpoint(true); try { Option<Protos.FrameworkID> frameworkID = workerStore.getFrameworkID(); if (frameworkID.isEmpty()) { LOG.info("Registering as new framework."); } else { LOG.info("Recovery scenario: re-registering using framework ID {}.", frameworkID.get().getValue()); frameworkInfo.setId(frameworkID.get()); } } catch (Exception e) { throw new ResourceManagerException("Unable to recover the framework ID.", e); } MesosConfiguration initializedMesosConfig = mesosConfig.withFrameworkInfo(frameworkInfo); MesosConfiguration.logMesosConfig(LOG, initializedMesosConfig); schedulerDriver = initializedMesosConfig.createDriver( new MesosResourceManagerSchedulerCallback(), false); selfActor = createSelfActor(); connectionMonitor = createConnectionMonitor(); launchCoordinator = createLaunchCoordinator(schedulerDriver, selfActor); reconciliationCoordinator = createReconciliationCoordinator(schedulerDriver); taskMonitor = createTaskMonitor(schedulerDriver); try { recoverWorkers(); } catch (Exception e) { throw new ResourceManagerException("Unable to recover Mesos worker state.", e); } try { LaunchableMesosWorker.configureArtifactServer(artifactServer, taskManagerContainerSpec); } catch (IOException e) { throw new ResourceManagerException("Unable to configure the artifact server with TaskManager artifacts.", e); } connectionMonitor.tell(new ConnectionMonitor.Start(), selfActor); schedulerDriver.start(); LOG.info("Mesos resource manager initialized."); } MesosResourceManager(
// base class
RpcService rpcService,
String resourceManagerEndpointId,
ResourceID resourceId,
ResourceManagerConfiguration resourceManagerConfiguration,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
SlotManager slotManager,
MetricRegistry metricRegistry,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
// Mesos specifics
Configuration flinkConfig,
MesosServices mesosServices,
MesosConfiguration mesosConfig,
MesosTaskManagerParameters taskManagerParameters,
ContainerSpecification taskManagerContainerSpec); @Override CompletableFuture<Void> postStop(); @Override void startNewWorker(ResourceProfile resourceProfile); @Override boolean stopWorker(RegisteredMesosWorkerNode workerNode); void acceptOffers(AcceptOffers msg); void reconcile(ReconciliationCoordinator.Reconcile message); void taskTerminated(TaskMonitor.TaskTerminated message); }### Answer:
@Test public void testInitialize() throws Exception { new Context() {{ startResourceManager(); LOG.info("initialized"); }}; } |
### Question:
MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { private void recoverWorkers() throws Exception { final List<MesosWorkerStore.Worker> tasksFromPreviousAttempts = workerStore.recoverWorkers(); assert(workersInNew.isEmpty()); assert(workersInLaunch.isEmpty()); assert(workersBeingReturned.isEmpty()); if (!tasksFromPreviousAttempts.isEmpty()) { LOG.info("Retrieved {} TaskManagers from previous attempt", tasksFromPreviousAttempts.size()); List<Tuple2<TaskRequest, String>> toAssign = new ArrayList<>(tasksFromPreviousAttempts.size()); for (final MesosWorkerStore.Worker worker : tasksFromPreviousAttempts) { LaunchableMesosWorker launchable = createLaunchableMesosWorker(worker.taskID(), worker.profile()); switch(worker.state()) { case New: workerStore.removeWorker(worker.taskID()); break; case Launched: workersInLaunch.put(extractResourceID(worker.taskID()), worker); toAssign.add(new Tuple2<>(launchable.taskRequest(), worker.hostname().get())); break; case Released: workersBeingReturned.put(extractResourceID(worker.taskID()), worker); break; } taskMonitor.tell(new TaskMonitor.TaskGoalStateUpdated(extractGoalState(worker)), selfActor); } if (toAssign.size() >= 1) { launchCoordinator.tell(new LaunchCoordinator.Assign(toAssign), selfActor); } } } MesosResourceManager(
// base class
RpcService rpcService,
String resourceManagerEndpointId,
ResourceID resourceId,
ResourceManagerConfiguration resourceManagerConfiguration,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
SlotManager slotManager,
MetricRegistry metricRegistry,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
// Mesos specifics
Configuration flinkConfig,
MesosServices mesosServices,
MesosConfiguration mesosConfig,
MesosTaskManagerParameters taskManagerParameters,
ContainerSpecification taskManagerContainerSpec); @Override CompletableFuture<Void> postStop(); @Override void startNewWorker(ResourceProfile resourceProfile); @Override boolean stopWorker(RegisteredMesosWorkerNode workerNode); void acceptOffers(AcceptOffers msg); void reconcile(ReconciliationCoordinator.Reconcile message); void taskTerminated(TaskMonitor.TaskTerminated message); }### Answer:
@Test public void testRecoverWorkers() throws Exception { new Context() {{ MesosWorkerStore.Worker worker1 = MesosWorkerStore.Worker.newWorker(task1); MesosWorkerStore.Worker worker2 = MesosWorkerStore.Worker.newWorker(task2).launchWorker(slave1, slave1host); MesosWorkerStore.Worker worker3 = MesosWorkerStore.Worker.newWorker(task3).launchWorker(slave1, slave1host).releaseWorker(); when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); when(rmServices.workerStore.recoverWorkers()).thenReturn(Arrays.asList(worker1, worker2, worker3)); startResourceManager(); assertThat(resourceManager.workersInNew.entrySet(), empty()); assertThat(resourceManager.workersInLaunch, hasEntry(extractResourceID(task2), worker2)); assertThat(resourceManager.workersBeingReturned, hasEntry(extractResourceID(task3), worker3)); resourceManager.taskRouter.expectMsgClass(TaskMonitor.TaskGoalStateUpdated.class); LaunchCoordinator.Assign actualAssign = resourceManager.launchCoordinator.expectMsgClass(LaunchCoordinator.Assign.class); assertThat(actualAssign.tasks(), hasSize(1)); assertThat(actualAssign.tasks().get(0).f0.getId(), equalTo(task2.getValue())); assertThat(actualAssign.tasks().get(0).f1, equalTo(slave1host)); resourceManager.launchCoordinator.expectNoMsg(); }}; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.