method2testcases
stringlengths
118
6.63k
### Question: WatcherService { public void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime) { Packet packet = Packet.of(switchId, portNo, packetNo); confirmations.remove(packet); carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer: @Test public void discovery() { WatcherService w = new WatcherService(carrier, 10); w.addWatch(new SwitchId(1), 1, 1); w.addWatch(new SwitchId(1), 2, 1); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 2, 3); assertThat(w.getConfirmations().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(SwitchId.class), anyInt(), anyLong(), anyLong()); w.confirmation(new SwitchId(1), 1, 0); w.confirmation(new SwitchId(2), 1, 2); assertThat(w.getConfirmations().size(), is(2)); w.discovery(new SwitchId(1), 1, new SwitchId(2), 1, 0, 4); w.discovery(new SwitchId(2), 1, new SwitchId(1), 1, 2, 4); w.tick(100); assertThat(w.getConfirmations().size(), is(0)); verify(carrier).discovered(eq(new SwitchId(1)), eq(1), eq(new SwitchId(2)), eq(1), anyLong()); verify(carrier).discovered(eq(new SwitchId(2)), eq(1), eq(new SwitchId(1)), eq(1), anyLong()); verify(carrier, times(2)).discovered(any(SwitchId.class), anyInt(), any(SwitchId.class), anyInt(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
### Question: DecisionMakerService { void discovered(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long currentTime) { carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); lastDiscovery.put(Endpoint.of(switchId, portNo), currentTime); } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }### Answer: @Test public void discovered() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 1L); w.discovered(new SwitchId(2), 20, new SwitchId(3), 30, 2L); verify(carrier).discovered(eq(new SwitchId(1)), eq(10), eq(new SwitchId(2)), eq(20), anyLong()); verify(carrier).discovered(eq(new SwitchId(2)), eq(20), eq(new SwitchId(3)), eq(30), anyLong()); }
### Question: DecisionMakerService { void failed(SwitchId switchId, int portNo, long currentTime) { Endpoint endpoint = Endpoint.of(switchId, portNo); if (!lastDiscovery.containsKey(endpoint)) { lastDiscovery.put(endpoint, currentTime - awaitTime); } long timeWindow = lastDiscovery.get(endpoint) + failTimeout; if (currentTime >= timeWindow) { carrier.failed(switchId, portNo, currentTime); } } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }### Answer: @Test public void failed() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.failed(new SwitchId(1), 10, 0); w.failed(new SwitchId(1), 10, 1); w.failed(new SwitchId(1), 10, 11); w.failed(new SwitchId(1), 10, 12); verify(carrier, times(2)).failed(eq(new SwitchId(1)), eq(10), anyLong()); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); verify(carrier).discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); reset(carrier); w.failed(new SwitchId(1), 10, 21); w.failed(new SwitchId(1), 10, 23); w.failed(new SwitchId(1), 10, 24); verify(carrier, never()).failed(any(SwitchId.class), anyInt(), anyInt()); w.failed(new SwitchId(1), 10, 31); verify(carrier).failed(new SwitchId(1), 10, 31); }
### Question: SessionService implements IService, IInputTranslator { public Session open(IOFSwitch sw) { return open(new MessageContext(), sw); } Session open(IOFSwitch sw); Session open(MessageContext context, IOFSwitch sw); @Override void setup(FloodlightModuleContext moduleContext); @Override Command makeCommand(CommandContext context, OfInput input); }### Answer: @Test public void positive() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteAlwaysSuccess(sw); doneWithSetUp(sw); CompletableFuture<Optional<OFMessage>> future; OFPacketOut pktOut = makePacketOut(sw.getOFFactory(), 1); try (Session session = subject.open(context, sw)) { future = session.write(pktOut); } Assert.assertFalse(future.isDone()); List<OFMessage> swActualWrite = swWriteMessages.getValues(); Assert.assertEquals(2, swActualWrite.size()); Assert.assertEquals(pktOut, swActualWrite.get(0)); Assert.assertEquals(OFType.BARRIER_REQUEST, swActualWrite.get(1).getType()); completeSessions(sw); Assert.assertTrue(future.isDone()); Optional<OFMessage> response = future.get(); Assert.assertFalse(response.isPresent()); } @Test public void switchWriteError() throws Throwable { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteSecondFail(sw); doneWithSetUp(sw); OFFactory ofFactory = sw.getOFFactory(); CompletableFuture<Optional<OFMessage>> future = null; try (Session session = subject.open(context, sw)) { session.write(makePacketOut(ofFactory, 1)); future = session.write(makePacketOut(ofFactory, 2)); } try { future.get(1, TimeUnit.SECONDS); Assert.fail(); } catch (ExecutionException e) { Assert.assertNotNull(e.getCause()); Assert.assertTrue(e.getCause() instanceof SwitchWriteException); } } @Test public void sessionBarrierWriteError() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteSecondFail(sw); doneWithSetUp(sw); CompletableFuture<Optional<OFMessage>> future = null; try (Session session = subject.open(context, sw)) { future = session.write(makePacketOut(sw.getOFFactory(), 1)); } try { future.get(1, TimeUnit.SECONDS); Assert.fail(); } catch (ExecutionException e) { Assert.assertNotNull(e.getCause()); Assert.assertTrue(e.getCause() instanceof SessionCloseException); } }
### Question: ConnectedDevicesService implements IService, IInputTranslator { @VisibleForTesting ArpPacketData deserializeArp(Ethernet eth, SwitchId switchId, long cookie) { try { List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(eth, vlans); if (payload instanceof ARP) { return new ArpPacketData((ARP) payload, vlans); } } catch (Exception exception) { logger.info("Could not deserialize ARP packet {} on switch {}. Cookie {}. Deserialization failure: {}", eth, switchId, Cookie.toString(cookie), exception.getMessage(), exception); return null; } logger.info("Got invalid ARP packet: {} on switch {}. Cookie {}", eth, switchId, cookie); return null; } @Override Command makeCommand(CommandContext context, OfInput input); @Override void setup(FloodlightModuleContext context); }### Answer: @Test public void deserializeArpTest() throws PacketParsingException { Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertTrue(data.getVlans().isEmpty()); assertEquals(buildArpPacket(arpPacket), data.getArp()); } @Test public void deserializeArpWithVlanTest() throws PacketParsingException { short vlan = 1234; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(1, data.getVlans().size()); assertEquals(Integer.valueOf(vlan), data.getVlans().get(0)); assertEquals(buildArpPacket(arpPacket), data.getArp()); } @Test public void deserializeArpWithTwoVlanTest() throws PacketParsingException { short innerVlan = 1234; short outerVlan = 2345; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(outerVlan), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(innerVlan), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(2, data.getVlans().size()); assertEquals(Integer.valueOf(outerVlan), data.getVlans().get(0)); assertEquals(Integer.valueOf(innerVlan), data.getVlans().get(1)); assertEquals(buildArpPacket(arpPacket), data.getArp()); } @Test public void deserializeArpWithQinQVlansTest() throws PacketParsingException { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.Q_IN_Q), shortToByteArray(vlan1), ethTypeToByteArray(EthType.BRIDGING), shortToByteArray(vlan2), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan3), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(3, data.getVlans().size()); assertEquals(Integer.valueOf(vlan1), data.getVlans().get(0)); assertEquals(Integer.valueOf(vlan2), data.getVlans().get(1)); assertEquals(Integer.valueOf(vlan3), data.getVlans().get(2)); assertEquals(buildArpPacket(arpPacket), data.getArp()); }
### Question: FloodlightModuleConfigurationProvider extends ValidatingConfigurationProvider { public static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext, IFloodlightModule module) { Map<String, String> configData = moduleContext.getConfigParams(module); FloodlightModuleConfigurationProvider provider = new FloodlightModuleConfigurationProvider(configData); dumpConfigData(module.getClass(), configData); return provider; } protected FloodlightModuleConfigurationProvider(Map<String, String> configData); static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext, IFloodlightModule module); static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext, Class<? extends IFloodlightModule> module); }### Answer: @Test public void shouldCreateConfigFromContextParameters() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "bootstrap-servers", TEST_BOOTSTRAP_SERVERS); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); KafkaChannelConfig kafkaConfig = provider.getConfiguration(KafkaChannelConfig.class); assertEquals(TEST_BOOTSTRAP_SERVERS, kafkaConfig.getBootstrapServers()); } @Test public void shouldCreateEnvConfigFromContextParameters() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "environment-naming-prefix", TEST_PREFIX); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); EnvironmentFloodlightConfig environmentConfig = provider.getConfiguration(EnvironmentFloodlightConfig.class); assertEquals(TEST_PREFIX, environmentConfig.getNamingPrefix()); } @Test public void shouldCreateConfigWithEnvPrefix() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "environment-naming-prefix", TEST_PREFIX); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); KafkaChannelConfig kafkaConsumerConfig = provider.getConfiguration(KafkaChannelConfig.class); assertEquals(TEST_PREFIX + "_floodlight", kafkaConsumerConfig.getGroupId()); }
### Question: PingResponseCommand extends PingCommand { @Override public Command call() { log.debug("{} - {}", getClass().getCanonicalName(), input); byte[] payload = unwrap(); if (payload == null) { return null; } log.info("Receive flow ping packet from switch {} OF-xid:{}", input.getDpId(), input.getMessage().getXid()); try { PingData pingData = decode(payload); getContext().setCorrelationId(pingData.getPingId().toString()); process(pingData); } catch (CorruptedNetworkDataException e) { logPing.error(String.format("dpid:%s %s", input.getDpId(), e)); } return null; } PingResponseCommand(CommandContext context, OfInput input); @Override Command call(); }### Answer: @Test public void success() throws Exception { final PingService realPingService = new PingService(); moduleContext.addService(PingService.class, realPingService); final ISwitchManager realSwitchManager = new SwitchManager(); moduleContext.addService(ISwitchManager.class, realSwitchManager); InputService inputService = createMock(InputService.class); moduleContext.addService(InputService.class, inputService); inputService.addTranslator(eq(OFType.PACKET_IN), anyObject()); replayAll(); final DatapathId dpIdBeta = DatapathId.of(0x0000fffe000002L); final Ping ping = new Ping(new NetworkEndpoint(new SwitchId(dpIdBeta.getLong()), 8), new NetworkEndpoint(new SwitchId(dpId.getLong()), 9), new FlowTransitEncapsulation(2, FlowEncapsulationType.TRANSIT_VLAN), 3); final PingData payload = PingData.of(ping); moduleContext.addConfigParam(new PathVerificationService(), "hmac256-secret", "secret"); realPingService.setup(moduleContext); byte[] signedPayload = realPingService.getSignature().sign(payload); byte[] wireData = realPingService.wrapData(ping, signedPayload).serialize(); OFFactory ofFactory = new OFFactoryVer13(); OFPacketIn message = ofFactory.buildPacketIn() .setReason(OFPacketInReason.ACTION).setXid(1L) .setCookie(PingService.OF_CATCH_RULE_COOKIE) .setData(wireData) .build(); FloodlightContext metadata = new FloodlightContext(); IPacket decodedEthernet = new Ethernet().deserialize(wireData, 0, wireData.length); Assert.assertTrue(decodedEthernet instanceof Ethernet); IFloodlightProviderService.bcStore.put( metadata, IFloodlightProviderService.CONTEXT_PI_PAYLOAD, (Ethernet) decodedEthernet); OfInput input = new OfInput(iofSwitch, message, metadata); final PingResponseCommand command = makeCommand(input); command.call(); final List<Message> replies = kafkaMessageCatcher.getValues(); Assert.assertEquals(1, replies.size()); InfoMessage response = (InfoMessage) replies.get(0); PingResponse pingResponse = (PingResponse) response.getData(); Assert.assertNull(pingResponse.getError()); Assert.assertNotNull(pingResponse.getMeters()); Assert.assertEquals(payload.getPingId(), pingResponse.getPingId()); }
### Question: IngressFlowModFactory { public OFFlowMod makeOuterVlanMatchSharedMessage() { FlowEndpoint endpoint = command.getEndpoint(); FlowSharedSegmentCookie cookie = FlowSharedSegmentCookie.builder(SharedSegmentType.QINQ_OUTER_VLAN) .portNumber(endpoint.getPortNumber()) .vlanId(endpoint.getOuterVlanId()) .build(); return flowModBuilderFactory.makeBuilder(of, TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)) .setCookie(U64.of(cookie.getValue())) .setMatch(of.buildMatch() .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlan(endpoint.getOuterVlanId())) .build()) .setInstructions(makeOuterVlanMatchInstructions()) .build(); } IngressFlowModFactory( OfFlowModBuilderFactory flowModBuilderFactory, IngressFlowSegmentBase command, IOFSwitch sw, Set<SwitchFeature> features); OFFlowMod makeOuterOnlyVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeSingleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDoubleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDefaultPortForwardMessage(MeterId effectiveMeterId); OFFlowMod makeOuterVlanMatchSharedMessage(); OFFlowMod makeOuterOnlyVlanServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeDefaultPortServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeCustomerPortSharedCatchMessage(); OFFlowMod makeLldpInputCustomerFlowMessage(); OFFlowMod makeArpInputCustomerFlowMessage(); Optional<OFFlowMod> makeServer42InputFlowMessage(int server42UpdPortOffset); }### Answer: @Test public void makeOuterVlanMatchSharedMessage() { final IngressFlowModFactory factory = makeFactory(); final IngressFlowSegmentBase command = factory.getCommand(); final FlowEndpoint endpoint = command.getEndpoint(); RoutingMetadata metadata = RoutingMetadata.builder() .outerVlanId(endpoint.getOuterVlanId()) .build(Collections.emptySet()); OFFlowAdd expected = of.buildFlowAdd() .setTableId(getTargetPreIngressTableId()) .setPriority(FlowSegmentCommand.FLOW_PRIORITY) .setCookie(U64.of( FlowSharedSegmentCookie.builder(SharedSegmentType.QINQ_OUTER_VLAN) .portNumber(endpoint.getPortNumber()) .vlanId(endpoint.getOuterVlanId()) .build().getValue())) .setMatch(OfAdapter.INSTANCE.matchVlanId(of, of.buildMatch(), endpoint.getOuterVlanId()) .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .build()) .setInstructions(ImmutableList.of( of.instructions().applyActions(Collections.singletonList(of.actions().popVlan())), of.instructions().writeMetadata(metadata.getValue(), metadata.getMask()), of.instructions().gotoTable(TableId.of(SwitchManager.INGRESS_TABLE_ID)))) .build(); verifyOfMessageEquals(expected, factory.makeOuterVlanMatchSharedMessage()); }
### Question: IngressFlowModFactory { public OFFlowMod makeCustomerPortSharedCatchMessage() { FlowEndpoint endpoint = command.getEndpoint(); return flowModBuilderFactory.makeBuilder(of, TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE) .setCookie(U64.of(Cookie.encodeIngressRulePassThrough(endpoint.getPortNumber()))) .setMatch(of.buildMatch() .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .build()) .setInstructions(makeCustomerPortSharedCatchInstructions()) .build(); } IngressFlowModFactory( OfFlowModBuilderFactory flowModBuilderFactory, IngressFlowSegmentBase command, IOFSwitch sw, Set<SwitchFeature> features); OFFlowMod makeOuterOnlyVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeSingleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDoubleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDefaultPortForwardMessage(MeterId effectiveMeterId); OFFlowMod makeOuterVlanMatchSharedMessage(); OFFlowMod makeOuterOnlyVlanServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeDefaultPortServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeCustomerPortSharedCatchMessage(); OFFlowMod makeLldpInputCustomerFlowMessage(); OFFlowMod makeArpInputCustomerFlowMessage(); Optional<OFFlowMod> makeServer42InputFlowMessage(int server42UpdPortOffset); }### Answer: @Test public void makeCustomerPortSharedCatchInstallMessage() { IngressFlowModFactory factory = makeFactory(); FlowEndpoint endpoint = factory.getCommand().getEndpoint(); OFFlowMod expected = of.buildFlowAdd() .setTableId(TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE) .setCookie(U64.of(Cookie.encodeIngressRulePassThrough(endpoint.getPortNumber()))) .setMatch(of.buildMatch().setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())).build()) .setInstructions(Collections.singletonList(of.instructions().gotoTable( TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)))) .build(); verifyOfMessageEquals(expected, factory.makeCustomerPortSharedCatchMessage()); }
### Question: EthernetPacketToolbox { public static IPacket extractPayload(Ethernet packet, List<Integer> vlanStack) { short rootVlan = packet.getVlanID(); if (0 < rootVlan) { vlanStack.add((int) rootVlan); } IPacket payload = packet.getPayload(); while (payload instanceof VlanTag) { short vlanId = ((VlanTag) payload).getVlanId(); vlanStack.add((int) vlanId); payload = payload.getPayload(); } return payload; } private EthernetPacketToolbox(); static IPacket injectVlan(IPacket payload, int vlanId, EthType type); static IPacket extractPayload(Ethernet packet, List<Integer> vlanStack); }### Answer: @Test public void extractEthernetPayloadTest() { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; byte[] originPayload = new byte[]{0x55, (byte) 0xAA}; Ethernet ethernet = buildEthernet( new byte[]{ 0x01, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x01, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B }, ethTypeToByteArray(EthType.Q_IN_Q), shortToByteArray(vlan1), ethTypeToByteArray(EthType.BRIDGING), shortToByteArray(vlan2), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan3), ethTypeToByteArray(EthType.IPv4), originPayload); List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(ethernet, vlans); assertEquals(3, vlans.size()); assertEquals(Integer.valueOf(vlan1), vlans.get(0)); assertEquals(Integer.valueOf(vlan2), vlans.get(1)); assertEquals(Integer.valueOf(vlan3), vlans.get(2)); assertArrayEquals(originPayload, payload.serialize()); }
### Question: OfFlowPresenceVerifier { public List<OFFlowMod> getMissing() { return expectedOfFlows.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } OfFlowPresenceVerifier( IOfFlowDumpProducer dumpProducer, List<OFFlowMod> expectedFlows, Set<SwitchFeature> switchFeatures); List<OFFlowMod> getMissing(); }### Answer: @Test public void inaccurateSetFieldVlanVidActionNegative() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.emptySet()); Assert.assertFalse(presenceVerifier.getMissing().isEmpty()); } @Test public void inaccurateSetFieldVlanVidActionPositive() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.singleton( SwitchFeature.INACCURATE_SET_VLAN_VID_ACTION)); Assert.assertTrue(presenceVerifier.getMissing().isEmpty()); }
### Question: CorrelationContext { public static String getId() { return Optional.ofNullable(ID.get()).orElse(DEFAULT_CORRELATION_ID); } private CorrelationContext(); static String getId(); static CorrelationContextClosable create(String correlationId); }### Answer: @Ignore("Fix applying aspects to test classes") @Test @NewCorrelationContextRequired public void shouldInitializeCorrelationId() { String correlationId = CorrelationContext.getId(); assertNotEquals(DEFAULT_CORRELATION_ID, correlationId); }
### Question: NoviflowSpecificFeature extends AbstractFeature { static boolean isNoviSwitch(IOFSwitch sw) { if (sw == null || sw.getSwitchDescription() == null) { return false; } String manufacturer = getManufacturer(sw); if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(manufacturer)) { return true; } SwitchDescription description = sw.getSwitchDescription(); if (E_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( Optional.ofNullable(description.getHardwareDescription()).orElse("")).matches()) { return true; } return manufacturer.toLowerCase().contains(NOVIFLOW_MANUFACTURER_SUFFIX); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }### Answer: @Test public void testIsNoviSwitch() { assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertTrue(isNoviSwitch(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isNoviSwitch(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isNoviSwitch(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isNoviSwitch(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isNoviSwitch(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); }
### Question: NoviflowSpecificFeature extends AbstractFeature { static boolean isWbSeries(IOFSwitch sw) { if (! isNoviSwitch(sw)) { return false; } if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(getManufacturer(sw))) { return true; } Optional<SwitchDescription> description = Optional.ofNullable(sw.getSwitchDescription()); return E_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( description .map(SwitchDescription::getHardwareDescription) .orElse("")).matches(); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }### Answer: @Test public void testIsWbSeries() { assertTrue(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isWbSeries(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertFalse(isWbSeries(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isWbSeries(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); }
### Question: NoviflowSpecificFeature extends AbstractFeature { static boolean isSmSeries(IOFSwitch sw) { if (! isNoviSwitch(sw)) { return false; } Optional<SwitchDescription> description = Optional.ofNullable(sw.getSwitchDescription()); return NOVIFLOW_VIRTUAL_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( description.map(SwitchDescription::getHardwareDescription) .orElse("")).matches(); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }### Answer: @Test public void testIsSmSeries() { assertTrue(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertFalse(isSmSeries(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertFalse(isSmSeries(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isSmSeries(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isSmSeries(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isSmSeries(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); }
### Question: BfdFeature extends AbstractFeature { @Override public Optional<SwitchFeature> discover(IOFSwitch sw) { Optional<SwitchFeature> empty = Optional.empty(); SwitchDescription description = sw.getSwitchDescription(); if (description == null || description.getSoftwareDescription() == null) { return empty; } if (!NOVIFLOW_SOFTWARE_DESCRIPTION_REGEX.matcher(description.getSoftwareDescription()).matches()) { return empty; } return Optional.of(SwitchFeature.BFD); } @Override Optional<SwitchFeature> discover(IOFSwitch sw); }### Answer: @Test public void testDiscoverOfSwitchWithoutBfdSupport() { Assert.assertFalse(bfdFeature.discover(createSwitchWithDescription(null)).isPresent()); assertWithoutBfdSupport("2.8.16.21"); assertWithoutBfdSupport("2.8.16.15"); assertWithoutBfdSupport("8.1.0.14"); }
### Question: OfPortStatsMapper { public PortStatsData toPostStatsData(List<OFPortStatsReply> data, SwitchId switchId) { try { List<PortStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toPortStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new PortStatsData(switchId, stats); } catch (NullPointerException | UnsupportedOperationException | IllegalArgumentException e) { log.error(String.format("Could not convert port stats data %s on switch %s", data, switchId), e); return null; } } PortStatsData toPostStatsData(List<OFPortStatsReply> data, SwitchId switchId); PortStatsEntry toPortStatsEntry(OFPortStatsEntry entry); static final OfPortStatsMapper INSTANCE; }### Answer: @Test public void testToPortStatsDataV13() { OFFactoryVer13 ofFactoryVer13 = new OFFactoryVer13(); OFPortStatsEntry ofPortStatsEntry = prebuildPortStatsEntry(ofFactoryVer13.buildPortStatsEntry()) .setRxFrameErr(U64.of(rxFrameErr)) .setRxOverErr(U64.of(rxOverErr)) .setRxCrcErr(U64.of(rxCrcErr)) .setCollisions(U64.of(collisions)).build(); OFPortStatsReply ofPortStatsReply = ofFactoryVer13.buildPortStatsReply() .setXid(xId) .setEntries(Collections.singletonList(ofPortStatsEntry)) .build(); PortStatsData data = OfPortStatsMapper.INSTANCE.toPostStatsData( Collections.singletonList(ofPortStatsReply), switchId); assertPortStatsData(data); } @Test public void testToPortStatsDataV14() { OFFactoryVer14 ofFactoryVer14 = new OFFactoryVer14(); OFPortStatsProp opticalProps = ofFactoryVer14.buildPortStatsPropOptical().setRxPwr(123).build(); OFPortStatsProp ethernetProps = ofFactoryVer14.buildPortStatsPropEthernet() .setRxFrameErr(U64.of(rxFrameErr)) .setRxOverErr(U64.of(rxOverErr)) .setRxCrcErr(U64.of(rxCrcErr)) .setCollisions(U64.of(collisions)) .build(); OFPortStatsEntry ofPortStatsEntry = prebuildPortStatsEntry(ofFactoryVer14.buildPortStatsEntry()) .setProperties(Lists.newArrayList(opticalProps, ethernetProps)) .build(); OFPortStatsReply ofPortStatsReply = ofFactoryVer14.buildPortStatsReply() .setXid(xId) .setEntries(Collections.singletonList(ofPortStatsEntry)) .build(); PortStatsData data = OfPortStatsMapper.INSTANCE.toPostStatsData( Collections.singletonList(ofPortStatsReply), switchId); assertPortStatsData(data); }
### Question: OfFlowStatsMapper { public FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId) { try { List<FlowStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toFlowStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new FlowStatsData(switchId, stats); } catch (NullPointerException | UnsupportedOperationException | IllegalArgumentException e) { log.error(String.format("Could not convert flow stats data %s on switch %s", data, switchId), e); return null; } } FlowEntry toFlowEntry(final OFFlowStatsEntry entry); FlowEntry toFlowEntry(final OFFlowMod entry); FlowMatchField toFlowMatchField(final Match match); FlowInstructions toFlowInstructions(final List<OFInstruction> instructions); GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry); GroupBucket toGroupBucket(OFBucket ofBucket); FlowApplyActions toFlowApplyActions(List<OFAction> ofApplyActions); FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId); FlowStatsEntry toFlowStatsEntry(OFFlowStatsEntry entry); static final OfFlowStatsMapper INSTANCE; }### Answer: @Test public void testToFlowStatsData() { OFFlowStatsEntry ofEntry = buildFlowStatsEntry(); OFFlowStatsReply ofReply = factory.buildFlowStatsReply() .setXid(xId) .setEntries(Collections.singletonList(ofEntry)) .build(); FlowStatsData data = OfFlowStatsMapper.INSTANCE.toFlowStatsData(Collections.singletonList(ofReply), switchId); assertEquals(switchId, data.getSwitchId()); assertEquals(1, data.getStats().size()); FlowStatsEntry entry = data.getStats().get(0); assertEquals(tableId, entry.getTableId()); assertEquals(cookie, entry.getCookie()); assertEquals(packetCount, entry.getPacketCount()); assertEquals(byteCount, entry.getByteCount()); }
### Question: OfFlowStatsMapper { public FlowEntry toFlowEntry(final OFFlowStatsEntry entry) { return FlowEntry.builder() .version(entry.getVersion().toString()) .durationSeconds(entry.getDurationSec()) .durationNanoSeconds(entry.getDurationNsec()) .hardTimeout(entry.getHardTimeout()) .idleTimeout(entry.getIdleTimeout()) .priority(entry.getPriority()) .byteCount(entry.getByteCount().getValue()) .packetCount(entry.getPacketCount().getValue()) .flags(entry.getFlags().stream() .map(OFFlowModFlags::name) .toArray(String[]::new)) .cookie(entry.getCookie().getValue()) .tableId(entry.getTableId().getValue()) .match(toFlowMatchField(entry.getMatch())) .instructions(toFlowInstructions(entry.getInstructions())) .build(); } FlowEntry toFlowEntry(final OFFlowStatsEntry entry); FlowEntry toFlowEntry(final OFFlowMod entry); FlowMatchField toFlowMatchField(final Match match); FlowInstructions toFlowInstructions(final List<OFInstruction> instructions); GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry); GroupBucket toGroupBucket(OFBucket ofBucket); FlowApplyActions toFlowApplyActions(List<OFAction> ofApplyActions); FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId); FlowStatsEntry toFlowStatsEntry(OFFlowStatsEntry entry); static final OfFlowStatsMapper INSTANCE; }### Answer: @Test public void testFlowEntry() { OFFlowStatsEntry ofEntry = buildFlowStatsEntry(); FlowEntry entry = OfFlowStatsMapper.INSTANCE.toFlowEntry(ofEntry); assertEquals(tableId, entry.getTableId()); assertEquals(cookie, entry.getCookie()); assertEquals(packetCount, entry.getPacketCount()); assertEquals(byteCount, entry.getByteCount()); assertEquals(durationSec, entry.getDurationSeconds()); assertEquals(durationNsec, entry.getDurationNanoSeconds()); assertEquals(hardTimeout, entry.getHardTimeout()); assertEquals(idleTimeout, entry.getIdleTimeout()); assertEquals(priority, entry.getPriority()); assertEquals(String.valueOf(vlanVid.getVlan()), entry.getMatch().getVlanVid()); assertEquals(ethType.toString(), entry.getMatch().getEthType()); assertEquals(ethDst.toString(), entry.getMatch().getEthDst()); assertEquals(port.toString(), entry.getMatch().getInPort()); assertEquals(ipProto.toString(), entry.getMatch().getIpProto()); assertEquals(udpSrc.toString(), entry.getMatch().getUdpSrc()); assertEquals(udpDst.toString(), entry.getMatch().getUdpDst()); FlowSetFieldAction flowSetEthSrcAction = new FlowSetFieldAction("eth_src", MAC_ADDRESS_1); FlowSetFieldAction flowSetEthDstAction = new FlowSetFieldAction("eth_dst", MAC_ADDRESS_2); FlowCopyFieldAction flowCopyFieldAction = FlowCopyFieldAction.builder() .bits(String.valueOf(bits)) .srcOffset(String.valueOf(srcOffset)) .dstOffset(String.valueOf(dstOffset)) .srcOxm(String.valueOf(oxmSrcHeader)) .dstOxm(String.valueOf(oxmDstHeader)) .build(); FlowSwapFieldAction flowSwapFieldAction = FlowSwapFieldAction.builder() .bits(String.valueOf(bits)) .srcOffset(String.valueOf(srcOffset)) .dstOffset(String.valueOf(dstOffset)) .srcOxm(String.valueOf(oxmSrcHeader)) .dstOxm(String.valueOf(oxmDstHeader)) .build(); FlowApplyActions applyActions = new FlowApplyActions(port.toString(), Lists.newArrayList(flowSetEthSrcAction, flowSetEthDstAction), ethType.toString(), null, null, null, group.toString(), flowCopyFieldAction, flowSwapFieldAction); FlowInstructions instructions = new FlowInstructions(applyActions, null, meterId, goToTable.getValue()); assertEquals(instructions, entry.getInstructions()); }
### Question: OfFlowStatsMapper { public GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry) { if (ofGroupDescStatsEntry == null) { return null; } return GroupEntry.builder() .groupType(ofGroupDescStatsEntry.getGroupType().toString()) .groupId(ofGroupDescStatsEntry.getGroup().getGroupNumber()) .buckets(ofGroupDescStatsEntry.getBuckets().stream() .map(this::toGroupBucket) .collect(toList())) .build(); } FlowEntry toFlowEntry(final OFFlowStatsEntry entry); FlowEntry toFlowEntry(final OFFlowMod entry); FlowMatchField toFlowMatchField(final Match match); FlowInstructions toFlowInstructions(final List<OFInstruction> instructions); GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry); GroupBucket toGroupBucket(OFBucket ofBucket); FlowApplyActions toFlowApplyActions(List<OFAction> ofApplyActions); FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId); FlowStatsEntry toFlowStatsEntry(OFFlowStatsEntry entry); static final OfFlowStatsMapper INSTANCE; }### Answer: @Test public void testFlowGroupEntry() { OFGroupDescStatsEntry entry = buildFlowGroupEntry(); GroupEntry result = OfFlowStatsMapper.INSTANCE.toFlowGroupEntry(entry); assertEquals(entry.getGroup().getGroupNumber(), result.getGroupId()); assertEquals(entry.getGroupType().toString(), result.getGroupType()); assertEquals(entry.getBuckets().size(), result.getBuckets().size()); GroupBucket firstBucket = result.getBuckets().get(0); assertEquals("12", firstBucket.getApplyActions().getFlowOutput()); GroupBucket secondBucket = result.getBuckets().get(1); assertEquals(EthType.VLAN_FRAME.toString(), secondBucket.getApplyActions().getPushVlan()); assertEquals("vlan_vid", secondBucket.getApplyActions().getSetFieldActions().get(0).getFieldName()); assertEquals("12", secondBucket.getApplyActions().getSetFieldActions().get(0).getFieldValue()); assertEquals("1", secondBucket.getApplyActions().getFlowOutput()); }
### Question: OfTableStatsMapper { @Mapping(source = "tableId.value", target = "tableId") @Mapping(source = "activeCount", target = "activeEntries") @Mapping(source = "lookupCount.value", target = "lookupCount") @Mapping(source = "matchedCount.value", target = "matchedCount") public abstract TableStatsEntry toTableStatsEntry(OFTableStatsEntry source); @Mapping(source = "tableId.value", target = "tableId") @Mapping(source = "activeCount", target = "activeEntries") @Mapping(source = "lookupCount.value", target = "lookupCount") @Mapping(source = "matchedCount.value", target = "matchedCount") abstract TableStatsEntry toTableStatsEntry(OFTableStatsEntry source); static final OfTableStatsMapper INSTANCE; }### Answer: @Test public void shouldConvertSuccessfully() { OFFactoryVer13 ofFactoryVer13 = new OFFactoryVer13(); OFTableStatsEntry entry = ofFactoryVer13.buildTableStatsEntry() .setTableId(TableId.of(11)) .setActiveCount(10) .setMatchedCount(U64.of(100001L)) .setLookupCount(U64.of(100002L)) .build(); TableStatsEntry result = OfTableStatsMapper.INSTANCE.toTableStatsEntry(entry); assertEquals(result.getTableId(), entry.getTableId().getValue()); assertEquals(result.getActiveEntries(), entry.getActiveCount()); assertEquals(result.getLookupCount(), entry.getLookupCount().getValue()); assertEquals(result.getMatchedCount(), entry.getMatchedCount().getValue()); }
### Question: OfPortDescConverter { public boolean isReservedPort(OFPort port) { return OFPort.MAX.getPortNumber() <= port.getPortNumber() && port.getPortNumber() <= -1; } PortDescription toPortDescription(OFPortDesc ofPortDesc); PortInfoData toPortInfoData(DatapathId dpId, OFPortDesc portDesc, net.floodlightcontroller.core.PortChangeType type); boolean isReservedPort(OFPort port); boolean isPortEnabled(OFPortDesc portDesc); static final OfPortDescConverter INSTANCE; }### Answer: @Test public void testReservedPortCheck() { for (OFPort port : new OFPort[]{ OFPort.LOCAL, OFPort.ALL, OFPort.CONTROLLER, OFPort.ANY, OFPort.FLOOD, OFPort.NO_MASK, OFPort.IN_PORT, OFPort.NORMAL, OFPort.TABLE}) { Assert.assertTrue(String.format("Port %s must be detected as RESERVED, but it's not", port), OfPortDescConverter.INSTANCE.isReservedPort(port)); } for (OFPort port : new OFPort[]{ OFPort.of(1), OFPort.of(OFPort.MAX.getPortNumber() - 1)}) { Assert.assertFalse(String.format("Port %s must be detected as NOT RESERVED, but it's not", port), OfPortDescConverter.INSTANCE.isReservedPort(port)); } }
### Question: OfPortDescConverter { public PortInfoData toPortInfoData(DatapathId dpId, OFPortDesc portDesc, net.floodlightcontroller.core.PortChangeType type) { return new PortInfoData( new SwitchId(dpId.getLong()), portDesc.getPortNo().getPortNumber(), mapChangeType(type), isPortEnabled(portDesc)); } PortDescription toPortDescription(OFPortDesc ofPortDesc); PortInfoData toPortInfoData(DatapathId dpId, OFPortDesc portDesc, net.floodlightcontroller.core.PortChangeType type); boolean isReservedPort(OFPort port); boolean isPortEnabled(OFPortDesc portDesc); static final OfPortDescConverter INSTANCE; }### Answer: @Test public void testPortChangeTypeMapping() { OFPortDesc portDesc = OFFactoryVer13.INSTANCE.buildPortDesc() .setPortNo(OFPort.of(1)) .setName("test") .build(); Map<org.openkilda.messaging.info.event.PortChangeType, net.floodlightcontroller.core.PortChangeType> expected = new HashMap<>(); expected.put(org.openkilda.messaging.info.event.PortChangeType.ADD, net.floodlightcontroller.core.PortChangeType.ADD); expected.put(org.openkilda.messaging.info.event.PortChangeType.OTHER_UPDATE, net.floodlightcontroller.core.PortChangeType.OTHER_UPDATE); expected.put(org.openkilda.messaging.info.event.PortChangeType.DELETE, net.floodlightcontroller.core.PortChangeType.DELETE); expected.put(org.openkilda.messaging.info.event.PortChangeType.UP, net.floodlightcontroller.core.PortChangeType.UP); expected.put(org.openkilda.messaging.info.event.PortChangeType.DOWN, net.floodlightcontroller.core.PortChangeType.DOWN); DatapathId dpId = DatapathId.of(1); for (Map.Entry<org.openkilda.messaging.info.event.PortChangeType, net.floodlightcontroller.core.PortChangeType> entry : expected.entrySet()) { PortInfoData encoded = OfPortDescConverter.INSTANCE.toPortInfoData(dpId, portDesc, entry.getValue()); Assert.assertSame(entry.getKey(), encoded.getState()); } }
### Question: OfMeterStatsMapper { public MeterStatsData toMeterStatsData(List<OFMeterStatsReply> data, SwitchId switchId) { try { List<MeterStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toMeterStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new MeterStatsData(switchId, stats); } catch (NullPointerException | UnsupportedOperationException | IllegalArgumentException e) { log.error(String.format("Could not convert meter stats data %s on switch %s", data, switchId), e); return null; } } MeterStatsData toMeterStatsData(List<OFMeterStatsReply> data, SwitchId switchId); MeterStatsEntry toMeterStatsEntry(OFMeterStats entry); static final OfMeterStatsMapper INSTANCE; }### Answer: @Test public void testToPortStatsDataV13() { OFFactoryVer13 factory = new OFFactoryVer13(); OFMeterBandStats bandStats = factory.meterBandStats(U64.of(bandPacketCount), U64.of(bandByteCount)); OFMeterStats meterStats = factory.buildMeterStats() .setMeterId(meterId) .setByteInCount(U64.of(meterByteCount)) .setPacketInCount(U64.of(meterPacketCount)) .setBandStats(Collections.singletonList(bandStats)) .build(); OFMeterStatsReply reply = factory.buildMeterStatsReply() .setEntries(Collections.singletonList(meterStats)) .build(); MeterStatsData data = OfMeterStatsMapper.INSTANCE.toMeterStatsData(Collections.singletonList(reply), switchId); assertEquals(switchId, data.getSwitchId()); assertEquals(1, data.getStats().size()); MeterStatsEntry statsEntry = data.getStats().get(0); assertEquals(bandByteCount, statsEntry.getByteInCount()); assertEquals(bandPacketCount, statsEntry.getPacketsInCount()); }
### Question: SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchAdded(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.ADDED); switchDiscovery(switchId, SwitchChangeType.ADDED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer: @Test public void switchAdded() throws Exception { SpeakerSwitchView expectedSwitchView = makeSwitchRecord(dpId, switchFeatures, true, true); Capture<Message> producedMessage = prepareAliveSwitchEvent(expectedSwitchView); replayAll(); service.switchAdded(dpId); verifySwitchEvent(SwitchChangeType.ADDED, expectedSwitchView, producedMessage); } @Test public void switchAddedMissing() throws Exception { Capture<Message> producedMessage = prepareRemovedSwitchEvent(); replayAll(); service.switchAdded(dpId); verifySwitchEvent(SwitchChangeType.ADDED, null, producedMessage); }
### Question: SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchRemoved(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.REMOVED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.REMOVED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer: @Test public void switchRemoved() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchRemoved(dpId); verifySwitchEvent(SwitchChangeType.REMOVED, null, producedMessage); }
### Question: SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchDeactivated(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.DEACTIVATED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.DEACTIVATED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer: @Test public void switchDeactivated() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchDeactivated(dpId); verifySwitchEvent(SwitchChangeType.DEACTIVATED, null, producedMessage); }
### Question: SwitchOperationsService implements ILinkOperationsServiceCarrier { public Switch patchSwitch(SwitchId switchId, SwitchPatch data) throws SwitchNotFoundException { return transactionManager.doInTransaction(() -> { Switch foundSwitch = switchRepository.findById(switchId) .orElseThrow(() -> new SwitchNotFoundException(switchId)); Optional.ofNullable(data.getPop()).ifPresent(pop -> foundSwitch.setPop(!"".equals(pop) ? pop : null)); Optional.ofNullable(data.getLocation()).ifPresent(location -> { Optional.ofNullable(location.getLatitude()).ifPresent(foundSwitch::setLatitude); Optional.ofNullable(location.getLongitude()).ifPresent(foundSwitch::setLongitude); Optional.ofNullable(location.getStreet()).ifPresent(foundSwitch::setStreet); Optional.ofNullable(location.getCity()).ifPresent(foundSwitch::setCity); Optional.ofNullable(location.getCountry()).ifPresent(foundSwitch::setCountry); }); switchRepository.detach(foundSwitch); return foundSwitch; }); } SwitchOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager, SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices( SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }### Answer: @Test public void shouldPatchSwitch() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); SwitchPatch switchPatch = new SwitchPatch("pop", new SwitchLocation(48.860611, 2.337633, "street", "city", "country")); switchOperationsService.patchSwitch(TEST_SWITCH_ID, switchPatch); Switch updatedSwitch = switchRepository.findById(TEST_SWITCH_ID).get(); assertEquals(switchPatch.getPop(), updatedSwitch.getPop()); assertEquals(switchPatch.getLocation().getLatitude(), updatedSwitch.getLatitude()); assertEquals(switchPatch.getLocation().getLongitude(), updatedSwitch.getLongitude()); assertEquals(switchPatch.getLocation().getStreet(), updatedSwitch.getStreet()); assertEquals(switchPatch.getLocation().getCity(), updatedSwitch.getCity()); assertEquals(switchPatch.getLocation().getCountry(), updatedSwitch.getCountry()); } @Test public void shouldSetNullPopWhenPopIsEmptyString() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); SwitchPatch switchPatch = new SwitchPatch("", null); switchOperationsService.patchSwitch(TEST_SWITCH_ID, switchPatch); Switch updatedSwitch = switchRepository.findById(TEST_SWITCH_ID).get(); assertNull(updatedSwitch.getPop()); }
### Question: SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchChanged(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.CHANGED); switchDiscovery(switchId, SwitchChangeType.CHANGED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer: @Test public void switchChanged() throws Exception { SpeakerSwitchView expectedSwitchRecord = makeSwitchRecord(dpId, switchFeatures, true, true); Capture<Message> producedMessage = prepareAliveSwitchEvent(expectedSwitchRecord); replayAll(); service.switchChanged(dpId); verifySwitchEvent(SwitchChangeType.CHANGED, expectedSwitchRecord, producedMessage); } @Test public void switchChangedMissing() throws Exception { Capture<Message> producedMessage = prepareRemovedSwitchEvent(); replayAll(); service.switchChanged(dpId); verifySwitchEvent(SwitchChangeType.CHANGED, null, producedMessage); }
### Question: SubscriptionInfo { public static SubscriptionInfo decode(ByteBuffer data) { data.rewind(); int version = data.getInt(); if (version == CURRENT_VERSION || version == 1) { UUID processId = new UUID(data.getLong(), data.getLong()); Set<TaskId> prevTasks = new HashSet<>(); int numPrevs = data.getInt(); for (int i = 0; i < numPrevs; i++) { TaskId id = TaskId.readFrom(data); prevTasks.add(id); } Set<TaskId> standbyTasks = new HashSet<>(); int numCached = data.getInt(); for (int i = 0; i < numCached; i++) { standbyTasks.add(TaskId.readFrom(data)); } String userEndPoint = null; if (version == CURRENT_VERSION) { int bytesLength = data.getInt(); if (bytesLength != 0) { byte[] bytes = new byte[bytesLength]; data.get(bytes); userEndPoint = new String(bytes, Charset.forName("UTF-8")); } } return new SubscriptionInfo(version, processId, prevTasks, standbyTasks, userEndPoint); } else { TaskAssignmentException ex = new TaskAssignmentException("unable to decode subscription data: version=" + version); log.error(ex.getMessage(), ex); throw ex; } } SubscriptionInfo(UUID processId, Set<TaskId> prevTasks, Set<TaskId> standbyTasks, String userEndPoint); private SubscriptionInfo(int version, UUID processId, Set<TaskId> prevTasks, Set<TaskId> standbyTasks, String userEndPoint); ByteBuffer encode(); static SubscriptionInfo decode(ByteBuffer data); @Override int hashCode(); @Override boolean equals(Object o); final int version; final UUID processId; final Set<TaskId> prevTasks; final Set<TaskId> standbyTasks; final String userEndPoint; }### Answer: @Test public void shouldBeBackwardCompatible() throws Exception { UUID processId = UUID.randomUUID(); Set<TaskId> activeTasks = new HashSet<>(Arrays.asList(new TaskId(0, 0), new TaskId(0, 1), new TaskId(1, 0))); Set<TaskId> standbyTasks = new HashSet<>(Arrays.asList(new TaskId(1, 1), new TaskId(2, 0))); final ByteBuffer v1Encoding = encodePreviousVersion(processId, activeTasks, standbyTasks); final SubscriptionInfo decode = SubscriptionInfo.decode(v1Encoding); assertEquals(activeTasks, decode.prevTasks); assertEquals(standbyTasks, decode.standbyTasks); assertEquals(processId, decode.processId); assertNull(decode.userEndPoint); }
### Question: ConnectorsResource { @GET @Path("/{connector}/config") public Map<String, String> getConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Map<String, String>> cb = new FutureCallback<>(); herder.connectorConfig(connector, cb); return completeOrForwardRequest(cb, "/connectors/" + connector + "/config", "GET", null, forward); } ConnectorsResource(Herder herder); @GET @Path("/") Collection<String> listConnectors(final @QueryParam("forward") Boolean forward); @POST @Path("/") Response createConnector(final @QueryParam("forward") Boolean forward, final CreateConnectorRequest createRequest); @GET @Path("/{connector}") ConnectorInfo getConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/config") Map<String, String> getConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/status") ConnectorStateInfo getConnectorStatus(final @PathParam("connector") String connector); @PUT @Path("/{connector}/config") Response putConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final Map<String, String> connectorConfig); @POST @Path("/{connector}/restart") void restartConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @PUT @Path("/{connector}/pause") Response pauseConnector(@PathParam("connector") String connector); @PUT @Path("/{connector}/resume") Response resumeConnector(@PathParam("connector") String connector); @GET @Path("/{connector}/tasks") List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @POST @Path("/{connector}/tasks") void putTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final List<Map<String, String>> taskConfigs); @GET @Path("/{connector}/tasks/{task}/status") ConnectorStateInfo.TaskState getTaskStatus(final @PathParam("connector") String connector, final @PathParam("task") Integer task); @POST @Path("/{connector}/tasks/{task}/restart") void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @QueryParam("forward") Boolean forward); @DELETE @Path("/{connector}") void destroyConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); }### Answer: @Test(expected = NotFoundException.class) public void testGetConnectorConfigConnectorNotFound() throws Throwable { final Capture<Callback<Map<String, String>>> cb = Capture.newInstance(); herder.connectorConfig(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackException(cb, new NotFoundException("not found")); PowerMock.replayAll(); connectorsResource.getConnectorConfig(CONNECTOR_NAME, FORWARD); PowerMock.verifyAll(); } @Test public void testGetConnectorConfig() throws Throwable { final Capture<Callback<Map<String, String>>> cb = Capture.newInstance(); herder.connectorConfig(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackResult(cb, CONNECTOR_CONFIG); PowerMock.replayAll(); Map<String, String> connConfig = connectorsResource.getConnectorConfig(CONNECTOR_NAME, FORWARD); assertEquals(CONNECTOR_CONFIG, connConfig); PowerMock.verifyAll(); }
### Question: ClientState { boolean reachedCapacity() { return assignedTasks.size() >= capacity; } ClientState(); ClientState(final int capacity); private ClientState(Set<TaskId> activeTasks, Set<TaskId> standbyTasks, Set<TaskId> assignedTasks, Set<TaskId> prevActiveTasks, Set<TaskId> prevAssignedTasks, int capacity); ClientState copy(); void assign(final TaskId taskId, final boolean active); Set<TaskId> activeTasks(); Set<TaskId> standbyTasks(); int assignedTaskCount(); void incrementCapacity(); int activeTaskCount(); void addPreviousActiveTasks(final Set<TaskId> prevTasks); void addPreviousStandbyTasks(final Set<TaskId> standbyTasks); @Override String toString(); }### Answer: @Test public void shouldHaveNotReachedCapacityWhenAssignedTasksLessThanCapacity() throws Exception { assertFalse(client.reachedCapacity()); }
### Question: ClientState { boolean hasMoreAvailableCapacityThan(final ClientState other) { if (this.capacity <= 0) { throw new IllegalStateException("Capacity of this ClientState must be greater than 0."); } if (other.capacity <= 0) { throw new IllegalStateException("Capacity of other ClientState must be greater than 0"); } final double otherLoad = (double) other.assignedTaskCount() / other.capacity; final double thisLoad = (double) assignedTaskCount() / capacity; if (thisLoad < otherLoad) return true; else if (thisLoad > otherLoad) return false; else return capacity > other.capacity; } ClientState(); ClientState(final int capacity); private ClientState(Set<TaskId> activeTasks, Set<TaskId> standbyTasks, Set<TaskId> assignedTasks, Set<TaskId> prevActiveTasks, Set<TaskId> prevAssignedTasks, int capacity); ClientState copy(); void assign(final TaskId taskId, final boolean active); Set<TaskId> activeTasks(); Set<TaskId> standbyTasks(); int assignedTaskCount(); void incrementCapacity(); int activeTaskCount(); void addPreviousActiveTasks(final Set<TaskId> prevTasks); void addPreviousStandbyTasks(final Set<TaskId> standbyTasks); @Override String toString(); }### Answer: @Test public void shouldHaveMoreAvailableCapacityWhenCapacityHigherAndSameAssignedTaskCount() throws Exception { final ClientState c2 = new ClientState(2); assertTrue(c2.hasMoreAvailableCapacityThan(client)); assertFalse(client.hasMoreAvailableCapacityThan(c2)); } @Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfCapacityOfThisClientStateIsZero() throws Exception { final ClientState c1 = new ClientState(0); c1.hasMoreAvailableCapacityThan(new ClientState(1)); } @Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfCapacityOfOtherClientStateIsZero() throws Exception { final ClientState c1 = new ClientState(1); c1.hasMoreAvailableCapacityThan(new ClientState(0)); }
### Question: QuickUnion { public void unite(T id1, T... idList) { for (T id2 : idList) { unitePair(id1, id2); } } void add(T id); boolean exists(T id); T root(T id); void unite(T id1, T... idList); }### Answer: @SuppressWarnings("unchecked") @Test public void testUnite() { QuickUnion<Long> qu = new QuickUnion<>(); long[] ids = { 1L, 2L, 3L, 4L, 5L }; for (long id : ids) { qu.add(id); } assertEquals(5, roots(qu, ids).size()); qu.unite(1L, 2L); assertEquals(4, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); qu.unite(3L, 4L); assertEquals(3, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(1L, 5L); assertEquals(2, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(5L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(3L, 5L); assertEquals(1, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(3L)); assertEquals(qu.root(3L), qu.root(4L)); assertEquals(qu.root(4L), qu.root(5L)); }
### Question: StoreChangelogReader implements ChangelogReader { public void restore() { final long start = time.milliseconds(); try { if (!consumer.subscription().isEmpty()) { throw new IllegalStateException(String.format("Restore consumer should have not subscribed to any partitions (%s) beforehand", consumer.subscription())); } final Map<TopicPartition, Long> endOffsets = consumer.endOffsets(stateRestorers.keySet()); final Map<TopicPartition, StateRestorer> needsRestoring = new HashMap<>(); for (final Map.Entry<TopicPartition, Long> entry : endOffsets.entrySet()) { TopicPartition topicPartition = entry.getKey(); Long offset = entry.getValue(); final StateRestorer restorer = stateRestorers.get(topicPartition); if (restorer.checkpoint() >= offset) { restorer.setRestoredOffset(restorer.checkpoint()); } else { needsRestoring.put(topicPartition, restorer); } } log.info("{} Starting restoring state stores from changelog topics {}", logPrefix, needsRestoring.keySet()); consumer.assign(needsRestoring.keySet()); final List<StateRestorer> needsPositionUpdate = new ArrayList<>(); for (final StateRestorer restorer : needsRestoring.values()) { if (restorer.checkpoint() != StateRestorer.NO_CHECKPOINT) { consumer.seek(restorer.partition(), restorer.checkpoint()); logRestoreOffsets(restorer.partition(), restorer.checkpoint(), endOffsets.get(restorer.partition())); restorer.setStartingOffset(consumer.position(restorer.partition())); } else { consumer.seekToBeginning(Collections.singletonList(restorer.partition())); needsPositionUpdate.add(restorer); } } for (final StateRestorer restorer : needsPositionUpdate) { final long position = consumer.position(restorer.partition()); restorer.setStartingOffset(position); logRestoreOffsets(restorer.partition(), position, endOffsets.get(restorer.partition())); } final Set<TopicPartition> partitions = new HashSet<>(needsRestoring.keySet()); while (!partitions.isEmpty()) { final ConsumerRecords<byte[], byte[]> allRecords = consumer.poll(10); final Iterator<TopicPartition> partitionIterator = partitions.iterator(); while (partitionIterator.hasNext()) { restorePartition(endOffsets, allRecords, partitionIterator); } } } finally { consumer.assign(Collections.<TopicPartition>emptyList()); log.debug("{} Took {} ms to restore all active states", logPrefix, time.milliseconds() - start); } } StoreChangelogReader(final String threadId, final Consumer<byte[], byte[]> consumer, final Time time, final long partitionValidationTimeoutMs); StoreChangelogReader(final Consumer<byte[], byte[]> consumer, final Time time, final long partitionValidationTimeoutMs); @Override void validatePartitionExists(final TopicPartition topicPartition, final String storeName); @Override void register(final StateRestorer restorer); void restore(); @Override Map<TopicPartition, Long> restoredOffsets(); }### Answer: @Test public void shouldThrowExceptionIfConsumerHasCurrentSubscription() throws Exception { consumer.subscribe(Collections.singleton("sometopic")); try { changelogReader.restore(); fail("Should have thrown IllegalStateException"); } catch (final IllegalStateException e) { } }
### Question: InternalTopicManager { public Map<String, Integer> getNumPartitions(final Set<String> topics) { for (int i = 0; i < MAX_TOPIC_READY_TRY; i++) { try { final MetadataResponse metadata = streamsKafkaClient.fetchMetadata(); final Map<String, Integer> existingTopicPartitions = fetchExistingPartitionCountByTopic(metadata); existingTopicPartitions.keySet().retainAll(topics); return existingTopicPartitions; } catch (StreamsException ex) { log.warn("Could not get number of partitions: " + ex.getMessage() + " Retry #" + i); } time.sleep(100L); } throw new StreamsException("Could not get number of partitions."); } InternalTopicManager(final StreamsKafkaClient streamsKafkaClient, final int replicationFactor, final long windowChangeLogAdditionalRetention, final Time time); void makeReady(final Map<InternalTopicConfig, Integer> topics); Map<String, Integer> getNumPartitions(final Set<String> topics); void close(); static final String CLEANUP_POLICY_PROP; static final String RETENTION_MS; static final Long WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT; }### Answer: @Test public void shouldReturnCorrectPartitionCounts() throws Exception { InternalTopicManager internalTopicManager = new InternalTopicManager(streamsKafkaClient, 1, WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT, time); Assert.assertEquals(Collections.singletonMap(topic, 1), internalTopicManager.getNumPartitions(Collections.singleton(topic))); }
### Question: InternalTopicManager { public void makeReady(final Map<InternalTopicConfig, Integer> topics) { for (int i = 0; i < MAX_TOPIC_READY_TRY; i++) { try { final MetadataResponse metadata = streamsKafkaClient.fetchMetadata(); final Map<String, Integer> existingTopicPartitions = fetchExistingPartitionCountByTopic(metadata); final Map<InternalTopicConfig, Integer> topicsToBeCreated = validateTopicPartitions(topics, existingTopicPartitions); if (metadata.brokers().size() < replicationFactor) { throw new StreamsException("Found only " + metadata.brokers().size() + " brokers, " + " but replication factor is " + replicationFactor + "." + " Decrease replication factor for internal topics via StreamsConfig parameter \"replication.factor\"" + " or add more brokers to your cluster."); } streamsKafkaClient.createTopics(topicsToBeCreated, replicationFactor, windowChangeLogAdditionalRetention, metadata); return; } catch (StreamsException ex) { log.warn("Could not create internal topics: " + ex.getMessage() + " Retry #" + i); } time.sleep(100L); } throw new StreamsException("Could not create internal topics."); } InternalTopicManager(final StreamsKafkaClient streamsKafkaClient, final int replicationFactor, final long windowChangeLogAdditionalRetention, final Time time); void makeReady(final Map<InternalTopicConfig, Integer> topics); Map<String, Integer> getNumPartitions(final Set<String> topics); void close(); static final String CLEANUP_POLICY_PROP; static final String RETENTION_MS; static final Long WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT; }### Answer: @Test public void shouldCreateRequiredTopics() throws Exception { InternalTopicManager internalTopicManager = new InternalTopicManager(streamsKafkaClient, 1, WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT, time); internalTopicManager.makeReady(Collections.singletonMap(new InternalTopicConfig(topic, Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), null), 1)); } @Test public void shouldNotCreateTopicIfExistsWithDifferentPartitions() throws Exception { InternalTopicManager internalTopicManager = new InternalTopicManager(streamsKafkaClient, 1, WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT, time); boolean exceptionWasThrown = false; try { internalTopicManager.makeReady(Collections.singletonMap(new InternalTopicConfig(topic, Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), null), 2)); } catch (StreamsException e) { exceptionWasThrown = true; } Assert.assertTrue(exceptionWasThrown); }
### Question: AbstractTask { protected void updateOffsetLimits() { log.debug("{} Updating store offset limits {}", logPrefix); for (final TopicPartition partition : partitions) { try { final OffsetAndMetadata metadata = consumer.committed(partition); stateMgr.putOffsetLimit(partition, metadata != null ? metadata.offset() : 0L); } catch (final AuthorizationException e) { throw new ProcessorStateException(String.format("task [%s] AuthorizationException when initializing offsets for %s", id, partition), e); } catch (final WakeupException e) { throw e; } catch (final KafkaException e) { throw new ProcessorStateException(String.format("task [%s] Failed to initialize offsets for %s", id, partition), e); } } } AbstractTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final boolean isStandby, final StateDirectory stateDirectory, final ThreadCache cache, final StreamsConfig config); abstract void resume(); abstract void commit(); abstract void suspend(); abstract void close(final boolean clean); final TaskId id(); final String applicationId(); final Set<TopicPartition> partitions(); final ProcessorTopology topology(); final ProcessorContext context(); final ThreadCache cache(); StateStore getStore(final String name); @Override String toString(); String toString(final String indent); }### Answer: @Test(expected = ProcessorStateException.class) public void shouldThrowProcessorStateExceptionOnInitializeOffsetsWhenAuthorizationException() throws Exception { final Consumer consumer = mockConsumer(new AuthorizationException("blah")); final AbstractTask task = createTask(consumer); task.updateOffsetLimits(); } @Test(expected = ProcessorStateException.class) public void shouldThrowProcessorStateExceptionOnInitializeOffsetsWhenKafkaException() throws Exception { final Consumer consumer = mockConsumer(new KafkaException("blah")); final AbstractTask task = createTask(consumer); task.updateOffsetLimits(); } @Test(expected = WakeupException.class) public void shouldThrowWakeupExceptionOnInitializeOffsetsWhenWakeupException() throws Exception { final Consumer consumer = mockConsumer(new WakeupException()); final AbstractTask task = createTask(consumer); task.updateOffsetLimits(); }
### Question: ConnectorsResource { @GET @Path("/{connector}/tasks") public List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<List<TaskInfo>> cb = new FutureCallback<>(); herder.taskConfigs(connector, cb); return completeOrForwardRequest(cb, "/connectors/" + connector + "/tasks", "GET", null, new TypeReference<List<TaskInfo>>() { }, forward); } ConnectorsResource(Herder herder); @GET @Path("/") Collection<String> listConnectors(final @QueryParam("forward") Boolean forward); @POST @Path("/") Response createConnector(final @QueryParam("forward") Boolean forward, final CreateConnectorRequest createRequest); @GET @Path("/{connector}") ConnectorInfo getConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/config") Map<String, String> getConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/status") ConnectorStateInfo getConnectorStatus(final @PathParam("connector") String connector); @PUT @Path("/{connector}/config") Response putConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final Map<String, String> connectorConfig); @POST @Path("/{connector}/restart") void restartConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @PUT @Path("/{connector}/pause") Response pauseConnector(@PathParam("connector") String connector); @PUT @Path("/{connector}/resume") Response resumeConnector(@PathParam("connector") String connector); @GET @Path("/{connector}/tasks") List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @POST @Path("/{connector}/tasks") void putTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final List<Map<String, String>> taskConfigs); @GET @Path("/{connector}/tasks/{task}/status") ConnectorStateInfo.TaskState getTaskStatus(final @PathParam("connector") String connector, final @PathParam("task") Integer task); @POST @Path("/{connector}/tasks/{task}/restart") void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @QueryParam("forward") Boolean forward); @DELETE @Path("/{connector}") void destroyConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); }### Answer: @Test public void testGetConnectorTaskConfigs() throws Throwable { final Capture<Callback<List<TaskInfo>>> cb = Capture.newInstance(); herder.taskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackResult(cb, TASK_INFOS); PowerMock.replayAll(); List<TaskInfo> taskInfos = connectorsResource.getTaskConfigs(CONNECTOR_NAME, FORWARD); assertEquals(TASK_INFOS, taskInfos); PowerMock.verifyAll(); } @Test(expected = NotFoundException.class) public void testGetConnectorTaskConfigsConnectorNotFound() throws Throwable { final Capture<Callback<List<TaskInfo>>> cb = Capture.newInstance(); herder.taskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackException(cb, new NotFoundException("connector not found")); PowerMock.replayAll(); connectorsResource.getTaskConfigs(CONNECTOR_NAME, FORWARD); PowerMock.verifyAll(); }
### Question: ConnectorsResource { @POST @Path("/{connector}/tasks") public void putTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final List<Map<String, String>> taskConfigs) throws Throwable { FutureCallback<Void> cb = new FutureCallback<>(); herder.putTaskConfigs(connector, taskConfigs, cb); completeOrForwardRequest(cb, "/connectors/" + connector + "/tasks", "POST", taskConfigs, forward); } ConnectorsResource(Herder herder); @GET @Path("/") Collection<String> listConnectors(final @QueryParam("forward") Boolean forward); @POST @Path("/") Response createConnector(final @QueryParam("forward") Boolean forward, final CreateConnectorRequest createRequest); @GET @Path("/{connector}") ConnectorInfo getConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/config") Map<String, String> getConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @GET @Path("/{connector}/status") ConnectorStateInfo getConnectorStatus(final @PathParam("connector") String connector); @PUT @Path("/{connector}/config") Response putConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final Map<String, String> connectorConfig); @POST @Path("/{connector}/restart") void restartConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @PUT @Path("/{connector}/pause") Response pauseConnector(@PathParam("connector") String connector); @PUT @Path("/{connector}/resume") Response resumeConnector(@PathParam("connector") String connector); @GET @Path("/{connector}/tasks") List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); @POST @Path("/{connector}/tasks") void putTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final List<Map<String, String>> taskConfigs); @GET @Path("/{connector}/tasks/{task}/status") ConnectorStateInfo.TaskState getTaskStatus(final @PathParam("connector") String connector, final @PathParam("task") Integer task); @POST @Path("/{connector}/tasks/{task}/restart") void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @QueryParam("forward") Boolean forward); @DELETE @Path("/{connector}") void destroyConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward); }### Answer: @Test public void testPutConnectorTaskConfigs() throws Throwable { final Capture<Callback<Void>> cb = Capture.newInstance(); herder.putTaskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.eq(TASK_CONFIGS), EasyMock.capture(cb)); expectAndCallbackResult(cb, null); PowerMock.replayAll(); connectorsResource.putTaskConfigs(CONNECTOR_NAME, FORWARD, TASK_CONFIGS); PowerMock.verifyAll(); } @Test(expected = NotFoundException.class) public void testPutConnectorTaskConfigsConnectorNotFound() throws Throwable { final Capture<Callback<Void>> cb = Capture.newInstance(); herder.putTaskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.eq(TASK_CONFIGS), EasyMock.capture(cb)); expectAndCallbackException(cb, new NotFoundException("not found")); PowerMock.replayAll(); connectorsResource.putTaskConfigs(CONNECTOR_NAME, FORWARD, TASK_CONFIGS); PowerMock.verifyAll(); }
### Question: AbstractHerder implements Herder, TaskStatus.Listener, ConnectorStatus.Listener { @Override public ConnectorStateInfo connectorStatus(String connName) { ConnectorStatus connector = statusBackingStore.get(connName); if (connector == null) throw new NotFoundException("No status found for connector " + connName); Collection<TaskStatus> tasks = statusBackingStore.getAll(connName); ConnectorStateInfo.ConnectorState connectorState = new ConnectorStateInfo.ConnectorState( connector.state().toString(), connector.workerId(), connector.trace()); List<ConnectorStateInfo.TaskState> taskStates = new ArrayList<>(); for (TaskStatus status : tasks) { taskStates.add(new ConnectorStateInfo.TaskState(status.id().task(), status.state().toString(), status.workerId(), status.trace())); } Collections.sort(taskStates); return new ConnectorStateInfo(connName, connectorState, taskStates); } AbstractHerder(Worker worker, String workerId, StatusBackingStore statusBackingStore, ConfigBackingStore configBackingStore); @Override void onStartup(String connector); @Override void onPause(String connector); @Override void onResume(String connector); @Override void onShutdown(String connector); @Override void onFailure(String connector, Throwable cause); @Override void onStartup(ConnectorTaskId id); @Override void onFailure(ConnectorTaskId id, Throwable cause); @Override void onShutdown(ConnectorTaskId id); @Override void onResume(ConnectorTaskId id); @Override void onPause(ConnectorTaskId id); @Override void onDeletion(String connector); @Override void pauseConnector(String connector); @Override void resumeConnector(String connector); @Override Plugins plugins(); @Override ConnectorStateInfo connectorStatus(String connName); @Override ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id); @Override ConfigInfos validateConnectorConfig(Map<String, String> connectorProps); static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups); }### Answer: @Test public void connectorStatus() { ConnectorTaskId taskId = new ConnectorTaskId(connector, 0); ConfigBackingStore configStore = strictMock(ConfigBackingStore.class); StatusBackingStore statusStore = strictMock(StatusBackingStore.class); AbstractHerder herder = partialMockBuilder(AbstractHerder.class) .withConstructor(Worker.class, String.class, StatusBackingStore.class, ConfigBackingStore.class) .withArgs(worker, workerId, statusStore, configStore) .addMockedMethod("generation") .createMock(); EasyMock.expect(herder.generation()).andStubReturn(generation); EasyMock.expect(statusStore.get(connector)) .andReturn(new ConnectorStatus(connector, AbstractStatus.State.RUNNING, workerId, generation)); EasyMock.expect(statusStore.getAll(connector)) .andReturn(Collections.singletonList( new TaskStatus(taskId, AbstractStatus.State.UNASSIGNED, workerId, generation))); replayAll(); ConnectorStateInfo state = herder.connectorStatus(connector); assertEquals(connector, state.name()); assertEquals("RUNNING", state.connector().state()); assertEquals(1, state.tasks().size()); assertEquals(workerId, state.connector().workerId()); ConnectorStateInfo.TaskState taskState = state.tasks().get(0); assertEquals(0, taskState.id()); assertEquals("UNASSIGNED", taskState.state()); assertEquals(workerId, taskState.workerId()); verifyAll(); }
### Question: AbstractHerder implements Herder, TaskStatus.Listener, ConnectorStatus.Listener { @Override public ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id) { TaskStatus status = statusBackingStore.get(id); if (status == null) throw new NotFoundException("No status found for task " + id); return new ConnectorStateInfo.TaskState(id.task(), status.state().toString(), status.workerId(), status.trace()); } AbstractHerder(Worker worker, String workerId, StatusBackingStore statusBackingStore, ConfigBackingStore configBackingStore); @Override void onStartup(String connector); @Override void onPause(String connector); @Override void onResume(String connector); @Override void onShutdown(String connector); @Override void onFailure(String connector, Throwable cause); @Override void onStartup(ConnectorTaskId id); @Override void onFailure(ConnectorTaskId id, Throwable cause); @Override void onShutdown(ConnectorTaskId id); @Override void onResume(ConnectorTaskId id); @Override void onPause(ConnectorTaskId id); @Override void onDeletion(String connector); @Override void pauseConnector(String connector); @Override void resumeConnector(String connector); @Override Plugins plugins(); @Override ConnectorStateInfo connectorStatus(String connName); @Override ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id); @Override ConfigInfos validateConnectorConfig(Map<String, String> connectorProps); static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups); }### Answer: @Test public void taskStatus() { ConnectorTaskId taskId = new ConnectorTaskId("connector", 0); String workerId = "workerId"; ConfigBackingStore configStore = strictMock(ConfigBackingStore.class); StatusBackingStore statusStore = strictMock(StatusBackingStore.class); AbstractHerder herder = partialMockBuilder(AbstractHerder.class) .withConstructor(Worker.class, String.class, StatusBackingStore.class, ConfigBackingStore.class) .withArgs(worker, workerId, statusStore, configStore) .addMockedMethod("generation") .createMock(); EasyMock.expect(herder.generation()).andStubReturn(5); final Capture<TaskStatus> statusCapture = EasyMock.newCapture(); statusStore.putSafe(EasyMock.capture(statusCapture)); EasyMock.expectLastCall(); EasyMock.expect(statusStore.get(taskId)).andAnswer(new IAnswer<TaskStatus>() { @Override public TaskStatus answer() throws Throwable { return statusCapture.getValue(); } }); replayAll(); herder.onFailure(taskId, new RuntimeException()); ConnectorStateInfo.TaskState taskState = herder.taskStatus(taskId); assertEquals(workerId, taskState.workerId()); assertEquals("FAILED", taskState.state()); assertEquals(0, taskState.id()); assertNotNull(taskState.trace()); verifyAll(); }
### Question: StandaloneHerder extends AbstractHerder { @Override public synchronized void restartConnector(String connName, Callback<Void> cb) { if (!configState.contains(connName)) cb.onCompletion(new NotFoundException("Connector " + connName + " not found", null), null); Map<String, String> config = configState.connectorConfig(connName); worker.stopConnector(connName); if (startConnector(config)) cb.onCompletion(null, null); else cb.onCompletion(new ConnectException("Failed to start connector: " + connName), null); } StandaloneHerder(Worker worker); StandaloneHerder(Worker worker, String workerId, StatusBackingStore statusBackingStore, MemoryConfigBackingStore configBackingStore); synchronized void start(); synchronized void stop(); @Override int generation(); @Override synchronized void connectors(Callback<Collection<String>> callback); @Override synchronized void connectorInfo(String connName, Callback<ConnectorInfo> callback); @Override void connectorConfig(String connName, final Callback<Map<String, String>> callback); @Override synchronized void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); @Override synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback); @Override synchronized void requestTaskReconfiguration(String connName); @Override synchronized void taskConfigs(String connName, Callback<List<TaskInfo>> callback); @Override void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback); @Override synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb); @Override synchronized void restartConnector(String connName, Callback<Void> cb); }### Answer: @Test public void testRestartConnector() throws Exception { expectAdd(SourceSink.SOURCE); Map<String, String> config = connectorConfig(SourceSink.SOURCE); expectConfigValidation(config); worker.stopConnector(CONNECTOR_NAME); EasyMock.expectLastCall().andReturn(true); worker.startConnector(EasyMock.eq(CONNECTOR_NAME), EasyMock.eq(config), EasyMock.anyObject(HerderConnectorContext.class), EasyMock.eq(herder), EasyMock.eq(TargetState.STARTED)); EasyMock.expectLastCall().andReturn(true); PowerMock.replayAll(); herder.putConnectorConfig(CONNECTOR_NAME, config, false, createCallback); FutureCallback<Void> cb = new FutureCallback<>(); herder.restartConnector(CONNECTOR_NAME, cb); cb.get(1000L, TimeUnit.MILLISECONDS); PowerMock.verifyAll(); }
### Question: StandaloneHerder extends AbstractHerder { @Override public synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb) { if (!configState.contains(taskId.connector())) cb.onCompletion(new NotFoundException("Connector " + taskId.connector() + " not found", null), null); Map<String, String> taskConfigProps = configState.taskConfig(taskId); if (taskConfigProps == null) cb.onCompletion(new NotFoundException("Task " + taskId + " not found", null), null); Map<String, String> connConfigProps = configState.connectorConfig(taskId.connector()); TargetState targetState = configState.targetState(taskId.connector()); worker.stopAndAwaitTask(taskId); if (worker.startTask(taskId, connConfigProps, taskConfigProps, this, targetState)) cb.onCompletion(null, null); else cb.onCompletion(new ConnectException("Failed to start task: " + taskId), null); } StandaloneHerder(Worker worker); StandaloneHerder(Worker worker, String workerId, StatusBackingStore statusBackingStore, MemoryConfigBackingStore configBackingStore); synchronized void start(); synchronized void stop(); @Override int generation(); @Override synchronized void connectors(Callback<Collection<String>> callback); @Override synchronized void connectorInfo(String connName, Callback<ConnectorInfo> callback); @Override void connectorConfig(String connName, final Callback<Map<String, String>> callback); @Override synchronized void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); @Override synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback); @Override synchronized void requestTaskReconfiguration(String connName); @Override synchronized void taskConfigs(String connName, Callback<List<TaskInfo>> callback); @Override void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback); @Override synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb); @Override synchronized void restartConnector(String connName, Callback<Void> cb); }### Answer: @Test public void testRestartTask() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId(CONNECTOR_NAME, 0); expectAdd(SourceSink.SOURCE); Map<String, String> connectorConfig = connectorConfig(SourceSink.SOURCE); expectConfigValidation(connectorConfig); worker.stopAndAwaitTask(taskId); EasyMock.expectLastCall(); worker.startTask(taskId, connectorConfig, taskConfig(SourceSink.SOURCE), herder, TargetState.STARTED); EasyMock.expectLastCall().andReturn(true); PowerMock.replayAll(); herder.putConnectorConfig(CONNECTOR_NAME, connectorConfig, false, createCallback); FutureCallback<Void> cb = new FutureCallback<>(); herder.restartTask(taskId, cb); cb.get(1000L, TimeUnit.MILLISECONDS); PowerMock.verifyAll(); }
### Question: StandaloneHerder extends AbstractHerder { @Override public void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback) { throw new UnsupportedOperationException("Kafka Connect in standalone mode does not support externally setting task configurations."); } StandaloneHerder(Worker worker); StandaloneHerder(Worker worker, String workerId, StatusBackingStore statusBackingStore, MemoryConfigBackingStore configBackingStore); synchronized void start(); synchronized void stop(); @Override int generation(); @Override synchronized void connectors(Callback<Collection<String>> callback); @Override synchronized void connectorInfo(String connName, Callback<ConnectorInfo> callback); @Override void connectorConfig(String connName, final Callback<Map<String, String>> callback); @Override synchronized void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); @Override synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback); @Override synchronized void requestTaskReconfiguration(String connName); @Override synchronized void taskConfigs(String connName, Callback<List<TaskInfo>> callback); @Override void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback); @Override synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb); @Override synchronized void restartConnector(String connName, Callback<Void> cb); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testPutTaskConfigs() { Callback<Void> cb = PowerMock.createMock(Callback.class); PowerMock.replayAll(); herder.putTaskConfigs(CONNECTOR_NAME, Arrays.asList(singletonMap("config", "value")), cb); PowerMock.verifyAll(); }
### Question: PluginDesc implements Comparable<PluginDesc<T>> { @JsonProperty("location") public String location() { return location; } PluginDesc(Class<? extends T> klass, String version, ClassLoader loader); @Override String toString(); Class<? extends T> pluginClass(); @JsonProperty("class") String className(); @JsonProperty("version") String version(); PluginType type(); @JsonProperty("type") String typeName(); @JsonProperty("location") String location(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(PluginDesc other); }### Answer: @Test public void testRegularPluginDesc() throws Exception { PluginDesc<Connector> connectorDesc = new PluginDesc<>( Connector.class, regularVersion, pluginLoader ); assertPluginDesc(connectorDesc, Connector.class, regularVersion, pluginLoader.location()); PluginDesc<Converter> converterDesc = new PluginDesc<>( Converter.class, snaphotVersion, pluginLoader ); assertPluginDesc(converterDesc, Converter.class, snaphotVersion, pluginLoader.location()); PluginDesc<Transformation> transformDesc = new PluginDesc<>( Transformation.class, noVersion, pluginLoader ); assertPluginDesc(transformDesc, Transformation.class, noVersion, pluginLoader.location()); } @Test public void testPluginDescWithNullVersion() throws Exception { String nullVersion = "null"; PluginDesc<SourceConnector> connectorDesc = new PluginDesc<>( SourceConnector.class, null, pluginLoader ); assertPluginDesc( connectorDesc, SourceConnector.class, nullVersion, pluginLoader.location() ); String location = "classpath"; PluginDesc<Converter> converterDesc = new PluginDesc<>( Converter.class, null, systemLoader ); assertPluginDesc(converterDesc, Converter.class, nullVersion, location); } @Test public void testRegularPluginDesc() { PluginDesc<Connector> connectorDesc = new PluginDesc<>( Connector.class, regularVersion, pluginLoader ); assertPluginDesc(connectorDesc, Connector.class, regularVersion, pluginLoader.location()); PluginDesc<Converter> converterDesc = new PluginDesc<>( Converter.class, snaphotVersion, pluginLoader ); assertPluginDesc(converterDesc, Converter.class, snaphotVersion, pluginLoader.location()); PluginDesc<Transformation> transformDesc = new PluginDesc<>( Transformation.class, noVersion, pluginLoader ); assertPluginDesc(transformDesc, Transformation.class, noVersion, pluginLoader.location()); } @Test public void testPluginDescWithNullVersion() { String nullVersion = "null"; PluginDesc<SourceConnector> connectorDesc = new PluginDesc<>( SourceConnector.class, null, pluginLoader ); assertPluginDesc( connectorDesc, SourceConnector.class, nullVersion, pluginLoader.location() ); String location = "classpath"; PluginDesc<Converter> converterDesc = new PluginDesc<>( Converter.class, null, systemLoader ); assertPluginDesc(converterDesc, Converter.class, nullVersion, location); }
### Question: PluginDesc implements Comparable<PluginDesc<T>> { @Override public int hashCode() { return Objects.hash(klass, version, type); } PluginDesc(Class<? extends T> klass, String version, ClassLoader loader); @Override String toString(); Class<? extends T> pluginClass(); @JsonProperty("class") String className(); @JsonProperty("version") String version(); PluginType type(); @JsonProperty("type") String typeName(); @JsonProperty("location") String location(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(PluginDesc other); }### Answer: @Test public void testPluginDescEquality() throws Exception { PluginDesc<Connector> connectorDescPluginPath = new PluginDesc<>( Connector.class, snaphotVersion, pluginLoader ); PluginDesc<Connector> connectorDescClasspath = new PluginDesc<>( Connector.class, snaphotVersion, systemLoader ); assertEquals(connectorDescPluginPath, connectorDescClasspath); assertEquals(connectorDescPluginPath.hashCode(), connectorDescClasspath.hashCode()); PluginDesc<Converter> converterDescPluginPath = new PluginDesc<>( Converter.class, noVersion, pluginLoader ); PluginDesc<Converter> converterDescClasspath = new PluginDesc<>( Converter.class, noVersion, systemLoader ); assertEquals(converterDescPluginPath, converterDescClasspath); assertEquals(converterDescPluginPath.hashCode(), converterDescClasspath.hashCode()); PluginDesc<Transformation> transformDescPluginPath = new PluginDesc<>( Transformation.class, null, pluginLoader ); PluginDesc<Transformation> transformDescClasspath = new PluginDesc<>( Transformation.class, noVersion, pluginLoader ); assertNotEquals(transformDescPluginPath, transformDescClasspath); } @Test public void testPluginDescEquality() { PluginDesc<Connector> connectorDescPluginPath = new PluginDesc<>( Connector.class, snaphotVersion, pluginLoader ); PluginDesc<Connector> connectorDescClasspath = new PluginDesc<>( Connector.class, snaphotVersion, systemLoader ); assertEquals(connectorDescPluginPath, connectorDescClasspath); assertEquals(connectorDescPluginPath.hashCode(), connectorDescClasspath.hashCode()); PluginDesc<Converter> converterDescPluginPath = new PluginDesc<>( Converter.class, noVersion, pluginLoader ); PluginDesc<Converter> converterDescClasspath = new PluginDesc<>( Converter.class, noVersion, systemLoader ); assertEquals(converterDescPluginPath, converterDescClasspath); assertEquals(converterDescPluginPath.hashCode(), converterDescClasspath.hashCode()); PluginDesc<Transformation> transformDescPluginPath = new PluginDesc<>( Transformation.class, null, pluginLoader ); PluginDesc<Transformation> transformDescClasspath = new PluginDesc<>( Transformation.class, noVersion, pluginLoader ); assertNotEquals(transformDescPluginPath, transformDescClasspath); }
### Question: DistributedHerder extends AbstractHerder implements Runnable { HerderRequest addRequest(Callable<Void> action, Callback<Void> callback) { return addRequest(0, action, callback); } DistributedHerder(DistributedConfig config, Time time, Worker worker, StatusBackingStore statusBackingStore, ConfigBackingStore configBackingStore, String restUrl); DistributedHerder(DistributedConfig config, Worker worker, String workerId, StatusBackingStore statusBackingStore, ConfigBackingStore configBackingStore, WorkerGroupMember member, String restUrl, Time time); @Override void start(); @Override void run(); void tick(); void halt(); @Override void stop(); @Override void connectors(final Callback<Collection<String>> callback); @Override void connectorInfo(final String connName, final Callback<ConnectorInfo> callback); @Override void connectorConfig(String connName, final Callback<Map<String, String>> callback); @Override void deleteConnectorConfig(final String connName, final Callback<Created<ConnectorInfo>> callback); @Override void putConnectorConfig(final String connName, final Map<String, String> config, final boolean allowReplace, final Callback<Created<ConnectorInfo>> callback); @Override void requestTaskReconfiguration(final String connName); @Override void taskConfigs(final String connName, final Callback<List<TaskInfo>> callback); @Override void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback); @Override void restartConnector(final String connName, final Callback<Void> callback); @Override void restartTask(final ConnectorTaskId id, final Callback<Void> callback); @Override int generation(); }### Answer: @Test public void testRequestProcessingOrder() throws Exception { final DistributedHerder.HerderRequest req1 = herder.addRequest(100, null, null); final DistributedHerder.HerderRequest req2 = herder.addRequest(10, null, null); final DistributedHerder.HerderRequest req3 = herder.addRequest(200, null, null); final DistributedHerder.HerderRequest req4 = herder.addRequest(200, null, null); assertEquals(req2, herder.requests.pollFirst()); assertEquals(req1, herder.requests.pollFirst()); assertEquals(req3, herder.requests.pollFirst()); assertEquals(req4, herder.requests.pollFirst()); }
### Question: WorkerCoordinator extends AbstractCoordinator implements Closeable { public String memberId() { Generation generation = generation(); if (generation != null) return generation.memberId; return JoinGroupRequest.UNKNOWN_MEMBER_ID; } WorkerCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, String restUrl, ConfigBackingStore configStorage, WorkerRebalanceListener listener); void requestRejoin(); @Override String protocolType(); void poll(long timeout); @Override List<ProtocolMetadata> metadata(); String memberId(); String ownerUrl(String connector); String ownerUrl(ConnectorTaskId task); static final String DEFAULT_SUBPROTOCOL; }### Answer: @Test public void testJoinLeaderCannotAssign() { EasyMock.expect(configStorage.snapshot()).andReturn(configState1); EasyMock.expect(configStorage.snapshot()).andReturn(configState2); PowerMock.replayAll(); final String memberId = "member"; client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(); client.prepareResponse(joinGroupFollowerResponse(1, memberId, "leader", Errors.NONE)); MockClient.RequestMatcher matcher = new MockClient.RequestMatcher() { @Override public boolean matches(AbstractRequest body) { SyncGroupRequest sync = (SyncGroupRequest) body; return sync.memberId().equals(memberId) && sync.generationId() == 1 && sync.groupAssignment().isEmpty(); } }; client.prepareResponse(matcher, syncGroupResponse(ConnectProtocol.Assignment.CONFIG_MISMATCH, "leader", 10L, Collections.<String>emptyList(), Collections.<ConnectorTaskId>emptyList(), Errors.NONE)); client.prepareResponse(joinGroupFollowerResponse(1, memberId, "leader", Errors.NONE)); client.prepareResponse(matcher, syncGroupResponse(ConnectProtocol.Assignment.NO_ERROR, "leader", 1L, Collections.<String>emptyList(), Collections.singletonList(taskId1x0), Errors.NONE)); coordinator.ensureActiveGroup(); PowerMock.verifyAll(); }
### Question: WorkerCoordinator extends AbstractCoordinator implements Closeable { public void requestRejoin() { rejoinRequested = true; } WorkerCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, String restUrl, ConfigBackingStore configStorage, WorkerRebalanceListener listener); void requestRejoin(); @Override String protocolType(); void poll(long timeout); @Override List<ProtocolMetadata> metadata(); String memberId(); String ownerUrl(String connector); String ownerUrl(ConnectorTaskId task); static final String DEFAULT_SUBPROTOCOL; }### Answer: @Test public void testRejoinGroup() { EasyMock.expect(configStorage.snapshot()).andReturn(configState1); EasyMock.expect(configStorage.snapshot()).andReturn(configState1); PowerMock.replayAll(); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(); client.prepareResponse(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); client.prepareResponse(syncGroupResponse(ConnectProtocol.Assignment.NO_ERROR, "leader", 1L, Collections.<String>emptyList(), Collections.singletonList(taskId1x0), Errors.NONE)); coordinator.ensureActiveGroup(); assertEquals(0, rebalanceListener.revokedCount); assertEquals(1, rebalanceListener.assignedCount); assertFalse(rebalanceListener.assignment.failed()); assertEquals(1L, rebalanceListener.assignment.offset()); assertEquals(Collections.emptyList(), rebalanceListener.assignment.connectors()); assertEquals(Collections.singletonList(taskId1x0), rebalanceListener.assignment.tasks()); coordinator.requestRejoin(); client.prepareResponse(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); client.prepareResponse(syncGroupResponse(ConnectProtocol.Assignment.NO_ERROR, "leader", 1L, Collections.singletonList(connectorId1), Collections.<ConnectorTaskId>emptyList(), Errors.NONE)); coordinator.ensureActiveGroup(); assertEquals(1, rebalanceListener.revokedCount); assertEquals(Collections.emptyList(), rebalanceListener.revokedConnectors); assertEquals(Collections.singletonList(taskId1x0), rebalanceListener.revokedTasks); assertEquals(2, rebalanceListener.assignedCount); assertFalse(rebalanceListener.assignment.failed()); assertEquals(1L, rebalanceListener.assignment.offset()); assertEquals(Collections.singletonList(connectorId1), rebalanceListener.assignment.connectors()); assertEquals(Collections.emptyList(), rebalanceListener.assignment.tasks()); PowerMock.verifyAll(); }
### Question: SourceTaskOffsetCommitter { public void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask) { long commitIntervalMs = config.getLong(WorkerConfig.OFFSET_COMMIT_INTERVAL_MS_CONFIG); ScheduledFuture<?> commitFuture = commitExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { commit(workerTask); } }, commitIntervalMs, commitIntervalMs, TimeUnit.MILLISECONDS); committers.put(id, commitFuture); } SourceTaskOffsetCommitter(WorkerConfig config, ScheduledExecutorService commitExecutorService, ConcurrentMap<ConnectorTaskId, ScheduledFuture<?>> committers); SourceTaskOffsetCommitter(WorkerConfig config); void close(long timeoutMs); void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask); void remove(ConnectorTaskId id); }### Answer: @Test public void testSchedule() throws Exception { Capture<Runnable> taskWrapper = EasyMock.newCapture(); ScheduledFuture commitFuture = PowerMock.createMock(ScheduledFuture.class); EasyMock.expect(executor.scheduleWithFixedDelay( EasyMock.capture(taskWrapper), eq(DEFAULT_OFFSET_COMMIT_INTERVAL_MS), eq(DEFAULT_OFFSET_COMMIT_INTERVAL_MS), eq(TimeUnit.MILLISECONDS)) ).andReturn(commitFuture); ConnectorTaskId taskId = PowerMock.createMock(ConnectorTaskId.class); WorkerSourceTask task = PowerMock.createMock(WorkerSourceTask.class); EasyMock.expect(committers.put(taskId, commitFuture)).andReturn(null); PowerMock.replayAll(); committer.schedule(taskId, task); assertTrue(taskWrapper.hasCaptured()); assertNotNull(taskWrapper.getValue()); PowerMock.verifyAll(); }
### Question: SourceTaskOffsetCommitter { public void remove(ConnectorTaskId id) { final ScheduledFuture<?> task = committers.remove(id); if (task == null) return; try { task.cancel(false); if (!task.isDone()) task.get(); } catch (CancellationException e) { log.trace("Offset commit thread was cancelled by another thread while removing connector task with id: {}", id); } catch (ExecutionException | InterruptedException e) { throw new ConnectException("Unexpected interruption in SourceTaskOffsetCommitter while removing task with id: " + id, e); } } SourceTaskOffsetCommitter(WorkerConfig config, ScheduledExecutorService commitExecutorService, ConcurrentMap<ConnectorTaskId, ScheduledFuture<?>> committers); SourceTaskOffsetCommitter(WorkerConfig config); void close(long timeoutMs); void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask); void remove(ConnectorTaskId id); }### Answer: @Test public void testRemove() throws Exception { ConnectorTaskId taskId = PowerMock.createMock(ConnectorTaskId.class); ScheduledFuture task = PowerMock.createMock(ScheduledFuture.class); EasyMock.expect(committers.remove(taskId)).andReturn(null); PowerMock.replayAll(); committer.remove(taskId); PowerMock.verifyAll(); PowerMock.resetAll(); EasyMock.expect(committers.remove(taskId)).andReturn(task); EasyMock.expect(task.cancel(eq(false))).andReturn(false); EasyMock.expect(task.isDone()).andReturn(false); EasyMock.expect(task.get()).andReturn(null); PowerMock.replayAll(); committer.remove(taskId); PowerMock.verifyAll(); PowerMock.resetAll(); EasyMock.expect(committers.remove(taskId)).andReturn(task); EasyMock.expect(task.cancel(eq(false))).andReturn(false); EasyMock.expect(task.isDone()).andReturn(false); EasyMock.expect(task.get()).andThrow(new CancellationException()); mockLog.trace(EasyMock.anyString(), EasyMock.<Object>anyObject()); PowerMock.expectLastCall(); PowerMock.replayAll(); committer.remove(taskId); PowerMock.verifyAll(); PowerMock.resetAll(); EasyMock.expect(committers.remove(taskId)).andReturn(task); EasyMock.expect(task.cancel(eq(false))).andReturn(false); EasyMock.expect(task.isDone()).andReturn(false); EasyMock.expect(task.get()).andThrow(new InterruptedException()); PowerMock.replayAll(); try { committer.remove(taskId); fail("Expected ConnectException to be raised"); } catch (ConnectException e) { } PowerMock.verifyAll(); }
### Question: OffsetStorageWriter { public synchronized boolean beginFlush() { if (flushing()) { log.error("Invalid call to OffsetStorageWriter flush() while already flushing, the " + "framework should not allow this"); throw new ConnectException("OffsetStorageWriter is already flushing"); } if (data.isEmpty()) return false; assert !flushing(); toFlush = data; data = new HashMap<>(); return true; } OffsetStorageWriter(OffsetBackingStore backingStore, String namespace, Converter keyConverter, Converter valueConverter); synchronized void offset(Map<String, ?> partition, Map<String, ?> offset); synchronized boolean beginFlush(); Future<Void> doFlush(final Callback<Void> callback); synchronized void cancelFlush(); }### Answer: @Test public void testNoOffsetsToFlush() { PowerMock.replayAll(); assertFalse(writer.beginFlush()); PowerMock.verifyAll(); }
### Question: Time { public static int fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Time object but the schema does not match."); Calendar calendar = Calendar.getInstance(UTC); calendar.setTime(value); long unixMillis = calendar.getTimeInMillis(); if (unixMillis < 0 || unixMillis > MILLIS_PER_DAY) { throw new DataException("Kafka Connect Time type should not have any date fields set to non-zero values."); } return (int) unixMillis; } static SchemaBuilder builder(); static int fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, int value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testFromLogical() { assertEquals(0, Time.fromLogical(Time.SCHEMA, EPOCH.getTime())); assertEquals(10000, Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime())); } @Test(expected = DataException.class) public void testFromLogicalInvalidHasDateComponents() { Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_DATE_COMPONENT.getTime()); }
### Question: Time { public static java.util.Date toLogical(Schema schema, int value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); if (value < 0 || value > MILLIS_PER_DAY) throw new DataException("Time values must use number of milliseconds greater than 0 and less than 86400000"); return new java.util.Date(value); } static SchemaBuilder builder(); static int fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, int value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Time.toLogical(Time.SCHEMA, 0)); assertEquals(EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime(), Time.toLogical(Time.SCHEMA, 10000)); }
### Question: Struct { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Struct struct = (Struct) o; return Objects.equals(schema, struct.schema) && Arrays.equals(values, struct.values); } Struct(Schema schema); Schema schema(); Object get(String fieldName); Object get(Field field); Object getWithoutDefault(String fieldName); Byte getInt8(String fieldName); Short getInt16(String fieldName); Integer getInt32(String fieldName); Long getInt64(String fieldName); Float getFloat32(String fieldName); Double getFloat64(String fieldName); Boolean getBoolean(String fieldName); String getString(String fieldName); byte[] getBytes(String fieldName); @SuppressWarnings("unchecked") List<T> getArray(String fieldName); @SuppressWarnings("unchecked") Map<K, V> getMap(String fieldName); Struct getStruct(String fieldName); Struct put(String fieldName, Object value); Struct put(Field field, Object value); void validate(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testEquals() { Struct struct1 = new Struct(FLAT_STRUCT_SCHEMA) .put("int8", (byte) 12) .put("int16", (short) 12) .put("int32", 12) .put("int64", (long) 12) .put("float32", 12.f) .put("float64", 12.) .put("boolean", true) .put("string", "foobar") .put("bytes", ByteBuffer.wrap("foobar".getBytes())); Struct struct2 = new Struct(FLAT_STRUCT_SCHEMA) .put("int8", (byte) 12) .put("int16", (short) 12) .put("int32", 12) .put("int64", (long) 12) .put("float32", 12.f) .put("float64", 12.) .put("boolean", true) .put("string", "foobar") .put("bytes", ByteBuffer.wrap("foobar".getBytes())); Struct struct3 = new Struct(FLAT_STRUCT_SCHEMA) .put("int8", (byte) 12) .put("int16", (short) 12) .put("int32", 12) .put("int64", (long) 12) .put("float32", 12.f) .put("float64", 12.) .put("boolean", true) .put("string", "mismatching string") .put("bytes", ByteBuffer.wrap("foobar".getBytes())); assertEquals(struct1, struct2); assertNotEquals(struct1, struct3); List<Byte> array = Arrays.asList((byte) 1, (byte) 2); Map<Integer, String> map = Collections.singletonMap(1, "string"); struct1 = new Struct(NESTED_SCHEMA) .put("array", array) .put("map", map) .put("nested", new Struct(NESTED_CHILD_SCHEMA).put("int8", (byte) 12)); List<Byte> array2 = Arrays.asList((byte) 1, (byte) 2); Map<Integer, String> map2 = Collections.singletonMap(1, "string"); struct2 = new Struct(NESTED_SCHEMA) .put("array", array2) .put("map", map2) .put("nested", new Struct(NESTED_CHILD_SCHEMA).put("int8", (byte) 12)); List<Byte> array3 = Arrays.asList((byte) 1, (byte) 2, (byte) 3); Map<Integer, String> map3 = Collections.singletonMap(2, "string"); struct3 = new Struct(NESTED_SCHEMA) .put("array", array3) .put("map", map3) .put("nested", new Struct(NESTED_CHILD_SCHEMA).put("int8", (byte) 13)); assertEquals(struct1, struct2); assertNotEquals(struct1, struct3); }
### Question: ConnectSchema implements Schema { @Override public List<Field> fields() { if (type != Type.STRUCT) throw new DataException("Cannot list fields on non-struct type"); return fields; } ConnectSchema(Type type, boolean optional, Object defaultValue, String name, Integer version, String doc, Map<String, String> parameters, List<Field> fields, Schema keySchema, Schema valueSchema); ConnectSchema(Type type, boolean optional, Object defaultValue, String name, Integer version, String doc); ConnectSchema(Type type); @Override Type type(); @Override boolean isOptional(); @Override Object defaultValue(); @Override String name(); @Override Integer version(); @Override String doc(); @Override Map<String, String> parameters(); @Override List<Field> fields(); Field field(String fieldName); @Override Schema keySchema(); @Override Schema valueSchema(); static void validateValue(Schema schema, Object value); static void validateValue(String name, Schema schema, Object value); void validateValue(Object value); @Override ConnectSchema schema(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Type schemaType(Class<?> klass); }### Answer: @Test(expected = DataException.class) public void testFieldsOnlyValidForStructs() { Schema.INT8_SCHEMA.fields(); } @Test public void testEmptyStruct() { final ConnectSchema emptyStruct = new ConnectSchema(Schema.Type.STRUCT, false, null, null, null, null); assertEquals(0, emptyStruct.fields().size()); new Struct(emptyStruct); }
### Question: SchemaBuilder implements Schema { @Override public Map<String, String> parameters() { return parameters == null ? null : Collections.unmodifiableMap(parameters); } SchemaBuilder(Type type); @Override boolean isOptional(); SchemaBuilder optional(); SchemaBuilder required(); @Override Object defaultValue(); SchemaBuilder defaultValue(Object value); @Override String name(); SchemaBuilder name(String name); @Override Integer version(); SchemaBuilder version(Integer version); @Override String doc(); SchemaBuilder doc(String doc); @Override Map<String, String> parameters(); SchemaBuilder parameter(String propertyName, String propertyValue); SchemaBuilder parameters(Map<String, String> props); @Override Type type(); static SchemaBuilder type(Type type); static SchemaBuilder int8(); static SchemaBuilder int16(); static SchemaBuilder int32(); static SchemaBuilder int64(); static SchemaBuilder float32(); static SchemaBuilder float64(); static SchemaBuilder bool(); static SchemaBuilder string(); static SchemaBuilder bytes(); static SchemaBuilder struct(); SchemaBuilder field(String fieldName, Schema fieldSchema); List<Field> fields(); Field field(String fieldName); static SchemaBuilder array(Schema valueSchema); static SchemaBuilder map(Schema keySchema, Schema valueSchema); @Override Schema keySchema(); @Override Schema valueSchema(); Schema build(); @Override Schema schema(); }### Answer: @Test public void testParameters() { Map<String, String> expectedParameters = new HashMap<>(); expectedParameters.put("foo", "val"); expectedParameters.put("bar", "baz"); Schema schema = SchemaBuilder.string().parameter("foo", "val").parameter("bar", "baz").build(); assertTypeAndDefault(schema, Schema.Type.STRING, false, null); assertMetadata(schema, null, null, null, expectedParameters); schema = SchemaBuilder.string().parameters(expectedParameters).build(); assertTypeAndDefault(schema, Schema.Type.STRING, false, null); assertMetadata(schema, null, null, null, expectedParameters); }
### Question: Date { public static int fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); Calendar calendar = Calendar.getInstance(UTC); calendar.setTime(value); if (calendar.get(Calendar.HOUR_OF_DAY) != 0 || calendar.get(Calendar.MINUTE) != 0 || calendar.get(Calendar.SECOND) != 0 || calendar.get(Calendar.MILLISECOND) != 0) { throw new DataException("Kafka Connect Date type should not have any time fields set to non-zero values."); } long unixMillis = calendar.getTimeInMillis(); return (int) (unixMillis / MILLIS_PER_DAY); } static SchemaBuilder builder(); static int fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, int value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testFromLogical() { assertEquals(0, Date.fromLogical(Date.SCHEMA, EPOCH.getTime())); assertEquals(10000, Date.fromLogical(Date.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_DAYS.getTime())); } @Test(expected = DataException.class) public void testFromLogicalInvalidHasTimeComponents() { Date.fromLogical(Date.SCHEMA, EPOCH_PLUS_TIME_COMPONENT.getTime()); }
### Question: Date { public static java.util.Date toLogical(Schema schema, int value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); return new java.util.Date(value * MILLIS_PER_DAY); } static SchemaBuilder builder(); static int fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, int value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Date.toLogical(Date.SCHEMA, 0)); assertEquals(EPOCH_PLUS_TEN_THOUSAND_DAYS.getTime(), Date.toLogical(Date.SCHEMA, 10000)); }
### Question: Timestamp { public static long fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Timestamp object but the schema does not match."); return value.getTime(); } static SchemaBuilder builder(); static long fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, long value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testFromLogical() { assertEquals(0L, Timestamp.fromLogical(Timestamp.SCHEMA, EPOCH.getTime())); assertEquals(TOTAL_MILLIS, Timestamp.fromLogical(Timestamp.SCHEMA, EPOCH_PLUS_MILLIS.getTime())); }
### Question: Timestamp { public static java.util.Date toLogical(Schema schema, long value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Timestamp object but the schema does not match."); return new java.util.Date(value); } static SchemaBuilder builder(); static long fromLogical(Schema schema, java.util.Date value); static java.util.Date toLogical(Schema schema, long value); static final String LOGICAL_NAME; static final Schema SCHEMA; }### Answer: @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, 0L)); assertEquals(EPOCH_PLUS_MILLIS.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, TOTAL_MILLIS)); }
### Question: ConnectorUtils { public static <T> List<List<T>> groupPartitions(List<T> elements, int numGroups) { if (numGroups <= 0) throw new IllegalArgumentException("Number of groups must be positive."); List<List<T>> result = new ArrayList<>(numGroups); int perGroup = elements.size() / numGroups; int leftover = elements.size() - (numGroups * perGroup); int assigned = 0; for (int group = 0; group < numGroups; group++) { int numThisGroup = group < leftover ? perGroup + 1 : perGroup; List<T> groupList = new ArrayList<>(numThisGroup); for (int i = 0; i < numThisGroup; i++) { groupList.add(elements.get(assigned)); assigned++; } result.add(groupList); } return result; } static List<List<T>> groupPartitions(List<T> elements, int numGroups); }### Answer: @Test public void testGroupPartitions() { List<List<Integer>> grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 1); assertEquals(Arrays.asList(FIVE_ELEMENTS), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 2); assertEquals(Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 3); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 5); assertEquals(Arrays.asList(Arrays.asList(1), Arrays.asList(2), Arrays.asList(3), Arrays.asList(4), Arrays.asList(5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 7); assertEquals(Arrays.asList(Arrays.asList(1), Arrays.asList(2), Arrays.asList(3), Arrays.asList(4), Arrays.asList(5), Collections.EMPTY_LIST, Collections.EMPTY_LIST), grouped); } @Test public void testGroupPartitions() { List<List<Integer>> grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 1); assertEquals(Arrays.asList(FIVE_ELEMENTS), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 2); assertEquals(Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 3); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 5); assertEquals(Arrays.asList(Arrays.asList(1), Arrays.asList(2), Arrays.asList(3), Arrays.asList(4), Arrays.asList(5)), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 7); assertEquals(Arrays.asList(Arrays.asList(1), Arrays.asList(2), Arrays.asList(3), Arrays.asList(4), Arrays.asList(5), Collections.emptyList(), Collections.emptyList()), grouped); } @Test(expected = IllegalArgumentException.class) public void testGroupPartitionsInvalidCount() { ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 0); }
### Question: StringConverter implements Converter { @Override public byte[] fromConnectData(String topic, Schema schema, Object value) { try { return serializer.serialize(topic, value == null ? null : value.toString()); } catch (SerializationException e) { throw new DataException("Failed to serialize to a string: ", e); } } StringConverter(); @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] fromConnectData(String topic, Schema schema, Object value); @Override SchemaAndValue toConnectData(String topic, byte[] value); }### Answer: @Test public void testStringToBytes() throws UnsupportedEncodingException { assertArrayEquals(SAMPLE_STRING.getBytes("UTF8"), converter.fromConnectData(TOPIC, Schema.STRING_SCHEMA, SAMPLE_STRING)); } @Test public void testNonStringToBytes() throws UnsupportedEncodingException { assertArrayEquals("true".getBytes("UTF8"), converter.fromConnectData(TOPIC, Schema.BOOLEAN_SCHEMA, true)); } @Test public void testNullToBytes() { assertEquals(null, converter.fromConnectData(TOPIC, Schema.OPTIONAL_STRING_SCHEMA, null)); } @Test public void testToBytesIgnoresSchema() throws UnsupportedEncodingException { assertArrayEquals("true".getBytes("UTF8"), converter.fromConnectData(TOPIC, null, true)); }
### Question: StringConverter implements Converter { @Override public SchemaAndValue toConnectData(String topic, byte[] value) { try { return new SchemaAndValue(Schema.OPTIONAL_STRING_SCHEMA, deserializer.deserialize(topic, value)); } catch (SerializationException e) { throw new DataException("Failed to deserialize string: ", e); } } StringConverter(); @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] fromConnectData(String topic, Schema schema, Object value); @Override SchemaAndValue toConnectData(String topic, byte[] value); }### Answer: @Test public void testBytesToString() { SchemaAndValue data = converter.toConnectData(TOPIC, SAMPLE_STRING.getBytes()); assertEquals(Schema.OPTIONAL_STRING_SCHEMA, data.schema()); assertEquals(SAMPLE_STRING, data.value()); } @Test public void testBytesNullToString() { SchemaAndValue data = converter.toConnectData(TOPIC, null); assertEquals(Schema.OPTIONAL_STRING_SCHEMA, data.schema()); assertEquals(null, data.value()); }
### Question: FileStreamSourceConnector extends SourceConnector { @Override public void start(Map<String, String> props) { filename = props.get(FILE_CONFIG); topic = props.get(TOPIC_CONFIG); if (topic == null || topic.isEmpty()) throw new ConnectException("FileStreamSourceConnector configuration must include 'topic' setting"); if (topic.contains(",")) throw new ConnectException("FileStreamSourceConnector should only have a single topic when used as a source."); } @Override String version(); @Override void start(Map<String, String> props); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); static final String TOPIC_CONFIG; static final String FILE_CONFIG; }### Answer: @Test(expected = ConnectException.class) public void testMultipleSourcesInvalid() { sourceProperties.put(FileStreamSourceConnector.TOPIC_CONFIG, MULTIPLE_TOPICS); connector.start(sourceProperties); }
### Question: FileStreamSourceConnector extends SourceConnector { @Override public Class<? extends Task> taskClass() { return FileStreamSourceTask.class; } @Override String version(); @Override void start(Map<String, String> props); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); static final String TOPIC_CONFIG; static final String FILE_CONFIG; }### Answer: @Test public void testTaskClass() { PowerMock.replayAll(); connector.start(sourceProperties); assertEquals(FileStreamSourceTask.class, connector.taskClass()); PowerMock.verifyAll(); }
### Question: FileStreamSinkConnector extends SinkConnector { @Override public Class<? extends Task> taskClass() { return FileStreamSinkTask.class; } @Override String version(); @Override void start(Map<String, String> props); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); static final String FILE_CONFIG; }### Answer: @Test public void testTaskClass() { PowerMock.replayAll(); connector.start(sinkProperties); assertEquals(FileStreamSinkTask.class, connector.taskClass()); PowerMock.verifyAll(); } @Test public void testTaskClass() { replayAll(); connector.start(sinkProperties); assertEquals(FileStreamSinkTask.class, connector.taskClass()); verifyAll(); }
### Question: FileStreamSourceTask extends SourceTask { @Override public void start(Map<String, String> props) { filename = props.get(FileStreamSourceConnector.FILE_CONFIG); if (filename == null || filename.isEmpty()) { stream = System.in; streamOffset = null; reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); } topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG); if (topic == null) throw new ConnectException("FileStreamSourceTask config missing topic setting"); } @Override String version(); @Override void start(Map<String, String> props); @Override List<SourceRecord> poll(); @Override void stop(); static final String FILENAME_FIELD; static final String POSITION_FIELD; }### Answer: @Test(expected = ConnectException.class) public void testMissingTopic() throws InterruptedException { replay(); config.remove(FileStreamSourceConnector.TOPIC_CONFIG); task.start(config); }
### Question: ApiVersions { public synchronized byte maxUsableProduceMagic() { return maxUsableProduceMagic; } synchronized void update(String nodeId, NodeApiVersions nodeApiVersions); synchronized void remove(String nodeId); synchronized NodeApiVersions get(String nodeId); synchronized byte maxUsableProduceMagic(); }### Answer: @Test public void testMaxUsableProduceMagic() { ApiVersions apiVersions = new ApiVersions(); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersions.update("0", NodeApiVersions.create()); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersions.update("1", NodeApiVersions.create(Collections.singleton( new ApiVersionsResponse.ApiVersion(ApiKeys.PRODUCE.id, (short) 0, (short) 2)))); assertEquals(RecordBatch.MAGIC_VALUE_V1, apiVersions.maxUsableProduceMagic()); apiVersions.remove("1"); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); } @Test public void testMaxUsableProduceMagic() { ApiVersions apiVersions = new ApiVersions(); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersions.update("0", NodeApiVersions.create()); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersions.update("1", NodeApiVersions.create(ApiKeys.PRODUCE.id, (short) 0, (short) 2)); assertEquals(RecordBatch.MAGIC_VALUE_V1, apiVersions.maxUsableProduceMagic()); apiVersions.remove("1"); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); }
### Question: ClientUtils { public static List<InetSocketAddress> parseAndValidateAddresses(List<String> urls) { List<InetSocketAddress> addresses = new ArrayList<>(); for (String url : urls) { if (url != null && !url.isEmpty()) { try { String host = getHost(url); Integer port = getPort(url); if (host == null || port == null) throw new ConfigException("Invalid url in " + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG + ": " + url); InetSocketAddress address = new InetSocketAddress(host, port); if (address.isUnresolved()) { log.warn("Removing server {} from {} as DNS resolution failed for {}", url, CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, host); } else { addresses.add(address); } } catch (IllegalArgumentException e) { throw new ConfigException("Invalid port in " + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG + ": " + url); } } } if (addresses.isEmpty()) throw new ConfigException("No resolvable bootstrap urls given in " + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG); return addresses; } static List<InetSocketAddress> parseAndValidateAddresses(List<String> urls); static void closeQuietly(Closeable c, String name, AtomicReference<Throwable> firstException); static ChannelBuilder createChannelBuilder(AbstractConfig config); }### Answer: @Test public void testParseAndValidateAddresses() { check("127.0.0.1:8000"); check("mydomain.com:8080"); check("[::1]:8000"); check("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:1234", "mydomain.com:10000"); List<InetSocketAddress> validatedAddresses = check("some.invalid.hostname.foo.bar.local:9999", "mydomain.com:10000"); assertEquals(1, validatedAddresses.size()); InetSocketAddress onlyAddress = validatedAddresses.get(0); assertEquals("mydomain.com", onlyAddress.getHostName()); assertEquals(10000, onlyAddress.getPort()); }
### Question: NetworkClient implements KafkaClient { @Override public long connectionDelay(Node node, long now) { return connectionStates.connectionDelay(node.idString(), now); } NetworkClient(Selectable selector, Metadata metadata, String clientId, int maxInFlightRequestsPerConnection, long reconnectBackoffMs, long reconnectBackoffMax, int socketSendBuffer, int socketReceiveBuffer, int requestTimeoutMs, Time time, boolean discoverBrokerVersions, ApiVersions apiVersions); NetworkClient(Selectable selector, Metadata metadata, String clientId, int maxInFlightRequestsPerConnection, long reconnectBackoffMs, long reconnectBackoffMax, int socketSendBuffer, int socketReceiveBuffer, int requestTimeoutMs, Time time, boolean discoverBrokerVersions, ApiVersions apiVersions, Sensor throttleTimeSensor); NetworkClient(Selectable selector, MetadataUpdater metadataUpdater, String clientId, int maxInFlightRequestsPerConnection, long reconnectBackoffMs, long reconnectBackoffMax, int socketSendBuffer, int socketReceiveBuffer, int requestTimeoutMs, Time time, boolean discoverBrokerVersions, ApiVersions apiVersions); private NetworkClient(MetadataUpdater metadataUpdater, Metadata metadata, Selectable selector, String clientId, int maxInFlightRequestsPerConnection, long reconnectBackoffMs, long reconnectBackoffMax, int socketSendBuffer, int socketReceiveBuffer, int requestTimeoutMs, Time time, boolean discoverBrokerVersions, ApiVersions apiVersions, Sensor throttleTimeSensor); @Override // 检测是否可以向一个Node发送请求 boolean ready(Node node, long now); @Override void disconnect(String nodeId); @Override void close(String nodeId); @Override long connectionDelay(Node node, long now); @Override boolean connectionFailed(Node node); @Override boolean isReady(Node node, long now); @Override void send(ClientRequest request, long now); @Override // 调用Selector.poll 进行网络IO // 执行完成后 触发回调逻辑 List<ClientResponse> poll(long timeout, long now); @Override int inFlightRequestCount(); @Override boolean hasInFlightRequests(); @Override int inFlightRequestCount(String node); @Override boolean hasInFlightRequests(String node); @Override boolean hasReadyNodes(); @Override void wakeup(); @Override void close(); @Override Node leastLoadedNode(long now); static AbstractResponse parseResponse(ByteBuffer responseBuffer, RequestHeader requestHeader); @Override ClientRequest newClientRequest(String nodeId, AbstractRequest.Builder<?> requestBuilder, long createdTimeMs, boolean expectResponse); @Override ClientRequest newClientRequest(String nodeId, AbstractRequest.Builder<?> requestBuilder, long createdTimeMs, boolean expectResponse, RequestCompletionHandler callback); boolean discoverBrokerVersions(); }### Answer: @Test public void testConnectionDelay() { long now = time.milliseconds(); long delay = client.connectionDelay(node, now); assertEquals(0, delay); } @Test public void testConnectionDelayConnected() { awaitReady(client, node); long now = time.milliseconds(); long delay = client.connectionDelay(node, now); assertEquals(Long.MAX_VALUE, delay); }
### Question: NodeApiVersions { @Override public String toString() { return toString(false); } NodeApiVersions(Collection<ApiVersion> nodeApiVersions); static NodeApiVersions create(); static NodeApiVersions create(Collection<ApiVersion> overrides); short usableVersion(ApiKeys apiKey); short usableVersion(ApiKeys apiKey, Short desiredVersion); @Override String toString(); String toString(boolean lineBreaks); ApiVersion apiVersion(ApiKeys apiKey); }### Answer: @Test public void testUnsupportedVersionsToString() { NodeApiVersions versions = new NodeApiVersions(Collections.<ApiVersion>emptyList()); StringBuilder bld = new StringBuilder(); String prefix = "("; for (ApiKeys apiKey : ApiKeys.values()) { bld.append(prefix).append(apiKey.name). append("(").append(apiKey.id).append("): UNSUPPORTED"); prefix = ", "; } bld.append(")"); assertEquals(bld.toString(), versions.toString()); } @Test public void testUnknownApiVersionsToString() { ApiVersion unknownApiVersion = new ApiVersion((short) 337, (short) 0, (short) 1); NodeApiVersions versions = new NodeApiVersions(Collections.singleton(unknownApiVersion)); assertTrue(versions.toString().endsWith("UNKNOWN(337): 0 to 1)")); } @Test public void testVersionsToString() { List<ApiVersion> versionList = new ArrayList<>(); for (ApiKeys apiKey : ApiKeys.values()) { if (apiKey == ApiKeys.CONTROLLED_SHUTDOWN_KEY) { versionList.add(new ApiVersion(apiKey.id, (short) 0, (short) 0)); } else if (apiKey == ApiKeys.DELETE_TOPICS) { versionList.add(new ApiVersion(apiKey.id, (short) 10000, (short) 10001)); } else { versionList.add(new ApiVersion(apiKey)); } } NodeApiVersions versions = new NodeApiVersions(versionList); StringBuilder bld = new StringBuilder(); String prefix = "("; for (ApiKeys apiKey : ApiKeys.values()) { bld.append(prefix); if (apiKey == ApiKeys.CONTROLLED_SHUTDOWN_KEY) { bld.append("ControlledShutdown(7): 0 [unusable: node too old]"); } else if (apiKey == ApiKeys.DELETE_TOPICS) { bld.append("DeleteTopics(20): 10000 to 10001 [unusable: node too new]"); } else { bld.append(apiKey.name).append("("). append(apiKey.id).append("): "); if (apiKey.oldestVersion() == apiKey.latestVersion()) { bld.append(apiKey.oldestVersion()); } else { bld.append(apiKey.oldestVersion()). append(" to "). append(apiKey.latestVersion()); } bld.append(" [usable: ").append(apiKey.latestVersion()). append("]"); } prefix = ", "; } bld.append(")"); assertEquals(bld.toString(), versions.toString()); }
### Question: NodeApiVersions { public short usableVersion(ApiKeys apiKey) { return usableVersion(apiKey, null); } NodeApiVersions(Collection<ApiVersion> nodeApiVersions); static NodeApiVersions create(); static NodeApiVersions create(Collection<ApiVersion> overrides); short usableVersion(ApiKeys apiKey); short usableVersion(ApiKeys apiKey, Short desiredVersion); @Override String toString(); String toString(boolean lineBreaks); ApiVersion apiVersion(ApiKeys apiKey); }### Answer: @Test public void testUsableVersionCalculation() { List<ApiVersion> versionList = new ArrayList<>(); versionList.add(new ApiVersion(ApiKeys.CONTROLLED_SHUTDOWN_KEY.id, (short) 0, (short) 0)); versionList.add(new ApiVersion(ApiKeys.FETCH.id, (short) 1, (short) 2)); NodeApiVersions versions = new NodeApiVersions(versionList); try { versions.usableVersion(ApiKeys.CONTROLLED_SHUTDOWN_KEY); Assert.fail("expected UnsupportedVersionException"); } catch (UnsupportedVersionException e) { } assertEquals(2, versions.usableVersion(ApiKeys.FETCH)); } @Test(expected = UnsupportedVersionException.class) public void testUsableVersionCalculationNoKnownVersions() { List<ApiVersion> versionList = new ArrayList<>(); NodeApiVersions versions = new NodeApiVersions(versionList); versions.usableVersion(ApiKeys.FETCH); } @Test public void testUsableVersionLatestVersions() { List<ApiVersion> versionList = new LinkedList<>(); for (ApiVersion apiVersion: ApiVersionsResponse.API_VERSIONS_RESPONSE.apiVersions()) { versionList.add(apiVersion); } versionList.add(new ApiVersion((short) 100, (short) 0, (short) 1)); NodeApiVersions versions = new NodeApiVersions(versionList); for (ApiKeys apiKey: ApiKeys.values()) { assertEquals(apiKey.latestVersion(), versions.usableVersion(apiKey)); } }
### Question: Fetcher implements SubscriptionState.Listener, Closeable { public Map<TopicPartition, List<ConsumerRecord<K, V>>> fetchedRecords() { Map<TopicPartition, List<ConsumerRecord<K, V>>> fetched = new HashMap<>(); int recordsRemaining = maxPollRecords; try { while (recordsRemaining > 0) { if (nextInLineRecords == null || nextInLineRecords.isFetched) { CompletedFetch completedFetch = completedFetches.peek(); if (completedFetch == null) break; nextInLineRecords = parseCompletedFetch(completedFetch); completedFetches.poll(); } else { List<ConsumerRecord<K, V>> records = fetchRecords(nextInLineRecords, recordsRemaining); TopicPartition partition = nextInLineRecords.partition; if (!records.isEmpty()) { List<ConsumerRecord<K, V>> currentRecords = fetched.get(partition); if (currentRecords == null) { fetched.put(partition, records); } else { List<ConsumerRecord<K, V>> newRecords = new ArrayList<>(records.size() + currentRecords.size()); newRecords.addAll(currentRecords); newRecords.addAll(records); fetched.put(partition, newRecords); } recordsRemaining -= records.size(); } } } } catch (KafkaException e) { if (fetched.isEmpty()) throw e; } return fetched; } Fetcher(ConsumerNetworkClient client, int minBytes, int maxBytes, int maxWaitMs, int fetchSize, int maxPollRecords, boolean checkCrcs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Metadata metadata, SubscriptionState subscriptions, Metrics metrics, FetcherMetricsRegistry metricsRegistry, Time time, long retryBackoffMs, IsolationLevel isolationLevel); boolean hasCompletedFetches(); int sendFetches(); void resetOffsetsIfNeeded(Set<TopicPartition> partitions); void updateFetchPositions(Set<TopicPartition> partitions); Map<String, List<PartitionInfo>> getAllTopicMetadata(long timeout); Map<String, List<PartitionInfo>> getTopicMetadata(MetadataRequest.Builder request, long timeout); Map<TopicPartition, OffsetAndTimestamp> getOffsetsByTimes(Map<TopicPartition, Long> timestampsToSearch, long timeout); Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, List<ConsumerRecord<K, V>>> fetchedRecords(); @Override void onAssignment(Set<TopicPartition> assignment); static Sensor throttleTimeSensor(Metrics metrics, FetcherMetricsRegistry metricsRegistry); @Override void close(); }### Answer: @Test public void testFetchRequestWhenRecordTooLarge() { try { client.setNodeApiVersions(NodeApiVersions.create(Collections.singletonList( new ApiVersionsResponse.ApiVersion(ApiKeys.FETCH.id, (short) 2, (short) 2)))); makeFetchRequestWithIncompleteRecord(); try { fetcher.fetchedRecords(); fail("RecordTooLargeException should have been raised"); } catch (RecordTooLargeException e) { assertTrue(e.getMessage().startsWith("There are some messages at [Partition=Offset]: ")); assertEquals(0, subscriptions.position(tp1).longValue()); } } finally { client.setNodeApiVersions(NodeApiVersions.create()); } } @Test public void testFetchRequestInternalError() { makeFetchRequestWithIncompleteRecord(); try { fetcher.fetchedRecords(); fail("RecordTooLargeException should have been raised"); } catch (KafkaException e) { assertTrue(e.getMessage().startsWith("Failed to make progress reading messages")); assertEquals(0, subscriptions.position(tp1).longValue()); } }
### Question: Fetcher implements SubscriptionState.Listener, Closeable { public int sendFetches() { Map<Node, FetchRequest.Builder> fetchRequestMap = createFetchRequests(); for (Map.Entry<Node, FetchRequest.Builder> fetchEntry : fetchRequestMap.entrySet()) { final FetchRequest.Builder request = fetchEntry.getValue(); final Node fetchTarget = fetchEntry.getKey(); log.debug("Sending {} fetch for partitions {} to broker {}", isolationLevel, request.fetchData().keySet(), fetchTarget); client.send(fetchTarget, request) .addListener(new RequestFutureListener<ClientResponse>() { @Override public void onSuccess(ClientResponse resp) { FetchResponse response = (FetchResponse) resp.responseBody(); if (!matchesRequestedPartitions(request, response)) { log.warn("Ignoring fetch response containing partitions {} since it does not match " + "the requested partitions {}", response.responseData().keySet(), request.fetchData().keySet()); return; } Set<TopicPartition> partitions = new HashSet<>(response.responseData().keySet()); FetchResponseMetricAggregator metricAggregator = new FetchResponseMetricAggregator(sensors, partitions); for (Map.Entry<TopicPartition, FetchResponse.PartitionData> entry : response.responseData().entrySet()) { TopicPartition partition = entry.getKey(); long fetchOffset = request.fetchData().get(partition).fetchOffset; FetchResponse.PartitionData fetchData = entry.getValue(); log.debug("Fetch {} at offset {} for partition {} returned fetch data {}", isolationLevel, fetchOffset, partition, fetchData); completedFetches.add(new CompletedFetch(partition, fetchOffset, fetchData, metricAggregator, resp.requestHeader().apiVersion())); } sensors.fetchLatency.record(resp.requestLatencyMs()); } @Override public void onFailure(RuntimeException e) { log.debug("Fetch request {} to {} failed", request.fetchData(), fetchTarget, e); } }); } return fetchRequestMap.size(); } Fetcher(ConsumerNetworkClient client, int minBytes, int maxBytes, int maxWaitMs, int fetchSize, int maxPollRecords, boolean checkCrcs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Metadata metadata, SubscriptionState subscriptions, Metrics metrics, FetcherMetricsRegistry metricsRegistry, Time time, long retryBackoffMs, IsolationLevel isolationLevel); boolean hasCompletedFetches(); int sendFetches(); void resetOffsetsIfNeeded(Set<TopicPartition> partitions); void updateFetchPositions(Set<TopicPartition> partitions); Map<String, List<PartitionInfo>> getAllTopicMetadata(long timeout); Map<String, List<PartitionInfo>> getTopicMetadata(MetadataRequest.Builder request, long timeout); Map<TopicPartition, OffsetAndTimestamp> getOffsetsByTimes(Map<TopicPartition, Long> timestampsToSearch, long timeout); Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, List<ConsumerRecord<K, V>>> fetchedRecords(); @Override void onAssignment(Set<TopicPartition> assignment); static Sensor throttleTimeSensor(Metrics metrics, FetcherMetricsRegistry metricsRegistry); @Override void close(); }### Answer: @Test public void testFetchOnPausedPartition() { subscriptions.assignFromUser(singleton(tp1)); subscriptions.seek(tp1, 0); subscriptions.pause(tp1); assertFalse(fetcher.sendFetches() > 0); assertTrue(client.requests().isEmpty()); }
### Question: Fetcher implements SubscriptionState.Listener, Closeable { public Map<String, List<PartitionInfo>> getAllTopicMetadata(long timeout) { return getTopicMetadata(MetadataRequest.Builder.allTopics(), timeout); } Fetcher(ConsumerNetworkClient client, int minBytes, int maxBytes, int maxWaitMs, int fetchSize, int maxPollRecords, boolean checkCrcs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Metadata metadata, SubscriptionState subscriptions, Metrics metrics, FetcherMetricsRegistry metricsRegistry, Time time, long retryBackoffMs, IsolationLevel isolationLevel); boolean hasCompletedFetches(); int sendFetches(); void resetOffsetsIfNeeded(Set<TopicPartition> partitions); void updateFetchPositions(Set<TopicPartition> partitions); Map<String, List<PartitionInfo>> getAllTopicMetadata(long timeout); Map<String, List<PartitionInfo>> getTopicMetadata(MetadataRequest.Builder request, long timeout); Map<TopicPartition, OffsetAndTimestamp> getOffsetsByTimes(Map<TopicPartition, Long> timestampsToSearch, long timeout); Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, long timeout); Map<TopicPartition, List<ConsumerRecord<K, V>>> fetchedRecords(); @Override void onAssignment(Set<TopicPartition> assignment); static Sensor throttleTimeSensor(Metrics metrics, FetcherMetricsRegistry metricsRegistry); @Override void close(); }### Answer: @Test public void testGetAllTopics() { client.prepareResponse(newMetadataResponse(topicName, Errors.NONE)); Map<String, List<PartitionInfo>> allTopics = fetcher.getAllTopicMetadata(5000L); assertEquals(cluster.topics().size(), allTopics.size()); } @Test public void testGetAllTopicsDisconnect() { client.prepareResponse(null, true); client.prepareResponse(newMetadataResponse(topicName, Errors.NONE)); Map<String, List<PartitionInfo>> allTopics = fetcher.getAllTopicMetadata(5000L); assertEquals(cluster.topics().size(), allTopics.size()); } @Test(expected = TimeoutException.class) public void testGetAllTopicsTimeout() { fetcher.getAllTopicMetadata(50L); } @Test public void testGetAllTopicsUnauthorized() { client.prepareResponse(newMetadataResponse(topicName, Errors.TOPIC_AUTHORIZATION_FAILED)); try { fetcher.getAllTopicMetadata(10L); fail(); } catch (TopicAuthorizationException e) { assertEquals(singleton(topicName), e.unauthorizedTopics()); } }
### Question: RequestFuture implements ConsumerNetworkClient.PollCondition { public void complete(T value) { try { if (value instanceof RuntimeException) throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException"); if (!result.compareAndSet(INCOMPLETE_SENTINEL, value)) throw new IllegalStateException("Invalid attempt to complete a request future which is already complete"); fireSuccess(); } finally { completedLatch.countDown(); } } boolean isDone(); boolean awaitDone(long timeout, TimeUnit unit); @SuppressWarnings("unchecked") T value(); boolean succeeded(); boolean failed(); boolean isRetriable(); RuntimeException exception(); void complete(T value); void raise(RuntimeException e); void raise(Errors error); void addListener(RequestFutureListener<T> listener); RequestFuture<S> compose(final RequestFutureAdapter<T, S> adapter); void chain(final RequestFuture<T> future); static RequestFuture<T> failure(RuntimeException e); static RequestFuture<Void> voidSuccess(); static RequestFuture<T> coordinatorNotAvailable(); static RequestFuture<T> leaderNotAvailable(); static RequestFuture<T> noBrokersAvailable(); static RequestFuture<T> staleMetadata(); @Override boolean shouldBlock(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testRuntimeExceptionInComplete() { RequestFuture<Exception> future = new RequestFuture<>(); future.complete(new RuntimeException()); } @Test(expected = IllegalStateException.class) public void invokeCompleteAfterAlreadyComplete() { RequestFuture<Void> future = new RequestFuture<>(); future.complete(null); future.complete(null); }
### Question: RequestFuture implements ConsumerNetworkClient.PollCondition { public void raise(RuntimeException e) { try { if (e == null) throw new IllegalArgumentException("The exception passed to raise must not be null"); if (!result.compareAndSet(INCOMPLETE_SENTINEL, e)) throw new IllegalStateException("Invalid attempt to complete a request future which is already complete"); fireFailure(); } finally { completedLatch.countDown(); } } boolean isDone(); boolean awaitDone(long timeout, TimeUnit unit); @SuppressWarnings("unchecked") T value(); boolean succeeded(); boolean failed(); boolean isRetriable(); RuntimeException exception(); void complete(T value); void raise(RuntimeException e); void raise(Errors error); void addListener(RequestFutureListener<T> listener); RequestFuture<S> compose(final RequestFutureAdapter<T, S> adapter); void chain(final RequestFuture<T> future); static RequestFuture<T> failure(RuntimeException e); static RequestFuture<Void> voidSuccess(); static RequestFuture<T> coordinatorNotAvailable(); static RequestFuture<T> leaderNotAvailable(); static RequestFuture<T> noBrokersAvailable(); static RequestFuture<T> staleMetadata(); @Override boolean shouldBlock(); }### Answer: @Test(expected = IllegalStateException.class) public void invokeRaiseAfterAlreadyFailed() { RequestFuture<Void> future = new RequestFuture<>(); future.raise(new RuntimeException()); future.raise(new RuntimeException()); }
### Question: ConsumerProtocol { public static PartitionAssignor.Subscription deserializeSubscription(ByteBuffer buffer) { Struct header = CONSUMER_PROTOCOL_HEADER_SCHEMA.read(buffer); Short version = header.getShort(VERSION_KEY_NAME); checkVersionCompatibility(version); Struct struct = SUBSCRIPTION_V0.read(buffer); ByteBuffer userData = struct.getBytes(USER_DATA_KEY_NAME); List<String> topics = new ArrayList<>(); for (Object topicObj : struct.getArray(TOPICS_KEY_NAME)) topics.add((String) topicObj); return new PartitionAssignor.Subscription(topics, userData); } static ByteBuffer serializeSubscription(PartitionAssignor.Subscription subscription); static PartitionAssignor.Subscription deserializeSubscription(ByteBuffer buffer); static PartitionAssignor.Assignment deserializeAssignment(ByteBuffer buffer); static ByteBuffer serializeAssignment(PartitionAssignor.Assignment assignment); static final String PROTOCOL_TYPE; static final String VERSION_KEY_NAME; static final String TOPICS_KEY_NAME; static final String TOPIC_KEY_NAME; static final String PARTITIONS_KEY_NAME; static final String TOPIC_PARTITIONS_KEY_NAME; static final String USER_DATA_KEY_NAME; static final short CONSUMER_PROTOCOL_V0; static final Schema CONSUMER_PROTOCOL_HEADER_SCHEMA; static final Schema SUBSCRIPTION_V0; static final Schema TOPIC_ASSIGNMENT_V0; static final Schema ASSIGNMENT_V0; }### Answer: @Test public void deserializeNewSubscriptionVersion() { short version = 100; Schema subscriptionSchemaV100 = new Schema( new Field(ConsumerProtocol.TOPICS_KEY_NAME, new ArrayOf(Type.STRING)), new Field(ConsumerProtocol.USER_DATA_KEY_NAME, Type.BYTES), new Field("foo", Type.STRING)); Struct subscriptionV100 = new Struct(subscriptionSchemaV100); subscriptionV100.set(ConsumerProtocol.TOPICS_KEY_NAME, new Object[]{"topic"}); subscriptionV100.set(ConsumerProtocol.USER_DATA_KEY_NAME, ByteBuffer.wrap(new byte[0])); subscriptionV100.set("foo", "bar"); Struct headerV100 = new Struct(ConsumerProtocol.CONSUMER_PROTOCOL_HEADER_SCHEMA); headerV100.set(ConsumerProtocol.VERSION_KEY_NAME, version); ByteBuffer buffer = ByteBuffer.allocate(subscriptionV100.sizeOf() + headerV100.sizeOf()); headerV100.writeTo(buffer); subscriptionV100.writeTo(buffer); buffer.flip(); Subscription subscription = ConsumerProtocol.deserializeSubscription(buffer); assertEquals(Arrays.asList("topic"), subscription.topics()); }
### Question: ConsumerProtocol { public static PartitionAssignor.Assignment deserializeAssignment(ByteBuffer buffer) { Struct header = CONSUMER_PROTOCOL_HEADER_SCHEMA.read(buffer); Short version = header.getShort(VERSION_KEY_NAME); checkVersionCompatibility(version); Struct struct = ASSIGNMENT_V0.read(buffer); ByteBuffer userData = struct.getBytes(USER_DATA_KEY_NAME); List<TopicPartition> partitions = new ArrayList<>(); for (Object structObj : struct.getArray(TOPIC_PARTITIONS_KEY_NAME)) { Struct assignment = (Struct) structObj; String topic = assignment.getString(TOPIC_KEY_NAME); for (Object partitionObj : assignment.getArray(PARTITIONS_KEY_NAME)) { Integer partition = (Integer) partitionObj; partitions.add(new TopicPartition(topic, partition)); } } return new PartitionAssignor.Assignment(partitions, userData); } static ByteBuffer serializeSubscription(PartitionAssignor.Subscription subscription); static PartitionAssignor.Subscription deserializeSubscription(ByteBuffer buffer); static PartitionAssignor.Assignment deserializeAssignment(ByteBuffer buffer); static ByteBuffer serializeAssignment(PartitionAssignor.Assignment assignment); static final String PROTOCOL_TYPE; static final String VERSION_KEY_NAME; static final String TOPICS_KEY_NAME; static final String TOPIC_KEY_NAME; static final String PARTITIONS_KEY_NAME; static final String TOPIC_PARTITIONS_KEY_NAME; static final String USER_DATA_KEY_NAME; static final short CONSUMER_PROTOCOL_V0; static final Schema CONSUMER_PROTOCOL_HEADER_SCHEMA; static final Schema SUBSCRIPTION_V0; static final Schema TOPIC_ASSIGNMENT_V0; static final Schema ASSIGNMENT_V0; }### Answer: @Test public void deserializeNewAssignmentVersion() { short version = 100; Schema assignmentSchemaV100 = new Schema( new Field(ConsumerProtocol.TOPIC_PARTITIONS_KEY_NAME, new ArrayOf(ConsumerProtocol.TOPIC_ASSIGNMENT_V0)), new Field(ConsumerProtocol.USER_DATA_KEY_NAME, Type.BYTES), new Field("foo", Type.STRING)); Struct assignmentV100 = new Struct(assignmentSchemaV100); assignmentV100.set(ConsumerProtocol.TOPIC_PARTITIONS_KEY_NAME, new Object[]{new Struct(ConsumerProtocol.TOPIC_ASSIGNMENT_V0) .set(ConsumerProtocol.TOPIC_KEY_NAME, "foo") .set(ConsumerProtocol.PARTITIONS_KEY_NAME, new Object[]{1})}); assignmentV100.set(ConsumerProtocol.USER_DATA_KEY_NAME, ByteBuffer.wrap(new byte[0])); assignmentV100.set("foo", "bar"); Struct headerV100 = new Struct(ConsumerProtocol.CONSUMER_PROTOCOL_HEADER_SCHEMA); headerV100.set(ConsumerProtocol.VERSION_KEY_NAME, version); ByteBuffer buffer = ByteBuffer.allocate(assignmentV100.sizeOf() + headerV100.sizeOf()); headerV100.writeTo(buffer); assignmentV100.writeTo(buffer); buffer.flip(); PartitionAssignor.Assignment assignment = ConsumerProtocol.deserializeAssignment(buffer); assertEquals(toSet(Arrays.asList(new TopicPartition("foo", 1))), toSet(assignment.partitions())); }
### Question: ConsumerCoordinator extends AbstractCoordinator { public void close(long timeoutMs) { client.disableWakeups(); long now = time.milliseconds(); long endTimeMs = now + timeoutMs; try { maybeAutoCommitOffsetsSync(timeoutMs); now = time.milliseconds(); if (pendingAsyncCommits.get() > 0 && endTimeMs > now) { ensureCoordinatorReady(now, endTimeMs - now); now = time.milliseconds(); } } finally { super.close(Math.max(0, endTimeMs - now)); } } ConsumerCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, List<PartitionAssignor> assignors, Metadata metadata, SubscriptionState subscriptions, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, boolean autoCommitEnabled, int autoCommitIntervalMs, ConsumerInterceptors<?, ?> interceptors, boolean excludeInternalTopics, final boolean leaveGroupOnClose); @Override String protocolType(); @Override List<ProtocolMetadata> metadata(); void updatePatternSubscription(Cluster cluster); void poll(long now, long remainingMs); long timeToNextPoll(long now); @Override boolean needRejoin(); void refreshCommittedOffsetsIfNeeded(); Map<TopicPartition, OffsetAndMetadata> fetchCommittedOffsets(Set<TopicPartition> partitions); void close(long timeoutMs); void commitOffsetsAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, final OffsetCommitCallback callback); boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, long timeoutMs); void maybeAutoCommitOffsetsNow(); }### Answer: @Test public void testLeaveGroupOnClose() { final String consumerId = "consumer"; subscriptions.subscribe(singleton(topic1), rebalanceListener); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(); client.prepareResponse(joinGroupFollowerResponse(1, consumerId, "leader", Errors.NONE)); client.prepareResponse(syncGroupResponse(singletonList(t1p), Errors.NONE)); coordinator.joinGroupIfNeeded(); final AtomicBoolean received = new AtomicBoolean(false); client.prepareResponse(new MockClient.RequestMatcher() { @Override public boolean matches(AbstractRequest body) { received.set(true); LeaveGroupRequest leaveRequest = (LeaveGroupRequest) body; return leaveRequest.memberId().equals(consumerId) && leaveRequest.groupId().equals(groupId); } }, new LeaveGroupResponse(Errors.NONE)); coordinator.close(0); assertTrue(received.get()); }
### Question: ConsumerCoordinator extends AbstractCoordinator { @Override public List<ProtocolMetadata> metadata() { this.joinedSubscription = subscriptions.subscription(); List<ProtocolMetadata> metadataList = new ArrayList<>(); for (PartitionAssignor assignor : assignors) { Subscription subscription = assignor.subscription(joinedSubscription); ByteBuffer metadata = ConsumerProtocol.serializeSubscription(subscription); metadataList.add(new ProtocolMetadata(assignor.name(), metadata)); } return metadataList; } ConsumerCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, List<PartitionAssignor> assignors, Metadata metadata, SubscriptionState subscriptions, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, boolean autoCommitEnabled, int autoCommitIntervalMs, ConsumerInterceptors<?, ?> interceptors, boolean excludeInternalTopics, final boolean leaveGroupOnClose); @Override String protocolType(); @Override List<ProtocolMetadata> metadata(); void updatePatternSubscription(Cluster cluster); void poll(long now, long remainingMs); long timeToNextPoll(long now); @Override boolean needRejoin(); void refreshCommittedOffsetsIfNeeded(); Map<TopicPartition, OffsetAndMetadata> fetchCommittedOffsets(Set<TopicPartition> partitions); void close(long timeoutMs); void commitOffsetsAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, final OffsetCommitCallback callback); boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, long timeoutMs); void maybeAutoCommitOffsetsNow(); }### Answer: @Test public void testProtocolMetadataOrder() { RoundRobinAssignor roundRobin = new RoundRobinAssignor(); RangeAssignor range = new RangeAssignor(); try (Metrics metrics = new Metrics(time)) { ConsumerCoordinator coordinator = buildCoordinator(metrics, Arrays.<PartitionAssignor>asList(roundRobin, range), ConsumerConfig.DEFAULT_EXCLUDE_INTERNAL_TOPICS, false, true); List<ProtocolMetadata> metadata = coordinator.metadata(); assertEquals(2, metadata.size()); assertEquals(roundRobin.name(), metadata.get(0).name()); assertEquals(range.name(), metadata.get(1).name()); } try (Metrics metrics = new Metrics(time)) { ConsumerCoordinator coordinator = buildCoordinator(metrics, Arrays.<PartitionAssignor>asList(range, roundRobin), ConsumerConfig.DEFAULT_EXCLUDE_INTERNAL_TOPICS, false, true); List<ProtocolMetadata> metadata = coordinator.metadata(); assertEquals(2, metadata.size()); assertEquals(range.name(), metadata.get(0).name()); assertEquals(roundRobin.name(), metadata.get(1).name()); } }
### Question: ConsumerNetworkClient implements Closeable { public RequestFuture<ClientResponse> send(Node node, AbstractRequest.Builder<?> requestBuilder) { long now = time.milliseconds(); RequestFutureCompletionHandler completionHandler = new RequestFutureCompletionHandler(); ClientRequest clientRequest = client.newClientRequest(node.idString(), requestBuilder, now, true, completionHandler); unsent.put(node, clientRequest); client.wakeup(); return completionHandler.future; } ConsumerNetworkClient(KafkaClient client, Metadata metadata, Time time, long retryBackoffMs, long requestTimeoutMs); RequestFuture<ClientResponse> send(Node node, AbstractRequest.Builder<?> requestBuilder); synchronized Node leastLoadedNode(); synchronized boolean hasReadyNodes(); void awaitMetadataUpdate(); boolean awaitMetadataUpdate(long timeout); void ensureFreshMetadata(); void wakeup(); void poll(RequestFuture<?> future); boolean poll(RequestFuture<?> future, long timeout); void poll(long timeout); void poll(long timeout, long now, PollCondition pollCondition); void poll(long timeout, long now, PollCondition pollCondition, boolean disableWakeup); void pollNoWakeup(); boolean awaitPendingRequests(Node node, long timeoutMs); int pendingRequestCount(Node node); boolean hasPendingRequests(Node node); int pendingRequestCount(); boolean hasPendingRequests(); void failUnsentRequests(Node node, RuntimeException e); void maybeTriggerWakeup(); void disableWakeups(); @Override void close(); boolean connectionFailed(Node node); void tryConnect(Node node); }### Answer: @Test public void send() { client.prepareResponse(heartbeatResponse(Errors.NONE)); RequestFuture<ClientResponse> future = consumerClient.send(node, heartbeat()); assertEquals(1, consumerClient.pendingRequestCount()); assertEquals(1, consumerClient.pendingRequestCount(node)); assertFalse(future.isDone()); consumerClient.poll(future); assertTrue(future.isDone()); assertTrue(future.succeeded()); ClientResponse clientResponse = future.value(); HeartbeatResponse response = (HeartbeatResponse) clientResponse.responseBody(); assertEquals(Errors.NONE, response.error()); }
### Question: ConsumerNetworkClient implements Closeable { public void poll(RequestFuture<?> future) { while (!future.isDone()) poll(MAX_POLL_TIMEOUT_MS, time.milliseconds(), future); } ConsumerNetworkClient(KafkaClient client, Metadata metadata, Time time, long retryBackoffMs, long requestTimeoutMs); RequestFuture<ClientResponse> send(Node node, AbstractRequest.Builder<?> requestBuilder); synchronized Node leastLoadedNode(); synchronized boolean hasReadyNodes(); void awaitMetadataUpdate(); boolean awaitMetadataUpdate(long timeout); void ensureFreshMetadata(); void wakeup(); void poll(RequestFuture<?> future); boolean poll(RequestFuture<?> future, long timeout); void poll(long timeout); void poll(long timeout, long now, PollCondition pollCondition); void poll(long timeout, long now, PollCondition pollCondition, boolean disableWakeup); void pollNoWakeup(); boolean awaitPendingRequests(Node node, long timeoutMs); int pendingRequestCount(Node node); boolean hasPendingRequests(Node node); int pendingRequestCount(); boolean hasPendingRequests(); void failUnsentRequests(Node node, RuntimeException e); void maybeTriggerWakeup(); void disableWakeups(); @Override void close(); boolean connectionFailed(Node node); void tryConnect(Node node); }### Answer: @Test public void doNotBlockIfPollConditionIsSatisfied() { NetworkClient mockNetworkClient = EasyMock.mock(NetworkClient.class); ConsumerNetworkClient consumerClient = new ConsumerNetworkClient(mockNetworkClient, metadata, time, 100, 1000); EasyMock.expect(mockNetworkClient.poll(EasyMock.eq(0L), EasyMock.anyLong())).andReturn(Collections.<ClientResponse>emptyList()); EasyMock.replay(mockNetworkClient); consumerClient.poll(Long.MAX_VALUE, time.milliseconds(), new ConsumerNetworkClient.PollCondition() { @Override public boolean shouldBlock() { return false; } }); EasyMock.verify(mockNetworkClient); } @Test public void blockWhenPollConditionNotSatisfied() { long timeout = 4000L; NetworkClient mockNetworkClient = EasyMock.mock(NetworkClient.class); ConsumerNetworkClient consumerClient = new ConsumerNetworkClient(mockNetworkClient, metadata, time, 100, 1000); EasyMock.expect(mockNetworkClient.inFlightRequestCount()).andReturn(1); EasyMock.expect(mockNetworkClient.poll(EasyMock.eq(timeout), EasyMock.anyLong())).andReturn(Collections.<ClientResponse>emptyList()); EasyMock.replay(mockNetworkClient); consumerClient.poll(timeout, time.milliseconds(), new ConsumerNetworkClient.PollCondition() { @Override public boolean shouldBlock() { return true; } }); EasyMock.verify(mockNetworkClient); } @Test public void blockOnlyForRetryBackoffIfNoInflightRequests() { long retryBackoffMs = 100L; NetworkClient mockNetworkClient = EasyMock.mock(NetworkClient.class); ConsumerNetworkClient consumerClient = new ConsumerNetworkClient(mockNetworkClient, metadata, time, retryBackoffMs, 1000L); EasyMock.expect(mockNetworkClient.inFlightRequestCount()).andReturn(0); EasyMock.expect(mockNetworkClient.poll(EasyMock.eq(retryBackoffMs), EasyMock.anyLong())).andReturn(Collections.<ClientResponse>emptyList()); EasyMock.replay(mockNetworkClient); consumerClient.poll(Long.MAX_VALUE, time.milliseconds(), new ConsumerNetworkClient.PollCondition() { @Override public boolean shouldBlock() { return true; } }); EasyMock.verify(mockNetworkClient); }
### Question: ConsumerNetworkClient implements Closeable { public void wakeup() { log.trace("Received user wakeup"); this.wakeup.set(true); this.client.wakeup(); } ConsumerNetworkClient(KafkaClient client, Metadata metadata, Time time, long retryBackoffMs, long requestTimeoutMs); RequestFuture<ClientResponse> send(Node node, AbstractRequest.Builder<?> requestBuilder); synchronized Node leastLoadedNode(); synchronized boolean hasReadyNodes(); void awaitMetadataUpdate(); boolean awaitMetadataUpdate(long timeout); void ensureFreshMetadata(); void wakeup(); void poll(RequestFuture<?> future); boolean poll(RequestFuture<?> future, long timeout); void poll(long timeout); void poll(long timeout, long now, PollCondition pollCondition); void poll(long timeout, long now, PollCondition pollCondition, boolean disableWakeup); void pollNoWakeup(); boolean awaitPendingRequests(Node node, long timeoutMs); int pendingRequestCount(Node node); boolean hasPendingRequests(Node node); int pendingRequestCount(); boolean hasPendingRequests(); void failUnsentRequests(Node node, RuntimeException e); void maybeTriggerWakeup(); void disableWakeups(); @Override void close(); boolean connectionFailed(Node node); void tryConnect(Node node); }### Answer: @Test public void wakeup() { RequestFuture<ClientResponse> future = consumerClient.send(node, heartbeat()); consumerClient.wakeup(); try { consumerClient.poll(0); fail(); } catch (WakeupException e) { } client.respond(heartbeatResponse(Errors.NONE)); consumerClient.poll(future); assertTrue(future.isDone()); }
### Question: ConsumerNetworkClient implements Closeable { public void awaitMetadataUpdate() { awaitMetadataUpdate(Long.MAX_VALUE); } ConsumerNetworkClient(KafkaClient client, Metadata metadata, Time time, long retryBackoffMs, long requestTimeoutMs); RequestFuture<ClientResponse> send(Node node, AbstractRequest.Builder<?> requestBuilder); synchronized Node leastLoadedNode(); synchronized boolean hasReadyNodes(); void awaitMetadataUpdate(); boolean awaitMetadataUpdate(long timeout); void ensureFreshMetadata(); void wakeup(); void poll(RequestFuture<?> future); boolean poll(RequestFuture<?> future, long timeout); void poll(long timeout); void poll(long timeout, long now, PollCondition pollCondition); void poll(long timeout, long now, PollCondition pollCondition, boolean disableWakeup); void pollNoWakeup(); boolean awaitPendingRequests(Node node, long timeoutMs); int pendingRequestCount(Node node); boolean hasPendingRequests(Node node); int pendingRequestCount(); boolean hasPendingRequests(); void failUnsentRequests(Node node, RuntimeException e); void maybeTriggerWakeup(); void disableWakeups(); @Override void close(); boolean connectionFailed(Node node); void tryConnect(Node node); }### Answer: @Test public void testAwaitForMetadataUpdateWithTimeout() { assertFalse(consumerClient.awaitMetadataUpdate(10L)); }
### Question: Heartbeat { public boolean shouldHeartbeat(long now) { return timeToNextHeartbeat(now) == 0; } Heartbeat(long sessionTimeout, long heartbeatInterval, long maxPollInterval, long retryBackoffMs); void poll(long now); void sentHeartbeat(long now); void failHeartbeat(); void receiveHeartbeat(long now); boolean shouldHeartbeat(long now); long lastHeartbeatSend(); long timeToNextHeartbeat(long now); boolean sessionTimeoutExpired(long now); long interval(); void resetTimeouts(long now); boolean pollTimeoutExpired(long now); }### Answer: @Test public void testShouldHeartbeat() { heartbeat.sentHeartbeat(time.milliseconds()); time.sleep((long) ((float) interval * 1.1)); assertTrue(heartbeat.shouldHeartbeat(time.milliseconds())); }
### Question: Heartbeat { public long timeToNextHeartbeat(long now) { long timeSinceLastHeartbeat = now - Math.max(lastHeartbeatSend, lastSessionReset); final long delayToNextHeartbeat; if (heartbeatFailed) delayToNextHeartbeat = retryBackoffMs; else delayToNextHeartbeat = heartbeatInterval; if (timeSinceLastHeartbeat > delayToNextHeartbeat) return 0; else return delayToNextHeartbeat - timeSinceLastHeartbeat; } Heartbeat(long sessionTimeout, long heartbeatInterval, long maxPollInterval, long retryBackoffMs); void poll(long now); void sentHeartbeat(long now); void failHeartbeat(); void receiveHeartbeat(long now); boolean shouldHeartbeat(long now); long lastHeartbeatSend(); long timeToNextHeartbeat(long now); boolean sessionTimeoutExpired(long now); long interval(); void resetTimeouts(long now); boolean pollTimeoutExpired(long now); }### Answer: @Test public void testTimeToNextHeartbeat() { heartbeat.sentHeartbeat(0); assertEquals(100, heartbeat.timeToNextHeartbeat(0)); assertEquals(0, heartbeat.timeToNextHeartbeat(100)); assertEquals(0, heartbeat.timeToNextHeartbeat(200)); }
### Question: Heartbeat { public boolean sessionTimeoutExpired(long now) { return now - Math.max(lastSessionReset, lastHeartbeatReceive) > sessionTimeout; } Heartbeat(long sessionTimeout, long heartbeatInterval, long maxPollInterval, long retryBackoffMs); void poll(long now); void sentHeartbeat(long now); void failHeartbeat(); void receiveHeartbeat(long now); boolean shouldHeartbeat(long now); long lastHeartbeatSend(); long timeToNextHeartbeat(long now); boolean sessionTimeoutExpired(long now); long interval(); void resetTimeouts(long now); boolean pollTimeoutExpired(long now); }### Answer: @Test public void testSessionTimeoutExpired() { heartbeat.sentHeartbeat(time.milliseconds()); time.sleep(305); assertTrue(heartbeat.sessionTimeoutExpired(time.milliseconds())); }
### Question: AbstractCoordinator implements Closeable { public synchronized void ensureCoordinatorReady() { ensureCoordinatorReady(0, Long.MAX_VALUE); } AbstractCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, boolean leaveGroupOnClose); synchronized void ensureCoordinatorReady(); void ensureActiveGroup(); boolean coordinatorUnknown(); @Override final void close(); synchronized void maybeLeaveGroup(); }### Answer: @Test public void testCoordinatorDiscoveryBackoff() { mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.blackout(coordinatorNode, 50L); long initialTime = mockTime.milliseconds(); coordinator.ensureCoordinatorReady(); long endTime = mockTime.milliseconds(); assertTrue(endTime - initialTime >= RETRY_BACKOFF_MS); }
### Question: AbstractCoordinator implements Closeable { protected synchronized RequestFuture<Void> lookupCoordinator() { if (findCoordinatorFuture == null) { Node node = this.client.leastLoadedNode(); if (node == null) { log.debug("No broker available to send GroupCoordinator request for group {}", groupId); return RequestFuture.noBrokersAvailable(); } else findCoordinatorFuture = sendGroupCoordinatorRequest(node); } return findCoordinatorFuture; } AbstractCoordinator(ConsumerNetworkClient client, String groupId, int rebalanceTimeoutMs, int sessionTimeoutMs, int heartbeatIntervalMs, Metrics metrics, String metricGrpPrefix, Time time, long retryBackoffMs, boolean leaveGroupOnClose); synchronized void ensureCoordinatorReady(); void ensureActiveGroup(); boolean coordinatorUnknown(); @Override final void close(); synchronized void maybeLeaveGroup(); }### Answer: @Test public void testLookupCoordinator() throws Exception { mockClient.setNode(null); RequestFuture<Void> noBrokersAvailableFuture = coordinator.lookupCoordinator(); assertTrue("Failed future expected", noBrokersAvailableFuture.failed()); mockClient.setNode(node); RequestFuture<Void> future = coordinator.lookupCoordinator(); assertFalse("Request not sent", future.isDone()); assertTrue("New request sent while one is in progress", future == coordinator.lookupCoordinator()); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(); assertTrue("New request not sent after previous completed", future != coordinator.lookupCoordinator()); }
### Question: SubscriptionState { public void position(TopicPartition tp, long offset) { assignedState(tp).position(offset); } SubscriptionState(OffsetResetStrategy defaultResetStrategy); void subscribe(Set<String> topics, ConsumerRebalanceListener listener); void subscribeFromPattern(Set<String> topics); void groupSubscribe(Collection<String> topics); void resetGroupSubscription(); void assignFromUser(Set<TopicPartition> partitions); void assignFromSubscribed(Collection<TopicPartition> assignments); void subscribe(Pattern pattern, ConsumerRebalanceListener listener); boolean hasPatternSubscription(); boolean hasNoSubscriptionOrUserAssignment(); void unsubscribe(); Pattern subscribedPattern(); Set<String> subscription(); Set<TopicPartition> pausedPartitions(); Set<String> groupSubscription(); void committed(TopicPartition tp, OffsetAndMetadata offset); OffsetAndMetadata committed(TopicPartition tp); void needRefreshCommits(); boolean refreshCommitsNeeded(); void commitsRefreshed(); void seek(TopicPartition tp, long offset); Set<TopicPartition> assignedPartitions(); List<TopicPartition> fetchablePartitions(); boolean partitionsAutoAssigned(); void position(TopicPartition tp, long offset); Long position(TopicPartition tp); Long partitionLag(TopicPartition tp, IsolationLevel isolationLevel); void updateHighWatermark(TopicPartition tp, long highWatermark); void updateLastStableOffset(TopicPartition tp, long lastStableOffset); Map<TopicPartition, OffsetAndMetadata> allConsumed(); void needOffsetReset(TopicPartition partition, OffsetResetStrategy offsetResetStrategy); void needOffsetReset(TopicPartition partition); boolean hasDefaultOffsetResetPolicy(); boolean isOffsetResetNeeded(TopicPartition partition); OffsetResetStrategy resetStrategy(TopicPartition partition); boolean hasAllFetchPositions(Collection<TopicPartition> partitions); boolean hasAllFetchPositions(); Set<TopicPartition> missingFetchPositions(); boolean isAssigned(TopicPartition tp); boolean isPaused(TopicPartition tp); boolean isFetchable(TopicPartition tp); boolean hasValidPosition(TopicPartition tp); void pause(TopicPartition tp); void resume(TopicPartition tp); void movePartitionToEnd(TopicPartition tp); ConsumerRebalanceListener listener(); void addListener(Listener listener); void fireOnAssignment(Set<TopicPartition> assignment); }### Answer: @Test(expected = IllegalStateException.class) public void cantChangePositionForNonAssignedPartition() { state.position(tp0, 1); }
### Question: SubscriptionState { public void subscribe(Set<String> topics, ConsumerRebalanceListener listener) { if (listener == null) throw new IllegalArgumentException("RebalanceListener cannot be null"); setSubscriptionType(SubscriptionType.AUTO_TOPICS); this.listener = listener; changeSubscription(topics); } SubscriptionState(OffsetResetStrategy defaultResetStrategy); void subscribe(Set<String> topics, ConsumerRebalanceListener listener); void subscribeFromPattern(Set<String> topics); void groupSubscribe(Collection<String> topics); void resetGroupSubscription(); void assignFromUser(Set<TopicPartition> partitions); void assignFromSubscribed(Collection<TopicPartition> assignments); void subscribe(Pattern pattern, ConsumerRebalanceListener listener); boolean hasPatternSubscription(); boolean hasNoSubscriptionOrUserAssignment(); void unsubscribe(); Pattern subscribedPattern(); Set<String> subscription(); Set<TopicPartition> pausedPartitions(); Set<String> groupSubscription(); void committed(TopicPartition tp, OffsetAndMetadata offset); OffsetAndMetadata committed(TopicPartition tp); void needRefreshCommits(); boolean refreshCommitsNeeded(); void commitsRefreshed(); void seek(TopicPartition tp, long offset); Set<TopicPartition> assignedPartitions(); List<TopicPartition> fetchablePartitions(); boolean partitionsAutoAssigned(); void position(TopicPartition tp, long offset); Long position(TopicPartition tp); Long partitionLag(TopicPartition tp, IsolationLevel isolationLevel); void updateHighWatermark(TopicPartition tp, long highWatermark); void updateLastStableOffset(TopicPartition tp, long lastStableOffset); Map<TopicPartition, OffsetAndMetadata> allConsumed(); void needOffsetReset(TopicPartition partition, OffsetResetStrategy offsetResetStrategy); void needOffsetReset(TopicPartition partition); boolean hasDefaultOffsetResetPolicy(); boolean isOffsetResetNeeded(TopicPartition partition); OffsetResetStrategy resetStrategy(TopicPartition partition); boolean hasAllFetchPositions(Collection<TopicPartition> partitions); boolean hasAllFetchPositions(); Set<TopicPartition> missingFetchPositions(); boolean isAssigned(TopicPartition tp); boolean isPaused(TopicPartition tp); boolean isFetchable(TopicPartition tp); boolean hasValidPosition(TopicPartition tp); void pause(TopicPartition tp); void resume(TopicPartition tp); void movePartitionToEnd(TopicPartition tp); ConsumerRebalanceListener listener(); void addListener(Listener listener); void fireOnAssignment(Set<TopicPartition> assignment); }### Answer: @Test(expected = IllegalStateException.class) public void cantSubscribeTopicAndPattern() { state.subscribe(singleton(topic), rebalanceListener); state.subscribe(Pattern.compile(".*"), rebalanceListener); } @Test(expected = IllegalStateException.class) public void cantSubscribePatternAndTopic() { state.subscribe(Pattern.compile(".*"), rebalanceListener); state.subscribe(singleton(topic), rebalanceListener); }
### Question: KafkaConsumer implements Consumer<K, V> { public Set<String> subscription() { acquire(); try { return Collections.unmodifiableSet(new HashSet<>(this.subscriptions.subscription())); } finally { release(); } } KafkaConsumer(Map<String, Object> configs); KafkaConsumer(Map<String, Object> configs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); KafkaConsumer(Properties properties); KafkaConsumer(Properties properties, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); @SuppressWarnings("unchecked") private KafkaConsumer(ConsumerConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); KafkaConsumer(String clientId, ConsumerCoordinator coordinator, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Fetcher<K, V> fetcher, ConsumerInterceptors<K, V> interceptors, Time time, ConsumerNetworkClient client, Metrics metrics, SubscriptionState subscriptions, Metadata metadata, long retryBackoffMs, long requestTimeoutMs); Set<TopicPartition> assignment(); Set<String> subscription(); @Override // 订阅指定的topic,并未消费者自动分配分区 void subscribe(Collection<String> topics, ConsumerRebalanceListener listener); @Override void subscribe(Collection<String> topics); @Override void subscribe(Pattern pattern, ConsumerRebalanceListener listener); void unsubscribe(); @Override // 用户手动订阅指定的topic并指定消费的分区,和subscribe方法互斥 void assign(Collection<TopicPartition> partitions); @Override // 负责从服务端获取消息 ConsumerRecords<K, V> poll(long timeout); @Override void commitSync(); @Override void commitSync(final Map<TopicPartition, OffsetAndMetadata> offsets); @Override void commitAsync(); @Override void commitAsync(OffsetCommitCallback callback); @Override void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback); @Override // 指定消费者起始消费的位置 void seek(TopicPartition partition, long offset); void seekToBeginning(Collection<TopicPartition> partitions); void seekToEnd(Collection<TopicPartition> partitions); long position(TopicPartition partition); @Override OffsetAndMetadata committed(TopicPartition partition); @Override Map<MetricName, ? extends Metric> metrics(); @Override List<PartitionInfo> partitionsFor(String topic); @Override Map<String, List<PartitionInfo>> listTopics(); @Override void pause(Collection<TopicPartition> partitions); @Override // 恢复consumer void resume(Collection<TopicPartition> partitions); @Override // 暂停consumer Set<TopicPartition> paused(); @Override Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch); @Override Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions); @Override Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions); @Override void close(); void close(long timeout, TimeUnit timeUnit); @Override void wakeup(); }### Answer: @Test public void testSubscription() { KafkaConsumer<byte[], byte[]> consumer = newConsumer(); consumer.subscribe(singletonList(topic)); assertEquals(singleton(topic), consumer.subscription()); assertTrue(consumer.assignment().isEmpty()); consumer.subscribe(Collections.<String>emptyList()); assertTrue(consumer.subscription().isEmpty()); assertTrue(consumer.assignment().isEmpty()); consumer.assign(singletonList(tp0)); assertTrue(consumer.subscription().isEmpty()); assertEquals(singleton(tp0), consumer.assignment()); consumer.unsubscribe(); assertTrue(consumer.subscription().isEmpty()); assertTrue(consumer.assignment().isEmpty()); consumer.close(); }
### Question: KafkaConsumer implements Consumer<K, V> { @Override public void pause(Collection<TopicPartition> partitions) { acquire(); try { for (TopicPartition partition: partitions) { log.debug("Pausing partition {}", partition); subscriptions.pause(partition); } } finally { release(); } } KafkaConsumer(Map<String, Object> configs); KafkaConsumer(Map<String, Object> configs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); KafkaConsumer(Properties properties); KafkaConsumer(Properties properties, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); @SuppressWarnings("unchecked") private KafkaConsumer(ConsumerConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); KafkaConsumer(String clientId, ConsumerCoordinator coordinator, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Fetcher<K, V> fetcher, ConsumerInterceptors<K, V> interceptors, Time time, ConsumerNetworkClient client, Metrics metrics, SubscriptionState subscriptions, Metadata metadata, long retryBackoffMs, long requestTimeoutMs); Set<TopicPartition> assignment(); Set<String> subscription(); @Override // 订阅指定的topic,并未消费者自动分配分区 void subscribe(Collection<String> topics, ConsumerRebalanceListener listener); @Override void subscribe(Collection<String> topics); @Override void subscribe(Pattern pattern, ConsumerRebalanceListener listener); void unsubscribe(); @Override // 用户手动订阅指定的topic并指定消费的分区,和subscribe方法互斥 void assign(Collection<TopicPartition> partitions); @Override // 负责从服务端获取消息 ConsumerRecords<K, V> poll(long timeout); @Override void commitSync(); @Override void commitSync(final Map<TopicPartition, OffsetAndMetadata> offsets); @Override void commitAsync(); @Override void commitAsync(OffsetCommitCallback callback); @Override void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback); @Override // 指定消费者起始消费的位置 void seek(TopicPartition partition, long offset); void seekToBeginning(Collection<TopicPartition> partitions); void seekToEnd(Collection<TopicPartition> partitions); long position(TopicPartition partition); @Override OffsetAndMetadata committed(TopicPartition partition); @Override Map<MetricName, ? extends Metric> metrics(); @Override List<PartitionInfo> partitionsFor(String topic); @Override Map<String, List<PartitionInfo>> listTopics(); @Override void pause(Collection<TopicPartition> partitions); @Override // 恢复consumer void resume(Collection<TopicPartition> partitions); @Override // 暂停consumer Set<TopicPartition> paused(); @Override Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch); @Override Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions); @Override Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions); @Override void close(); void close(long timeout, TimeUnit timeUnit); @Override void wakeup(); }### Answer: @Test public void testPause() { KafkaConsumer<byte[], byte[]> consumer = newConsumer(); consumer.assign(singletonList(tp0)); assertEquals(singleton(tp0), consumer.assignment()); assertTrue(consumer.paused().isEmpty()); consumer.pause(singleton(tp0)); assertEquals(singleton(tp0), consumer.paused()); consumer.resume(singleton(tp0)); assertTrue(consumer.paused().isEmpty()); consumer.unsubscribe(); assertTrue(consumer.paused().isEmpty()); consumer.close(); }
### Question: ConsumerRecord { @Deprecated public long checksum() { if (checksum == null) this.checksum = DefaultRecord.computePartialChecksum(timestamp, serializedKeySize, serializedValueSize); return this.checksum; } ConsumerRecord(String topic, int partition, long offset, K key, V value); ConsumerRecord(String topic, int partition, long offset, long timestamp, TimestampType timestampType, long checksum, int serializedKeySize, int serializedValueSize, K key, V value); ConsumerRecord(String topic, int partition, long offset, long timestamp, TimestampType timestampType, Long checksum, int serializedKeySize, int serializedValueSize, K key, V value, Headers headers); String topic(); int partition(); Headers headers(); K key(); V value(); long offset(); long timestamp(); TimestampType timestampType(); @Deprecated long checksum(); int serializedKeySize(); int serializedValueSize(); @Override String toString(); static final long NO_TIMESTAMP; static final int NULL_SIZE; static final int NULL_CHECKSUM; }### Answer: @Test @SuppressWarnings("deprecation") public void testNullChecksumInConstructor() { String key = "key"; String value = "value"; long timestamp = 242341324L; ConsumerRecord<String, String> record = new ConsumerRecord<>("topic", 0, 23L, timestamp, TimestampType.CREATE_TIME, null, key.length(), value.length(), key, value, new RecordHeaders()); assertEquals(DefaultRecord.computePartialChecksum(timestamp, key.length(), value.length()), record.checksum()); }
### Question: Metadata { public Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation) { this(refreshBackoffMs, metadataExpireMs, allowAutoTopicCreation, false, new ClusterResourceListeners()); } Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation); Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation, boolean topicExpiryEnabled, ClusterResourceListeners clusterResourceListeners); synchronized Cluster fetch(); synchronized void add(String topic); synchronized long timeToNextUpdate(long nowMs); synchronized int requestUpdate(); synchronized boolean updateRequested(); synchronized void awaitUpdate(final int lastVersion, final long maxWaitMs); synchronized void setTopics(Collection<String> topics); synchronized Set<String> topics(); synchronized boolean containsTopic(String topic); synchronized void update(Cluster cluster, Set<String> unavailableTopics, long now); synchronized void failedUpdate(long now); synchronized int version(); synchronized long lastSuccessfulUpdate(); boolean allowAutoTopicCreation(); synchronized void needMetadataForAllTopics(boolean needMetadataForAllTopics); synchronized boolean needMetadataForAllTopics(); synchronized void addListener(Listener listener); synchronized void removeListener(Listener listener); static final long TOPIC_EXPIRY_MS; }### Answer: @Test public void testMetadata() throws Exception { long time = 0; metadata.update(Cluster.empty(), Collections.<String>emptySet(), time); assertFalse("No update needed.", metadata.timeToNextUpdate(time) == 0); metadata.requestUpdate(); assertFalse("Still no updated needed due to backoff", metadata.timeToNextUpdate(time) == 0); time += refreshBackoffMs; assertTrue("Update needed now that backoff time expired", metadata.timeToNextUpdate(time) == 0); String topic = "my-topic"; Thread t1 = asyncFetch(topic, 500); Thread t2 = asyncFetch(topic, 500); assertTrue("Awaiting update", t1.isAlive()); assertTrue("Awaiting update", t2.isAlive()); while (t1.isAlive() || t2.isAlive()) { if (metadata.timeToNextUpdate(time) == 0) { metadata.update(TestUtils.singletonCluster(topic, 1), Collections.<String>emptySet(), time); time += refreshBackoffMs; } Thread.sleep(1); } t1.join(); t2.join(); assertFalse("No update needed.", metadata.timeToNextUpdate(time) == 0); time += metadataExpireMs; assertTrue("Update needed due to stale metadata.", metadata.timeToNextUpdate(time) == 0); }
### Question: Metadata { public synchronized long timeToNextUpdate(long nowMs) { long timeToExpire = needUpdate ? 0 : Math.max(this.lastSuccessfulRefreshMs + this.metadataExpireMs - nowMs, 0); long timeToAllowUpdate = this.lastRefreshMs + this.refreshBackoffMs - nowMs; return Math.max(timeToExpire, timeToAllowUpdate); } Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation); Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation, boolean topicExpiryEnabled, ClusterResourceListeners clusterResourceListeners); synchronized Cluster fetch(); synchronized void add(String topic); synchronized long timeToNextUpdate(long nowMs); synchronized int requestUpdate(); synchronized boolean updateRequested(); synchronized void awaitUpdate(final int lastVersion, final long maxWaitMs); synchronized void setTopics(Collection<String> topics); synchronized Set<String> topics(); synchronized boolean containsTopic(String topic); synchronized void update(Cluster cluster, Set<String> unavailableTopics, long now); synchronized void failedUpdate(long now); synchronized int version(); synchronized long lastSuccessfulUpdate(); boolean allowAutoTopicCreation(); synchronized void needMetadataForAllTopics(boolean needMetadataForAllTopics); synchronized boolean needMetadataForAllTopics(); synchronized void addListener(Listener listener); synchronized void removeListener(Listener listener); static final long TOPIC_EXPIRY_MS; }### Answer: @Test public void testTimeToNextUpdate() { checkTimeToNextUpdate(100, 1000); checkTimeToNextUpdate(1000, 100); checkTimeToNextUpdate(0, 0); checkTimeToNextUpdate(0, 100); checkTimeToNextUpdate(100, 0); }
### Question: Metadata { public synchronized void failedUpdate(long now) { this.lastRefreshMs = now; } Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation); Metadata(long refreshBackoffMs, long metadataExpireMs, boolean allowAutoTopicCreation, boolean topicExpiryEnabled, ClusterResourceListeners clusterResourceListeners); synchronized Cluster fetch(); synchronized void add(String topic); synchronized long timeToNextUpdate(long nowMs); synchronized int requestUpdate(); synchronized boolean updateRequested(); synchronized void awaitUpdate(final int lastVersion, final long maxWaitMs); synchronized void setTopics(Collection<String> topics); synchronized Set<String> topics(); synchronized boolean containsTopic(String topic); synchronized void update(Cluster cluster, Set<String> unavailableTopics, long now); synchronized void failedUpdate(long now); synchronized int version(); synchronized long lastSuccessfulUpdate(); boolean allowAutoTopicCreation(); synchronized void needMetadataForAllTopics(boolean needMetadataForAllTopics); synchronized boolean needMetadataForAllTopics(); synchronized void addListener(Listener listener); synchronized void removeListener(Listener listener); static final long TOPIC_EXPIRY_MS; }### Answer: @Test public void testFailedUpdate() { long time = 100; metadata.update(Cluster.empty(), Collections.<String>emptySet(), time); assertEquals(100, metadata.timeToNextUpdate(1000)); metadata.failedUpdate(1100); assertEquals(100, metadata.timeToNextUpdate(1100)); assertEquals(100, metadata.lastSuccessfulUpdate()); metadata.needMetadataForAllTopics(true); metadata.update(Cluster.empty(), Collections.<String>emptySet(), time); assertEquals(100, metadata.timeToNextUpdate(1000)); }