method2testcases
stringlengths
118
6.63k
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { static ResourceID extractResourceID(Protos.TaskID taskId) { return new ResourceID(taskId.getValue()); } 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 testRequestNewWorkers() throws Exception { new Context() {{ startResourceManager(); when(rmServices.workerStore.newTaskID()).thenReturn(task1).thenThrow(new AssertionFailedError()); rmServices.slotManagerStarted.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); CompletableFuture<Void> allocateResourceFuture = resourceManager.callAsync( () -> { rmServices.rmActions.allocateResource(resourceProfile1); return null; }, timeout); allocateResourceFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); MesosWorkerStore.Worker expected = MesosWorkerStore.Worker.newWorker(task1, resourceProfile1); verify(rmServices.workerStore, Mockito.timeout(timeout.toMilliseconds())).putWorker(expected); assertThat(resourceManager.workersInNew, hasEntry(extractResourceID(task1), expected)); resourceManager.taskRouter.expectMsgClass(TaskMonitor.TaskGoalStateUpdated.class); resourceManager.launchCoordinator.expectMsgClass(LaunchCoordinator.Launch.class); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { public void acceptOffers(AcceptOffers msg) { try { List<TaskMonitor.TaskGoalStateUpdated> toMonitor = new ArrayList<>(msg.operations().size()); for (Protos.Offer.Operation op : msg.operations()) { if (op.getType() == Protos.Offer.Operation.Type.LAUNCH) { for (Protos.TaskInfo info : op.getLaunch().getTaskInfosList()) { MesosWorkerStore.Worker worker = workersInNew.remove(extractResourceID(info.getTaskId())); assert (worker != null); worker = worker.launchWorker(info.getSlaveId(), msg.hostname()); workerStore.putWorker(worker); workersInLaunch.put(extractResourceID(worker.taskID()), worker); LOG.info("Launching Mesos task {} on host {}.", worker.taskID().getValue(), worker.hostname().get()); toMonitor.add(new TaskMonitor.TaskGoalStateUpdated(extractGoalState(worker))); } } } for (TaskMonitor.TaskGoalStateUpdated update : toMonitor) { taskMonitor.tell(update, selfActor); } schedulerDriver.acceptOffers(msg.offerIds(), msg.operations(), msg.filters()); } catch (Exception ex) { onFatalError(new ResourceManagerException("unable to accept offers", ex)); } } 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 testAcceptOffers() throws Exception { new Context() {{ startResourceManager(); MesosWorkerStore.Worker worker1 = allocateWorker(task1, resourceProfile1); Protos.TaskInfo task1info = Protos.TaskInfo.newBuilder() .setTaskId(task1).setName("").setSlaveId(slave1).build(); AcceptOffers msg = new AcceptOffers(slave1host, singletonList(offer1), singletonList(launch(task1info))); resourceManager.acceptOffers(msg); MesosWorkerStore.Worker worker1launched = worker1.launchWorker(slave1, slave1host); verify(rmServices.workerStore).putWorker(worker1launched); assertThat(resourceManager.workersInNew.entrySet(), empty()); assertThat(resourceManager.workersInLaunch, hasEntry(extractResourceID(task1), worker1launched)); resourceManager.taskRouter.expectMsg( new TaskMonitor.TaskGoalStateUpdated(extractGoalState(worker1launched))); verify(rmServices.schedulerDriver).acceptOffers(msg.offerIds(), msg.operations(), msg.filters()); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void statusUpdate(StatusUpdate message) { taskMonitor.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); schedulerDriver.acknowledgeStatusUpdate(message.status()); } 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 testStatusHandling() throws Exception { new Context() {{ startResourceManager(); resourceManager.statusUpdate(new StatusUpdate(Protos.TaskStatus.newBuilder() .setTaskId(task1).setSlaveId(slave1).setState(Protos.TaskState.TASK_LOST).build())); resourceManager.reconciliationCoordinator.expectMsgClass(StatusUpdate.class); resourceManager.taskRouter.expectMsgClass(StatusUpdate.class); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { @Override protected RegisteredMesosWorkerNode workerStarted(ResourceID resourceID) { MesosWorkerStore.Worker inLaunch = workersInLaunch.get(resourceID); if (inLaunch != null) { return new RegisteredMesosWorkerNode(inLaunch); } else { return null; } } 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 testWorkerStarted() throws Exception { new Context() {{ MesosWorkerStore.Worker worker1launched = MesosWorkerStore.Worker.newWorker(task1).launchWorker(slave1, slave1host); when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); when(rmServices.workerStore.recoverWorkers()).thenReturn(singletonList(worker1launched)); startResourceManager(); assertThat(resourceManager.workersInLaunch, hasEntry(extractResourceID(task1), worker1launched)); final int dataPort = 1234; final HardwareDescription hardwareDescription = new HardwareDescription(1, 2L, 3L, 4L); CompletableFuture<RegistrationResponse> successfulFuture = resourceManager.registerTaskExecutor(task1Executor.address, task1Executor.resourceID, slotReport, dataPort, hardwareDescription, timeout); RegistrationResponse response = successfulFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); assertTrue(response instanceof TaskExecutorRegistrationSuccess); assertThat(resourceManager.workersInLaunch, hasEntry(extractResourceID(task1), worker1launched)); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { @Override public boolean stopWorker(RegisteredMesosWorkerNode workerNode) { LOG.info("Stopping worker {}.", workerNode.getResourceID()); try { if (workersInLaunch.containsKey(workerNode.getResourceID())) { MesosWorkerStore.Worker worker = workersInLaunch.remove(workerNode.getResourceID()); worker = worker.releaseWorker(); workerStore.putWorker(worker); workersBeingReturned.put(extractResourceID(worker.taskID()), worker); taskMonitor.tell(new TaskMonitor.TaskGoalStateUpdated(extractGoalState(worker)), selfActor); if (worker.hostname().isDefined()) { launchCoordinator.tell(new LaunchCoordinator.Unassign(worker.taskID(), worker.hostname().get()), selfActor); } } else if (workersBeingReturned.containsKey(workerNode.getResourceID())) { LOG.info("Ignoring request to stop worker {} because it is already being stopped.", workerNode.getResourceID()); } else { LOG.warn("Unrecognized worker {}.", workerNode.getResourceID()); } } catch (Exception e) { onFatalError(new ResourceManagerException("Unable to release a worker.", e)); } return true; } 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 testStopWorker() throws Exception { new Context() {{ MesosWorkerStore.Worker worker1launched = MesosWorkerStore.Worker.newWorker(task1).launchWorker(slave1, slave1host); when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); when(rmServices.workerStore.recoverWorkers()).thenReturn(singletonList(worker1launched)); startResourceManager(); resourceManager.launchCoordinator.expectMsgClass(LaunchCoordinator.Assign.class); resourceManager.stopWorker(new RegisteredMesosWorkerNode(worker1launched)); MesosWorkerStore.Worker worker1Released = worker1launched.releaseWorker(); verify(rmServices.workerStore).putWorker(worker1Released); assertThat(resourceManager.workersInLaunch.entrySet(), empty()); assertThat(resourceManager.workersBeingReturned, hasEntry(extractResourceID(task1), worker1Released)); resourceManager.taskRouter.expectMsgClass(TaskMonitor.TaskGoalStateUpdated.class); resourceManager.launchCoordinator.expectMsgClass(LaunchCoordinator.Unassign.class); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void registered(Registered message) { connectionMonitor.tell(message, selfActor); try { workerStore.setFrameworkID(Option.apply(message.frameworkId())); } catch (Exception ex) { onFatalError(new ResourceManagerException("Unable to store the assigned framework ID.", ex)); return; } launchCoordinator.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); taskMonitor.tell(message, 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 testRegistered() throws Exception { new Context() {{ startResourceManager(); Protos.MasterInfo masterInfo = Protos.MasterInfo.newBuilder() .setId("master1").setIp(0).setPort(5050).build(); resourceManager.registered(new Registered(framework1, masterInfo)); verify(rmServices.workerStore).setFrameworkID(Option.apply(framework1)); resourceManager.connectionMonitor.expectMsgClass(Registered.class); resourceManager.reconciliationCoordinator.expectMsgClass(Registered.class); resourceManager.launchCoordinator.expectMsgClass(Registered.class); resourceManager.taskRouter.expectMsgClass(Registered.class); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void reregistered(ReRegistered message) { connectionMonitor.tell(message, selfActor); launchCoordinator.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); taskMonitor.tell(message, 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 testReRegistered() throws Exception { new Context() {{ when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); startResourceManager(); Protos.MasterInfo masterInfo = Protos.MasterInfo.newBuilder() .setId("master1").setIp(0).setPort(5050).build(); resourceManager.reregistered(new ReRegistered(masterInfo)); resourceManager.connectionMonitor.expectMsgClass(ReRegistered.class); resourceManager.reconciliationCoordinator.expectMsgClass(ReRegistered.class); resourceManager.launchCoordinator.expectMsgClass(ReRegistered.class); resourceManager.taskRouter.expectMsgClass(ReRegistered.class); }}; }
### Question: MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void disconnected(Disconnected message) { connectionMonitor.tell(message, selfActor); launchCoordinator.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); taskMonitor.tell(message, 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 testDisconnected() throws Exception { new Context() {{ when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); startResourceManager(); resourceManager.disconnected(new Disconnected()); resourceManager.connectionMonitor.expectMsgClass(Disconnected.class); resourceManager.reconciliationCoordinator.expectMsgClass(Disconnected.class); resourceManager.launchCoordinator.expectMsgClass(Disconnected.class); resourceManager.taskRouter.expectMsgClass(Disconnected.class); }}; }
### Question: MesosTaskManagerParameters { public List<Protos.Volume> containerVolumes() { return containerVolumes; } MesosTaskManagerParameters( double cpus, int gpus, ContainerType containerType, Option<String> containerImageName, ContaineredTaskManagerParameters containeredParameters, List<Protos.Volume> containerVolumes, List<Protos.Parameter> dockerParameters, List<ConstraintEvaluator> constraints, String command, Option<String> bootstrapCommand, Option<String> taskManagerHostname); double cpus(); int gpus(); ContainerType containerType(); Option<String> containerImageName(); ContaineredTaskManagerParameters containeredParameters(); List<Protos.Volume> containerVolumes(); List<Protos.Parameter> dockerParameters(); List<ConstraintEvaluator> constraints(); Option<String> getTaskManagerHostname(); String command(); Option<String> bootstrapCommand(); @Override String toString(); static MesosTaskManagerParameters create(Configuration flinkConfig); static List<Protos.Volume> buildVolumes(Option<String> containerVolumes); static List<Protos.Parameter> buildDockerParameters(Option<String> dockerParameters); static final Pattern TASK_ID_PATTERN; static final ConfigOption<Integer> MESOS_RM_TASKS_SLOTS; static final ConfigOption<Integer> MESOS_RM_TASKS_MEMORY_MB; static final ConfigOption<Double> MESOS_RM_TASKS_CPUS; static final ConfigOption<Integer> MESOS_RM_TASKS_GPUS; static final ConfigOption<String> MESOS_RM_CONTAINER_TYPE; static final ConfigOption<String> MESOS_RM_CONTAINER_IMAGE_NAME; static final ConfigOption<String> MESOS_TM_HOSTNAME; static final ConfigOption<String> MESOS_TM_CMD; static final ConfigOption<String> MESOS_TM_BOOTSTRAP_CMD; static final ConfigOption<String> MESOS_RM_CONTAINER_VOLUMES; static final ConfigOption<String> MESOS_RM_CONTAINER_DOCKER_PARAMETERS; static final ConfigOption<String> MESOS_CONSTRAINTS_HARD_HOSTATTR; static final String MESOS_RESOURCEMANAGER_TASKS_CONTAINER_TYPE_MESOS; static final String MESOS_RESOURCEMANAGER_TASKS_CONTAINER_TYPE_DOCKER; }### Answer: @Test public void testContainerVolumes() throws Exception { Configuration config = new Configuration(); config.setString(MesosTaskManagerParameters.MESOS_RM_CONTAINER_VOLUMES, "/host/path:/container/path:ro"); MesosTaskManagerParameters params = MesosTaskManagerParameters.create(config); assertEquals(1, params.containerVolumes().size()); assertEquals("/container/path", params.containerVolumes().get(0).getContainerPath()); assertEquals("/host/path", params.containerVolumes().get(0).getHostPath()); assertEquals(Protos.Volume.Mode.RO, params.containerVolumes().get(0).getMode()); }
### Question: Offer implements VirtualMachineLease { @Override public double cpuCores() { return cpuCores; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testCpuCores() { Offer offer = new Offer(offer(resources(cpus(1.0)), attrs())); Assert.assertEquals(1.0, offer.cpuCores(), EPSILON); }
### Question: Offer implements VirtualMachineLease { public double gpus() { return getScalarValue("gpus"); } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testGPUs() { Offer offer = new Offer(offer(resources(gpus(1.0)), attrs())); Assert.assertEquals(1.0, offer.gpus(), EPSILON); }
### Question: Offer implements VirtualMachineLease { @Override public double memoryMB() { return memoryMB; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testMemoryMB() { Offer offer = new Offer(offer(resources(mem(1024.0)), attrs())); Assert.assertEquals(1024.0, offer.memoryMB(), EPSILON); }
### Question: Offer implements VirtualMachineLease { @Override public double networkMbps() { return networkMbps; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testNetworkMbps() { Offer offer = new Offer(offer(resources(network(10.0)), attrs())); Assert.assertEquals(10.0, offer.networkMbps(), EPSILON); }
### Question: Offer implements VirtualMachineLease { @Override public double diskMB() { return diskMB; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testDiskMB() { Offer offer = new Offer(offer(resources(disk(1024.0)), attrs())); Assert.assertEquals(1024.0, offer.diskMB(), EPSILON); }
### Question: Offer implements VirtualMachineLease { @Override public List<Range> portRanges() { return portRanges; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer: @Test public void testPortRanges() { Offer offer = new Offer(offer(resources(ports(range(8080, 8081))), attrs())); Assert.assertEquals(Collections.singletonList(range(8080, 8081)), ranges(offer.portRanges())); }
### Question: RegisterApplicationMasterResponseReflector { @VisibleForTesting List<Container> getContainersFromPreviousAttemptsUnsafe(final Object response) { if (method != null && response != null) { try { @SuppressWarnings("unchecked") final List<Container> containers = (List<Container>) method.invoke(response); if (containers != null && !containers.isEmpty()) { return containers; } } catch (Exception t) { logger.error("Error invoking 'getContainersFromPreviousAttempts()'", t); } } return Collections.emptyList(); } RegisterApplicationMasterResponseReflector(final Logger log); @VisibleForTesting RegisterApplicationMasterResponseReflector(final Logger log, final Class<?> clazz); }### Answer: @Test public void testCallsMethodIfPresent() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class); final List<Container> containersFromPreviousAttemptsUnsafe = registerApplicationMasterResponseReflector.getContainersFromPreviousAttemptsUnsafe(new HasMethod()); assertThat(containersFromPreviousAttemptsUnsafe, hasSize(1)); } @Test public void testDoesntCallMethodIfAbsent() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class); final List<Container> containersFromPreviousAttemptsUnsafe = registerApplicationMasterResponseReflector.getContainersFromPreviousAttemptsUnsafe(new Object()); assertThat(containersFromPreviousAttemptsUnsafe, empty()); }
### Question: RegisterApplicationMasterResponseReflector { @VisibleForTesting Method getMethod() { return method; } RegisterApplicationMasterResponseReflector(final Logger log); @VisibleForTesting RegisterApplicationMasterResponseReflector(final Logger log, final Class<?> clazz); }### Answer: @Test public void testGetMethodReflectiveHadoop22() { assumeTrue( "Method getContainersFromPreviousAttempts is not supported by Hadoop: " + VersionInfo.getVersion(), isHadoopVersionGreaterThanOrEquals(2, 2)); final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG); final Method method = registerApplicationMasterResponseReflector.getMethod(); assertThat(method, notNullValue()); }
### Question: Utils { public static void deleteApplicationFiles(final Map<String, String> env) { final String applicationFilesDir = env.get(YarnConfigKeys.FLINK_YARN_FILES); if (!StringUtils.isNullOrWhitespaceOnly(applicationFilesDir)) { final org.apache.flink.core.fs.Path path = new org.apache.flink.core.fs.Path(applicationFilesDir); try { final org.apache.flink.core.fs.FileSystem fileSystem = path.getFileSystem(); if (!fileSystem.delete(path, true)) { LOG.error("Deleting yarn application files under {} was unsuccessful.", applicationFilesDir); } } catch (final IOException e) { LOG.error("Could not properly delete yarn application files directory {}.", applicationFilesDir, e); } } else { LOG.debug("No yarn application files directory set. Therefore, cannot clean up the data."); } } private Utils(); static int calculateHeapSize(int memory, org.apache.flink.configuration.Configuration conf); static void setupYarnClassPath(Configuration conf, Map<String, String> appMasterEnv); static void deleteApplicationFiles(final Map<String, String> env); static void setTokensFor(ContainerLaunchContext amContainer, List<Path> paths, Configuration conf); static void addToEnvironment(Map<String, String> environment, String variable, String value); static Map<String, String> getEnvironmentVariables(String envPrefix, org.apache.flink.configuration.Configuration flinkConfiguration); static final String KEYTAB_FILE_NAME; static final String KRB5_FILE_NAME; static final String YARN_SITE_FILE_NAME; }### Answer: @Test public void testDeleteApplicationFiles() throws Exception { final Path applicationFilesDir = temporaryFolder.newFolder(".flink").toPath(); Files.createFile(applicationFilesDir.resolve("flink.jar")); assertThat(Files.list(temporaryFolder.getRoot().toPath()).count(), equalTo(1L)); assertThat(Files.list(applicationFilesDir).count(), equalTo(1L)); Utils.deleteApplicationFiles(Collections.singletonMap( YarnConfigKeys.FLINK_YARN_FILES, applicationFilesDir.toString())); assertThat(Files.list(temporaryFolder.getRoot().toPath()).count(), equalTo(0L)); } @Test public void testDeleteApplicationFiles() throws Exception { final Path applicationFilesDir = temporaryFolder.newFolder(".flink").toPath(); Files.createFile(applicationFilesDir.resolve("flink.jar")); try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) { assertThat(files.count(), equalTo(1L)); } try (Stream<Path> files = Files.list(applicationFilesDir)) { assertThat(files.count(), equalTo(1L)); } Utils.deleteApplicationFiles(Collections.singletonMap( YarnConfigKeys.FLINK_YARN_FILES, applicationFilesDir.toString())); try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) { assertThat(files.count(), equalTo(0L)); } }
### Question: PrometheusReporter implements MetricReporter { @VisibleForTesting int getPort() { Preconditions.checkState(httpServer != null, "Server has not been initialized."); return port; } @Override void open(MetricConfig config); @Override void close(); @Override void notifyOfAddedMetric(final Metric metric, final String metricName, final MetricGroup group); @Override void notifyOfRemovedMetric(final Metric metric, final String metricName, final MetricGroup group); }### Answer: @Test public void cannotStartTwoReportersOnSamePort() throws Exception { final MetricRegistryImpl fixedPort1 = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(createConfigWithOneReporter("test1", portRangeProvider.next()))); assertThat(fixedPort1.getReporters(), hasSize(1)); PrometheusReporter firstReporter = (PrometheusReporter) fixedPort1.getReporters().get(0); final MetricRegistryImpl fixedPort2 = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(createConfigWithOneReporter("test2", String.valueOf(firstReporter.getPort())))); assertThat(fixedPort2.getReporters(), hasSize(0)); fixedPort1.shutdown().get(); fixedPort2.shutdown().get(); }
### Question: JarIdPathParameter extends MessagePathParameter<String> { @Override protected String convertFromString(final String value) throws ConversionException { final Path path = Paths.get(value); if (path.getParent() != null) { throw new ConversionException(String.format("%s must be a filename only (%s)", KEY, path)); } return value; } protected JarIdPathParameter(); static final String KEY; }### Answer: @Test(expected = ConversionException.class) public void testJarIdWithParentDir() throws Exception { jarIdPathParameter.convertFromString("../../test.jar"); } @Test public void testConvertFromString() throws Exception { final String expectedJarId = "test.jar"; final String jarId = jarIdPathParameter.convertFromString(expectedJarId); assertEquals(expectedJarId, jarId); }
### Question: ListStateDescriptor extends StateDescriptor<ListState<T>, List<T>> { public ListStateDescriptor(String name, Class<T> elementTypeClass) { super(name, new ListTypeInfo<>(elementTypeClass), null); } ListStateDescriptor(String name, Class<T> elementTypeClass); ListStateDescriptor(String name, TypeInformation<T> elementTypeInfo); ListStateDescriptor(String name, TypeSerializer<T> typeSerializer); @Override ListState<T> bind(StateBinder stateBinder); TypeSerializer<T> getElementSerializer(); @Override Type getType(); }### Answer: @Test public void testListStateDescriptor() throws Exception { TypeSerializer<String> serializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ListStateDescriptor<String> descr = new ListStateDescriptor<>("testName", serializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertTrue(descr.getSerializer() instanceof ListSerializer); assertNotNull(descr.getElementSerializer()); assertEquals(serializer, descr.getElementSerializer()); ListStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertTrue(copy.getSerializer() instanceof ListSerializer); assertNotNull(copy.getElementSerializer()); assertEquals(serializer, copy.getElementSerializer()); }
### Question: ListStateDescriptor extends StateDescriptor<ListState<T>, List<T>> { public TypeSerializer<T> getElementSerializer() { final TypeSerializer<List<T>> rawSerializer = getSerializer(); if (!(rawSerializer instanceof ListSerializer)) { throw new IllegalStateException(); } return ((ListSerializer<T>) rawSerializer).getElementSerializer(); } ListStateDescriptor(String name, Class<T> elementTypeClass); ListStateDescriptor(String name, TypeInformation<T> elementTypeInfo); ListStateDescriptor(String name, TypeSerializer<T> typeSerializer); @Override ListState<T> bind(StateBinder stateBinder); TypeSerializer<T> getElementSerializer(); @Override Type getType(); }### Answer: @Test public void testSerializerDuplication() { TypeSerializer<String> statefulSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ListStateDescriptor<String> descr = new ListStateDescriptor<>("foobar", statefulSerializer); TypeSerializer<String> serializerA = descr.getElementSerializer(); TypeSerializer<String> serializerB = descr.getElementSerializer(); assertNotSame(serializerA, serializerB); TypeSerializer<List<String>> listSerializerA = descr.getSerializer(); TypeSerializer<List<String>> listSerializerB = descr.getSerializer(); assertNotSame(listSerializerA, listSerializerB); }
### Question: StateDescriptor implements Serializable { public TypeSerializer<T> getSerializer() { if (serializer != null) { return serializer.duplicate(); } else { throw new IllegalStateException("Serializer not yet initialized."); } } protected StateDescriptor(String name, TypeSerializer<T> serializer, @Nullable T defaultValue); protected StateDescriptor(String name, TypeInformation<T> typeInfo, @Nullable T defaultValue); protected StateDescriptor(String name, Class<T> type, @Nullable T defaultValue); String getName(); T getDefaultValue(); TypeSerializer<T> getSerializer(); void setQueryable(String queryableStateName); @Nullable String getQueryableStateName(); boolean isQueryable(); abstract S bind(StateBinder stateBinder); boolean isSerializerInitialized(); void initializeSerializerUnlessSet(ExecutionConfig executionConfig); @Override final int hashCode(); @Override final boolean equals(Object o); @Override String toString(); abstract Type getType(); }### Answer: @Test public void testSerializerDuplication() throws Exception { TypeSerializer<String> statefulSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); TestStateDescriptor<String> descr = new TestStateDescriptor<>("foobar", statefulSerializer); TypeSerializer<String> serializerA = descr.getSerializer(); TypeSerializer<String> serializerB = descr.getSerializer(); assertNotSame(serializerA, serializerB); }
### Question: ReducingStateDescriptor extends StateDescriptor<ReducingState<T>, T> { public ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, Class<T> typeClass) { super(name, typeClass, null); this.reduceFunction = checkNotNull(reduceFunction); if (reduceFunction instanceof RichFunction) { throw new UnsupportedOperationException("ReduceFunction of ReducingState can not be a RichFunction."); } } ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, Class<T> typeClass); ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, TypeInformation<T> typeInfo); ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, TypeSerializer<T> typeSerializer); @Override ReducingState<T> bind(StateBinder stateBinder); ReduceFunction<T> getReduceFunction(); @Override Type getType(); }### Answer: @Test public void testReducingStateDescriptor() throws Exception { ReduceFunction<String> reducer = (a, b) -> a; TypeSerializer<String> serializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ReducingStateDescriptor<String> descr = new ReducingStateDescriptor<>("testName", reducer, serializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertEquals(serializer, descr.getSerializer()); assertEquals(reducer, descr.getReduceFunction()); ReducingStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertEquals(serializer, copy.getSerializer()); }
### Question: MapStateDescriptor extends StateDescriptor<MapState<UK, UV>, Map<UK, UV>> { public MapStateDescriptor(String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer) { super(name, new MapSerializer<>(keySerializer, valueSerializer), null); } MapStateDescriptor(String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer); MapStateDescriptor(String name, TypeInformation<UK> keyTypeInfo, TypeInformation<UV> valueTypeInfo); MapStateDescriptor(String name, Class<UK> keyClass, Class<UV> valueClass); @Override MapState<UK, UV> bind(StateBinder stateBinder); @Override Type getType(); TypeSerializer<UK> getKeySerializer(); TypeSerializer<UV> getValueSerializer(); }### Answer: @Test public void testMapStateDescriptor() throws Exception { TypeSerializer<Integer> keySerializer = new KryoSerializer<>(Integer.class, new ExecutionConfig()); TypeSerializer<String> valueSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); MapStateDescriptor<Integer, String> descr = new MapStateDescriptor<>("testName", keySerializer, valueSerializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertTrue(descr.getSerializer() instanceof MapSerializer); assertNotNull(descr.getKeySerializer()); assertEquals(keySerializer, descr.getKeySerializer()); assertNotNull(descr.getValueSerializer()); assertEquals(valueSerializer, descr.getValueSerializer()); MapStateDescriptor<Integer, String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertTrue(copy.getSerializer() instanceof MapSerializer); assertNotNull(copy.getKeySerializer()); assertEquals(keySerializer, copy.getKeySerializer()); assertNotNull(copy.getValueSerializer()); assertEquals(valueSerializer, copy.getValueSerializer()); }
### Question: JarIdPathParameter extends MessagePathParameter<String> { @Override protected String convertToString(final String value) { return value; } protected JarIdPathParameter(); static final String KEY; }### Answer: @Test public void testConvertToString() throws Exception { final String expected = "test.jar"; final String toString = jarIdPathParameter.convertToString(expected); assertEquals(expected, toString); }
### Question: ResourceSpec implements Serializable { public boolean isValid() { if (this.cpuCores >= 0 && this.heapMemoryInMB >= 0 && this.directMemoryInMB >= 0 && this.nativeMemoryInMB >= 0 && this.stateSizeInMB >= 0) { for (Resource resource : extendedResources.values()) { if (resource.getValue() < 0) { return false; } } return true; } else { return false; } } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testIsValid() throws Exception { ResourceSpec rs = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertTrue(rs.isValid()); rs = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1). build(); assertTrue(rs.isValid()); rs = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(-1). build(); assertFalse(rs.isValid()); }
### Question: ResourceSpec implements Serializable { public boolean lessThanOrEqual(@Nonnull ResourceSpec other) { int cmp1 = Double.compare(this.cpuCores, other.cpuCores); int cmp2 = Integer.compare(this.heapMemoryInMB, other.heapMemoryInMB); int cmp3 = Integer.compare(this.directMemoryInMB, other.directMemoryInMB); int cmp4 = Integer.compare(this.nativeMemoryInMB, other.nativeMemoryInMB); int cmp5 = Integer.compare(this.stateSizeInMB, other.stateSizeInMB); if (cmp1 <= 0 && cmp2 <= 0 && cmp3 <= 0 && cmp4 <= 0 && cmp5 <= 0) { for (Resource resource : extendedResources.values()) { if (!other.extendedResources.containsKey(resource.getName()) || other.extendedResources.get(resource.getName()).getResourceAggregateType() != resource.getResourceAggregateType() || other.extendedResources.get(resource.getName()).getValue() < resource.getValue()) { return false; } } return true; } return false; } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testLessThanOrEqual() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertTrue(rs1.lessThanOrEqual(rs2)); assertTrue(rs2.lessThanOrEqual(rs1)); ResourceSpec rs3 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); assertTrue(rs1.lessThanOrEqual(rs3)); assertFalse(rs3.lessThanOrEqual(rs1)); ResourceSpec rs4 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertFalse(rs4.lessThanOrEqual(rs3)); assertTrue(rs3.lessThanOrEqual(rs4)); }
### Question: JarDeleteHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, EmptyResponseBody, JarDeleteMessageParameters> { @Override protected CompletableFuture<EmptyResponseBody> handleRequest( @Nonnull final HandlerRequest<EmptyRequestBody, JarDeleteMessageParameters> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { final String jarId = request.getPathParameter(JarIdPathParameter.class); return CompletableFuture.supplyAsync(() -> { final Path jarToDelete = jarDir.resolve(jarId); if (!Files.exists(jarToDelete)) { throw new CompletionException(new RestHandlerException( String.format("File %s does not exist in %s.", jarId, jarDir), HttpResponseStatus.BAD_REQUEST)); } else { try { Files.delete(jarToDelete); return EmptyResponseBody.getInstance(); } catch (final IOException e) { throw new CompletionException(new RestHandlerException( String.format("Failed to delete jar %s.", jarToDelete), HttpResponseStatus.INTERNAL_SERVER_ERROR, e)); } } }, executor); } JarDeleteHandler( final CompletableFuture<String> localRestAddress, final GatewayRetriever<? extends RestfulGateway> leaderRetriever, final Time timeout, final Map<String, String> responseHeaders, final MessageHeaders<EmptyRequestBody, EmptyResponseBody, JarDeleteMessageParameters> messageHeaders, final Path jarDir, final Executor executor); }### Answer: @Test public void testDeleteJarById() throws Exception { assertThat(Files.exists(jarDir.resolve(TEST_JAR_NAME)), equalTo(true)); final HandlerRequest<EmptyRequestBody, JarDeleteMessageParameters> request = createRequest(TEST_JAR_NAME); jarDeleteHandler.handleRequest(request, restfulGateway).get(); assertThat(Files.exists(jarDir.resolve(TEST_JAR_NAME)), equalTo(false)); } @Test public void testDeleteUnknownJar() throws Exception { final HandlerRequest<EmptyRequestBody, JarDeleteMessageParameters> request = createRequest("doesnotexist.jar"); try { jarDeleteHandler.handleRequest(request, restfulGateway).get(); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripCompletionException(e.getCause()); assertThat(throwable, instanceOf(RestHandlerException.class)); final RestHandlerException restHandlerException = (RestHandlerException) throwable; assertThat(restHandlerException.getMessage(), containsString("File doesnotexist.jar does not exist in")); assertThat(restHandlerException.getHttpResponseStatus(), equalTo(HttpResponseStatus.BAD_REQUEST)); } } @Test public void testFailedDelete() throws Exception { makeJarDirReadOnly(); final HandlerRequest<EmptyRequestBody, JarDeleteMessageParameters> request = createRequest(TEST_JAR_NAME); try { jarDeleteHandler.handleRequest(request, restfulGateway).get(); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripCompletionException(e.getCause()); assertThat(throwable, instanceOf(RestHandlerException.class)); final RestHandlerException restHandlerException = (RestHandlerException) throwable; assertThat(restHandlerException.getMessage(), containsString("Failed to delete jar")); assertThat(restHandlerException.getHttpResponseStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); } }
### Question: ResourceSpec implements Serializable { @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj != null && obj.getClass() == ResourceSpec.class) { ResourceSpec that = (ResourceSpec) obj; return this.cpuCores == that.cpuCores && this.heapMemoryInMB == that.heapMemoryInMB && this.directMemoryInMB == that.directMemoryInMB && this.nativeMemoryInMB == that.nativeMemoryInMB && this.stateSizeInMB == that.stateSizeInMB && Objects.equals(this.extendedResources, that.extendedResources); } else { return false; } } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testEquals() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertTrue(rs1.equals(rs2)); assertTrue(rs2.equals(rs1)); ResourceSpec rs3 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); ResourceSpec rs4 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1). build(); assertFalse(rs3.equals(rs4)); ResourceSpec rs5 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertTrue(rs3.equals(rs5)); }
### Question: ResourceSpec implements Serializable { @Override public int hashCode() { final long cpuBits = Double.doubleToLongBits(cpuCores); int result = (int) (cpuBits ^ (cpuBits >>> 32)); result = 31 * result + heapMemoryInMB; result = 31 * result + directMemoryInMB; result = 31 * result + nativeMemoryInMB; result = 31 * result + stateSizeInMB; result = 31 * result + extendedResources.hashCode(); return result; } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testHashCode() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertEquals(rs1.hashCode(), rs2.hashCode()); ResourceSpec rs3 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); ResourceSpec rs4 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1). build(); assertFalse(rs3.hashCode() == rs4.hashCode()); ResourceSpec rs5 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertEquals(rs3.hashCode(), rs5.hashCode()); }
### Question: ResourceSpec implements Serializable { public ResourceSpec merge(ResourceSpec other) { ResourceSpec target = new ResourceSpec( Math.max(this.cpuCores, other.cpuCores), this.heapMemoryInMB + other.heapMemoryInMB, this.directMemoryInMB + other.directMemoryInMB, this.nativeMemoryInMB + other.nativeMemoryInMB, this.stateSizeInMB + other.stateSizeInMB); target.extendedResources.putAll(extendedResources); for (Resource resource : other.extendedResources.values()) { target.extendedResources.merge(resource.getName(), resource, (v1, v2) -> v1.merge(v2)); } return target; } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testMerge() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs3 = rs1.merge(rs2); assertEquals(1.1, rs3.getGPUResource(), 0.000001); ResourceSpec rs4 = rs1.merge(rs3); assertEquals(2.2, rs4.getGPUResource(), 0.000001); }
### Question: ResourceSpec implements Serializable { public static Builder newBuilder() { return new Builder(); } protected ResourceSpec( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int stateSizeInMB, Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer: @Test public void testSerializable() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); byte[] buffer = InstantiationUtil.serializeObject(rs1); ResourceSpec rs2 = InstantiationUtil.deserializeObject(buffer, ClassLoader.getSystemClassLoader()); assertEquals(rs1, rs2); }
### Question: ParallelismQueryParameter extends MessageQueryParameter<Integer> { @Override public Integer convertStringToValue(final String value) { return Integer.valueOf(value); } ParallelismQueryParameter(); @Override Integer convertStringToValue(final String value); @Override String convertValueToString(final Integer value); }### Answer: @Test public void testConvertStringToValue() { assertEquals("42", parallelismQueryParameter.convertValueToString(42)); } @Test public void testConvertValueFromString() { assertEquals(42, (int) parallelismQueryParameter.convertStringToValue("42")); }
### Question: JarHandlerUtils { public static List<String> tokenizeArguments(@Nullable final String args) { if (args == null) { return Collections.emptyList(); } final Matcher matcher = ARGUMENTS_TOKENIZE_PATTERN.matcher(args); final List<String> tokens = new ArrayList<>(); while (matcher.find()) { tokens.add(matcher.group() .trim() .replace("\"", "") .replace("\'", "")); } return tokens; } static List<String> tokenizeArguments(@Nullable final String args); }### Answer: @Test public void testTokenizeNonQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo bar"); assertThat(arguments.get(0), equalTo("--foo")); assertThat(arguments.get(1), equalTo("bar")); } @Test public void testTokenizeSingleQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo 'bar baz '"); assertThat(arguments.get(0), equalTo("--foo")); assertThat(arguments.get(1), equalTo("bar baz ")); } @Test public void testTokenizeDoubleQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--name \"K. Bote \""); assertThat(arguments.get(0), equalTo("--name")); assertThat(arguments.get(1), equalTo("K. Bote ")); }
### Question: ExecutionConfig implements Serializable, Archiveable<ArchivedExecutionConfig> { public void disableGenericTypes() { disableGenericTypes = true; } ExecutionConfig enableClosureCleaner(); ExecutionConfig disableClosureCleaner(); boolean isClosureCleanerEnabled(); @PublicEvolving ExecutionConfig setAutoWatermarkInterval(long interval); @PublicEvolving long getAutoWatermarkInterval(); @PublicEvolving ExecutionConfig setLatencyTrackingInterval(long interval); @PublicEvolving long getLatencyTrackingInterval(); @PublicEvolving boolean isLatencyTrackingEnabled(); int getParallelism(); ExecutionConfig setParallelism(int parallelism); @PublicEvolving int getMaxParallelism(); @PublicEvolving void setMaxParallelism(int maxParallelism); long getTaskCancellationInterval(); ExecutionConfig setTaskCancellationInterval(long interval); @PublicEvolving long getTaskCancellationTimeout(); @PublicEvolving ExecutionConfig setTaskCancellationTimeout(long timeout); @PublicEvolving void setRestartStrategy(RestartStrategies.RestartStrategyConfiguration restartStrategyConfiguration); @PublicEvolving @SuppressWarnings("deprecation") RestartStrategies.RestartStrategyConfiguration getRestartStrategy(); @Deprecated int getNumberOfExecutionRetries(); @Deprecated long getExecutionRetryDelay(); @Deprecated ExecutionConfig setNumberOfExecutionRetries(int numberOfExecutionRetries); @Deprecated ExecutionConfig setExecutionRetryDelay(long executionRetryDelay); void setExecutionMode(ExecutionMode executionMode); ExecutionMode getExecutionMode(); void enableForceKryo(); void disableForceKryo(); boolean isForceKryoEnabled(); void enableGenericTypes(); void disableGenericTypes(); boolean hasGenericTypesDisabled(); void enableForceAvro(); void disableForceAvro(); boolean isForceAvroEnabled(); ExecutionConfig enableObjectReuse(); ExecutionConfig disableObjectReuse(); boolean isObjectReuseEnabled(); @PublicEvolving void setCodeAnalysisMode(CodeAnalysisMode codeAnalysisMode); @PublicEvolving CodeAnalysisMode getCodeAnalysisMode(); ExecutionConfig enableSysoutLogging(); ExecutionConfig disableSysoutLogging(); boolean isSysoutLoggingEnabled(); GlobalJobParameters getGlobalJobParameters(); void setGlobalJobParameters(GlobalJobParameters globalJobParameters); void addDefaultKryoSerializer(Class<?> type, T serializer); void addDefaultKryoSerializer(Class<?> type, Class<? extends Serializer<?>> serializerClass); void registerTypeWithKryoSerializer(Class<?> type, T serializer); @SuppressWarnings("rawtypes") void registerTypeWithKryoSerializer(Class<?> type, Class<? extends Serializer> serializerClass); void registerPojoType(Class<?> type); void registerKryoType(Class<?> type); LinkedHashMap<Class<?>, SerializableSerializer<?>> getRegisteredTypesWithKryoSerializers(); LinkedHashMap<Class<?>, Class<? extends Serializer<?>>> getRegisteredTypesWithKryoSerializerClasses(); LinkedHashMap<Class<?>, SerializableSerializer<?>> getDefaultKryoSerializers(); LinkedHashMap<Class<?>, Class<? extends Serializer<?>>> getDefaultKryoSerializerClasses(); LinkedHashSet<Class<?>> getRegisteredKryoTypes(); LinkedHashSet<Class<?>> getRegisteredPojoTypes(); boolean isAutoTypeRegistrationDisabled(); void disableAutoTypeRegistration(); boolean isUseSnapshotCompression(); void setUseSnapshotCompression(boolean useSnapshotCompression); @Internal boolean isFailTaskOnCheckpointError(); @Internal void setFailTaskOnCheckpointError(boolean failTaskOnCheckpointError); @Override boolean equals(Object obj); @Override int hashCode(); boolean canEqual(Object obj); @Override @Internal ArchivedExecutionConfig archive(); @Deprecated static final int PARALLELISM_AUTO_MAX; static final int PARALLELISM_DEFAULT; static final int PARALLELISM_UNKNOWN; }### Answer: @Test public void testDisableGenericTypes() { ExecutionConfig conf = new ExecutionConfig(); TypeInformation<Object> typeInfo = new GenericTypeInfo<Object>(Object.class); TypeSerializer<Object> serializer = typeInfo.createSerializer(conf); assertTrue(serializer instanceof KryoSerializer); conf.disableGenericTypes(); try { typeInfo.createSerializer(conf); fail("should have failed with an exception"); } catch (UnsupportedOperationException e) { } }
### Question: LocalFileSystem extends FileSystem { @Override public boolean rename(final Path src, final Path dst) throws IOException { final File srcFile = pathToFile(src); final File dstFile = pathToFile(dst); final File dstParent = dstFile.getParentFile(); dstParent.mkdirs(); try { Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING); return true; } catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) { return false; } } LocalFileSystem(); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override FileStatus getFileStatus(Path f); @Override URI getUri(); @Override Path getWorkingDirectory(); @Override Path getHomeDirectory(); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataInputStream open(final Path f); @Override boolean exists(Path f); @Override FileStatus[] listStatus(final Path f); @Override boolean delete(final Path f, final boolean recursive); @Override boolean mkdirs(final Path f); @Override FSDataOutputStream create(final Path filePath, final WriteMode overwrite); @Override boolean rename(final Path src, final Path dst); @Override boolean isDistributedFS(); @Override FileSystemKind getKind(); static URI getLocalFsURI(); static LocalFileSystem getSharedInstance(); }### Answer: @Test public void testRenameNonExistingFile() throws IOException { final FileSystem fs = FileSystem.getLocalFileSystem(); final File srcFile = new File(temporaryFolder.newFolder(), "someFile.txt"); final File destFile = new File(temporaryFolder.newFolder(), "target"); final Path srcFilePath = new Path(srcFile.toURI()); final Path destFilePath = new Path(destFile.toURI()); assertFalse(fs.rename(srcFilePath, destFilePath)); } @Test public void testRenameFileWithNoAccess() throws IOException { final FileSystem fs = FileSystem.getLocalFileSystem(); final File srcFile = temporaryFolder.newFile("someFile.txt"); final File destFile = new File(temporaryFolder.newFolder(), "target"); Assume.assumeTrue(srcFile.getParentFile().setWritable(false, false)); Assume.assumeTrue(srcFile.setWritable(false, false)); try { final Path srcFilePath = new Path(srcFile.toURI()); final Path destFilePath = new Path(destFile.toURI()); assertFalse(fs.rename(srcFilePath, destFilePath)); } finally { srcFile.getParentFile().setWritable(true, false); srcFile.setWritable(true, false); } }
### Question: LocalFileSystem extends FileSystem { @Override public FileSystemKind getKind() { return FileSystemKind.FILE_SYSTEM; } LocalFileSystem(); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override FileStatus getFileStatus(Path f); @Override URI getUri(); @Override Path getWorkingDirectory(); @Override Path getHomeDirectory(); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataInputStream open(final Path f); @Override boolean exists(Path f); @Override FileStatus[] listStatus(final Path f); @Override boolean delete(final Path f, final boolean recursive); @Override boolean mkdirs(final Path f); @Override FSDataOutputStream create(final Path filePath, final WriteMode overwrite); @Override boolean rename(final Path src, final Path dst); @Override boolean isDistributedFS(); @Override FileSystemKind getKind(); static URI getLocalFsURI(); static LocalFileSystem getSharedInstance(); }### Answer: @Test public void testKind() { final FileSystem fs = FileSystem.getLocalFileSystem(); assertEquals(FileSystemKind.FILE_SYSTEM, fs.getKind()); }
### Question: JarUploadHandler extends AbstractRestHandler<RestfulGateway, FileUpload, JarUploadResponseBody, EmptyMessageParameters> { @Override protected CompletableFuture<JarUploadResponseBody> handleRequest( @Nonnull final HandlerRequest<FileUpload, EmptyMessageParameters> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { final FileUpload fileUpload = request.getRequestBody(); return CompletableFuture.supplyAsync(() -> { if (!fileUpload.getPath().getFileName().toString().endsWith(".jar")) { deleteUploadedFile(fileUpload); throw new CompletionException(new RestHandlerException( "Only Jar files are allowed.", HttpResponseStatus.BAD_REQUEST)); } else { final Path destination = jarDir.resolve(fileUpload.getPath().getFileName()); try { Files.move(fileUpload.getPath(), destination); } catch (IOException e) { deleteUploadedFile(fileUpload); throw new CompletionException(new RestHandlerException( String.format("Could not move uploaded jar file [%s] to [%s].", fileUpload.getPath(), destination), HttpResponseStatus.INTERNAL_SERVER_ERROR, e)); } return new JarUploadResponseBody(fileUpload.getPath() .normalize() .toString()); } }, executor); } JarUploadHandler( final CompletableFuture<String> localRestAddress, final GatewayRetriever<? extends RestfulGateway> leaderRetriever, final Time timeout, final Map<String, String> responseHeaders, final MessageHeaders<FileUpload, JarUploadResponseBody, EmptyMessageParameters> messageHeaders, final Path jarDir, final Executor executor); }### Answer: @Test public void testRejectNonJarFiles() throws Exception { final Path uploadedFile = Files.createFile(jarDir.resolve("katrin.png")); final HandlerRequest<FileUpload, EmptyMessageParameters> request = createRequest(uploadedFile); try { jarUploadHandler.handleRequest(request, mockDispatcherGateway).get(); fail("Expected exception not thrown."); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripCompletionException(e.getCause()); assertThat(throwable, instanceOf(RestHandlerException.class)); final RestHandlerException restHandlerException = (RestHandlerException) throwable; assertThat(restHandlerException.getHttpResponseStatus(), equalTo(HttpResponseStatus.BAD_REQUEST)); } } @Test public void testUploadJar() throws Exception { final Path uploadedFile = Files.createFile(jarDir.resolve("Kafka010Example.jar")); final HandlerRequest<FileUpload, EmptyMessageParameters> request = createRequest(uploadedFile); final JarUploadResponseBody jarUploadResponseBody = jarUploadHandler.handleRequest(request, mockDispatcherGateway).get(); assertThat(jarUploadResponseBody.getStatus(), equalTo(JarUploadResponseBody.UploadStatus.success)); assertThat(jarUploadResponseBody.getFilename(), equalTo(uploadedFile.normalize().toString())); } @Test public void testFailedUpload() throws Exception { final Path uploadedFile = jarDir.resolve("Kafka010Example.jar"); final HandlerRequest<FileUpload, EmptyMessageParameters> request = createRequest(uploadedFile); try { jarUploadHandler.handleRequest(request, mockDispatcherGateway).get(); fail("Expected exception not thrown."); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripCompletionException(e.getCause()); assertThat(throwable, instanceOf(RestHandlerException.class)); final RestHandlerException restHandlerException = (RestHandlerException) throwable; assertThat(restHandlerException.getMessage(), containsString("Could not move uploaded jar file")); assertThat(restHandlerException.getHttpResponseStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); } }
### Question: JsonRowSerializationSchema implements SerializationSchema<Row> { @Override public byte[] serialize(Row row) { if (node == null) { node = mapper.createObjectNode(); } try { convertRow(node, (RowTypeInfo) typeInfo, row); return mapper.writeValueAsBytes(node); } catch (Throwable t) { throw new RuntimeException("Could not serialize row '" + row + "'. " + "Make sure that the schema matches the input.", t); } } JsonRowSerializationSchema(TypeInformation<Row> typeInfo); JsonRowSerializationSchema(String jsonSchema); @Override byte[] serialize(Row row); }### Answer: @Test public void testSerializationOfTwoRows() throws IOException { final TypeInformation<Row> rowSchema = Types.ROW_NAMED( new String[] {"f1", "f2", "f3"}, Types.INT, Types.BOOLEAN, Types.STRING); final Row row1 = new Row(3); row1.setField(0, 1); row1.setField(1, true); row1.setField(2, "str"); final JsonRowSerializationSchema serializationSchema = new JsonRowSerializationSchema(rowSchema); final JsonRowDeserializationSchema deserializationSchema = new JsonRowDeserializationSchema(rowSchema); byte[] bytes = serializationSchema.serialize(row1); assertEquals(row1, deserializationSchema.deserialize(bytes)); final Row row2 = new Row(3); row2.setField(0, 10); row2.setField(1, false); row2.setField(2, "newStr"); bytes = serializationSchema.serialize(row2); assertEquals(row2, deserializationSchema.deserialize(bytes)); } @Test(expected = RuntimeException.class) public void testSerializeRowWithInvalidNumberOfFields() { final TypeInformation<Row> rowSchema = Types.ROW_NAMED( new String[] {"f1", "f2", "f3"}, Types.INT, Types.BOOLEAN, Types.STRING); final Row row = new Row(1); row.setField(0, 1); final JsonRowSerializationSchema serializationSchema = new JsonRowSerializationSchema(rowSchema); serializationSchema.serialize(row); }
### Question: AllowNonRestoredStateQueryParameter extends MessageQueryParameter<Boolean> { @Override public Boolean convertStringToValue(final String value) { return Boolean.valueOf(value); } protected AllowNonRestoredStateQueryParameter(); @Override Boolean convertStringToValue(final String value); @Override String convertValueToString(final Boolean value); }### Answer: @Test public void testConvertStringToValue() { assertEquals("false", allowNonRestoredStateQueryParameter.convertValueToString(false)); assertEquals("true", allowNonRestoredStateQueryParameter.convertValueToString(true)); } @Test public void testConvertValueFromString() { assertEquals(false, allowNonRestoredStateQueryParameter.convertStringToValue("false")); assertEquals(true, allowNonRestoredStateQueryParameter.convertStringToValue("true")); assertEquals(true, allowNonRestoredStateQueryParameter.convertStringToValue("TRUE")); }
### Question: KafkaConsumerThread extends Thread { public void shutdown() { running = false; unassignedPartitionsQueue.close(); handover.wakeupProducer(); synchronized (consumerReassignmentLock) { if (consumer != null) { consumer.wakeup(); } else { hasBufferedWakeup = true; } } } KafkaConsumerThread( Logger log, Handover handover, Properties kafkaProperties, ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>> unassignedPartitionsQueue, KafkaConsumerCallBridge consumerCallBridge, String threadName, long pollTimeout, boolean useMetrics, MetricGroup consumerMetricGroup, MetricGroup subtaskMetricGroup); @Override void run(); void shutdown(); }### Answer: @Test(timeout = 10000) public void testCloseWithoutAssignedPartitions() throws Exception { final KafkaConsumer<byte[], byte[]> mockConsumer = createMockConsumer( new LinkedHashMap<TopicPartition, Long>(), Collections.<TopicPartition, Long>emptyMap(), false, null, null); final MultiShotLatch getBatchBlockingInvoked = new MultiShotLatch(); final ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>> unassignedPartitionsQueue = new ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>>() { @Override public List<KafkaTopicPartitionState<TopicPartition>> getBatchBlocking() throws InterruptedException { getBatchBlockingInvoked.trigger(); return super.getBatchBlocking(); } }; final TestKafkaConsumerThread testThread = new TestKafkaConsumerThread(mockConsumer, unassignedPartitionsQueue, new Handover()); testThread.start(); getBatchBlockingInvoked.await(); testThread.shutdown(); testThread.join(); }
### Question: DelegatingConfiguration extends Configuration { @Override public boolean equals(Object obj) { if (obj instanceof DelegatingConfiguration) { DelegatingConfiguration other = (DelegatingConfiguration) obj; return this.prefix.equals(other.prefix) && this.backingConfig.equals(other.backingConfig); } else { return false; } } DelegatingConfiguration(); DelegatingConfiguration(Configuration backingConfig, String prefix); @Override String getString(String key, String defaultValue); @Override String getString(ConfigOption<String> configOption); @Override String getString(ConfigOption<String> configOption, String overrideDefault); @Override void setString(String key, String value); @Override void setString(ConfigOption<String> key, String value); @Override Class<T> getClass(String key, Class<? extends T> defaultValue, ClassLoader classLoader); @Override void setClass(String key, Class<?> klazz); @Override int getInteger(String key, int defaultValue); @Override int getInteger(ConfigOption<Integer> configOption); @Override int getInteger(ConfigOption<Integer> configOption, int overrideDefault); @Override void setInteger(String key, int value); @Override void setInteger(ConfigOption<Integer> key, int value); @Override long getLong(String key, long defaultValue); @Override long getLong(ConfigOption<Long> configOption); @Override long getLong(ConfigOption<Long> configOption, long overrideDefault); @Override void setLong(String key, long value); @Override void setLong(ConfigOption<Long> key, long value); @Override boolean getBoolean(String key, boolean defaultValue); @Override boolean getBoolean(ConfigOption<Boolean> configOption); @Override void setBoolean(String key, boolean value); @Override void setBoolean(ConfigOption<Boolean> key, boolean value); @Override boolean getBoolean(ConfigOption<Boolean> configOption, boolean overrideDefault); @Override float getFloat(String key, float defaultValue); @Override float getFloat(ConfigOption<Float> configOption); @Override float getFloat(ConfigOption<Float> configOption, float overrideDefault); @Override void setFloat(String key, float value); @Override void setFloat(ConfigOption<Float> key, float value); @Override double getDouble(String key, double defaultValue); @Override double getDouble(ConfigOption<Double> configOption); @Override double getDouble(ConfigOption<Double> configOption, double overrideDefault); @Override void setDouble(String key, double value); @Override void setDouble(ConfigOption<Double> key, double value); @Override byte[] getBytes(final String key, final byte[] defaultValue); @Override void setBytes(final String key, final byte[] bytes); @Override String getValue(ConfigOption<?> configOption); @Override void addAllToProperties(Properties props); @Override void addAll(Configuration other); @Override void addAll(Configuration other, String prefix); @Override String toString(); @Override Set<String> keySet(); @Override Configuration clone(); @Override Map<String, String> toMap(); @Override boolean containsKey(String key); @Override boolean contains(ConfigOption<?> configOption); @Override void read(DataInputView in); @Override void write(DataOutputView out); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testIfDelegatesImplementAllMethods() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method[] confMethods = Configuration.class.getDeclaredMethods(); Method[] delegateMethods = DelegatingConfiguration.class.getDeclaredMethods(); for (Method configurationMethod : confMethods) { if (!Modifier.isPublic(configurationMethod.getModifiers())) { continue; } boolean hasMethod = false; lookForWrapper: for (Method wrapperMethod : delegateMethods) { if (configurationMethod.getName().equals(wrapperMethod.getName())) { Class<?>[] wrapperMethodParams = wrapperMethod.getParameterTypes(); Class<?>[] configMethodParams = configurationMethod.getParameterTypes(); if (wrapperMethodParams.length != configMethodParams.length) { continue; } for (int i = 0; i < wrapperMethodParams.length; i++) { if (wrapperMethodParams[i] != configMethodParams[i]) { continue lookForWrapper; } } hasMethod = true; break; } } assertTrue("Configuration method '" + configurationMethod.getName() + "' has not been wrapped correctly in DelegatingConfiguration wrapper", hasMethod); } }
### Question: BucketingSink extends RichSinkFunction<T> implements InputTypeConfigurable, CheckpointedFunction, CheckpointListener, ProcessingTimeCallback { @Override public void open(Configuration parameters) throws Exception { super.open(parameters); state = new State<>(); processingTimeService = ((StreamingRuntimeContext) getRuntimeContext()).getProcessingTimeService(); long currentProcessingTime = processingTimeService.getCurrentProcessingTime(); processingTimeService.registerTimer(currentProcessingTime + inactiveBucketCheckInterval, this); this.clock = new Clock() { @Override public long currentTimeMillis() { return processingTimeService.getCurrentProcessingTime(); } }; } BucketingSink(String basePath); BucketingSink<T> setFSConfig(Configuration config); BucketingSink<T> setFSConfig(org.apache.hadoop.conf.Configuration config); @Override @SuppressWarnings("unchecked") void setInputType(TypeInformation<?> type, ExecutionConfig executionConfig); @Override void initializeState(FunctionInitializationContext context); @Override void open(Configuration parameters); @Override void close(); @Override void invoke(T value); @Override void onProcessingTime(long timestamp); @Override void notifyCheckpointComplete(long checkpointId); @Override void snapshotState(FunctionSnapshotContext context); BucketingSink<T> setBatchSize(long batchSize); BucketingSink<T> setInactiveBucketCheckInterval(long interval); BucketingSink<T> setInactiveBucketThreshold(long threshold); BucketingSink<T> setBucketer(Bucketer<T> bucketer); BucketingSink<T> setWriter(Writer<T> writer); BucketingSink<T> setInProgressSuffix(String inProgressSuffix); BucketingSink<T> setInProgressPrefix(String inProgressPrefix); BucketingSink<T> setPendingSuffix(String pendingSuffix); BucketingSink<T> setPendingPrefix(String pendingPrefix); BucketingSink<T> setValidLengthSuffix(String validLengthSuffix); BucketingSink<T> setValidLengthPrefix(String validLengthPrefix); BucketingSink<T> setPartSuffix(String partSuffix); BucketingSink<T> setPartPrefix(String partPrefix); BucketingSink<T> setUseTruncate(boolean useTruncate); @Deprecated BucketingSink<T> disableCleanupOnOpen(); BucketingSink<T> setAsyncTimeout(long timeout); @VisibleForTesting State<T> getState(); static FileSystem createHadoopFileSystem( Path path, @Nullable Configuration extraUserConf); }### Answer: @Test public void testInactivityPeriodWithLateNotify() throws Exception { final File outDir = tempFolder.newFolder(); OneInputStreamOperatorTestHarness<String, Object> testHarness = createRescalingTestSink(outDir, 1, 0, 100); testHarness.setup(); testHarness.open(); testHarness.setProcessingTime(0L); testHarness.processElement(new StreamRecord<>("test1", 1L)); testHarness.processElement(new StreamRecord<>("test2", 1L)); checkLocalFs(outDir, 2, 0 , 0, 0); testHarness.setProcessingTime(101L); checkLocalFs(outDir, 0, 2, 0, 0); testHarness.snapshot(0, 0); checkLocalFs(outDir, 0, 2, 0, 0); testHarness.processElement(new StreamRecord<>("test3", 1L)); testHarness.processElement(new StreamRecord<>("test4", 1L)); testHarness.setProcessingTime(202L); testHarness.snapshot(1, 0); checkLocalFs(outDir, 0, 4, 0, 0); testHarness.notifyOfCompletedCheckpoint(0); checkLocalFs(outDir, 0, 2, 2, 0); testHarness.notifyOfCompletedCheckpoint(1); checkLocalFs(outDir, 0, 0, 4, 0); }
### Question: DelegatingConfiguration extends Configuration { @Override public Set<String> keySet() { if (this.prefix == null) { return this.backingConfig.keySet(); } final HashSet<String> set = new HashSet<>(); int prefixLen = this.prefix.length(); for (String key : this.backingConfig.keySet()) { if (key.startsWith(prefix)) { set.add(key.substring(prefixLen)); } } return set; } DelegatingConfiguration(); DelegatingConfiguration(Configuration backingConfig, String prefix); @Override String getString(String key, String defaultValue); @Override String getString(ConfigOption<String> configOption); @Override String getString(ConfigOption<String> configOption, String overrideDefault); @Override void setString(String key, String value); @Override void setString(ConfigOption<String> key, String value); @Override Class<T> getClass(String key, Class<? extends T> defaultValue, ClassLoader classLoader); @Override void setClass(String key, Class<?> klazz); @Override int getInteger(String key, int defaultValue); @Override int getInteger(ConfigOption<Integer> configOption); @Override int getInteger(ConfigOption<Integer> configOption, int overrideDefault); @Override void setInteger(String key, int value); @Override void setInteger(ConfigOption<Integer> key, int value); @Override long getLong(String key, long defaultValue); @Override long getLong(ConfigOption<Long> configOption); @Override long getLong(ConfigOption<Long> configOption, long overrideDefault); @Override void setLong(String key, long value); @Override void setLong(ConfigOption<Long> key, long value); @Override boolean getBoolean(String key, boolean defaultValue); @Override boolean getBoolean(ConfigOption<Boolean> configOption); @Override void setBoolean(String key, boolean value); @Override void setBoolean(ConfigOption<Boolean> key, boolean value); @Override boolean getBoolean(ConfigOption<Boolean> configOption, boolean overrideDefault); @Override float getFloat(String key, float defaultValue); @Override float getFloat(ConfigOption<Float> configOption); @Override float getFloat(ConfigOption<Float> configOption, float overrideDefault); @Override void setFloat(String key, float value); @Override void setFloat(ConfigOption<Float> key, float value); @Override double getDouble(String key, double defaultValue); @Override double getDouble(ConfigOption<Double> configOption); @Override double getDouble(ConfigOption<Double> configOption, double overrideDefault); @Override void setDouble(String key, double value); @Override void setDouble(ConfigOption<Double> key, double value); @Override byte[] getBytes(final String key, final byte[] defaultValue); @Override void setBytes(final String key, final byte[] bytes); @Override String getValue(ConfigOption<?> configOption); @Override void addAllToProperties(Properties props); @Override void addAll(Configuration other); @Override void addAll(Configuration other, String prefix); @Override String toString(); @Override Set<String> keySet(); @Override Configuration clone(); @Override Map<String, String> toMap(); @Override boolean containsKey(String key); @Override boolean contains(ConfigOption<?> configOption); @Override void read(DataInputView in); @Override void write(DataOutputView out); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testDelegationConfigurationWithNullPrefix() { Configuration backingConf = new Configuration(); backingConf.setValueInternal("test-key", "value"); DelegatingConfiguration configuration = new DelegatingConfiguration( backingConf, null); Set<String> keySet = configuration.keySet(); assertEquals(keySet, backingConf.keySet()); } @Test public void testDelegationConfigurationWithPrefix() { String prefix = "pref-"; String expectedKey = "key"; Configuration backingConf = new Configuration(); backingConf.setValueInternal(prefix + expectedKey, "value"); DelegatingConfiguration configuration = new DelegatingConfiguration(backingConf, prefix); Set<String> keySet = configuration.keySet(); assertEquals(keySet.size(), 1); assertEquals(keySet.iterator().next(), expectedKey); backingConf = new Configuration(); backingConf.setValueInternal("test-key", "value"); configuration = new DelegatingConfiguration(backingConf, prefix); keySet = configuration.keySet(); assertTrue(keySet.isEmpty()); }
### Question: RMQSource extends MultipleIdsMessageAcknowledgingSourceBase<OUT, String, Long> implements ResultTypeQueryable<OUT> { @Override public void open(Configuration config) throws Exception { super.open(config); ConnectionFactory factory = setupConnectionFactory(); try { connection = factory.newConnection(); channel = connection.createChannel(); if (channel == null) { throw new RuntimeException("None of RabbitMQ channels are available"); } setupQueue(); consumer = new QueueingConsumer(channel); RuntimeContext runtimeContext = getRuntimeContext(); if (runtimeContext instanceof StreamingRuntimeContext && ((StreamingRuntimeContext) runtimeContext).isCheckpointingEnabled()) { autoAck = false; channel.txSelect(); } else { autoAck = true; } LOG.debug("Starting RabbitMQ source with autoAck status: " + autoAck); channel.basicConsume(queueName, autoAck, consumer); } catch (IOException e) { throw new RuntimeException("Cannot create RMQ connection with " + queueName + " at " + rmqConnectionConfig.getHost(), e); } running = true; } RMQSource(RMQConnectionConfig rmqConnectionConfig, String queueName, DeserializationSchema<OUT> deserializationSchema); RMQSource(RMQConnectionConfig rmqConnectionConfig, String queueName, boolean usesCorrelationId, DeserializationSchema<OUT> deserializationSchema); @Override void open(Configuration config); @Override void close(); @Override void run(SourceContext<OUT> ctx); @Override void cancel(); @Override TypeInformation<OUT> getProducedType(); }### Answer: @Test public void testCheckpointing() throws Exception { source.autoAck = false; StreamSource<String, RMQSource<String>> src = new StreamSource<>(source); AbstractStreamOperatorTestHarness<String> testHarness = new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0); testHarness.open(); sourceThread.start(); Thread.sleep(5); final Random random = new Random(System.currentTimeMillis()); int numSnapshots = 50; long previousSnapshotId; long lastSnapshotId = 0; long totalNumberOfAcks = 0; for (int i = 0; i < numSnapshots; i++) { long snapshotId = random.nextLong(); OperatorSubtaskState data; synchronized (DummySourceContext.lock) { data = testHarness.snapshot(snapshotId, System.currentTimeMillis()); previousSnapshotId = lastSnapshotId; lastSnapshotId = messageId; } Thread.sleep(5); final long numIds = lastSnapshotId - previousSnapshotId; RMQTestSource sourceCopy = new RMQTestSource(); StreamSource<String, RMQTestSource> srcCopy = new StreamSource<>(sourceCopy); AbstractStreamOperatorTestHarness<String> testHarnessCopy = new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0); testHarnessCopy.setup(); testHarnessCopy.initializeState(data); testHarnessCopy.open(); ArrayDeque<Tuple2<Long, Set<String>>> deque = sourceCopy.getRestoredState(); Set<String> messageIds = deque.getLast().f1; assertEquals(numIds, messageIds.size()); if (messageIds.size() > 0) { assertTrue(messageIds.contains(Long.toString(lastSnapshotId))); } synchronized (DummySourceContext.lock) { source.notifyCheckpointComplete(snapshotId); } totalNumberOfAcks += numIds; } Mockito.verify(source.channel, Mockito.times((int) totalNumberOfAcks)).basicAck(Mockito.anyLong(), Mockito.eq(false)); Mockito.verify(source.channel, Mockito.times(numSnapshots)).txCommit(); }
### Question: CoreOptions { public static String[] getParentFirstLoaderPatterns(Configuration config) { String base = config.getString(ALWAYS_PARENT_FIRST_LOADER_PATTERNS); String append = config.getString(ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL); String[] basePatterns = base.isEmpty() ? new String[0] : base.split(";"); if (append.isEmpty()) { return basePatterns; } else { String[] appendPatterns = append.split(";"); String[] joinedPatterns = new String[basePatterns.length + appendPatterns.length]; System.arraycopy(basePatterns, 0, joinedPatterns, 0, basePatterns.length); System.arraycopy(appendPatterns, 0, joinedPatterns, basePatterns.length, appendPatterns.length); return joinedPatterns; } } static String[] getParentFirstLoaderPatterns(Configuration config); static ConfigOption<Integer> fileSystemConnectionLimit(String scheme); static ConfigOption<Integer> fileSystemConnectionLimitIn(String scheme); static ConfigOption<Integer> fileSystemConnectionLimitOut(String scheme); static ConfigOption<Long> fileSystemConnectionLimitTimeout(String scheme); static ConfigOption<Long> fileSystemConnectionLimitStreamInactivityTimeout(String scheme); static final ConfigOption<String> CLASSLOADER_RESOLVE_ORDER; static final ConfigOption<String> ALWAYS_PARENT_FIRST_LOADER_PATTERNS; static final ConfigOption<String> ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL; static final ConfigOption<String> FLINK_JVM_OPTIONS; static final ConfigOption<String> FLINK_JM_JVM_OPTIONS; static final ConfigOption<String> FLINK_TM_JVM_OPTIONS; @SuppressWarnings("unused") static final ConfigOption<String> FLINK_LOG_DIR; @SuppressWarnings("unused") static final ConfigOption<Integer> FLINK_LOG_MAX; @SuppressWarnings("unused") static final ConfigOption<String> FLINK_SSH_OPTIONS; @Documentation.OverrideDefault("System.getProperty(\"java.io.tmpdir\")") static final ConfigOption<String> TMP_DIRS; static final ConfigOption<Integer> DEFAULT_PARALLELISM; static final ConfigOption<String> DEFAULT_FILESYSTEM_SCHEME; static final ConfigOption<Boolean> FILESYTEM_DEFAULT_OVERRIDE; static final ConfigOption<Boolean> FILESYSTEM_OUTPUT_ALWAYS_CREATE_DIRECTORY; static final String NEW_MODE; static final String LEGACY_MODE; static final ConfigOption<String> MODE; }### Answer: @Test public void testGetParentFirstLoaderPatterns() { Configuration config = new Configuration(); Assert.assertArrayEquals( CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS.defaultValue().split(";"), CoreOptions.getParentFirstLoaderPatterns(config)); config.setString(CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS, "hello;world"); Assert.assertArrayEquals( "hello;world".split(";"), CoreOptions.getParentFirstLoaderPatterns(config)); config.setString(CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL, "how;are;you"); Assert.assertArrayEquals( "hello;world;how;are;you".split(";"), CoreOptions.getParentFirstLoaderPatterns(config)); config.setString(CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS, ""); Assert.assertArrayEquals( "how;are;you".split(";"), CoreOptions.getParentFirstLoaderPatterns(config)); }
### Question: KinesisConfigUtil { public static KinesisProducerConfiguration getValidatedProducerConfiguration(Properties config) { checkNotNull(config, "config can not be null"); validateAwsConfiguration(config); KinesisProducerConfiguration kpc = KinesisProducerConfiguration.fromProperties(config); kpc.setRegion(config.getProperty(AWSConfigConstants.AWS_REGION)); kpc.setCredentialsProvider(AWSUtil.getCredentialsProvider(config)); kpc.setCredentialsRefreshDelay(100); if (!config.containsKey(RATE_LIMIT)) { kpc.setRateLimit(DEFAULT_RATE_LIMIT); } if (!config.containsKey(THREADING_MODEL)) { kpc.setThreadingModel(DEFAULT_THREADING_MODEL); } if (!config.containsKey(THREAD_POOL_SIZE)) { kpc.setThreadPoolSize(DEFAULT_THREAD_POOL_SIZE); } return kpc; } static void validateConsumerConfiguration(Properties config); static Properties replaceDeprecatedProducerKeys(Properties configProps); static KinesisProducerConfiguration getValidatedProducerConfiguration(Properties config); static void validateAwsConfiguration(Properties config); }### Answer: @Test public void testUnparsableLongForProducerConfiguration() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Error trying to set field RateLimit with the value 'unparsableLong'"); Properties testConfig = new Properties(); testConfig.setProperty(AWSConfigConstants.AWS_REGION, "us-east-1"); testConfig.setProperty("RateLimit", "unparsableLong"); KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); } @Test public void testRateLimitInProducerConfiguration() { Properties testConfig = new Properties(); testConfig.setProperty(AWSConfigConstants.AWS_REGION, "us-east-1"); KinesisProducerConfiguration kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(100, kpc.getRateLimit()); testConfig.setProperty(KinesisConfigUtil.RATE_LIMIT, "150"); kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(150, kpc.getRateLimit()); } @Test public void testThreadingModelInProducerConfiguration() { Properties testConfig = new Properties(); testConfig.setProperty(AWSConfigConstants.AWS_REGION, "us-east-1"); KinesisProducerConfiguration kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(KinesisProducerConfiguration.ThreadingModel.POOLED, kpc.getThreadingModel()); testConfig.setProperty(KinesisConfigUtil.THREADING_MODEL, "PER_REQUEST"); kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(KinesisProducerConfiguration.ThreadingModel.PER_REQUEST, kpc.getThreadingModel()); } @Test public void testThreadPoolSizeInProducerConfiguration() { Properties testConfig = new Properties(); testConfig.setProperty(AWSConfigConstants.AWS_REGION, "us-east-1"); KinesisProducerConfiguration kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(10, kpc.getThreadPoolSize()); testConfig.setProperty(KinesisConfigUtil.THREAD_POOL_SIZE, "12"); kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals(12, kpc.getThreadPoolSize()); } @Test public void testCorrectlySetRegionInProducerConfiguration() { String region = "us-east-1"; Properties testConfig = new Properties(); testConfig.setProperty(AWSConfigConstants.AWS_REGION, region); KinesisProducerConfiguration kpc = KinesisConfigUtil.getValidatedProducerConfiguration(testConfig); assertEquals("incorrect region", region, kpc.getRegion()); }
### Question: GlobalConfiguration { public static Configuration loadConfiguration() { final String configDir = System.getenv(ConfigConstants.ENV_FLINK_CONF_DIR); if (configDir == null) { return new Configuration(); } return loadConfiguration(configDir, null); } private GlobalConfiguration(); static Configuration loadConfiguration(); static Configuration loadConfiguration(final String configDir); static Configuration loadConfiguration(final String configDir, @Nullable final Configuration dynamicProperties); static Configuration loadConfigurationWithDynamicProperties(Configuration dynamicProperties); static boolean isSensitive(String key); static final String FLINK_CONF_FILENAME; static final String HIDDEN_CONTENT; }### Answer: @Test public void testConfigurationYAML() { File tmpDir = tempFolder.getRoot(); File confFile = new File(tmpDir, GlobalConfiguration.FLINK_CONF_FILENAME); try { try (final PrintWriter pw = new PrintWriter(confFile)) { pw.println("###########################"); pw.println("# Some : comments : to skip"); pw.println("###########################"); pw.println("mykey1: myvalue1"); pw.println("mykey2 : myvalue2"); pw.println("mykey3:myvalue3"); pw.println(" some nonsense without colon and whitespace separator"); pw.println(" : "); pw.println(" "); pw.println(" "); pw.println("mykey4: myvalue4# some comments"); pw.println(" mykey5 : myvalue5 "); pw.println("mykey6: my: value6"); pw.println("mykey7: "); pw.println(": myvalue8"); pw.println("mykey9: myvalue9"); pw.println("mykey9: myvalue10"); } catch (FileNotFoundException e) { e.printStackTrace(); } Configuration conf = GlobalConfiguration.loadConfiguration(tmpDir.getAbsolutePath()); assertEquals(6, conf.keySet().size()); assertEquals("myvalue1", conf.getString("mykey1", null)); assertEquals("myvalue2", conf.getString("mykey2", null)); assertEquals("null", conf.getString("mykey3", "null")); assertEquals("myvalue4", conf.getString("mykey4", null)); assertEquals("myvalue5", conf.getString("mykey5", null)); assertEquals("my: value6", conf.getString("mykey6", null)); assertEquals("null", conf.getString("mykey7", "null")); assertEquals("null", conf.getString("mykey8", "null")); assertEquals("myvalue10", conf.getString("mykey9", null)); } finally { confFile.delete(); tmpDir.delete(); } } @Test(expected = IllegalArgumentException.class) public void testFailIfNull() { GlobalConfiguration.loadConfiguration(null); } @Test(expected = IllegalConfigurationException.class) public void testFailIfNotLoaded() { GlobalConfiguration.loadConfiguration("/some/path/" + UUID.randomUUID()); } @Test(expected = IllegalConfigurationException.class) public void testInvalidConfiguration() throws IOException { GlobalConfiguration.loadConfiguration(tempFolder.getRoot().getAbsolutePath()); } @Test public void testInvalidYamlFile() throws IOException { final File confFile = tempFolder.newFile(GlobalConfiguration.FLINK_CONF_FILENAME); try (PrintWriter pw = new PrintWriter(confFile)) { pw.append("invalid"); } assertNotNull(GlobalConfiguration.loadConfiguration(tempFolder.getRoot().getAbsolutePath())); }
### Question: KinesisConfigUtil { public static void validateAwsConfiguration(Properties config) { if (config.containsKey(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER)) { String credentialsProviderType = config.getProperty(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER); CredentialProvider providerType; try { providerType = CredentialProvider.valueOf(credentialsProviderType); } catch (IllegalArgumentException e) { StringBuilder sb = new StringBuilder(); for (CredentialProvider type : CredentialProvider.values()) { sb.append(type.toString()).append(", "); } throw new IllegalArgumentException("Invalid AWS Credential Provider Type set in config. Valid values are: " + sb.toString()); } if (providerType == CredentialProvider.BASIC) { if (!config.containsKey(AWSConfigConstants.AWS_ACCESS_KEY_ID) || !config.containsKey(AWSConfigConstants.AWS_SECRET_ACCESS_KEY)) { throw new IllegalArgumentException("Please set values for AWS Access Key ID ('" + AWSConfigConstants.AWS_ACCESS_KEY_ID + "') " + "and Secret Key ('" + AWSConfigConstants.AWS_SECRET_ACCESS_KEY + "') when using the BASIC AWS credential provider type."); } } } if (!config.containsKey(AWSConfigConstants.AWS_REGION)) { throw new IllegalArgumentException("The AWS region ('" + AWSConfigConstants.AWS_REGION + "') must be set in the config."); } else { if (!AWSUtil.isValidRegion(config.getProperty(AWSConfigConstants.AWS_REGION))) { StringBuilder sb = new StringBuilder(); for (Regions region : Regions.values()) { sb.append(region.getName()).append(", "); } throw new IllegalArgumentException("Invalid AWS region set in config. Valid values are: " + sb.toString()); } } } static void validateConsumerConfiguration(Properties config); static Properties replaceDeprecatedProducerKeys(Properties configProps); static KinesisProducerConfiguration getValidatedProducerConfiguration(Properties config); static void validateAwsConfiguration(Properties config); }### Answer: @Test public void testUnrecognizableCredentialProviderTypeInConfig() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid AWS Credential Provider Type"); Properties testConfig = TestUtils.getStandardProperties(); testConfig.setProperty(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER, "wrongProviderType"); KinesisConfigUtil.validateAwsConfiguration(testConfig); }
### Question: FlinkKinesisProducer extends RichSinkFunction<OUT> implements CheckpointedFunction { public void setCustomPartitioner(KinesisPartitioner<OUT> partitioner) { checkNotNull(partitioner, "partitioner cannot be null"); checkArgument( InstantiationUtil.isSerializable(partitioner), "The provided custom partitioner is not serializable: " + partitioner.getClass().getName() + ". " + "Please check that it does not contain references to non-serializable instances."); this.customPartitioner = partitioner; } FlinkKinesisProducer(final SerializationSchema<OUT> schema, Properties configProps); FlinkKinesisProducer(KinesisSerializationSchema<OUT> schema, Properties configProps); void setFailOnError(boolean failOnError); void setDefaultStream(String defaultStream); void setDefaultPartition(String defaultPartition); void setCustomPartitioner(KinesisPartitioner<OUT> partitioner); @Override void open(Configuration parameters); @Override void invoke(OUT value, Context context); @Override void close(); @Override void initializeState(FunctionInitializationContext context); @Override void snapshotState(FunctionSnapshotContext context); }### Answer: @Test public void testConfigureWithNonSerializableCustomPartitionerFails() { exception.expect(IllegalArgumentException.class); exception.expectMessage("The provided custom partitioner is not serializable"); new FlinkKinesisProducer<>(new SimpleStringSchema(), TestUtils.getStandardProperties()) .setCustomPartitioner(new NonSerializableCustomPartitioner()); } @Test public void testConfigureWithSerializableCustomPartitioner() { new FlinkKinesisProducer<>(new SimpleStringSchema(), TestUtils.getStandardProperties()) .setCustomPartitioner(new SerializableCustomPartitioner()); }
### Question: KinesisDataFetcher { public static boolean isThisSubtaskShouldSubscribeTo(int shardHash, int totalNumberOfConsumerSubtasks, int indexOfThisConsumerSubtask) { return (Math.abs(shardHash % totalNumberOfConsumerSubtasks)) == indexOfThisConsumerSubtask; } KinesisDataFetcher(List<String> streams, SourceFunction.SourceContext<T> sourceContext, RuntimeContext runtimeContext, Properties configProps, KinesisDeserializationSchema<T> deserializationSchema, KinesisShardAssigner shardAssigner); @VisibleForTesting protected KinesisDataFetcher(List<String> streams, SourceFunction.SourceContext<T> sourceContext, Object checkpointLock, RuntimeContext runtimeContext, Properties configProps, KinesisDeserializationSchema<T> deserializationSchema, KinesisShardAssigner shardAssigner, AtomicReference<Throwable> error, List<KinesisStreamShardState> subscribedShardsState, HashMap<String, String> subscribedStreamsToLastDiscoveredShardIds, KinesisProxyInterface kinesis); void runFetcher(); HashMap<StreamShardMetadata, SequenceNumber> snapshotState(); void shutdownFetcher(); void awaitTermination(); void advanceLastDiscoveredShardOfStream(String stream, String shardId); List<StreamShardHandle> discoverNewShardsToSubscribe(); int registerNewSubscribedShardState(KinesisStreamShardState newSubscribedShardState); static boolean isThisSubtaskShouldSubscribeTo(int shardHash, int totalNumberOfConsumerSubtasks, int indexOfThisConsumerSubtask); @VisibleForTesting List<KinesisStreamShardState> getSubscribedShardsState(); static StreamShardMetadata convertToStreamShardMetadata(StreamShardHandle streamShardHandle); static StreamShardHandle convertToStreamShardHandle(StreamShardMetadata streamShardMetadata); static final KinesisShardAssigner DEFAULT_SHARD_ASSIGNER; }### Answer: @Test public void testIsThisSubtaskShouldSubscribeTo() { assertTrue(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(0, 2, 0)); assertFalse(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(1, 2, 0)); assertTrue(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(2, 2, 0)); assertFalse(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(0, 2, 1)); assertTrue(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(1, 2, 1)); assertFalse(KinesisDataFetcher.isThisSubtaskShouldSubscribeTo(2, 2, 1)); }
### Question: FlinkKinesisConsumer extends RichParallelSourceFunction<T> implements ResultTypeQueryable<T>, CheckpointedFunction { @Override public void run(SourceContext<T> sourceContext) throws Exception { KinesisDataFetcher<T> fetcher = createFetcher(streams, sourceContext, getRuntimeContext(), configProps, deserializer); List<StreamShardHandle> allShards = fetcher.discoverNewShardsToSubscribe(); for (StreamShardHandle shard : allShards) { StreamShardMetadata.EquivalenceWrapper kinesisStreamShard = new StreamShardMetadata.EquivalenceWrapper(KinesisDataFetcher.convertToStreamShardMetadata(shard)); if (sequenceNumsToRestore != null) { if (sequenceNumsToRestore.containsKey(kinesisStreamShard)) { fetcher.registerNewSubscribedShardState( new KinesisStreamShardState(kinesisStreamShard.getShardMetadata(), shard, sequenceNumsToRestore.get(kinesisStreamShard))); if (LOG.isInfoEnabled()) { LOG.info("Subtask {} is seeding the fetcher with restored shard {}," + " starting state set to the restored sequence number {}", getRuntimeContext().getIndexOfThisSubtask(), shard.toString(), sequenceNumsToRestore.get(kinesisStreamShard)); } } else { fetcher.registerNewSubscribedShardState( new KinesisStreamShardState(kinesisStreamShard.getShardMetadata(), shard, SentinelSequenceNumber.SENTINEL_EARLIEST_SEQUENCE_NUM.get())); if (LOG.isInfoEnabled()) { LOG.info("Subtask {} is seeding the fetcher with new discovered shard {}," + " starting state set to the SENTINEL_EARLIEST_SEQUENCE_NUM", getRuntimeContext().getIndexOfThisSubtask(), shard.toString()); } } } else { SentinelSequenceNumber startingSeqNum = InitialPosition.valueOf(configProps.getProperty( ConsumerConfigConstants.STREAM_INITIAL_POSITION, ConsumerConfigConstants.DEFAULT_STREAM_INITIAL_POSITION)).toSentinelSequenceNumber(); fetcher.registerNewSubscribedShardState( new KinesisStreamShardState(kinesisStreamShard.getShardMetadata(), shard, startingSeqNum.get())); if (LOG.isInfoEnabled()) { LOG.info("Subtask {} will be seeded with initial shard {}, starting state set as sequence number {}", getRuntimeContext().getIndexOfThisSubtask(), shard.toString(), startingSeqNum.get()); } } } if (!running) { return; } this.fetcher = fetcher; fetcher.runFetcher(); fetcher.awaitTermination(); sourceContext.close(); } FlinkKinesisConsumer(String stream, DeserializationSchema<T> deserializer, Properties configProps); FlinkKinesisConsumer(String stream, KinesisDeserializationSchema<T> deserializer, Properties configProps); FlinkKinesisConsumer(List<String> streams, KinesisDeserializationSchema<T> deserializer, Properties configProps); KinesisShardAssigner getShardAssigner(); void setShardAssigner(KinesisShardAssigner shardAssigner); @Override void run(SourceContext<T> sourceContext); @Override void cancel(); @Override void close(); @Override TypeInformation<T> getProducedType(); @Override void initializeState(FunctionInitializationContext context); @Override void snapshotState(FunctionSnapshotContext context); }### Answer: @Test @SuppressWarnings("unchecked") public void testFetcherShouldNotBeRestoringFromFailureIfNotRestoringFromCheckpoint() throws Exception { KinesisDataFetcher mockedFetcher = Mockito.mock(KinesisDataFetcher.class); PowerMockito.whenNew(KinesisDataFetcher.class).withAnyArguments().thenReturn(mockedFetcher); PowerMockito.mockStatic(KinesisConfigUtil.class); PowerMockito.doNothing().when(KinesisConfigUtil.class); TestableFlinkKinesisConsumer consumer = new TestableFlinkKinesisConsumer( "fakeStream", new Properties(), 10, 2); consumer.open(new Configuration()); consumer.run(Mockito.mock(SourceFunction.SourceContext.class)); }
### Question: GlobalConfiguration { public static boolean isSensitive(String key) { Preconditions.checkNotNull(key, "key is null"); final String keyInLower = key.toLowerCase(); for (String hideKey : SENSITIVE_KEYS) { if (keyInLower.length() >= hideKey.length() && keyInLower.contains(hideKey)) { return true; } } return false; } private GlobalConfiguration(); static Configuration loadConfiguration(); static Configuration loadConfiguration(final String configDir); static Configuration loadConfiguration(final String configDir, @Nullable final Configuration dynamicProperties); static Configuration loadConfigurationWithDynamicProperties(Configuration dynamicProperties); static boolean isSensitive(String key); static final String FLINK_CONF_FILENAME; static final String HIDDEN_CONTENT; }### Answer: @Test public void testHiddenKey() { assertTrue(GlobalConfiguration.isSensitive("password123")); assertTrue(GlobalConfiguration.isSensitive("123pasSword")); assertTrue(GlobalConfiguration.isSensitive("PasSword")); assertTrue(GlobalConfiguration.isSensitive("Secret")); assertFalse(GlobalConfiguration.isSensitive("Hello")); }
### Question: StringUtils { public static String arrayToString(Object array) { if (array == null) { throw new NullPointerException(); } if (array instanceof int[]) { return Arrays.toString((int[]) array); } if (array instanceof long[]) { return Arrays.toString((long[]) array); } if (array instanceof Object[]) { return Arrays.toString((Object[]) array); } if (array instanceof byte[]) { return Arrays.toString((byte[]) array); } if (array instanceof double[]) { return Arrays.toString((double[]) array); } if (array instanceof float[]) { return Arrays.toString((float[]) array); } if (array instanceof boolean[]) { return Arrays.toString((boolean[]) array); } if (array instanceof char[]) { return Arrays.toString((char[]) array); } if (array instanceof short[]) { return Arrays.toString((short[]) array); } if (array.getClass().isArray()) { return "<unknown array type>"; } else { throw new IllegalArgumentException("The given argument is no array."); } } private StringUtils(); static String byteToHexString(final byte[] bytes, final int start, final int end); static String byteToHexString(final byte[] bytes); static byte[] hexStringToByte(final String hex); static String arrayAwareToString(Object o); static String arrayToString(Object array); static String showControlCharacters(String str); static String getRandomString(Random rnd, int minLength, int maxLength); static String getRandomString(Random rnd, int minLength, int maxLength, char minValue, char maxValue); static void writeString(@Nonnull String str, DataOutputView out); static String readString(DataInputView in); static void writeNullableString(@Nullable String str, DataOutputView out); static @Nullable String readNullableString(DataInputView in); static boolean isNullOrWhitespaceOnly(String str); @Nullable static String concatenateWithAnd(@Nullable String s1, @Nullable String s2); }### Answer: @Test public void testArrayToString() { double[] array = {1.0}; String controlString = StringUtils.arrayToString(array); assertEquals("[1.0]", controlString); }
### Question: AbstractID implements Comparable<AbstractID>, java.io.Serializable { @Override public int compareTo(AbstractID o) { int diff1 = Long.compare(this.upperPart, o.upperPart); int diff2 = Long.compare(this.lowerPart, o.lowerPart); return diff1 == 0 ? diff2 : diff1; } AbstractID(byte[] bytes); AbstractID(long lowerPart, long upperPart); AbstractID(AbstractID id); AbstractID(); long getLowerPart(); long getUpperPart(); byte[] getBytes(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override int compareTo(AbstractID o); static final int SIZE; }### Answer: @Test public void testCompare() throws Exception { AbstractID id1 = new AbstractID(0, 0); AbstractID id2 = new AbstractID(1, 0); AbstractID id3 = new AbstractID(0, 1); AbstractID id4 = new AbstractID(-1, 0); AbstractID id5 = new AbstractID(0, -1); AbstractID id6 = new AbstractID(-1, -1); AbstractID id7 = new AbstractID(Long.MAX_VALUE, Long.MAX_VALUE); AbstractID id8 = new AbstractID(Long.MIN_VALUE, Long.MIN_VALUE); AbstractID id9 = new AbstractID(Long.MAX_VALUE, Long.MIN_VALUE); AbstractID id10 = new AbstractID(Long.MIN_VALUE, Long.MAX_VALUE); assertEquals(0, id1.compareTo(CommonTestUtils.createCopySerializable(id1))); assertEquals(0, id2.compareTo(CommonTestUtils.createCopySerializable(id2))); assertEquals(0, id3.compareTo(CommonTestUtils.createCopySerializable(id3))); assertEquals(0, id4.compareTo(CommonTestUtils.createCopySerializable(id4))); assertEquals(0, id5.compareTo(CommonTestUtils.createCopySerializable(id5))); assertEquals(0, id6.compareTo(CommonTestUtils.createCopySerializable(id6))); assertEquals(0, id7.compareTo(CommonTestUtils.createCopySerializable(id7))); assertEquals(0, id8.compareTo(CommonTestUtils.createCopySerializable(id8))); assertEquals(0, id9.compareTo(CommonTestUtils.createCopySerializable(id9))); assertEquals(0, id10.compareTo(CommonTestUtils.createCopySerializable(id10))); assertCompare(id1, id2, -1); assertCompare(id1, id3, -1); assertCompare(id1, id4, 1); assertCompare(id1, id5, 1); assertCompare(id1, id6, 1); assertCompare(id2, id5, 1); assertCompare(id3, id5, 1); assertCompare(id2, id6, 1); assertCompare(id3, id6, 1); assertCompare(id1, id7, -1); assertCompare(id1, id8, 1); assertCompare(id7, id8, 1); assertCompare(id9, id10, -1); assertCompare(id7, id9, 1); assertCompare(id7, id10, 1); assertCompare(id8, id9, -1); assertCompare(id8, id10, -1); }
### Question: MinWatermarkGauge implements Gauge<Long> { @Override public Long getValue() { return Math.min(watermarkGauge1.getValue(), watermarkGauge2.getValue()); } MinWatermarkGauge(WatermarkGauge watermarkGauge1, WatermarkGauge watermarkGauge2); @Override Long getValue(); }### Answer: @Test public void testSetCurrentLowWatermark() { WatermarkGauge metric1 = new WatermarkGauge(); WatermarkGauge metric2 = new WatermarkGauge(); MinWatermarkGauge metric = new MinWatermarkGauge(metric1, metric2); Assert.assertEquals(Long.MIN_VALUE, metric.getValue().longValue()); metric1.setCurrentWatermark(1); Assert.assertEquals(Long.MIN_VALUE, metric.getValue().longValue()); metric2.setCurrentWatermark(2); Assert.assertEquals(1L, metric.getValue().longValue()); metric1.setCurrentWatermark(3); Assert.assertEquals(2L, metric.getValue().longValue()); }
### Question: StreamTask extends AbstractInvokable implements AsyncExceptionHandler { public String getName() { return getEnvironment().getTaskInfo().getTaskNameWithSubtasks(); } protected StreamTask(Environment env); protected StreamTask( Environment environment, @Nullable ProcessingTimeService timeProvider); StreamTaskStateInitializer createStreamTaskStateInitializer(); @Override final void invoke(); @Override final void cancel(); final boolean isRunning(); final boolean isCanceled(); String getName(); Object getCheckpointLock(); CheckpointStorage getCheckpointStorage(); StreamConfig getConfiguration(); Map<String, Accumulator<?, ?>> getAccumulatorMap(); StreamStatusMaintainer getStreamStatusMaintainer(); @Override boolean triggerCheckpoint(CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions); @Override void triggerCheckpointOnBarrier( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics); @Override void abortCheckpointOnBarrier(long checkpointId, Throwable cause); ExecutorService getAsyncOperationsThreadPool(); @Override void notifyCheckpointComplete(long checkpointId); ProcessingTimeService getProcessingTimeService(); @Override void handleAsyncException(String message, Throwable exception); @Override String toString(); CloseableRegistry getCancelables(); @VisibleForTesting static List<StreamRecordWriter<SerializationDelegate<StreamRecord<OUT>>>> createStreamRecordWriters( StreamConfig configuration, Environment environment); static final ThreadGroup TRIGGER_THREAD_GROUP; }### Answer: @Test public void testStateBackendLoadingAndClosing() throws Exception { Configuration taskManagerConfig = new Configuration(); taskManagerConfig.setString(CheckpointingOptions.STATE_BACKEND, TestMemoryStateBackendFactory.class.getName()); StreamConfig cfg = new StreamConfig(new Configuration()); cfg.setStateKeySerializer(mock(TypeSerializer.class)); cfg.setOperatorID(new OperatorID(4711L, 42L)); TestStreamSource<Long, MockSourceFunction> streamSource = new TestStreamSource<>(new MockSourceFunction()); cfg.setStreamOperator(streamSource); cfg.setTimeCharacteristic(TimeCharacteristic.ProcessingTime); Task task = createTask(StateBackendTestSource.class, cfg, taskManagerConfig); StateBackendTestSource.fail = false; task.startTaskThread(); task.getExecutingThread().join(); verify(TestStreamSource.operatorStateBackend).close(); verify(TestStreamSource.keyedStateBackend).close(); verify(TestStreamSource.rawOperatorStateInputs).close(); verify(TestStreamSource.rawKeyedStateInputs).close(); verify(TestStreamSource.operatorStateBackend).dispose(); verify(TestStreamSource.keyedStateBackend).dispose(); assertEquals(ExecutionState.FINISHED, task.getExecutionState()); } @Test public void testStateBackendClosingOnFailure() throws Exception { Configuration taskManagerConfig = new Configuration(); taskManagerConfig.setString(CheckpointingOptions.STATE_BACKEND, TestMemoryStateBackendFactory.class.getName()); StreamConfig cfg = new StreamConfig(new Configuration()); cfg.setStateKeySerializer(mock(TypeSerializer.class)); cfg.setOperatorID(new OperatorID(4711L, 42L)); TestStreamSource<Long, MockSourceFunction> streamSource = new TestStreamSource<>(new MockSourceFunction()); cfg.setStreamOperator(streamSource); cfg.setTimeCharacteristic(TimeCharacteristic.ProcessingTime); Task task = createTask(StateBackendTestSource.class, cfg, taskManagerConfig); StateBackendTestSource.fail = true; task.startTaskThread(); task.getExecutingThread().join(); verify(TestStreamSource.operatorStateBackend).close(); verify(TestStreamSource.keyedStateBackend).close(); verify(TestStreamSource.rawOperatorStateInputs).close(); verify(TestStreamSource.rawKeyedStateInputs).close(); verify(TestStreamSource.operatorStateBackend).dispose(); verify(TestStreamSource.keyedStateBackend).dispose(); assertEquals(ExecutionState.FAILED, task.getExecutionState()); }
### Question: LambdaUtil { public static <E extends Throwable> void withContextClassLoader( final ClassLoader cl, final ThrowingRunnable<E> r) throws E { final Thread currentThread = Thread.currentThread(); final ClassLoader oldClassLoader = currentThread.getContextClassLoader(); try { currentThread.setContextClassLoader(cl); r.run(); } finally { currentThread.setContextClassLoader(oldClassLoader); } } private LambdaUtil(); static void applyToAllWhileSuppressingExceptions( Iterable<T> inputs, ThrowingConsumer<T, ? extends Exception> throwingConsumer); static void withContextClassLoader( final ClassLoader cl, final ThrowingRunnable<E> r); static R withContextClassLoader( final ClassLoader cl, final SupplierWithException<R, E> s); }### Answer: @Test public void testRunWithContextClassLoaderRunnable() throws Exception { final ClassLoader aPrioriContextClassLoader = Thread.currentThread().getContextClassLoader(); try { final ClassLoader original = new URLClassLoader(new URL[0]); final ClassLoader temp = new URLClassLoader(new URL[0]); Thread.currentThread().setContextClassLoader(original); LambdaUtil.withContextClassLoader(temp, () -> assertSame(temp, Thread.currentThread().getContextClassLoader())); assertSame(original, Thread.currentThread().getContextClassLoader()); } finally { Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader); } } @Test public void testRunWithContextClassLoaderSupplier() throws Exception { final ClassLoader aPrioriContextClassLoader = Thread.currentThread().getContextClassLoader(); try { final ClassLoader original = new URLClassLoader(new URL[0]); final ClassLoader temp = new URLClassLoader(new URL[0]); Thread.currentThread().setContextClassLoader(original); LambdaUtil.withContextClassLoader(temp, () -> { assertSame(temp, Thread.currentThread().getContextClassLoader()); return true; }); assertSame(original, Thread.currentThread().getContextClassLoader()); } finally { Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader); } }
### Question: SystemProcessingTimeService extends ProcessingTimeService { @Override public ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period) { long nextTimestamp = getCurrentProcessingTime() + initialDelay; try { return timerService.scheduleAtFixedRate( new RepeatedTriggerTask(status, task, checkpointLock, callback, nextTimestamp, period), initialDelay, period, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { final int status = this.status.get(); if (status == STATUS_QUIESCED) { return new NeverCompleteFuture(initialDelay); } else if (status == STATUS_SHUTDOWN) { throw new IllegalStateException("Timer service is shut down"); } else { throw e; } } } SystemProcessingTimeService(AsyncExceptionHandler failureHandler, Object checkpointLock); SystemProcessingTimeService( AsyncExceptionHandler task, Object checkpointLock, ThreadFactory threadFactory); @Override long getCurrentProcessingTime(); @Override ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target); @Override ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period); @Override boolean isTerminated(); @Override void quiesce(); @Override void awaitPendingAfterQuiesce(); @Override void shutdownService(); @Override boolean shutdownAndAwaitPending(long time, TimeUnit timeUnit); @Override boolean shutdownServiceUninterruptible(long timeoutMs); }### Answer: @Test(timeout = 10000) public void testScheduleAtFixedRate() throws Exception { final Object lock = new Object(); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final long period = 10L; final int countDown = 3; final SystemProcessingTimeService timer = new SystemProcessingTimeService( new ReferenceSettingExceptionHandler(errorRef), lock); final CountDownLatch countDownLatch = new CountDownLatch(countDown); try { timer.scheduleAtFixedRate(new ProcessingTimeCallback() { @Override public void onProcessingTime(long timestamp) throws Exception { countDownLatch.countDown(); } }, 0L, period); countDownLatch.await(); if (errorRef.get() != null) { throw new Exception(errorRef.get()); } } finally { timer.shutdownService(); } } @Test public void testExceptionReportingScheduleAtFixedRate() throws InterruptedException { final AtomicBoolean exceptionWasThrown = new AtomicBoolean(false); final OneShotLatch latch = new OneShotLatch(); final Object lock = new Object(); ProcessingTimeService timeServiceProvider = new SystemProcessingTimeService( new AsyncExceptionHandler() { @Override public void handleAsyncException(String message, Throwable exception) { exceptionWasThrown.set(true); latch.trigger(); } }, lock); timeServiceProvider.scheduleAtFixedRate( new ProcessingTimeCallback() { @Override public void onProcessingTime(long timestamp) throws Exception { throw new Exception("Exception in Timer"); } }, 0L, 100L); latch.await(); assertTrue(exceptionWasThrown.get()); }
### Question: SystemProcessingTimeService extends ProcessingTimeService { @Override public ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target) { long delay = Math.max(timestamp - getCurrentProcessingTime(), 0); try { return timerService.schedule( new TriggerTask(status, task, checkpointLock, target, timestamp), delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { final int status = this.status.get(); if (status == STATUS_QUIESCED) { return new NeverCompleteFuture(delay); } else if (status == STATUS_SHUTDOWN) { throw new IllegalStateException("Timer service is shut down"); } else { throw e; } } } SystemProcessingTimeService(AsyncExceptionHandler failureHandler, Object checkpointLock); SystemProcessingTimeService( AsyncExceptionHandler task, Object checkpointLock, ThreadFactory threadFactory); @Override long getCurrentProcessingTime(); @Override ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target); @Override ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period); @Override boolean isTerminated(); @Override void quiesce(); @Override void awaitPendingAfterQuiesce(); @Override void shutdownService(); @Override boolean shutdownAndAwaitPending(long time, TimeUnit timeUnit); @Override boolean shutdownServiceUninterruptible(long timeoutMs); }### Answer: @Test public void testExceptionReporting() throws InterruptedException { final AtomicBoolean exceptionWasThrown = new AtomicBoolean(false); final OneShotLatch latch = new OneShotLatch(); final Object lock = new Object(); ProcessingTimeService timeServiceProvider = new SystemProcessingTimeService( new AsyncExceptionHandler() { @Override public void handleAsyncException(String message, Throwable exception) { exceptionWasThrown.set(true); latch.trigger(); } }, lock); timeServiceProvider.registerTimer(System.currentTimeMillis(), new ProcessingTimeCallback() { @Override public void onProcessingTime(long timestamp) throws Exception { throw new Exception("Exception in Timer"); } }); latch.await(); assertTrue(exceptionWasThrown.get()); }
### Question: SystemProcessingTimeService extends ProcessingTimeService { @Override public boolean shutdownServiceUninterruptible(long timeoutMs) { final Deadline deadline = Deadline.fromNow(Duration.ofMillis(timeoutMs)); boolean shutdownComplete = false; boolean receivedInterrupt = false; do { try { shutdownComplete = shutdownAndAwaitPending(deadline.timeLeft().toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException iex) { receivedInterrupt = true; LOG.trace("Intercepted attempt to interrupt timer service shutdown.", iex); } } while (deadline.hasTimeLeft() && !shutdownComplete); if (receivedInterrupt) { Thread.currentThread().interrupt(); } return shutdownComplete; } SystemProcessingTimeService(AsyncExceptionHandler failureHandler, Object checkpointLock); SystemProcessingTimeService( AsyncExceptionHandler task, Object checkpointLock, ThreadFactory threadFactory); @Override long getCurrentProcessingTime(); @Override ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target); @Override ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period); @Override boolean isTerminated(); @Override void quiesce(); @Override void awaitPendingAfterQuiesce(); @Override void shutdownService(); @Override boolean shutdownAndAwaitPending(long time, TimeUnit timeUnit); @Override boolean shutdownServiceUninterruptible(long timeoutMs); }### Answer: @Test public void testShutdownServiceUninterruptible() { final Object lock = new Object(); final OneShotLatch blockUntilTriggered = new OneShotLatch(); final AtomicBoolean timerFinished = new AtomicBoolean(false); final SystemProcessingTimeService timeService = createBlockingSystemProcessingTimeService(lock, blockUntilTriggered, timerFinished); Assert.assertFalse(timeService.isTerminated()); final Thread interruptTarget = Thread.currentThread(); final AtomicBoolean runInterrupts = new AtomicBoolean(true); final Thread interruptCallerThread = new Thread(() -> { while (runInterrupts.get()) { interruptTarget.interrupt(); try { Thread.sleep(1); } catch (InterruptedException ignore) { } } }); interruptCallerThread.start(); final long timeoutMs = 50L; final long startTime = System.nanoTime(); Assert.assertFalse(timeService.isTerminated()); Assert.assertFalse(timeService.shutdownServiceUninterruptible(timeoutMs)); Assert.assertTrue(timeService.isTerminated()); Assert.assertFalse(timerFinished.get()); Assert.assertTrue((System.nanoTime() - startTime) >= (1_000_000L * timeoutMs)); runInterrupts.set(false); do { try { interruptCallerThread.join(); } catch (InterruptedException ignore) { } } while (interruptCallerThread.isAlive()); blockUntilTriggered.trigger(); Assert.assertTrue(timeService.shutdownServiceUninterruptible(timeoutMs)); Assert.assertTrue(timerFinished.get()); }
### Question: TwoPhaseCommitSinkFunction extends RichSinkFunction<IN> implements CheckpointedFunction, CheckpointListener { @Override public void initializeState(FunctionInitializationContext context) throws Exception { state = context.getOperatorStateStore().getListState(stateDescriptor); if (context.isRestored()) { LOG.info("{} - restoring state", name()); for (State<TXN, CONTEXT> operatorState : state.get()) { userContext = operatorState.getContext(); List<TransactionHolder<TXN>> recoveredTransactions = operatorState.getPendingCommitTransactions(); for (TransactionHolder<TXN> recoveredTransaction : recoveredTransactions) { recoverAndCommitInternal(recoveredTransaction); LOG.info("{} committed recovered transaction {}", name(), recoveredTransaction); } recoverAndAbort(operatorState.getPendingTransaction().handle); LOG.info("{} aborted recovered transaction {}", name(), operatorState.getPendingTransaction()); if (userContext.isPresent()) { finishRecoveringContext(); } } } if (userContext == null) { LOG.info("{} - no state to restore", name()); userContext = initializeUserContext(); } this.pendingCommitTransactions.clear(); currentTransactionHolder = beginTransactionInternal(); LOG.debug("{} - started new transaction '{}'", name(), currentTransactionHolder); } TwoPhaseCommitSinkFunction( TypeSerializer<TXN> transactionSerializer, TypeSerializer<CONTEXT> contextSerializer); @VisibleForTesting TwoPhaseCommitSinkFunction( TypeSerializer<TXN> transactionSerializer, TypeSerializer<CONTEXT> contextSerializer, Clock clock); @Override final void invoke(IN value); @Override final void invoke( IN value, Context context); @Override final void notifyCheckpointComplete(long checkpointId); @Override void snapshotState(FunctionSnapshotContext context); @Override void initializeState(FunctionInitializationContext context); @Override void close(); }### Answer: @Test public void testFailBeforeNotify() throws Exception { harness.open(); harness.processElement("42", 0); harness.snapshot(0, 1); harness.processElement("43", 2); OperatorSubtaskState snapshot = harness.snapshot(1, 3); tmpDirectory.setWritable(false); try { harness.processElement("44", 4); harness.snapshot(2, 5); fail("something should fail"); } catch (Exception ex) { if (!(ex.getCause() instanceof ContentDump.NotWritableException)) { throw ex; } } closeTestHarness(); tmpDirectory.setWritable(true); setUpTestHarness(); harness.initializeState(snapshot); assertExactlyOnce(Arrays.asList("42", "43")); closeTestHarness(); assertEquals(0, tmpDirectory.listFiles().size()); }
### Question: RocksDBKeySerializationUtils { public static boolean isAmbiguousKeyPossible(TypeSerializer keySerializer, TypeSerializer namespaceSerializer) { return (keySerializer.getLength() < 0) && (namespaceSerializer.getLength() < 0); } static int readKeyGroup(int keyGroupPrefixBytes, DataInputView inputView); static K readKey( TypeSerializer<K> keySerializer, ByteArrayInputStreamWithPos inputStream, DataInputView inputView, boolean ambiguousKeyPossible); static N readNamespace( TypeSerializer<N> namespaceSerializer, ByteArrayInputStreamWithPos inputStream, DataInputView inputView, boolean ambiguousKeyPossible); static void writeNameSpace( N namespace, TypeSerializer<N> namespaceSerializer, ByteArrayOutputStreamWithPos keySerializationStream, DataOutputView keySerializationDataOutputView, boolean ambiguousKeyPossible); static boolean isAmbiguousKeyPossible(TypeSerializer keySerializer, TypeSerializer namespaceSerializer); static void writeKeyGroup( int keyGroup, int keyGroupPrefixBytes, DataOutputView keySerializationDateDataOutputView); static void writeKey( K key, TypeSerializer<K> keySerializer, ByteArrayOutputStreamWithPos keySerializationStream, DataOutputView keySerializationDataOutputView, boolean ambiguousKeyPossible); }### Answer: @Test public void testIsAmbiguousKeyPossible() { Assert.assertFalse(RocksDBKeySerializationUtils.isAmbiguousKeyPossible( IntSerializer.INSTANCE, StringSerializer.INSTANCE)); Assert.assertTrue(RocksDBKeySerializationUtils.isAmbiguousKeyPossible( StringSerializer.INSTANCE, StringSerializer.INSTANCE)); }
### Question: AkkaRpcService implements RpcService { @Override public ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit) { checkNotNull(runnable, "runnable"); checkNotNull(unit, "unit"); checkArgument(delay >= 0L, "delay must be zero or larger"); return internalScheduledExecutor.schedule(runnable, delay, unit); } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect( final String address, final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer: @Test public void testScheduleRunnable() throws Exception { final OneShotLatch latch = new OneShotLatch(); final long delay = 100; final long start = System.nanoTime(); ScheduledFuture<?> scheduledFuture = akkaRpcService.scheduleRunnable(new Runnable() { @Override public void run() { latch.trigger(); } }, delay, TimeUnit.MILLISECONDS); scheduledFuture.get(); assertTrue(latch.isTriggered()); final long stop = System.nanoTime(); assertTrue("call was not properly delayed", ((stop - start) / 1000000) >= delay); }
### Question: AkkaRpcService implements RpcService { @Override public void execute(Runnable runnable) { actorSystem.dispatcher().execute(runnable); } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect( final String address, final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer: @Test public void testExecuteRunnable() throws Exception { final OneShotLatch latch = new OneShotLatch(); akkaRpcService.execute(() -> latch.trigger()); latch.await(30L, TimeUnit.SECONDS); } @Test public void testExecuteCallable() throws InterruptedException, ExecutionException, TimeoutException { final OneShotLatch latch = new OneShotLatch(); final int expected = 42; CompletableFuture<Integer> result = akkaRpcService.execute(new Callable<Integer>() { @Override public Integer call() throws Exception { latch.trigger(); return expected; } }); int actual = result.get(30L, TimeUnit.SECONDS); assertEquals(expected, actual); assertTrue(latch.isTriggered()); }
### Question: AkkaRpcService implements RpcService { @Override public String getAddress() { return address; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect( final String address, final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer: @Test public void testGetAddress() { assertEquals(AkkaUtils.getAddress(actorSystem).host().get(), akkaRpcService.getAddress()); }
### Question: AkkaRpcService implements RpcService { @Override public int getPort() { return port; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect( final String address, final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer: @Test public void testGetPort() { assertEquals(AkkaUtils.getAddress(actorSystem).port().get(), akkaRpcService.getPort()); }
### Question: AkkaRpcService implements RpcService { @Override public CompletableFuture<Void> getTerminationFuture() { return terminationFuture; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect( final String address, final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer: @Test(timeout = 60000) public void testTerminationFuture() throws Exception { final ActorSystem actorSystem = AkkaUtils.createDefaultActorSystem(); final AkkaRpcService rpcService = new AkkaRpcService(actorSystem, Time.milliseconds(1000)); CompletableFuture<Void> terminationFuture = rpcService.getTerminationFuture(); assertFalse(terminationFuture.isDone()); CompletableFuture.runAsync(rpcService::stopService, actorSystem.dispatcher()); terminationFuture.get(); }
### Question: SubtaskIndexPathParameter extends MessagePathParameter<Integer> { @Override protected Integer convertFromString(final String value) throws ConversionException { final int subtaskIndex = Integer.parseInt(value); if (subtaskIndex >= 0) { return subtaskIndex; } else { throw new ConversionException("subtaskindex must be positive, was: " + subtaskIndex); } } SubtaskIndexPathParameter(); static final String KEY; }### Answer: @Test public void testConversionFromString() throws Exception { assertThat(subtaskIndexPathParameter.convertFromString("2147483647"), equalTo(Integer.MAX_VALUE)); } @Test public void testConversionFromStringNegativeNumber() throws Exception { try { subtaskIndexPathParameter.convertFromString("-2147483648"); fail("Expected exception not thrown"); } catch (final ConversionException e) { assertThat(e.getMessage(), equalTo("subtaskindex must be positive, was: " + Integer .MIN_VALUE)); } }
### Question: SubtaskIndexPathParameter extends MessagePathParameter<Integer> { @Override protected String convertToString(final Integer value) { return value.toString(); } SubtaskIndexPathParameter(); static final String KEY; }### Answer: @Test public void testConvertToString() throws Exception { assertThat(subtaskIndexPathParameter.convertToString(Integer.MAX_VALUE), equalTo("2147483647")); }
### Question: HandlerRequestUtils { public static <X, P extends MessageQueryParameter<X>, R extends RequestBody, M extends MessageParameters> X getQueryParameter( final HandlerRequest<R, M> request, final Class<P> queryParameterClass) throws RestHandlerException { return getQueryParameter(request, queryParameterClass, null); } static X getQueryParameter( final HandlerRequest<R, M> request, final Class<P> queryParameterClass); static X getQueryParameter( final HandlerRequest<R, M> request, final Class<P> queryParameterClass, final X defaultValue); }### Answer: @Test public void testGetQueryParameter() throws Exception { final Boolean queryParameter = HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Collections.singletonList("true"))), TestBooleanQueryParameter.class); assertThat(queryParameter, equalTo(true)); } @Test public void testGetQueryParameterRepeated() throws Exception { try { HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Arrays.asList("true", "false"))), TestBooleanQueryParameter.class); } catch (final RestHandlerException e) { assertThat(e.getMessage(), containsString("Expected only one value")); } } @Test public void testGetQueryParameterDefaultValue() throws Exception { final Boolean allowNonRestoredState = HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Collections.emptyList())), TestBooleanQueryParameter.class, true); assertThat(allowNonRestoredState, equalTo(true)); }
### Question: FileUtils { public static void deleteDirectory(File directory) throws IOException { checkNotNull(directory, "directory"); guardIfWindows(FileUtils::deleteDirectoryInternal, directory); } private FileUtils(); static String getRandomFilename(final String prefix); static String readFile(File file, String charsetName); static String readFileUtf8(File file); static void writeFile(File file, String contents, String encoding); static void writeFileUtf8(File file, String contents); static void deleteFileOrDirectory(File file); static void deleteDirectory(File directory); static void deleteDirectoryQuietly(File directory); static void cleanDirectory(File directory); static boolean deletePathIfEmpty(FileSystem fileSystem, Path path); }### Answer: @Test public void testDeleteDirectory() throws Exception { File doesNotExist = new File(tmp.newFolder(), "abc"); FileUtils.deleteDirectory(doesNotExist); File cannotDeleteParent = tmp.newFolder(); File cannotDeleteChild = new File(cannotDeleteParent, "child"); try { assumeTrue(cannotDeleteChild.createNewFile()); assumeTrue(cannotDeleteParent.setWritable(false)); assumeTrue(cannotDeleteChild.setWritable(false)); FileUtils.deleteDirectory(cannotDeleteParent); fail("this should fail with an exception"); } catch (AccessDeniedException ignored) { } finally { cannotDeleteParent.setWritable(true); cannotDeleteChild.setWritable(true); } } @Test public void testDeleteDirectoryWhichIsAFile() throws Exception { File file = tmp.newFile(); try { FileUtils.deleteDirectory(file); fail("this should fail with an exception"); } catch (IOException ignored) { } }
### Question: ExceptionUtils { public static String stringifyException(final Throwable e) { if (e == null) { return STRINGIFIED_NULL_EXCEPTION; } try { StringWriter stm = new StringWriter(); PrintWriter wrt = new PrintWriter(stm); e.printStackTrace(wrt); wrt.close(); return stm.toString(); } catch (Throwable t) { return e.getClass().getName() + " (error while printing stack trace)"; } } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer: @Test public void testStringifyNullException() { assertNotNull(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION); assertEquals(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION, ExceptionUtils.stringifyException(null)); }
### Question: ExceptionUtils { public static boolean isJvmFatalError(Throwable t) { return (t instanceof InternalError) || (t instanceof UnknownError) || (t instanceof ThreadDeath); } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer: @Test public void testJvmFatalError() { assertFalse(ExceptionUtils.isJvmFatalError(new Error())); assertFalse(ExceptionUtils.isJvmFatalError(new LinkageError())); assertTrue(ExceptionUtils.isJvmFatalError(new InternalError())); assertTrue(ExceptionUtils.isJvmFatalError(new UnknownError())); }
### Question: AbstractTaskManagerFileHandler extends AbstractHandler<RestfulGateway, EmptyRequestBody, M> { @Override protected void respondToRequest(ChannelHandlerContext ctx, HttpRequest httpRequest, HandlerRequest<EmptyRequestBody, M> handlerRequest, RestfulGateway gateway) throws RestHandlerException { final ResourceID taskManagerId = handlerRequest.getPathParameter(TaskManagerIdPathParameter.class); final CompletableFuture<TransientBlobKey> blobKeyFuture; try { blobKeyFuture = fileBlobKeys.get(taskManagerId); } catch (ExecutionException e) { final Throwable cause = ExceptionUtils.stripExecutionException(e); if (cause instanceof RestHandlerException) { throw (RestHandlerException) cause; } else { throw new RestHandlerException("Could not retrieve file blob key future.", HttpResponseStatus.INTERNAL_SERVER_ERROR, e); } } final CompletableFuture<Void> resultFuture = blobKeyFuture.thenAcceptAsync( (TransientBlobKey blobKey) -> { final File file; try { file = transientBlobService.getFile(blobKey); } catch (IOException e) { throw new CompletionException(new FlinkException("Could not retrieve file from transient blob store.", e)); } try { transferFile( ctx, file, httpRequest); } catch (FlinkException e) { throw new CompletionException(new FlinkException("Could not transfer file to client.", e)); } }, ctx.executor()); resultFuture.whenComplete( (Void ignored, Throwable throwable) -> { if (throwable != null) { log.debug("Failed to transfer file from TaskExecutor {}.", taskManagerId, throwable); fileBlobKeys.invalidate(taskManagerId); final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable); final ErrorResponseBody errorResponseBody; final HttpResponseStatus httpResponseStatus; if (strippedThrowable instanceof UnknownTaskExecutorException) { errorResponseBody = new ErrorResponseBody("Unknown TaskExecutor " + taskManagerId + '.'); httpResponseStatus = HttpResponseStatus.NOT_FOUND; } else { errorResponseBody = new ErrorResponseBody("Internal server error: " + throwable.getMessage() + '.'); httpResponseStatus = INTERNAL_SERVER_ERROR; } HandlerUtils.sendErrorResponse( ctx, httpRequest, errorResponseBody, httpResponseStatus, responseHeaders); } }); } protected AbstractTaskManagerFileHandler( @Nonnull CompletableFuture<String> localAddressFuture, @Nonnull GatewayRetriever<? extends RestfulGateway> leaderRetriever, @Nonnull Time timeout, @Nonnull Map<String, String> responseHeaders, @Nonnull UntypedResponseMessageHeaders<EmptyRequestBody, M> untypedResponseMessageHeaders, @Nonnull GatewayRetriever<ResourceManagerGateway> resourceManagerGatewayRetriever, @Nonnull TransientBlobService transientBlobService, @Nonnull Time cacheEntryDuration); }### Answer: @Test public void testFileServing() throws Exception { final Time cacheEntryDuration = Time.milliseconds(1000L); final Queue<CompletableFuture<TransientBlobKey>> requestFileUploads = new ArrayDeque<>(1); requestFileUploads.add(CompletableFuture.completedFuture(transientBlobKey1)); final TestTaskManagerFileHandler testTaskManagerFileHandler = createTestTaskManagerFileHandler(cacheEntryDuration, requestFileUploads, EXPECTED_TASK_MANAGER_ID); final File outputFile = temporaryFolder.newFile(); final TestingChannelHandlerContext testingContext = new TestingChannelHandlerContext(outputFile); testTaskManagerFileHandler.respondToRequest( testingContext, HTTP_REQUEST, handlerRequest, null); assertThat(outputFile.length(), is(greaterThan(0L))); assertThat(FileUtils.readFileUtf8(outputFile), is(equalTo(fileContent1))); }
### Question: JobExecutionResultHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, JobExecutionResultResponseBody, JobMessageParameters> { @Override protected CompletableFuture<JobExecutionResultResponseBody> handleRequest( @Nonnull final HandlerRequest<EmptyRequestBody, JobMessageParameters> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { final JobID jobId = request.getPathParameter(JobIDPathParameter.class); final CompletableFuture<JobStatus> jobStatusFuture = gateway.requestJobStatus(jobId, timeout); return jobStatusFuture.thenCompose( jobStatus -> { if (jobStatus.isGloballyTerminalState()) { return gateway .requestJobResult(jobId, timeout) .thenApply(JobExecutionResultResponseBody::created); } else { return CompletableFuture.completedFuture( JobExecutionResultResponseBody.inProgress()); } }).exceptionally(throwable -> { throw propagateException(throwable); }); } JobExecutionResultHandler( final CompletableFuture<String> localRestAddress, final GatewayRetriever<? extends RestfulGateway> leaderRetriever, final Time timeout, final Map<String, String> responseHeaders); }### Answer: @Test public void testResultInProgress() throws Exception { final TestingRestfulGateway testingRestfulGateway = TestingRestfulGateway.newBuilder() .setRequestJobStatusFunction( jobId -> CompletableFuture.completedFuture(JobStatus.RUNNING)) .build(); final JobExecutionResultResponseBody responseBody = jobExecutionResultHandler.handleRequest( testRequest, testingRestfulGateway).get(); assertThat( responseBody.getStatus().getId(), equalTo(QueueStatus.Id.IN_PROGRESS)); } @Test public void testCompletedResult() throws Exception { final JobStatus jobStatus = JobStatus.FINISHED; final ArchivedExecutionGraph executionGraph = new ArchivedExecutionGraphBuilder() .setJobID(TEST_JOB_ID) .setState(jobStatus) .build(); final TestingRestfulGateway testingRestfulGateway = TestingRestfulGateway.newBuilder() .setRequestJobStatusFunction( jobId -> { assertThat(jobId, equalTo(TEST_JOB_ID)); return CompletableFuture.completedFuture(jobStatus); }) .setRequestJobResultFunction( jobId -> { assertThat(jobId, equalTo(TEST_JOB_ID)); return CompletableFuture.completedFuture(JobResult.createFrom(executionGraph)); } ) .build(); final JobExecutionResultResponseBody responseBody = jobExecutionResultHandler.handleRequest( testRequest, testingRestfulGateway).get(); assertThat( responseBody.getStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); assertThat(responseBody.getJobExecutionResult(), not(nullValue())); } @Test public void testPropagateFlinkJobNotFoundExceptionAsRestHandlerException() throws Exception { final TestingRestfulGateway testingRestfulGateway = TestingRestfulGateway.newBuilder() .setRequestJobStatusFunction( jobId -> FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId)) ) .build(); try { jobExecutionResultHandler.handleRequest( testRequest, testingRestfulGateway).get(); fail("Expected exception not thrown"); } catch (final ExecutionException e) { final Throwable cause = ExceptionUtils.stripCompletionException(e.getCause()); assertThat(cause, instanceOf(RestHandlerException.class)); assertThat( ((RestHandlerException) cause).getHttpResponseStatus(), equalTo(HttpResponseStatus.NOT_FOUND)); } }
### Question: ExceptionUtils { public static void rethrowIfFatalError(Throwable t) { if (isJvmFatalError(t)) { throw (Error) t; } } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer: @Test public void testRethrowFatalError() { try { ExceptionUtils.rethrowIfFatalError(new InternalError()); fail(); } catch (InternalError ignored) {} ExceptionUtils.rethrowIfFatalError(new NoClassDefFoundError()); }
### Question: JobSubmitHandler extends AbstractRestHandler<DispatcherGateway, JobSubmitRequestBody, JobSubmitResponseBody, EmptyMessageParameters> { @Override protected CompletableFuture<JobSubmitResponseBody> handleRequest(@Nonnull HandlerRequest<JobSubmitRequestBody, EmptyMessageParameters> request, @Nonnull DispatcherGateway gateway) throws RestHandlerException { JobGraph jobGraph; try { ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(request.getRequestBody().serializedJobGraph)); jobGraph = (JobGraph) objectIn.readObject(); } catch (Exception e) { throw new RestHandlerException( "Failed to deserialize JobGraph.", HttpResponseStatus.BAD_REQUEST, e); } return gateway.submitJob(jobGraph, timeout) .thenApply(ack -> new JobSubmitResponseBody("/jobs/" + jobGraph.getJobID())); } JobSubmitHandler( CompletableFuture<String> localRestAddress, GatewayRetriever<? extends DispatcherGateway> leaderRetriever, Time timeout, Map<String, String> headers); }### Answer: @Test public void testSerializationFailureHandling() throws Exception { DispatcherGateway mockGateway = mock(DispatcherGateway.class); when(mockGateway.submitJob(any(JobGraph.class), any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get())); GatewayRetriever<DispatcherGateway> mockGatewayRetriever = mock(GatewayRetriever.class); JobSubmitHandler handler = new JobSubmitHandler( CompletableFuture.completedFuture("http: mockGatewayRetriever, RpcUtils.INF_TIMEOUT, Collections.emptyMap()); JobSubmitRequestBody request = new JobSubmitRequestBody(new byte[0]); try { handler.handleRequest(new HandlerRequest<>(request, EmptyMessageParameters.getInstance()), mockGateway); Assert.fail(); } catch (RestHandlerException rhe) { Assert.assertEquals(HttpResponseStatus.BAD_REQUEST, rhe.getHttpResponseStatus()); } } @Test public void testSuccessfulJobSubmission() throws Exception { DispatcherGateway mockGateway = mock(DispatcherGateway.class); when(mockGateway.submitJob(any(JobGraph.class), any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get())); GatewayRetriever<DispatcherGateway> mockGatewayRetriever = mock(GatewayRetriever.class); JobSubmitHandler handler = new JobSubmitHandler( CompletableFuture.completedFuture("http: mockGatewayRetriever, RpcUtils.INF_TIMEOUT, Collections.emptyMap()); JobGraph job = new JobGraph("testjob"); JobSubmitRequestBody request = new JobSubmitRequestBody(job); handler.handleRequest(new HandlerRequest<>(request, EmptyMessageParameters.getInstance()), mockGateway) .get(); }
### Question: AbstractMetricsHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, MetricCollectionResponseBody, M> { @Override protected final CompletableFuture<MetricCollectionResponseBody> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody, M> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { metricFetcher.update(); final MetricStore.ComponentMetricStore componentMetricStore = getComponentMetricStore( request, metricFetcher.getMetricStore()); if (componentMetricStore == null || componentMetricStore.metrics == null) { return CompletableFuture.completedFuture( new MetricCollectionResponseBody(Collections.emptyList())); } final Set<String> requestedMetrics = new HashSet<>(request.getQueryParameter( MetricsFilterParameter.class)); if (requestedMetrics.isEmpty()) { return CompletableFuture.completedFuture( new MetricCollectionResponseBody(getAvailableMetrics(componentMetricStore))); } else { final List<Metric> metrics = getRequestedMetrics(componentMetricStore, requestedMetrics); return CompletableFuture.completedFuture(new MetricCollectionResponseBody(metrics)); } } AbstractMetricsHandler( CompletableFuture<String> localRestAddress, GatewayRetriever<? extends RestfulGateway> leaderRetriever, Time timeout, Map<String, String> headers, MessageHeaders<EmptyRequestBody, MetricCollectionResponseBody, M> messageHeaders, MetricFetcher metricFetcher); }### Answer: @Test public void testListMetrics() throws Exception { final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.emptyMap()), mockDispatcherGateway); assertTrue(completableFuture.isDone()); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); assertThat(metricCollectionResponseBody.getMetrics(), hasSize(1)); final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next(); assertThat(metric.getId(), equalTo(TEST_METRIC_NAME)); assertThat(metric.getValue(), equalTo(null)); } @Test public void testReturnEmptyListIfNoComponentMetricStore() throws Exception { testMetricsHandler.returnComponentMetricStore = false; final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.emptyMap()), mockDispatcherGateway); assertTrue(completableFuture.isDone()); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); assertThat(metricCollectionResponseBody.getMetrics(), empty()); } @Test public void testGetMetrics() throws Exception { final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap(METRICS_FILTER_QUERY_PARAM, Collections.singletonList(TEST_METRIC_NAME))), mockDispatcherGateway); assertTrue(completableFuture.isDone()); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); assertThat(metricCollectionResponseBody.getMetrics(), hasSize(1)); final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next(); assertThat(metric.getId(), equalTo(TEST_METRIC_NAME)); assertThat(metric.getValue(), equalTo(Integer.toString(TEST_METRIC_VALUE))); } @Test public void testReturnEmptyListIfRequestedMetricIsUnknown() throws Exception { final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap(METRICS_FILTER_QUERY_PARAM, Collections.singletonList("unknown_metric"))), mockDispatcherGateway); assertTrue(completableFuture.isDone()); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); assertThat(metricCollectionResponseBody.getMetrics(), empty()); }
### Question: SubtaskExecutionAttemptAccumulatorsHandler extends AbstractSubtaskAttemptHandler<SubtaskExecutionAttemptAccumulatorsInfo, SubtaskAttemptMessageParameters> implements JsonArchivist { @Override protected SubtaskExecutionAttemptAccumulatorsInfo handleRequest( HandlerRequest<EmptyRequestBody, SubtaskAttemptMessageParameters> request, AccessExecution execution) throws RestHandlerException { return createAccumulatorInfo(execution); } SubtaskExecutionAttemptAccumulatorsHandler( CompletableFuture<String> localRestAddress, GatewayRetriever<? extends RestfulGateway> leaderRetriever, Time timeout, Map<String, String> responseHeaders, MessageHeaders<EmptyRequestBody, SubtaskExecutionAttemptAccumulatorsInfo, SubtaskAttemptMessageParameters> messageHeaders, ExecutionGraphCache executionGraphCache, Executor executor); @Override Collection<ArchivedJson> archiveJsonWithPath(AccessExecutionGraph graph); }### Answer: @Test public void testHandleRequest() throws Exception { final RestHandlerConfiguration restHandlerConfiguration = RestHandlerConfiguration.fromConfiguration(new Configuration()); final SubtaskExecutionAttemptAccumulatorsHandler handler = new SubtaskExecutionAttemptAccumulatorsHandler( CompletableFuture.completedFuture("127.0.0.1:9527"), () -> null, Time.milliseconds(100L), Collections.emptyMap(), SubtaskExecutionAttemptAccumulatorsHeaders.getInstance(), new ExecutionGraphCache( restHandlerConfiguration.getTimeout(), Time.milliseconds(restHandlerConfiguration.getRefreshInterval())), TestingUtils.defaultExecutor()); final HandlerRequest<EmptyRequestBody, SubtaskAttemptMessageParameters> request = new HandlerRequest<>( EmptyRequestBody.getInstance(), new SubtaskAttemptMessageParameters() ); final Map<String, OptionalFailure<Accumulator<?, ?>>> userAccumulators = new HashMap<>(3); userAccumulators.put("IntCounter", OptionalFailure.of(new IntCounter(10))); userAccumulators.put("LongCounter", OptionalFailure.of(new LongCounter(100L))); userAccumulators.put("Failure", OptionalFailure.ofFailure(new FlinkRuntimeException("Test"))); final StringifiedAccumulatorResult[] accumulatorResults = StringifiedAccumulatorResult.stringifyAccumulatorResults(userAccumulators); final int attemptNum = 1; final int subtaskIndex = 2; final ArchivedExecution execution = new ArchivedExecution( accumulatorResults, null, new ExecutionAttemptID(), attemptNum, ExecutionState.FINISHED, null, null, subtaskIndex, new long[ExecutionState.values().length]); final SubtaskExecutionAttemptAccumulatorsInfo accumulatorsInfo = handler.handleRequest(request, execution); final ArrayList<UserAccumulator> userAccumulatorList = new ArrayList<>(userAccumulators.size()); for (StringifiedAccumulatorResult accumulatorResult : accumulatorResults) { userAccumulatorList.add( new UserAccumulator( accumulatorResult.getName(), accumulatorResult.getType(), accumulatorResult.getValue())); } final SubtaskExecutionAttemptAccumulatorsInfo expected = new SubtaskExecutionAttemptAccumulatorsInfo( subtaskIndex, attemptNum, execution.getAttemptId().toString(), userAccumulatorList); assertEquals(expected, accumulatorsInfo); }
### Question: ExceptionUtils { public static <T extends Throwable> Optional<T> findThrowable(Throwable throwable, Class<T> searchType) { if (throwable == null || searchType == null) { return Optional.empty(); } Throwable t = throwable; while (t != null) { if (searchType.isAssignableFrom(t.getClass())) { return Optional.of(searchType.cast(t)); } else { t = t.getCause(); } } return Optional.empty(); } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer: @Test public void testFindThrowableByType() { assertTrue(ExceptionUtils.findThrowable( new RuntimeException(new IllegalStateException()), IllegalStateException.class).isPresent()); }
### Question: JobVertexBackPressureHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, JobVertexBackPressureInfo, JobVertexMessageParameters> { @Override protected CompletableFuture<JobVertexBackPressureInfo> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { final JobID jobId = request.getPathParameter(JobIDPathParameter.class); final JobVertexID jobVertexId = request.getPathParameter(JobVertexIdPathParameter.class); return gateway .requestOperatorBackPressureStats(jobId, jobVertexId) .thenApply( operatorBackPressureStats -> operatorBackPressureStats.getOperatorBackPressureStats().map( JobVertexBackPressureHandler::createJobVertexBackPressureInfo).orElse( JobVertexBackPressureInfo.deprecated())); } JobVertexBackPressureHandler( CompletableFuture<String> localRestAddress, GatewayRetriever<? extends RestfulGateway> leaderRetriever, Time timeout, Map<String, String> responseHeaders, MessageHeaders<EmptyRequestBody, JobVertexBackPressureInfo, JobVertexMessageParameters> messageHeaders); }### Answer: @Test public void testAbsentBackPressure() throws Exception { final Map<String, String> pathParameters = new HashMap<>(); pathParameters.put(JobIDPathParameter.KEY, TEST_JOB_ID_BACK_PRESSURE_STATS_ABSENT.toString()); pathParameters.put(JobVertexIdPathParameter.KEY, new JobVertexID().toString()); final HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request = new HandlerRequest<>( EmptyRequestBody.getInstance(), new JobVertexMessageParameters(), pathParameters, Collections.emptyMap()); final CompletableFuture<JobVertexBackPressureInfo> jobVertexBackPressureInfoCompletableFuture = jobVertexBackPressureHandler.handleRequest(request, restfulGateway); final JobVertexBackPressureInfo jobVertexBackPressureInfo = jobVertexBackPressureInfoCompletableFuture.get(); assertThat(jobVertexBackPressureInfo.getStatus(), equalTo(VertexBackPressureStatus.DEPRECATED)); }
### Question: RestServerEndpoint implements AutoCloseableAsync { @VisibleForTesting static void createUploadDir(final Path uploadDir, final Logger log) throws IOException { if (!Files.exists(uploadDir)) { log.warn("Upload directory {} does not exist, or has been deleted externally. " + "Previously uploaded files are no longer available.", uploadDir); checkAndCreateUploadDir(uploadDir, log); } } RestServerEndpoint(RestServerEndpointConfiguration configuration); final void start(); @Nullable InetSocketAddress getServerAddress(); String getRestBaseUrl(); @Override CompletableFuture<Void> closeAsync(); }### Answer: @Test public void testCreateUploadDir() throws Exception { final File file = temporaryFolder.newFolder(); final Path testUploadDir = file.toPath().resolve("testUploadDir"); assertFalse(Files.exists(testUploadDir)); RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER); assertTrue(Files.exists(testUploadDir)); } @Test public void testCreateUploadDirFails() throws Exception { final File file = temporaryFolder.newFolder(); Assume.assumeTrue(file.setWritable(false)); final Path testUploadDir = file.toPath().resolve("testUploadDir"); assertFalse(Files.exists(testUploadDir)); try { RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER); fail("Expected exception not thrown."); } catch (IOException e) { } }
### Question: RestClient { public <M extends MessageHeaders<R, P, U>, U extends MessageParameters, R extends RequestBody, P extends ResponseBody> CompletableFuture<P> sendRequest(String targetAddress, int targetPort, M messageHeaders, U messageParameters, R request) throws IOException { Preconditions.checkNotNull(targetAddress); Preconditions.checkArgument(0 <= targetPort && targetPort < 65536, "The target port " + targetPort + " is not in the range (0, 65536]."); Preconditions.checkNotNull(messageHeaders); Preconditions.checkNotNull(request); Preconditions.checkNotNull(messageParameters); Preconditions.checkState(messageParameters.isResolved(), "Message parameters were not resolved."); String targetUrl = MessageParameters.resolveUrl(messageHeaders.getTargetRestEndpointURL(), messageParameters); LOG.debug("Sending request of class {} to {}:{}{}", request.getClass(), targetAddress, targetPort, targetUrl); StringWriter sw = new StringWriter(); objectMapper.writeValue(sw, request); ByteBuf payload = Unpooled.wrappedBuffer(sw.toString().getBytes(ConfigConstants.DEFAULT_CHARSET)); FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, messageHeaders.getHttpMethod().getNettyHttpMethod(), targetUrl, payload); httpRequest.headers() .add(HttpHeaders.Names.CONTENT_LENGTH, payload.capacity()) .add(HttpHeaders.Names.CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE) .set(HttpHeaders.Names.HOST, targetAddress + ':' + targetPort) .set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); final JavaType responseType; final Collection<Class<?>> typeParameters = messageHeaders.getResponseTypeParameters(); if (typeParameters.isEmpty()) { responseType = objectMapper.constructType(messageHeaders.getResponseClass()); } else { responseType = objectMapper.getTypeFactory().constructParametricType( messageHeaders.getResponseClass(), typeParameters.toArray(new Class<?>[typeParameters.size()])); } return submitRequest(targetAddress, targetPort, httpRequest, responseType); } RestClient(RestClientConfiguration configuration, Executor executor); void shutdown(Time timeout); CompletableFuture<P> sendRequest(String targetAddress, int targetPort, M messageHeaders, U messageParameters, R request); }### Answer: @Test public void testConnectionTimeout() throws Exception { final Configuration config = new Configuration(); config.setLong(RestOptions.CONNECTION_TIMEOUT, 1); final RestClient restClient = new RestClient(RestClientConfiguration.fromConfiguration(config), Executors.directExecutor()); final String unroutableIp = "10.255.255.1"; try { restClient.sendRequest( unroutableIp, 80, new TestMessageHeaders(), EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance()) .get(60, TimeUnit.SECONDS); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripExecutionException(e); assertThat(throwable, instanceOf(ConnectTimeoutException.class)); assertThat(throwable.getMessage(), containsString(unroutableIp)); } }
### Question: MetricRegistryImpl implements MetricRegistry { public boolean isShutdown() { synchronized (lock) { return isShutdown; } } MetricRegistryImpl(MetricRegistryConfiguration config); void startQueryService(ActorSystem actorSystem, ResourceID resourceID); @Override @Nullable String getMetricQueryServicePath(); @Override char getDelimiter(); @Override char getDelimiter(int reporterIndex); @Override int getNumberReporters(); @VisibleForTesting List<MetricReporter> getReporters(); boolean isShutdown(); CompletableFuture<Void> shutdown(); @Override ScopeFormats getScopeFormats(); @Override void register(Metric metric, String metricName, AbstractMetricGroup group); @Override void unregister(Metric metric, String metricName, AbstractMetricGroup group); @VisibleForTesting @Nullable ActorRef getQueryService(); }### Answer: @Test public void testIsShutdown() throws Exception { MetricRegistryImpl metricRegistry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration()); Assert.assertFalse(metricRegistry.isShutdown()); metricRegistry.shutdown().get(); Assert.assertTrue(metricRegistry.isShutdown()); }
### Question: TaskIOMetricGroup extends ProxyMetricGroup<TaskMetricGroup> { public TaskIOMetricGroup(TaskMetricGroup parent) { super(parent); this.numBytesOut = counter(MetricNames.IO_NUM_BYTES_OUT); this.numBytesInLocal = counter(MetricNames.IO_NUM_BYTES_IN_LOCAL); this.numBytesInRemote = counter(MetricNames.IO_NUM_BYTES_IN_REMOTE); this.numBytesOutRate = meter(MetricNames.IO_NUM_BYTES_OUT_RATE, new MeterView(numBytesOut, 60)); this.numBytesInRateLocal = meter(MetricNames.IO_NUM_BYTES_IN_LOCAL_RATE, new MeterView(numBytesInLocal, 60)); this.numBytesInRateRemote = meter(MetricNames.IO_NUM_BYTES_IN_REMOTE_RATE, new MeterView(numBytesInRemote, 60)); this.numRecordsIn = counter(MetricNames.IO_NUM_RECORDS_IN, new SumCounter()); this.numRecordsOut = counter(MetricNames.IO_NUM_RECORDS_OUT, new SumCounter()); this.numRecordsInRate = meter(MetricNames.IO_NUM_RECORDS_IN_RATE, new MeterView(numRecordsIn, 60)); this.numRecordsOutRate = meter(MetricNames.IO_NUM_RECORDS_OUT_RATE, new MeterView(numRecordsOut, 60)); } TaskIOMetricGroup(TaskMetricGroup parent); IOMetrics createSnapshot(); Counter getNumBytesOutCounter(); Counter getNumBytesInLocalCounter(); Counter getNumBytesInRemoteCounter(); Counter getNumRecordsInCounter(); Counter getNumRecordsOutCounter(); Meter getNumBytesInLocalRateMeter(); Meter getNumBytesInRemoteRateMeter(); Meter getNumBytesOutRateMeter(); void initializeBufferMetrics(Task task); void reuseRecordsInputCounter(Counter numRecordsInCounter); void reuseRecordsOutputCounter(Counter numRecordsOutCounter); }### Answer: @Test public void testTaskIOMetricGroup() { TaskMetricGroup task = UnregisteredMetricGroups.createUnregisteredTaskMetricGroup(); TaskIOMetricGroup taskIO = task.getIOMetricGroup(); assertNotNull(taskIO.getNumRecordsInCounter()); assertNotNull(taskIO.getNumRecordsOutCounter()); Counter c1 = new SimpleCounter(); c1.inc(32L); Counter c2 = new SimpleCounter(); c2.inc(64L); taskIO.reuseRecordsInputCounter(c1); taskIO.reuseRecordsOutputCounter(c2); assertEquals(32L, taskIO.getNumRecordsInCounter().getCount()); assertEquals(64L, taskIO.getNumRecordsOutCounter().getCount()); taskIO.getNumBytesInLocalCounter().inc(100L); taskIO.getNumBytesInRemoteCounter().inc(150L); taskIO.getNumBytesOutCounter().inc(250L); IOMetrics io = taskIO.createSnapshot(); assertEquals(32L, io.getNumRecordsIn()); assertEquals(64L, io.getNumRecordsOut()); assertEquals(100L, io.getNumBytesInLocal()); assertEquals(150L, io.getNumBytesInRemote()); assertEquals(250L, io.getNumBytesOut()); }
### Question: AbstractMetricGroup implements MetricGroup { public Map<String, String> getAllVariables() { if (variables == null) { synchronized (this) { if (variables == null) { variables = new HashMap<>(); putVariables(variables); if (parent != null) { variables.putAll(parent.getAllVariables()); } } } } return variables; } AbstractMetricGroup(MetricRegistry registry, String[] scope, A parent); Map<String, String> getAllVariables(); String getLogicalScope(CharacterFilter filter); String getLogicalScope(CharacterFilter filter, char delimiter); String[] getScopeComponents(); QueryScopeInfo getQueryServiceMetricInfo(CharacterFilter filter); String getMetricIdentifier(String metricName); String getMetricIdentifier(String metricName, CharacterFilter filter); String getMetricIdentifier(String metricName, CharacterFilter filter, int reporterIndex); void close(); final boolean isClosed(); @Override Counter counter(int name); @Override Counter counter(String name); @Override C counter(int name, C counter); @Override C counter(String name, C counter); @Override G gauge(int name, G gauge); @Override G gauge(String name, G gauge); @Override H histogram(int name, H histogram); @Override H histogram(String name, H histogram); @Override M meter(int name, M meter); @Override M meter(String name, M meter); @Override MetricGroup addGroup(int name); @Override MetricGroup addGroup(String name); @Override MetricGroup addGroup(String key, String value); }### Answer: @Test public void testGetAllVariables() throws Exception { MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration()); AbstractMetricGroup group = new AbstractMetricGroup<AbstractMetricGroup<?>>(registry, new String[0], null) { @Override protected QueryScopeInfo createQueryServiceMetricInfo(CharacterFilter filter) { return null; } @Override protected String getGroupName(CharacterFilter filter) { return ""; } }; assertTrue(group.getAllVariables().isEmpty()); registry.shutdown().get(); }
### Question: AbstractMetricGroup implements MetricGroup { public String getMetricIdentifier(String metricName) { return getMetricIdentifier(metricName, null); } AbstractMetricGroup(MetricRegistry registry, String[] scope, A parent); Map<String, String> getAllVariables(); String getLogicalScope(CharacterFilter filter); String getLogicalScope(CharacterFilter filter, char delimiter); String[] getScopeComponents(); QueryScopeInfo getQueryServiceMetricInfo(CharacterFilter filter); String getMetricIdentifier(String metricName); String getMetricIdentifier(String metricName, CharacterFilter filter); String getMetricIdentifier(String metricName, CharacterFilter filter, int reporterIndex); void close(); final boolean isClosed(); @Override Counter counter(int name); @Override Counter counter(String name); @Override C counter(int name, C counter); @Override C counter(String name, C counter); @Override G gauge(int name, G gauge); @Override G gauge(String name, G gauge); @Override H histogram(int name, H histogram); @Override H histogram(String name, H histogram); @Override M meter(int name, M meter); @Override M meter(String name, M meter); @Override MetricGroup addGroup(int name); @Override MetricGroup addGroup(String name); @Override MetricGroup addGroup(String key, String value); }### Answer: @Test public void testScopeGenerationWithoutReporters() throws Exception { Configuration config = new Configuration(); config.setString(MetricOptions.SCOPE_NAMING_TM, "A.B.C.D"); MetricRegistryImpl testRegistry = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(config)); try { TaskManagerMetricGroup group = new TaskManagerMetricGroup(testRegistry, "host", "id"); assertEquals("MetricReporters list should be empty", 0, testRegistry.getReporters().size()); assertEquals("A.B.X.D.1", group.getMetricIdentifier("1", FILTER_C)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, -1)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, 2)); } finally { testRegistry.shutdown().get(); } } @Test public void testScopeGenerationWithoutReporters() throws Exception { Configuration config = new Configuration(); config.setString(MetricOptions.SCOPE_NAMING_TM, "A.B.C.D"); MetricRegistryImpl testRegistry = new MetricRegistryImpl( MetricRegistryConfiguration.fromConfiguration(config)); try { TaskManagerMetricGroup group = new TaskManagerMetricGroup(testRegistry, "host", "id"); assertEquals("MetricReporters list should be empty", 0, testRegistry.getReporters().size()); assertEquals("A.B.X.D.1", group.getMetricIdentifier("1", FILTER_C)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, -1)); assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, 2)); } finally { testRegistry.shutdown().get(); } }
### Question: TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { @Override protected QueryScopeInfo.TaskQueryScopeInfo createQueryServiceMetricInfo(CharacterFilter filter) { return new QueryScopeInfo.TaskQueryScopeInfo( this.parent.jobId.toString(), String.valueOf(this.vertexId), this.subtaskIndex); } TaskMetricGroup( MetricRegistry registry, TaskManagerJobMetricGroup parent, @Nullable JobVertexID vertexId, AbstractID executionId, @Nullable String taskName, int subtaskIndex, int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer: @Test public void testCreateQueryServiceMetricInfo() { JobID jid = new JobID(); JobVertexID vid = new JobVertexID(); AbstractID eid = new AbstractID(); TaskManagerMetricGroup tm = new TaskManagerMetricGroup(registry, "host", "id"); TaskManagerJobMetricGroup job = new TaskManagerJobMetricGroup(registry, tm, jid, "jobname"); TaskMetricGroup task = new TaskMetricGroup(registry, job, vid, eid, "taskName", 4, 5); QueryScopeInfo.TaskQueryScopeInfo info = task.createQueryServiceMetricInfo(new DummyCharacterFilter()); assertEquals("", info.scope); assertEquals(jid.toString(), info.jobID); assertEquals(vid.toString(), info.vertexID); assertEquals(4, info.subtaskIndex); }
### Question: TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { @Override public void close() { super.close(); parent.removeTaskMetricGroup(executionId); } TaskMetricGroup( MetricRegistry registry, TaskManagerJobMetricGroup parent, @Nullable JobVertexID vertexId, AbstractID executionId, @Nullable String taskName, int subtaskIndex, int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer: @Test public void testTaskMetricGroupCleanup() throws Exception { CountingMetricRegistry registry = new CountingMetricRegistry(new Configuration()); TaskManagerMetricGroup taskManagerMetricGroup = new TaskManagerMetricGroup(registry, "localhost", "0"); TaskManagerJobMetricGroup taskManagerJobMetricGroup = new TaskManagerJobMetricGroup(registry, taskManagerMetricGroup, new JobID(), "job"); TaskMetricGroup taskMetricGroup = new TaskMetricGroup(registry, taskManagerJobMetricGroup, new JobVertexID(), new AbstractID(), "task", 0, 0); assertTrue(registry.getNumberRegisteredMetrics() > 0); taskMetricGroup.close(); assertEquals(0, registry.getNumberRegisteredMetrics()); registry.shutdown().get(); }
### Question: TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { public OperatorMetricGroup addOperator(String name) { return addOperator(OperatorID.fromJobVertexID(vertexId), name); } TaskMetricGroup( MetricRegistry registry, TaskManagerJobMetricGroup parent, @Nullable JobVertexID vertexId, AbstractID executionId, @Nullable String taskName, int subtaskIndex, int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer: @Test public void testOperatorNameTruncation() throws Exception { Configuration cfg = new Configuration(); cfg.setString(MetricOptions.SCOPE_NAMING_OPERATOR, ScopeFormat.SCOPE_OPERATOR_NAME); MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(cfg)); TaskManagerMetricGroup tm = new TaskManagerMetricGroup(registry, "host", "id"); TaskManagerJobMetricGroup job = new TaskManagerJobMetricGroup(registry, tm, new JobID(), "jobname"); TaskMetricGroup taskMetricGroup = new TaskMetricGroup(registry, job, new JobVertexID(), new AbstractID(), "task", 0, 0); String originalName = new String(new char[100]).replace("\0", "-"); OperatorMetricGroup operatorMetricGroup = taskMetricGroup.addOperator(originalName); String storedName = operatorMetricGroup.getScopeComponents()[0]; Assert.assertEquals(TaskMetricGroup.METRICS_OPERATOR_NAME_MAX_LENGTH, storedName.length()); Assert.assertEquals(originalName.substring(0, TaskMetricGroup.METRICS_OPERATOR_NAME_MAX_LENGTH), storedName); registry.shutdown().get(); }
### Question: TaskEventDispatcher { public void registerPartition(ResultPartitionID partitionId) { checkNotNull(partitionId); synchronized (registeredHandlers) { LOG.debug("registering {}", partitionId); if (registeredHandlers.put(partitionId, new TaskEventHandler()) != null) { throw new IllegalStateException( "Partition " + partitionId + " already registered at task event dispatcher."); } } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer: @Test public void registerPartitionTwice() throws Exception { ResultPartitionID partitionId = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); ted.registerPartition(partitionId); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("already registered at task event dispatcher"); ted.registerPartition(partitionId); }
### Question: TaskEventDispatcher { public void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType) { checkNotNull(partitionId); checkNotNull(eventListener); checkNotNull(eventType); TaskEventHandler taskEventHandler; synchronized (registeredHandlers) { taskEventHandler = registeredHandlers.get(partitionId); } if (taskEventHandler == null) { throw new IllegalStateException( "Partition " + partitionId + " not registered at task event dispatcher."); } taskEventHandler.subscribe(eventListener, eventType); } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer: @Test public void subscribeToEventNotRegistered() throws Exception { TaskEventDispatcher ted = new TaskEventDispatcher(); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("not registered at task event dispatcher"); ted.subscribeToEvent(new ResultPartitionID(), new ZeroShotEventListener(), TaskEvent.class); }
### Question: TaskEventDispatcher { public void unregisterPartition(ResultPartitionID partitionId) { checkNotNull(partitionId); synchronized (registeredHandlers) { LOG.debug("unregistering {}", partitionId); registeredHandlers.remove(partitionId); } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer: @Test public void unregisterPartition() throws Exception { ResultPartitionID partitionId1 = new ResultPartitionID(); ResultPartitionID partitionId2 = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); AllWorkersDoneEvent event = new AllWorkersDoneEvent(); assertFalse(ted.publish(partitionId1, event)); ted.registerPartition(partitionId1); ted.registerPartition(partitionId2); OneShotEventListener eventListener1a = new OneShotEventListener(event); ZeroShotEventListener eventListener1b = new ZeroShotEventListener(); OneShotEventListener eventListener2 = new OneShotEventListener(event); ted.subscribeToEvent(partitionId1, eventListener1a, AllWorkersDoneEvent.class); ted.subscribeToEvent(partitionId2, eventListener1b, AllWorkersDoneEvent.class); ted.subscribeToEvent(partitionId1, eventListener2, AllWorkersDoneEvent.class); ted.unregisterPartition(partitionId2); assertTrue(ted.publish(partitionId1, event)); assertTrue("listener should have fired for AllWorkersDoneEvent", eventListener1a.fired); assertTrue("listener should have fired for AllWorkersDoneEvent", eventListener2.fired); assertFalse(ted.publish(partitionId2, event)); }
### Question: TaskEventDispatcher { public void clearAll() { synchronized (registeredHandlers) { registeredHandlers.clear(); } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer: @Test public void clearAll() throws Exception { ResultPartitionID partitionId = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); ted.registerPartition(partitionId); ZeroShotEventListener eventListener1 = new ZeroShotEventListener(); ted.subscribeToEvent(partitionId, eventListener1, AllWorkersDoneEvent.class); ted.clearAll(); assertFalse(ted.publish(partitionId, new AllWorkersDoneEvent())); }
### Question: CreditBasedPartitionRequestClientHandler extends ChannelInboundHandlerAdapter implements NetworkClientHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { decodeMsg(msg); } catch (Throwable t) { notifyAllChannelsOfErrorAndClose(t); } } @Override void addInputChannel(RemoteInputChannel listener); @Override void removeInputChannel(RemoteInputChannel listener); @Override void cancelRequestFor(InputChannelID inputChannelId); @Override void notifyCreditAvailable(final RemoteInputChannel inputChannel); @Override void channelActive(final ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void userEventTriggered(ChannelHandlerContext ctx, Object msg); @Override void channelWritabilityChanged(ChannelHandlerContext ctx); }### Answer: @Test public void testNotifyCreditAvailableAfterReleased() throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = new PartitionRequestClient( channel, handler, mock(ConnectionID.class), mock(PartitionRequestClientFactory.class)); final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32); final SingleInputGate inputGate = createSingleInputGate(); final RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, client); try { final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6); inputGate.setBufferPool(bufferPool); final int numExclusiveBuffers = 2; inputGate.assignExclusiveSegments(networkBufferPool, numExclusiveBuffers); inputChannel.requestSubpartition(0); Object readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound, instanceOf(PartitionRequest.class)); assertEquals(2, ((PartitionRequest) readFromOutbound).credit); final BufferResponse bufferResponse = createBufferResponse( TestBufferFactory.createBuffer(32), 0, inputChannel.getInputChannelId(), 1); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse); assertEquals(2, inputChannel.getUnannouncedCredit()); inputGate.releaseAllResources(); readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound, instanceOf(CloseRequest.class)); channel.runPendingTasks(); assertNull(channel.readOutbound()); } finally { inputGate.releaseAllResources(); networkBufferPool.destroyAllBufferPools(); networkBufferPool.destroy(); } } @Test public void testNotifyCreditAvailableAfterReleased() throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = new NettyPartitionRequestClient( channel, handler, mock(ConnectionID.class), mock(PartitionRequestClientFactory.class)); final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32, 2); final SingleInputGate inputGate = createSingleInputGate(1); final RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, client, networkBufferPool); try { final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6); inputGate.setBufferPool(bufferPool); inputGate.assignExclusiveSegments(); inputChannel.requestSubpartition(0); Object readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound, instanceOf(PartitionRequest.class)); assertEquals(2, ((PartitionRequest) readFromOutbound).credit); final BufferResponse bufferResponse = createBufferResponse( TestBufferFactory.createBuffer(32), 0, inputChannel.getInputChannelId(), 1); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse); assertEquals(2, inputChannel.getUnannouncedCredit()); inputGate.close(); readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound, instanceOf(CloseRequest.class)); channel.runPendingTasks(); assertNull(channel.readOutbound()); } finally { inputGate.close(); networkBufferPool.destroyAllBufferPools(); networkBufferPool.destroy(); } }
### Question: PipelinedSubpartition extends ResultSubpartition { @Override public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) throws IOException { synchronized (buffers) { checkState(!isReleased); checkState(readView == null, "Subpartition %s of is being (or already has been) consumed, " + "but pipelined subpartitions can only be consumed once.", index, parent.getPartitionId()); LOG.debug("Creating read view for subpartition {} of partition {}.", index, parent.getPartitionId()); readView = new PipelinedSubpartitionView(this, availabilityListener); if (!buffers.isEmpty()) { notifyDataAvailable(); } } return readView; } PipelinedSubpartition(int index, ResultPartition parent); @Override boolean add(BufferConsumer bufferConsumer); @Override void flush(); @Override void finish(); @Override void release(); @Override int releaseMemory(); @Override boolean isReleased(); @Override PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener); boolean isAvailable(); @Override String toString(); @Override int unsynchronizedGetNumberOfQueuedBuffers(); }### Answer: @Test public void testIllegalReadViewRequest() throws Exception { final PipelinedSubpartition subpartition = createSubpartition(); assertNotNull(subpartition.createReadView(new NoOpBufferAvailablityListener())); try { subpartition.createReadView(new NoOpBufferAvailablityListener()); fail("Did not throw expected exception after duplicate notifyNonEmpty view request."); } catch (IllegalStateException expected) { } }
### Question: PipelinedSubpartition extends ResultSubpartition { @Override public boolean isReleased() { return isReleased; } PipelinedSubpartition(int index, ResultPartition parent); @Override boolean add(BufferConsumer bufferConsumer); @Override void flush(); @Override void finish(); @Override void release(); @Override int releaseMemory(); @Override boolean isReleased(); @Override PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener); boolean isAvailable(); @Override String toString(); @Override int unsynchronizedGetNumberOfQueuedBuffers(); }### Answer: @Test public void testIsReleasedChecksParent() throws Exception { PipelinedSubpartition subpartition = mock(PipelinedSubpartition.class); PipelinedSubpartitionView reader = new PipelinedSubpartitionView( subpartition, mock(BufferAvailabilityListener.class)); assertFalse(reader.isReleased()); verify(subpartition, times(1)).isReleased(); when(subpartition.isReleased()).thenReturn(true); assertTrue(reader.isReleased()); verify(subpartition, times(2)).isReleased(); }
### Question: RemoteInputChannel extends InputChannel implements BufferRecycler, BufferListener { void retriggerSubpartitionRequest(int subpartitionIndex) throws IOException, InterruptedException { checkState(partitionRequestClient != null, "Missing initial subpartition request."); if (increaseBackoff()) { partitionRequestClient.requestSubpartition( partitionId, subpartitionIndex, this, getCurrentBackoff()); } else { failPartitionRequest(); } } RemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ConnectionID connectionId, ConnectionManager connectionManager, TaskIOMetricGroup metrics); RemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ConnectionID connectionId, ConnectionManager connectionManager, int initialBackOff, int maxBackoff, TaskIOMetricGroup metrics); @VisibleForTesting @Override void requestSubpartition(int subpartitionIndex); @Override boolean isReleased(); @Override String toString(); @Override void recycle(MemorySegment segment); int getNumberOfAvailableBuffers(); int getNumberOfRequiredBuffers(); int getSenderBacklog(); @Override boolean notifyBufferAvailable(Buffer buffer); @Override void notifyBufferDestroyed(); int getUnannouncedCredit(); int getAndResetUnannouncedCredit(); int getNumberOfQueuedBuffers(); int unsynchronizedGetNumberOfQueuedBuffers(); InputChannelID getInputChannelId(); int getInitialCredit(); BufferProvider getBufferProvider(); @Nullable Buffer requestBuffer(); void onBuffer(Buffer buffer, int sequenceNumber, int backlog); void onEmptyBuffer(int sequenceNumber, int backlog); void onFailedPartitionRequest(); void onError(Throwable cause); }### Answer: @Test(expected = IllegalStateException.class) public void testRetriggerWithoutPartitionRequest() throws Exception { Tuple2<Integer, Integer> backoff = new Tuple2<Integer, Integer>(500, 3000); PartitionRequestClient connClient = mock(PartitionRequestClient.class); SingleInputGate inputGate = mock(SingleInputGate.class); RemoteInputChannel ch = createRemoteInputChannel(inputGate, connClient, backoff); ch.retriggerSubpartitionRequest(0); }