src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ParseConfigUtils { private Map<String, Object> mergeDimensionItems(Map<String, Map<String, Object>> items) { Map<String, Object> flatMap = new HashMap<>(); Set<String> keySet = items.keySet(); if (keySet.contains("application")) { flatMap.putAll(items.get("application")); keySet.remove("application"); } if (!keySet.isEmpty()) { TreeSet<String> sortedKeys = new TreeSet<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); sortedKeys.addAll(keySet); sortedKeys.forEach(key -> flatMap.putAll(items.get(key))); } return flatMap; } ParseConfigUtils(UpdateHandler updateHandler); private ParseConfigUtils(); void initWithUpdateHandler(UpdateHandler updateHandler); void refreshConfigItems(Map<String, Map<String, Object>> remoteItems); static ParseConfigUtils getInstance(); String getCurrentVersionInfo(); void refreshConfigItemsIncremental(Map<String, Object> action); } | @Test public void testMergeDimensionItems() { boolean status = true; Map<String, Object> application = new HashMap<>(); application.put("key1", "application1"); application.put("key2", "application2"); application.put("key3", "application3"); application.put("key4", "application4"); Map<String, Object> service = new HashMap<>(); service.put("key1", "service1"); service.put("key2", "service2"); service.put("key3", "service3"); Map<String, Object> version = new HashMap<>(); version.put("key1", "version1"); version.put("key2", "version1"); Map<String, Object> tag = new HashMap<>(); tag.put("key1", "tag1"); Map<String, Map<String, Object>> items = new LinkedHashMap<String, Map<String, Object>>(); items.put("application", application); items.put("service@app", service); items.put("service@app#version", version); items.put("service@app#version!tag", tag); Map<String, Object> result = null; try { result = Deencapsulation.invoke(pc, "mergeDimensionItems", items); } catch (Exception e) { status = false; } Assert.assertTrue(status); Assert.assertEquals(application.get("key4"), result.get("key4")); Assert.assertEquals(service.get("key3"), result.get("key3")); Assert.assertEquals(version.get("key2"), result.get("key2")); Assert.assertEquals(tag.get("key1"), result.get("key1")); } |
MemberDiscovery { public String getConfigServer() { synchronized (lock) { if (configServerAddresses.isEmpty()) { throw new IllegalStateException("Config center address is not available."); } int index = Math.abs(counter.get() % configServerAddresses.size()); return configServerAddresses.get(index); } } MemberDiscovery(List<String> configCenterUri); String getConfigServer(); @Subscribe void onConnFailEvent(ConnFailEvent e); void refreshMembers(JsonObject members); } | @Test public void testGetConfigServerURIs() { MemberDiscovery dc = new MemberDiscovery(ConfigCenterConfig.INSTANCE.getServerUri()); assertNotNull(dc.getConfigServer()); } |
ConfigCenterConfig { public List<String> getServerUri() { return Deployment.getSystemBootStrapInfo(DeploymentProvider.SYSTEM_KEY_CONFIG_CENTER).getAccessURL(); } private ConfigCenterConfig(); static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config); static ConcurrentCompositeConfiguration getConcurrentCompositeConfiguration(); int getRefreshMode(); int getRefreshPort(); String getTenantName(); String getDomainName(); String getToken(); String getApiVersion(); int getRefreshInterval(); int getFirstRefreshInterval(); Boolean isProxyEnable(); String getProxyHost(); int getProxyPort(); String getProxyUsername(); String getProxyPasswd(); @SuppressWarnings("unchecked") String getServiceName(); List<String> getServerUri(); boolean getAutoDiscoveryEnabled(); int getConnectionTimeout(); int getEventLoopSize(); int getVerticalInstanceCount(); int getIdleTimeoutInSeconds(); String getEnvironment(); static final ConfigCenterConfig INSTANCE; static final String CONNECTION_TIME_OUT; static final String EVENT_LOOP_SIZE; static final String VERTICAL_INSTANCE_COUNT; static final String IDLE_TIMEOUT_IN_SECONDES; } | @Test public void getServerUri() { List<String> servers = ConfigCenterConfig.INSTANCE.getServerUri(); Assert.assertEquals("https: Assert.assertEquals("https: } |
ZeroConfigRegistryService { public void heartbeat(ServerMicroserviceInstance receivedInstance) { String serviceId = receivedInstance.getServiceId(); String instanceId = receivedInstance.getInstanceId(); Map<String, ServerMicroserviceInstance> serverMicroserviceInstanceMap = ServerUtil.microserviceInstanceMap .get(serviceId); if (serverMicroserviceInstanceMap != null && serverMicroserviceInstanceMap .containsKey(instanceId)) { ServerMicroserviceInstance instance = serverMicroserviceInstanceMap.get(instanceId); instance.setLastHeartbeatTimeStamp(Instant.now()); } else { receivedInstance.setEvent(REGISTER_EVENT); LOGGER.info( "Received HEARTBEAT event from serviceId: {}, instancdId: {} for the first time. Register it instead.", serviceId, instanceId); this.registerMicroserviceInstance(receivedInstance); } } void registerMicroserviceInstance(ServerMicroserviceInstance receivedInstance); void unregisterMicroserviceInstance(ServerMicroserviceInstance receivedInstance); ServerMicroserviceInstance findServiceInstance(String serviceId,
String instanceId); List<ServerMicroserviceInstance> getMicroserviceInstance(String consumerId,
String providerId); void heartbeat(ServerMicroserviceInstance receivedInstance); boolean heartbeat(String microserviceId, String microserviceInstanceId); ServerMicroserviceInstance getMicroservice(String microserviceId); List<ServerMicroserviceInstance> findServiceInstances(String appId, String serviceName); } | @Test public void test_heartbeat_whenInstanceExist_shouldReturnTrue() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(false); boolean returnedResult = target.heartbeat(serviceId, instanceId); Assert.assertTrue(returnedResult); }
@Test public void test_heartbeat_whenInstanceNotExist_shouldReturnFalse() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(false); boolean returnedResult = target.heartbeat(serviceId, instanceId1); Assert.assertFalse(returnedResult); } |
ConfigCenterConfig { public String getEnvironment() { return BootStrapProperties.readServiceEnvironment(finalConfig); } private ConfigCenterConfig(); static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config); static ConcurrentCompositeConfiguration getConcurrentCompositeConfiguration(); int getRefreshMode(); int getRefreshPort(); String getTenantName(); String getDomainName(); String getToken(); String getApiVersion(); int getRefreshInterval(); int getFirstRefreshInterval(); Boolean isProxyEnable(); String getProxyHost(); int getProxyPort(); String getProxyUsername(); String getProxyPasswd(); @SuppressWarnings("unchecked") String getServiceName(); List<String> getServerUri(); boolean getAutoDiscoveryEnabled(); int getConnectionTimeout(); int getEventLoopSize(); int getVerticalInstanceCount(); int getIdleTimeoutInSeconds(); String getEnvironment(); static final ConfigCenterConfig INSTANCE; static final String CONNECTION_TIME_OUT; static final String EVENT_LOOP_SIZE; static final String VERTICAL_INSTANCE_COUNT; static final String IDLE_TIMEOUT_IN_SECONDES; } | @Test public void getEnvironment() { Assert.assertEquals("testing", ConfigCenterConfig.INSTANCE.getEnvironment()); System.setProperty("SERVICECOMB_ENV", "development"); ConfigCenterConfig.setConcurrentCompositeConfiguration(ConfigUtil.createLocalConfig()); Assert.assertEquals("development", ConfigCenterConfig.INSTANCE.getEnvironment()); } |
NacosConfigurationSourceImpl implements ConfigCenterConfigurationSource { @Override public void addUpdateListener(WatchedUpdateListener watchedUpdateListener) { listeners.add(watchedUpdateListener); } NacosConfigurationSourceImpl(); @Override boolean isValidSource(Configuration localConfiguration); @Override void init(Configuration localConfiguration); @Override void addUpdateListener(WatchedUpdateListener watchedUpdateListener); @Override void removeUpdateListener(WatchedUpdateListener watchedUpdateListener); @Override Map<String, Object> getCurrentData(); List<WatchedUpdateListener> getCurrentListeners(); } | @Test public void testCreate() throws Exception { NacosConfigurationSourceImpl nacosConfigurationSource = new NacosConfigurationSourceImpl(); nacosConfigurationSource.addUpdateListener(result -> Assert.assertTrue(!result.getAdded().isEmpty())); UpdateHandler udateHandler = Deencapsulation.getField(nacosConfigurationSource, UpdateHandler.class); Map<String, Object> createItems = new HashMap<>(); createItems.put("nacosTestKey", "testValue"); udateHandler.handle(CREATE, createItems); }
@Test public void testUpdate() throws Exception { NacosConfigurationSourceImpl nacosConfigurationSource = new NacosConfigurationSourceImpl(); nacosConfigurationSource.addUpdateListener(result -> Assert.assertTrue(!result.getChanged().isEmpty())); UpdateHandler udateHandler = Deencapsulation.getField(nacosConfigurationSource, UpdateHandler.class); Map<String, Object> updateItems = new HashMap<>(); updateItems.put("nacosTestKey", "testValue"); udateHandler.handle(SET, updateItems); } |
NacosConfigurationSourceImpl implements ConfigCenterConfigurationSource { @Override public void removeUpdateListener(WatchedUpdateListener watchedUpdateListener) { listeners.remove(watchedUpdateListener); } NacosConfigurationSourceImpl(); @Override boolean isValidSource(Configuration localConfiguration); @Override void init(Configuration localConfiguration); @Override void addUpdateListener(WatchedUpdateListener watchedUpdateListener); @Override void removeUpdateListener(WatchedUpdateListener watchedUpdateListener); @Override Map<String, Object> getCurrentData(); List<WatchedUpdateListener> getCurrentListeners(); } | @Test public void testRemoveUpdateListener() { NacosConfigurationSourceImpl nacosConfigurationSource = new NacosConfigurationSourceImpl(); WatchedUpdateListener watchedUpdateListener = Mockito.mock(WatchedUpdateListener.class); nacosConfigurationSource.addUpdateListener(watchedUpdateListener); nacosConfigurationSource.removeUpdateListener(watchedUpdateListener); Assert.assertTrue(nacosConfigurationSource.getCurrentListeners().isEmpty()); } |
NacosClient { public void refreshNacosConfig() { new ConfigRefresh().refreshConfig(); } NacosClient(UpdateHandler updateHandler); void refreshNacosConfig(); } | @Test public void refreshNacosConfig() { NacosConfigurationSourceImpl impl = new NacosConfigurationSourceImpl(); UpdateHandler updateHandler = impl.new UpdateHandler(); NacosClient nacosClient = new NacosClient(updateHandler); Map<String, Object> originMap = Deencapsulation.getField(nacosClient, "originalConfigMap"); originMap.put("nacos","12345"); Assert.assertEquals(1, originMap.size()); } |
KieUtil { public static Map<String, Object> processValueType(KVDoc kvDoc) { ValueType valueType = parseValueType(kvDoc.getValueType()); if (valueType == (ValueType.YAML) || valueType == (ValueType.YML)) { return Parser.findParser(Parser.CONTENT_TYPE_YAML).parse(kvDoc.getValue(), kvDoc.getKey(), true); } else if (valueType == (ValueType.PROPERTIES)) { return Parser.findParser(Parser.CONTENT_TYPE_PROPERTIES).parse(kvDoc.getValue(), kvDoc.getKey(), true); } else { return Parser.findParser(Parser.CONTENT_TYPE_RAW).parse(kvDoc.getValue(), kvDoc.getKey(), true); } } static String encrypt(String dataStr); static Map<String, Object> getConfigByLabel(KVResponse resp); static Map<String, Object> processValueType(KVDoc kvDoc); } | @Test public void test_processValueType() { KVDoc kvDoc = new KVDoc(); kvDoc.setKey("hello"); kvDoc.setValue("world"); Map<String, Object> result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello")); kvDoc.setValueType("text"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello")); kvDoc.setValueType("string"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello")); kvDoc.setValueType("json"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello")); kvDoc.setValueType("yml"); kvDoc.setValue("hello: world"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello.hello")); kvDoc.setValueType("yaml"); kvDoc.setValue("hello: world"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello.hello")); kvDoc.setValueType("properties"); kvDoc.setValue("hello=world"); result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello.hello")); } |
KieClient { public void refreshKieConfig() { if (enableLongPolling) { EXECUTOR.execute(new ConfigRefresh(serviceUri)); } else { EXECUTOR.scheduleWithFixedDelay(new ConfigRefresh(serviceUri), firstRefreshInterval, refreshInterval, TimeUnit.MILLISECONDS); } } KieClient(UpdateHandler updateHandler); void refreshKieConfig(); void destroy(); } | @SuppressWarnings("unchecked") @Test public void testRefreshKieConfig() { HttpClientRequest request = Mockito.mock(HttpClientRequest.class); Mockito.when(request.method()).thenReturn(HttpMethod.GET); Mockito.when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap()); Buffer rsp = Mockito.mock(Buffer.class); Mockito.when(rsp.toJsonObject()).thenReturn(new JsonObject(mockKvResponse)); HttpClientResponse event = Mockito.mock(HttpClientResponse.class); Mockito.when(event.bodyHandler(Mockito.any(Handler.class))).then(invocation -> { Handler<Buffer> handler = invocation.getArgumentAt(0, Handler.class); handler.handle(rsp); return null; }); Mockito.when(event.statusCode()).thenReturn(200); HttpClient httpClient = Mockito.mock(HttpClient.class); Mockito.when( httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Handler.class))) .then(invocation -> { Handler<HttpClientResponse> handler = invocation.getArgumentAt(3, Handler.class); handler.handle(event); return request; }); new MockUp<HttpClientWithContext>() { @Mock public void runOnContext(RunHandler handler) { handler.run(httpClient); } }; UpdateHandler updateHandler = new KieConfigurationSourceImpl().new UpdateHandler(); KieClient kie = new KieClient(updateHandler); kie.refreshKieConfig(); } |
KieClient { public void destroy() { if (EXECUTOR != null) { EXECUTOR.shutdown(); EXECUTOR = null; } } KieClient(UpdateHandler updateHandler); void refreshKieConfig(); void destroy(); } | @Test public void destroy() { KieClient kieClient = new KieClient(null); ScheduledExecutorService executor = Deencapsulation.getField(kieClient, "EXECUTOR"); Assert.assertFalse(executor.isShutdown()); executor.shutdown(); Assert.assertTrue(executor.isShutdown()); } |
KieConfig { public String getServerUri() { return finalConfig.getString(SERVER_URL_KEY); } private KieConfig(); static ConcurrentCompositeConfiguration getFinalConfig(); static void setFinalConfig(ConcurrentCompositeConfiguration finalConfig); int getConnectionTimeOut(); int getEventLoopSize(); int getVerticalInstanceCount(); int getIdleTimeoutInSeconds(); String getVersion(); String getServiceName(); String getTags(); String getEnvironment(); String getAppName(); String getDomainName(); String getServerUri(); int getRefreshInterval(); int getFirstRefreshInterval(); boolean enableLongPolling(); Boolean isProxyEnable(); String getProxyHost(); int getProxyPort(); String getProxyUsername(); String getProxyPasswd(); static final KieConfig INSTANCE; static final String CONNECTION_TIME_OUT; static final String EVENT_LOOP_SIZE; static final String VERTICAL_INSTANCE_COUNT; static final String IDLE_TIMEOUT_IN_SECONDES; } | @Test public void getServerUri() { String servers = KieConfig.INSTANCE.getServerUri(); Assert.assertEquals("https: } |
KieConfig { public String getEnvironment() { return BootStrapProperties.readServiceEnvironment(finalConfig); } private KieConfig(); static ConcurrentCompositeConfiguration getFinalConfig(); static void setFinalConfig(ConcurrentCompositeConfiguration finalConfig); int getConnectionTimeOut(); int getEventLoopSize(); int getVerticalInstanceCount(); int getIdleTimeoutInSeconds(); String getVersion(); String getServiceName(); String getTags(); String getEnvironment(); String getAppName(); String getDomainName(); String getServerUri(); int getRefreshInterval(); int getFirstRefreshInterval(); boolean enableLongPolling(); Boolean isProxyEnable(); String getProxyHost(); int getProxyPort(); String getProxyUsername(); String getProxyPasswd(); static final KieConfig INSTANCE; static final String CONNECTION_TIME_OUT; static final String EVENT_LOOP_SIZE; static final String VERTICAL_INSTANCE_COUNT; static final String IDLE_TIMEOUT_IN_SECONDES; } | @Test public void getEnvironment() { Assert.assertEquals("testing", KieConfig.INSTANCE.getEnvironment()); System.setProperty("SERVICECOMB_ENV", "development"); KieConfig.setFinalConfig(ConfigUtil.createLocalConfig()); Assert.assertEquals("development", KieConfig.INSTANCE.getEnvironment()); } |
KieWatcher { public void refreshConfigItems(Map<String, Object> remoteItems) { String md5Vaule = KieUtil.encrypt(remoteItems.toString()); if (CollectionUtils.isEmpty(remoteItems)) { updateHandler.handle("delete", lastTimeData); lastTimeData = remoteItems; return; } if (StringUtils.isEmpty(refreshRecord)) { refreshRecord = md5Vaule; updateHandler.handle("create", remoteItems); lastTimeData = remoteItems; return; } if (md5Vaule.equals(refreshRecord)) { return; } refreshRecord = md5Vaule; doRefresh(remoteItems); lastTimeData = remoteItems; } private KieWatcher(); void setUpdateHandler(UpdateHandler updateHandler); void refreshConfigItems(Map<String, Object> remoteItems); static final KieWatcher INSTANCE; } | @Test public void testRefreshConfigItems() { boolean status = true; Map<String, Object> configMap = new HashMap<>(); configMap.put("key1", "application1"); configMap.put("key2", "application2"); configMap.put("key3", "application3"); configMap.put("key4", "application4"); Map<String, Object> result = null; try { result = Deencapsulation.invoke(KieWatcher.INSTANCE, "refreshConfigItems", configMap); } catch (Exception e) { status = false; } Assert.assertTrue(status); } |
ZeroConfigRegistryService { public ServerMicroserviceInstance getMicroservice(String microserviceId) { Map<String, ServerMicroserviceInstance> instanceIdMap = ServerUtil.microserviceInstanceMap .get(microserviceId); if (instanceIdMap != null) { List<ServerMicroserviceInstance> serverMicroserviceInstanceList = new ArrayList<>( instanceIdMap.values()); return serverMicroserviceInstanceList.get(0); } return null; } void registerMicroserviceInstance(ServerMicroserviceInstance receivedInstance); void unregisterMicroserviceInstance(ServerMicroserviceInstance receivedInstance); ServerMicroserviceInstance findServiceInstance(String serviceId,
String instanceId); List<ServerMicroserviceInstance> getMicroserviceInstance(String consumerId,
String providerId); void heartbeat(ServerMicroserviceInstance receivedInstance); boolean heartbeat(String microserviceId, String microserviceInstanceId); ServerMicroserviceInstance getMicroservice(String microserviceId); List<ServerMicroserviceInstance> findServiceInstances(String appId, String serviceName); } | @Test public void test_getMicroservice_whenServiceExist_shouldReturnService() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); ServerMicroserviceInstance returnedResult = target.getMicroservice(serviceId); Assert.assertNotNull(returnedResult); Assert.assertEquals(serviceId, returnedResult.getServiceId()); }
@Test public void test_getMicroservice_whenServiceNotExist_shouldReturnNull() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); ServerMicroserviceInstance returnedResult = target.getMicroservice(otherServiceId); Assert.assertNull(returnedResult); } |
ZeroConfigRegistryService { public List<ServerMicroserviceInstance> findServiceInstances(String appId, String serviceName) { List<ServerMicroserviceInstance> resultInstanceList = new ArrayList<>(); ServerUtil.microserviceInstanceMap.forEach((serviceId, instanceIdMap) -> { instanceIdMap.forEach((instanceId, instance) -> { if (appId.equals(instance.getAppId()) && serviceName.equals(instance.getServiceName())) { resultInstanceList.add(instance); } }); }); return resultInstanceList; } void registerMicroserviceInstance(ServerMicroserviceInstance receivedInstance); void unregisterMicroserviceInstance(ServerMicroserviceInstance receivedInstance); ServerMicroserviceInstance findServiceInstance(String serviceId,
String instanceId); List<ServerMicroserviceInstance> getMicroserviceInstance(String consumerId,
String providerId); void heartbeat(ServerMicroserviceInstance receivedInstance); boolean heartbeat(String microserviceId, String microserviceInstanceId); ServerMicroserviceInstance getMicroservice(String microserviceId); List<ServerMicroserviceInstance> findServiceInstances(String appId, String serviceName); } | @Test public void test_findServiceInstances_whenInstanceExist_shouldReturnInstanceList() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); List<ServerMicroserviceInstance> returnedResult = target .findServiceInstances(appId, serviceName); Assert.assertTrue(!returnedResult.isEmpty()); Assert.assertEquals(2, returnedResult.size()); }
@Test public void test_findServiceInstances_whenNoInstanceExist_shouldReturnEmptyInstanceList() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); List<ServerMicroserviceInstance> returnedResult = target .findServiceInstances(appId, otherServiceName); Assert.assertTrue(returnedResult.isEmpty()); } |
LoadbalanceExceptionUtils extends ExceptionUtils { public static CseException createLoadbalanceException(String code, Throwable cause, Object... args) { String msg = String.format(ERROR_DESC_MGR.ensureFindValue(code), args); CseException exception = new CseException(code, msg, cause); return exception; } static CseException createLoadbalanceException(String code, Throwable cause, Object... args); static final String CSE_HANDLER_LB_WRONG_RULE; } | @Test public void testLoadbalanceExceptionUtils() { assertEquals("servicecomb.handler.lb.wrong.rule", LoadbalanceExceptionUtils.CSE_HANDLER_LB_WRONG_RULE); CseException cseException = LoadbalanceExceptionUtils.createLoadbalanceException("servicecomb.handler.lb.wrong.rule", new Throwable(), "ARGS"); Assert.assertNotNull(cseException); } |
IsolationDiscoveryFilter implements DiscoveryFilter { @Override public DiscoveryTreeNode discovery(DiscoveryContext context, DiscoveryTreeNode parent) { Map<String, MicroserviceInstance> instances = parent.data(); Invocation invocation = context.getInputParameters(); if (!Configuration.INSTANCE.isIsolationFilterOpen(invocation.getMicroserviceName())) { return parent; } Map<String, MicroserviceInstance> filteredServers = new HashMap<>(); instances.entrySet().forEach(stringMicroserviceInstanceEntry -> { MicroserviceInstance instance = stringMicroserviceInstanceEntry.getValue(); if (allowVisit(invocation, instance)) { filteredServers.put(stringMicroserviceInstanceEntry.getKey(), instance); } }); DiscoveryTreeNode child = new DiscoveryTreeNode(); if (ZoneAwareDiscoveryFilter.GROUP_Instances_All .equals(context.getContextParameter(ZoneAwareDiscoveryFilter.KEY_ZONE_AWARE_STEP)) && filteredServers.isEmpty() && emptyProtection.get()) { LOGGER.warn("All servers have been isolated, allow one of them based on load balance rule."); child.data(instances); } else { child.data(filteredServers); } parent.child("filterred", child); return child; } IsolationDiscoveryFilter(); @Override int getOrder(); @Override boolean enabled(); @Override boolean isGroupingFilter(); @Override DiscoveryTreeNode discovery(DiscoveryContext context, DiscoveryTreeNode parent); static final String TRYING_INSTANCES_EXISTING; public EventBus eventBus; } | @Test public void discovery_no_instance_reach_error_threshold() { DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); }
@Test public void discovery_isolate_error_instance() { ServiceCombServer server0 = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(data.get("i0")); for (int i = 0; i < 4; ++i) { ServiceCombLoadBalancerStats.INSTANCE.markFailure(server0); } DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); ServiceCombLoadBalancerStats.INSTANCE.markFailure(server0); Assert.assertFalse(ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServerStats(server0).isIsolated()); childNode = filter.discovery(discoveryContext, discoveryTreeNode); childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i1", "i2")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); Assert.assertTrue(ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServerStats(server0).isIsolated()); }
@Test public void discovery_try_isolated_instance_after_singleTestTime() { ServiceCombServer server0 = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(data.get("i0")); ServiceCombServerStats serviceCombServerStats = ServiceCombLoadBalancerStats.INSTANCE .getServiceCombServerStats(server0); for (int i = 0; i < 5; ++i) { serviceCombServerStats.markFailure(); } letIsolatedInstancePassSingleTestTime(serviceCombServerStats); ServiceCombLoadBalancerStats.INSTANCE.markIsolated(server0, true); Assert.assertTrue(ServiceCombServerStats.isolatedServerCanTry()); Assert.assertNull(TestServiceCombServerStats.getTryingIsolatedServerInvocation()); DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); Assert.assertTrue(serviceCombServerStats.isIsolated()); Assert.assertFalse(ServiceCombServerStats.isolatedServerCanTry()); Assert.assertSame(invocation, TestServiceCombServerStats.getTryingIsolatedServerInvocation()); }
@Test public void discovery_not_try_isolated_instance_concurrently() { ServiceCombServer server0 = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(data.get("i0")); ServiceCombServerStats serviceCombServerStats = ServiceCombLoadBalancerStats.INSTANCE .getServiceCombServerStats(server0); for (int i = 0; i < 5; ++i) { serviceCombServerStats.markFailure(); } ServiceCombLoadBalancerStats.INSTANCE.markIsolated(server0, true); letIsolatedInstancePassSingleTestTime(serviceCombServerStats); Assert.assertTrue(ServiceCombServerStats.isolatedServerCanTry()); DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); Assert.assertFalse(ServiceCombServerStats.isolatedServerCanTry()); childNode = filter.discovery(discoveryContext, discoveryTreeNode); childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i1", "i2")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); ServiceCombServerStats .checkAndReleaseTryingChance(invocation); childNode = filter.discovery(discoveryContext, discoveryTreeNode); childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); Assert.assertFalse(ServiceCombServerStats.isolatedServerCanTry()); }
@Test public void discovery_keep_minIsolationTime() { ServiceCombServer server0 = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(data.get("i0")); ServiceCombLoadBalancerStats.INSTANCE.markIsolated(server0, true); ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server0); DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i1", "i2")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); ServiceCombServerStats serviceCombServerStats = ServiceCombLoadBalancerStats.INSTANCE .getServiceCombServerStats(server0); Deencapsulation.setField(serviceCombServerStats, "lastVisitTime", System.currentTimeMillis() - Configuration.INSTANCE.getMinIsolationTime(invocation.getMicroserviceName()) - 1); childNode = filter.discovery(discoveryContext, discoveryTreeNode); childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); }
@Test public void discovery_recover_instance() { ServiceCombServer server0 = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(data.get("i0")); ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server0); ServiceCombServerStats serviceCombServerStats = ServiceCombLoadBalancerStats.INSTANCE .getServiceCombServerStats(server0); Deencapsulation.setField(serviceCombServerStats, "lastVisitTime", System.currentTimeMillis() - Configuration.INSTANCE.getMinIsolationTime(invocation.getMicroserviceName()) - 1); ServiceCombLoadBalancerStats.INSTANCE.markIsolated(server0, true); DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.assertEquals(data.get("i0"), childNodeData.get("i0")); Assert.assertEquals(data.get("i1"), childNodeData.get("i1")); Assert.assertEquals(data.get("i2"), childNodeData.get("i2")); Assert.assertFalse(ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServerStats(server0).isIsolated()); } |
InstancePropertyDiscoveryFilter extends AbstractDiscoveryFilter { protected boolean allowVisit(MicroserviceInstance instance, Map<String, String> filterOptions) { Map<String, String> propertiesMap = instance.getProperties(); for (Entry<String, String> entry : filterOptions.entrySet()) { if (!entry.getValue().equals(propertiesMap.get(entry.getKey()))) { return false; } } return true; } @Override int getOrder(); @Override boolean enabled(); @Override boolean isGroupingFilter(); } | @Test public void testAllowVisit() { Map<String, String> filterOptions = new HashMap<>(); Assert.assertTrue(filter.allowVisit(instance, filterOptions)); filterOptions.put("tag0", "value0"); Assert.assertTrue(filter.allowVisit(instance, filterOptions)); filterOptions.put("tag2", "value2"); Assert.assertFalse(filter.allowVisit(instance, filterOptions)); filterOptions.clear(); filterOptions.put("tag0", "value1"); Assert.assertFalse(filter.allowVisit(instance, filterOptions)); } |
ServerDiscoveryFilter extends EndpointDiscoveryFilter { @Override protected Object createEndpoint(String transportName, String endpoint, MicroserviceInstance instance) { Transport transport = SCBEngine.getInstance().getTransportManager().findTransport(transportName); if (transport == null) { LOGGER.info("not deployed transport {}, ignore {}.", transportName, endpoint); return null; } return new ServiceCombServer(transport, new CacheEndpoint(endpoint, instance)); } } | @Test public void createEndpoint_TransportNotExist() { new Expectations(transportManager) { { transportManager.findTransport(anyString); result = null; } }; ServiceCombServer server = (ServiceCombServer) filter.createEndpoint(Const.RESTFUL, null, null); Assert.assertNull(server); }
@Test public void createEndpointNormal() { new Expectations(transportManager) { { transportManager.findTransport(anyString); result = trasport; } }; MicroserviceInstance instance = new MicroserviceInstance(); instance.setInstanceId("0000001"); ServiceCombServer server = (ServiceCombServer) filter .createEndpoint(Const.RESTFUL, "rest: Assert.assertSame(instance, server.getInstance()); Assert.assertSame(trasport, server.getEndpoint().getTransport()); Assert.assertEquals("rest: } |
Configuration { public int getRetryNextServer(String microservice) { return getRetryServer(microservice, RETRY_ON_NEXT); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testConfigurationWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.getRetryNextServer("test"); assertNotNull(Configuration.INSTANCE.getRetryNextServer("test")); }
@Test public void testConfigurationWithGetpropertyReturnsStringNum() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "1234"; } }; Configuration.INSTANCE.getRetryNextServer("test"); assertNotNull(Configuration.INSTANCE.getRetryNextServer("test")); } |
Configuration { public int getRetrySameServer(String microservice) { return getRetryServer(microservice, RETRY_ON_SAME); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testGetRetryOnSameWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.getRetrySameServer("test"); assertNotNull(Configuration.INSTANCE.getRetrySameServer("test")); }
@Test public void testGetRetryOnSameWithGetpropertyReturnsStringNum() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "1234"; } }; Configuration.INSTANCE.getRetrySameServer("test"); assertNotNull(Configuration.INSTANCE.getRetrySameServer("test")); } |
Configuration { public boolean isRetryEnabled(String microservice) { String p = getStringProperty("false", ROOT + microservice + "." + RETRY_ENABLED, ROOT + RETRY_ENABLED); return Boolean.parseBoolean(p); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testIsRetryEnabledWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.isRetryEnabled("test"); assertNotNull(Configuration.INSTANCE.isRetryEnabled("test")); }
@Test public void testIsRetryEnabledWithGetpropertyReturnsStringNum() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "1234"; } }; Configuration.INSTANCE.isRetryEnabled("test"); assertNotNull(Configuration.INSTANCE.isRetryEnabled("test")); } |
Configuration { public int getSuccessiveFailedTimes(String microservice) { final int defaultValue = 5; String p = getStringProperty("5", ROOT + microservice + "." + SUCCESSIVE_FAILED_TIMES, ROOT + SUCCESSIVE_FAILED_TIMES); try { return Integer.parseInt(p); } catch (NumberFormatException e) { return defaultValue; } } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testGetSuccessiveFailedTimes() { assertNotNull(Configuration.INSTANCE.getSuccessiveFailedTimes("test")); } |
Configuration { public int getSessionTimeoutInSeconds(String microservice) { final int defaultValue = 30; String p = getStringProperty("30", ROOT + microservice + "." + SESSION_TIMEOUT_IN_SECONDS, ROOT + SESSION_TIMEOUT_IN_SECONDS); try { return Integer.parseInt(p); } catch (NumberFormatException e) { return defaultValue; } } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testGetSessionTimeoutInSeconds() { assertNotNull(Configuration.INSTANCE.getSessionTimeoutInSeconds("test")); } |
Configuration { public int getMaxSingleTestWindow() { final int defaultValue = 60000; String p = getStringProperty(Integer.toString(defaultValue), ROOT + FILTER_ISOLATION + FILTER_MAX_SINGLE_TEST_WINDOW); try { int result = Integer.parseInt(p); if (result >= 0) { return result; } return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHandler(String microservice); boolean isRetryEnabled(String microservice); int getRetryNextServer(String microservice); int getRetrySameServer(String microservice); boolean isIsolationFilterOpen(String microservice); int getErrorThresholdPercentage(String microservice); int getEnableRequestThreshold(String microservice); int getSingleTestTime(String microservice); int getMaxSingleTestWindow(); int getMinIsolationTime(String microservice); Map<String, String> getFlowsplitFilterOptions(String microservice); static String getStringProperty(String defaultValue, String... keys); int getContinuousFailureThreshold(String microservice); static final String ROOT; static final String SERVER_EXPIRED_IN_SECONDS; static final String TIMER_INTERVAL_IN_MILLIS; static final String RULE_STRATEGY_NAME; static final String ROOT_20; static final String RETRY_HANDLER; static final String RETRY_ENABLED; static final String RETRY_ON_NEXT; static final String RETRY_ON_SAME; static final String SESSION_TIMEOUT_IN_SECONDS; static final String SUCCESSIVE_FAILED_TIMES; static final String FILTER_ISOLATION; static final String FILTER_OPEN; static final String FILTER_ERROR_PERCENTAGE; static final String FILTER_ENABLE_REQUEST; static final String FILTER_SINGLE_TEST; static final String FILTER_MAX_SINGLE_TEST_WINDOW; static final String FILTER_MIN_ISOLATION_TIME; static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD; static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN; static final Configuration INSTANCE; } | @Test public void testGetMaxSingleTestWindow() { assertEquals(60000, Configuration.INSTANCE.getMaxSingleTestWindow()); ArchaiusUtils.setProperty("servicecomb.loadbalance.isolation.maxSingleTestWindow", 5000); assertEquals(5000, Configuration.INSTANCE.getMaxSingleTestWindow()); } |
LoadbalanceHandler implements Handler { private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, LoadBalancer chosenLB) throws Exception { long time = System.currentTimeMillis(); int currentHandler = invocation.getHandlerIndex(); SyncResponseExecutor orginExecutor; Executor newExecutor; if (invocation.getResponseExecutor() instanceof SyncResponseExecutor) { orginExecutor = (SyncResponseExecutor) invocation.getResponseExecutor(); newExecutor = new Executor() { @Override public void execute(Runnable command) { RETRY_POOL.submit(command); } }; invocation.setResponseExecutor(newExecutor); } else { orginExecutor = null; newExecutor = null; } ExecutionListener<Invocation, Response> listener = new ExecutionListener<Invocation, Response>() { @Override public void onExecutionStart(ExecutionContext<Invocation> context) throws AbortExecutionException { } @Override public void onStartWithServer(ExecutionContext<Invocation> context, ExecutionInfo info) throws AbortExecutionException { } @Override public void onExceptionWithServer(ExecutionContext<Invocation> context, Throwable exception, ExecutionInfo info) { context.getRequest().getTraceIdLogger() .error(LOGGER, "Invoke server failed. Operation {}; server {}; {}-{} msg {}", context.getRequest().getInvocationQualifiedName(), context.getRequest().getEndpoint(), info.getNumberOfPastServersAttempted(), info.getNumberOfPastAttemptsOnServer(), ExceptionUtils.getExceptionMessageWithoutTrace(exception)); } @Override public void onExecutionSuccess(ExecutionContext<Invocation> context, Response response, ExecutionInfo info) { if (info.getNumberOfPastServersAttempted() > 0 || info.getNumberOfPastAttemptsOnServer() > 0) { context.getRequest().getTraceIdLogger().error(LOGGER, "Invoke server success. Operation {}; server {}", context.getRequest().getInvocationQualifiedName(), context.getRequest().getEndpoint()); } if (orginExecutor != null) { orginExecutor.execute(() -> { asyncResp.complete(response); }); } else { asyncResp.complete(response); } } @Override public void onExecutionFailed(ExecutionContext<Invocation> context, Throwable finalException, ExecutionInfo info) { context.getRequest().getTraceIdLogger().error(LOGGER, "Invoke all server failed. Operation {}, e={}", context.getRequest().getInvocationQualifiedName(), ExceptionUtils.getExceptionMessageWithoutTrace(finalException)); if (orginExecutor != null) { orginExecutor.execute(() -> { fail(finalException); }); } else { fail(finalException); } } private void fail(Throwable finalException) { int depth = 10; Throwable t = finalException; while (depth-- > 0) { if (t instanceof InvocationException) { asyncResp.consumerFail(t); return; } t = finalException.getCause(); } asyncResp.consumerFail(finalException); } }; List<ExecutionListener<Invocation, Response>> listeners = new ArrayList<>(0); listeners.add(listener); ExecutionContext<Invocation> context = new ExecutionContext<>(invocation, null, null, null); LoadBalancerCommand<Response> command = LoadBalancerCommand.<Response>builder() .withLoadBalancer(new RetryLoadBalancer(chosenLB)) .withServerLocator(invocation) .withRetryHandler(ExtensionsManager.createRetryHandler(invocation.getMicroserviceName())) .withListeners(listeners) .withExecutionContext(context) .build(); Observable<Response> observable = command.submit(new ServerOperation<Response>() { public Observable<Response> call(Server s) { return Observable.create(f -> { try { ServiceCombServer server = (ServiceCombServer) s; chosenLB.getLoadBalancerStats().incrementNumRequests(s); invocation.setHandlerIndex(currentHandler); invocation.setEndpoint(server.getEndpoint()); invocation.next(resp -> { if (isFailedResponse(resp)) { invocation.getTraceIdLogger().error(LOGGER, "service {}, call error, msg is {}, server is {} ", invocation.getInvocationQualifiedName(), ExceptionUtils.getExceptionMessageWithoutTrace((Throwable) resp.getResult()), s); chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(s); ServiceCombLoadBalancerStats.INSTANCE.markFailure(server); f.onError(resp.getResult()); } else { chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(s); chosenLB.getLoadBalancerStats().noteResponseTime(s, (System.currentTimeMillis() - time)); ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server); f.onNext(resp); f.onCompleted(); } }); } catch (Exception e) { invocation.getTraceIdLogger() .error(LOGGER, "execution error, msg is {}", ExceptionUtils.getExceptionMessageWithoutTrace(e)); f.onError(e); } }); } }); observable.subscribe(response -> { }, error -> { }, () -> { }); } LoadbalanceHandler(DiscoveryTree discoveryTree); LoadbalanceHandler(); @Override void handle(Invocation invocation, AsyncResponse asyncResp); static final String CONTEXT_KEY_SERVER_LIST; static final String SERVICECOMB_SERVER_ENDPOINT; static final boolean supportDefinedEndpoint; } | @Test public void sendWithRetry(@Injectable LoadBalancer loadBalancer) { Holder<String> result = new Holder<>(); Deencapsulation.invoke(handler, "sendWithRetry", invocation, (AsyncResponse) resp -> { result.value = resp.getResult(); }, loadBalancer); } |
LoadbalanceHandler implements Handler { protected boolean isFailedResponse(Response resp) { if (resp.isFailed()) { if (InvocationException.class.isInstance(resp.getResult())) { InvocationException e = (InvocationException) resp.getResult(); return e.getStatusCode() == ExceptionFactory.CONSUMER_INNER_STATUS_CODE || e.getStatusCode() == 503; } else { return true; } } else { return false; } } LoadbalanceHandler(DiscoveryTree discoveryTree); LoadbalanceHandler(); @Override void handle(Invocation invocation, AsyncResponse asyncResp); static final String CONTEXT_KEY_SERVER_LIST; static final String SERVICECOMB_SERVER_ENDPOINT; static final boolean supportDefinedEndpoint; } | @Test public void testIsFailedResponse() { Assert.assertFalse(handler.isFailedResponse(Response.create(400, "", ""))); Assert.assertFalse(handler.isFailedResponse(Response.create(500, "", ""))); Assert.assertTrue(handler.isFailedResponse(Response.create(490, "", ""))); Assert.assertTrue(handler.isFailedResponse(Response.consumerFailResp(new NullPointerException()))); } |
ExtensionsManager { public static RuleExt createLoadBalancerRule(String microservice) { RuleExt rule = null; for (ExtensionsFactory factory : extentionFactories) { if (factory.isSupport(Configuration.RULE_STRATEGY_NAME, Configuration.INSTANCE.getRuleStrategyName(microservice))) { rule = factory.createLoadBalancerRule( Configuration.INSTANCE.getRuleStrategyName(microservice)); break; } } if (rule == null) { rule = new RoundRobinRuleExt(); } LOGGER.info("Using load balance rule {} for microservice {}.", rule.getClass().getName(), microservice); return rule; } static void addExtentionsFactory(ExtensionsFactory factory); static RuleExt createLoadBalancerRule(String microservice); static RetryHandler createRetryHandler(String microservice); } | @Test public void testRuleName() { System.setProperty("servicecomb.loadbalance.mytest1.strategy.name", "RoundRobin"); System.setProperty("servicecomb.loadbalance.mytest2.strategy.name", "Random"); System.setProperty("servicecomb.loadbalance.mytest3.strategy.name", "WeightedResponse"); System.setProperty("servicecomb.loadbalance.mytest4.strategy.name", "SessionStickiness"); BeansHolder holder = new BeansHolder(); List<ExtensionsFactory> extensionsFactories = new ArrayList<>(); extensionsFactories.add(new RuleNameExtentionsFactory()); extensionsFactories.add(new DefaultRetryExtensionsFactory()); Deencapsulation.setField(holder, "extentionsFactories", extensionsFactories); holder.init(); Assert.assertEquals(RoundRobinRuleExt.class.getName(), ExtensionsManager.createLoadBalancerRule("mytest1").getClass().getName()); Assert.assertEquals(RandomRuleExt.class.getName(), ExtensionsManager.createLoadBalancerRule("mytest2").getClass().getName()); Assert.assertEquals(WeightedResponseTimeRuleExt.class.getName(), ExtensionsManager.createLoadBalancerRule("mytest3").getClass().getName()); Assert.assertEquals(SessionStickinessRule.class.getName(), ExtensionsManager.createLoadBalancerRule("mytest4").getClass().getName()); System.getProperties().remove("servicecomb.loadbalance.mytest1.strategy.name"); System.getProperties().remove("servicecomb.loadbalance.mytest2.strategy.name"); System.getProperties().remove("servicecomb.loadbalance.mytest3.strategy.name"); System.getProperties().remove("servicecomb.loadbalance.mytest4.strategy.name"); } |
ExtensionsManager { public static RetryHandler createRetryHandler(String microservice) { RetryHandler handler = null; for (ExtensionsFactory factory : extentionFactories) { if (factory.isSupport(Configuration.RETRY_HANDLER, Configuration.INSTANCE.getRetryHandler(microservice))) { handler = factory.createRetryHandler(Configuration.INSTANCE.getRetryHandler(microservice), microservice); break; } } LOGGER.debug("Using retry handler {} for microservice {}.", handler.getClass().getName(), microservice); return handler; } static void addExtentionsFactory(ExtensionsFactory factory); static RuleExt createLoadBalancerRule(String microservice); static RetryHandler createRetryHandler(String microservice); } | @Test public void testRuleClassName() { BeansHolder holder = new BeansHolder(); List<ExtensionsFactory> extensionsFactories = new ArrayList<>(); extensionsFactories.add(new RuleNameExtentionsFactory()); extensionsFactories.add(new DefaultRetryExtensionsFactory()); Deencapsulation.setField(holder, "extentionsFactories", extensionsFactories); holder.init(); RetryHandler retryHandler = ExtensionsManager.createRetryHandler("mytest1"); Assert.assertTrue(DefaultLoadBalancerRetryHandler.class.isInstance(retryHandler)); Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), false)); Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), true)); Assert.assertTrue(retryHandler.isRetriableException(new InvocationException(503, "", ""), true)); Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), false)); Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), true)); Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), false)); Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), true)); Assert.assertFalse(retryHandler.isRetriableException(new IOException(), true)); } |
RoundRobinRuleExt implements RuleExt { @Override public ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation) { if (servers.isEmpty()) { return null; } int index = Math.abs(counter.getAndIncrement()) % servers.size(); return servers.get(index); } @Override ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation); } | @Test public void testRoundRobin() { RoundRobinRuleExt rule = new RoundRobinRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 2; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, 1); } AtomicInteger server1 = new AtomicInteger(0); AtomicInteger server2 = new AtomicInteger(0); for (int i = 0; i < 2000; i++) { if (rule.choose(servers, invocation).toString().equals("server 0")) { server1.incrementAndGet(); } else { server2.incrementAndGet(); } } Assert.assertEquals(server1.get(), server2.get()); }
@Test public void testBenchmarkRobin() { RoundRobinRuleExt rule = new RoundRobinRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 100; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, 2); } long begin = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { rule.choose(servers, invocation); } long taken = System.currentTimeMillis() - begin; System.out.println("taken " + taken); Assert.assertEquals("actual token " + taken, taken < 10 * 5, true); } |
WeightedResponseTimeRuleExt extends RoundRobinRuleExt { @Override public ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation) { List<Double> stats = calculateTotalWeights(servers); if (stats.size() > 0) { double finalTotal = stats.get(stats.size() - 1); List<Double> weights = new ArrayList<>(servers.size()); for (int i = 0; i < stats.size() - 1; i++) { weights.add(finalTotal - stats.get(i)); } double ran = ThreadLocalRandom.current().nextDouble() * finalTotal * (servers.size() - 1); for (int i = 0; i < weights.size(); i++) { ran -= weights.get(i); if (ran < 0) { return servers.get(i); } } return servers.get(servers.size() - 1); } return super.choose(servers, invocation); } @Override void setLoadBalancer(LoadBalancer loadBalancer); @Override ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation); } | @Test public void testRoundRobin() { WeightedResponseTimeRuleExt rule = new WeightedResponseTimeRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 2; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, 1); } AtomicInteger server1 = new AtomicInteger(0); AtomicInteger server2 = new AtomicInteger(0); for (int i = 0; i < 2000; i++) { if (rule.choose(servers, invocation).toString().equals("server 0")) { server1.incrementAndGet(); } else { server2.incrementAndGet(); } } Assert.assertEquals(server1.get(), server2.get()); }
@Test public void testWeighed() { WeightedResponseTimeRuleExt rule = new WeightedResponseTimeRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 2; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, 20 * Math.pow(4, i + 1)); } AtomicInteger server1 = new AtomicInteger(0); AtomicInteger server2 = new AtomicInteger(0); for (int i = 0; i < 2000; i++) { if (rule.choose(servers, invocation).toString().equals("server 0")) { server1.incrementAndGet(); } else { server2.incrementAndGet(); } } double percent = (double) server1.get() / (server2.get() + server1.get()); System.out.println("percent" + percent); Assert.assertEquals("actually percent: " + percent, 0.70d < percent, percent < 0.90d); }
@Test public void testBenchmark() { WeightedResponseTimeRuleExt rule = new WeightedResponseTimeRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 100; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, i); } long begin = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { rule.choose(servers, invocation); } long taken = System.currentTimeMillis() - begin; System.out.println("taken " + taken); Assert.assertEquals("actually taken: " + taken, taken < 1000 * 5, true); }
@Test public void testBenchmarkRobin() { WeightedResponseTimeRuleExt rule = new WeightedResponseTimeRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 100; i++) { ServiceCombServer server = Mockito.mock(ServiceCombServer.class); Mockito.when(server.toString()).thenReturn("server " + i); servers.add(server); loadBalancer.getLoadBalancerStats().noteResponseTime(server, 2); } long begin = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { rule.choose(servers, invocation); } long taken = System.currentTimeMillis() - begin; System.out.println("taken " + taken); Assert.assertEquals("actually taken: " + taken, taken < 200 * 5, true); } |
ServiceCombServerStats { public static boolean applyForTryingChance(Invocation invocation) { TryingIsolatedServerMarker marker = globalAllowIsolatedServerTryingFlag.get(); if (marker == null) { return globalAllowIsolatedServerTryingFlag.compareAndSet(null, new TryingIsolatedServerMarker(invocation)); } if (marker.isOutdated()) { return globalAllowIsolatedServerTryingFlag.compareAndSet(marker, new TryingIsolatedServerMarker(invocation)); } return false; } ServiceCombServerStats(); ServiceCombServerStats(Clock clock); static boolean isolatedServerCanTry(); static boolean applyForTryingChance(Invocation invocation); static void checkAndReleaseTryingChance(Invocation invocation); void markIsolated(boolean isolated); void markSuccess(); void markFailure(); long getLastVisitTime(); long getLastActiveTime(); long getCountinuousFailureCount(); long getTotalRequests(); long getSuccessRequests(); long getFailedRequests(); int getSuccessRate(); int getFailedRate(); boolean isIsolated(); } | @Test public void testGlobalAllowIsolatedServerTryingFlag_apply_with_null_precondition() { Invocation invocation = new Invocation(); Assert.assertTrue(ServiceCombServerStats.applyForTryingChance(invocation)); Assert.assertSame(invocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation()); }
@Test public void testGlobalAllowIsolatedServerTryingFlag_apply_with_chance_occupied() { Invocation invocation = new Invocation(); Assert.assertTrue(ServiceCombServerStats.applyForTryingChance(invocation)); Assert.assertSame(invocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation()); Invocation otherInvocation = new Invocation(); Assert.assertFalse(ServiceCombServerStats.applyForTryingChance(otherInvocation)); Assert.assertSame(invocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation()); }
@Test public void testGlobalAllowIsolatedServerTryingFlag_apply_with_flag_outdated() { Invocation invocation = new Invocation(); Assert.assertTrue(ServiceCombServerStats.applyForTryingChance(invocation)); Assert.assertSame(invocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation()); ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().clock = new MockClock(new Holder<>( ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().startTryingTimestamp + 60000 )); Invocation otherInvocation = new Invocation(); Assert.assertTrue(ServiceCombServerStats.applyForTryingChance(otherInvocation)); Assert .assertSame(otherInvocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation()); } |
ServiceCombServer extends Server { public Endpoint getEndpoint() { return endpoint; } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); } | @Test public void testGetEndpoint() { cs.getEndpoint(); assertNotNull(cs.getEndpoint()); } |
ServiceCombServer extends Server { public boolean equals(Object o) { if (o instanceof ServiceCombServer) { return this.instance.getInstanceId().equals(((ServiceCombServer) o).instance.getInstanceId()); } else { return false; } } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); } | @Test public void testEqualsMethod() { Assert.assertFalse(cs.equals((Object) "abcd")); MicroserviceInstance instance1 = new MicroserviceInstance(); instance1.setInstanceId("1234"); ServiceCombServer other = new ServiceCombServer(transport, new CacheEndpoint("1234", instance1)); Assert.assertFalse(cs.equals(other)); MicroserviceInstance instance2 = new MicroserviceInstance(); instance2.setInstanceId("123456"); other = new ServiceCombServer(transport, new CacheEndpoint("abcd", instance2)); Assert.assertTrue(cs.equals(other)); } |
ServiceCombServer extends Server { public String toString() { return endpoint.getEndpoint(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); } | @Test public void testToStringMethod() { cs.toString(); assertNotNull(cs.toString()); } |
ServiceCombServer extends Server { public String getHost() { return endpoint.getEndpoint(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); } | @Test public void testGetHost() { cs.getHost(); assertNotNull(cs.getHost()); } |
ServiceCombServer extends Server { public int hashCode() { return this.instance.getInstanceId().hashCode(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); } | @Test public void testHashCodeMethod() { cs.hashCode(); assertNotNull(cs.hashCode()); } |
ProviderQpsFlowControlHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { if (invocation.getHandlerIndex() > 0) { invocation.next(asyncResp); return; } if (!Config.INSTANCE.isProviderEnabled()) { return; } String microserviceName = invocation.getContext(Const.SRC_MICROSERVICE); QpsStrategy qpsStrategy = StringUtils.isEmpty(microserviceName) ? qpsControllerMgr.getGlobalQpsStrategy() : qpsControllerMgr.getOrCreate(microserviceName, invocation); isLimitNewRequest(qpsStrategy, asyncResp); } @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testGlobalQpsControl(final @Injectable Invocation invocation, final @Injectable AsyncResponse asyncResp) throws Exception { new Expectations() { { invocation.getHandlerIndex(); result = 0; invocation.getContext(Const.SRC_MICROSERVICE); result = "test"; invocation.getOperationMeta(); result = QpsControllerManagerTest.getMockOperationMeta("pojo", "server", "opr"); invocation.getSchemaId(); result = "server"; asyncResp.producerFail((Throwable) any); result = new RuntimeException("test error"); } }; ProviderQpsFlowControlHandler gHandler = new ProviderQpsFlowControlHandler(); gHandler.handle(invocation, asyncResp); ArchaiusUtils.setProperty(Config.PROVIDER_LIMIT_KEY_GLOBAL, 3); expectedException.expect(RuntimeException.class); expectedException.expectMessage("test error"); gHandler.handle(invocation, asyncResp); gHandler.handle(invocation, asyncResp); }
@Test public void testHandleOnSourceMicroserviceNameIsNull() throws Exception { Mockito.when(invocation.getContext(Const.SRC_MICROSERVICE)).thenReturn(null); Mockito.when(invocation.getHandlerIndex()).thenReturn(0); ArchaiusUtils.setProperty("servicecomb.flowcontrol.Provider.qps.global.limit", 1); ProviderQpsFlowControlHandler.qpsControllerMgr .setGlobalQpsStrategy(Config.PROVIDER_LIMIT_KEY_GLOBAL, Config.PROVIDER_BUCKET_KEY_GLOBAL); handler.handle(invocation, asyncResp); handler.handle(invocation, asyncResp); Mockito.verify(invocation, times(2)).getContext(Const.SRC_MICROSERVICE); Mockito.verify(asyncResp, times(1)).producerFail(Mockito.any(Exception.class)); }
@Test public void testHandleOnSourceOnHandlerIndexIsGreaterThan0() throws Exception { Mockito.when(invocation.getContext(Const.SRC_MICROSERVICE)).thenReturn(null); Mockito.when(invocation.getHandlerIndex()).thenReturn(1); handler.handle(invocation, asyncResp); handler.handle(invocation, asyncResp); Mockito.verify(invocation, times(0)).getContext(Mockito.anyString()); }
@Test public void testHandle() throws Exception { Mockito.when(invocation.getContext(Const.SRC_MICROSERVICE)).thenReturn("test"); OperationMeta mockOperationMeta = QpsControllerManagerTest.getMockOperationMeta("pojo", "server", "opr"); Mockito.when(invocation.getOperationMeta()).thenReturn(mockOperationMeta); Mockito.when(invocation.getSchemaId()).thenReturn("server"); new MockUp<QpsControllerManager>() { @Mock protected QpsStrategy create(String qualifiedNameKey) { AbstractQpsStrategy strategy = new FixedWindowStrategy(); strategy.setKey(qualifiedNameKey); strategy.setQpsLimit(1L); return strategy; } }; handler.handle(invocation, asyncResp); handler.handle(invocation, asyncResp); ArgumentCaptor<InvocationException> captor = ArgumentCaptor.forClass(InvocationException.class); Mockito.verify(asyncResp, times(1)).producerFail(captor.capture()); InvocationException invocationException = captor.getValue(); assertEquals(QpsConst.TOO_MANY_REQUESTS_STATUS, invocationException.getStatus()); assertEquals("rejected by qps flowcontrol", ((CommonExceptionData) invocationException.getErrorData()).getMessage()); }
@Test public void testHandleIsLimitNewRequestAsFalse() throws Exception { Mockito.when(invocation.getContext(Const.SRC_MICROSERVICE)).thenReturn("test"); OperationMeta mockOperationMeta = QpsControllerManagerTest .getMockOperationMeta("pojo", "server", "opr"); Mockito.when(invocation.getOperationMeta()).thenReturn(mockOperationMeta); Mockito.when(invocation.getSchemaId()).thenReturn("server"); new MockUp<QpsControllerManager>() { @Mock protected QpsStrategy create(String qualifiedNameKey) { AbstractQpsStrategy strategy = new FixedWindowStrategy(); strategy.setKey(qualifiedNameKey); strategy.setQpsLimit(1L); return strategy; } }; handler.handle(invocation, asyncResp); Mockito.verify(invocation, times(0)).next(asyncResp); Mockito.verify(asyncResp, times(0)).producerFail(Mockito.any(Exception.class)); } |
ProviderQpsFlowControlHandler implements Handler { private boolean isLimitNewRequest(QpsStrategy qpsStrategy, AsyncResponse asyncResp) { if (qpsStrategy.isLimitNewRequest()) { CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol"); asyncResp.producerFail(new InvocationException(QpsConst.TOO_MANY_REQUESTS_STATUS, errorData)); return true; } else { return false; } } @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testQpsController() { AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("abc"); qpsStrategy.setQpsLimit(100L); assertFalse(qpsStrategy.isLimitNewRequest()); qpsStrategy.setQpsLimit(1L); assertTrue(qpsStrategy.isLimitNewRequest()); } |
OperationPerfGroup { public void addOperationPerf(OperationPerf operationPerf) { operationPerfs.add(operationPerf); if (summary == null) { summary = new OperationPerf(); summary.setOperation(""); } summary.add(operationPerf); } OperationPerfGroup(String transport, String status); String getTransport(); String getStatus(); List<OperationPerf> getOperationPerfs(); OperationPerf getSummary(); void addOperationPerf(OperationPerf operationPerf); } | @Test public void addOperationPerf() { OperationPerf opPerf = Utils.createOperationPerf(op); group.addOperationPerf(opPerf); group.addOperationPerf(opPerf); Assert.assertThat(group.getOperationPerfs(), Matchers.contains(opPerf, opPerf)); OperationPerf summary = group.getSummary(); PerfInfo perfInfo = summary.findStage(MeterInvocationConst.STAGE_TOTAL); Assert.assertEquals(20, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); perfInfo = summary.findStage(MeterInvocationConst.STAGE_EXECUTION); Assert.assertEquals(20, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); } |
QpsControllerManager { public QpsStrategy getOrCreate(String microserviceName, Invocation invocation) { return qualifiedNameControllerMap .computeIfAbsent( microserviceName + SEPARATOR + invocation.getOperationMeta().getSchemaQualifiedName(), key -> create(key, microserviceName, invocation)); } QpsStrategy getOrCreate(String microserviceName, Invocation invocation); QpsControllerManager setLimitKeyPrefix(String limitKeyPrefix); QpsControllerManager setBucketKeyPrefix(String bucketKeyPrefix); QpsControllerManager setGlobalQpsStrategy(String globalLimitKey, String globalBucketKey); QpsStrategy getGlobalQpsStrategy(); static final String SEPARATOR; } | @Test public void testGetOrCreate(@Mocked Invocation invocation, @Mocked OperationMeta operationMeta) { new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "server"; operationMeta.getSchemaQualifiedName(); result = "server.test"; } }; QpsControllerManager testQpsControllerManager = new QpsControllerManager() .setLimitKeyPrefix(Config.CONSUMER_LIMIT_KEY_PREFIX); initTestQpsControllerManager(testQpsControllerManager, invocation, operationMeta); setConfigWithDefaultPrefix("pojo", 100); QpsStrategy qpsStrategy = testQpsControllerManager.getOrCreate("pojo", invocation); Assert.assertEquals("pojo", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertTrue(100 == ((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); qpsStrategy = testQpsControllerManager.getOrCreate("pojo2", invocation); Assert.assertEquals("pojo2", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); qpsStrategy = testQpsControllerManager.getOrCreate("poj", invocation); Assert.assertEquals("poj", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); ArchaiusUtils.setProperty("servicecomb.flowcontrol.Consumer.qps.limit.poj.server", 10000); qpsStrategy = testQpsControllerManager.getOrCreate("poj", invocation); Assert.assertEquals("poj.server", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertEquals(((AbstractQpsStrategy) qpsStrategy).getQpsLimit(), (Long) 10000L); ArchaiusUtils.setProperty("servicecomb.flowcontrol.Consumer.qps.limit.poj.server.test", 20000); qpsStrategy = testQpsControllerManager.getOrCreate("poj", invocation); Assert.assertEquals("poj.server.test", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertEquals(((AbstractQpsStrategy) qpsStrategy).getQpsLimit(), (Long) 20000L); testGetOrCreateCommon(testQpsControllerManager, invocation, operationMeta); }
@Test public void testQualifiedNameKey(@Mocked Invocation invocation, @Mocked OperationMeta operationMeta) { new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "schema"; operationMeta.getSchemaQualifiedName(); result = "schema.opr"; } }; QpsControllerManager qpsControllerManager = new QpsControllerManager(); QpsStrategy qpsStrategy = qpsControllerManager.getOrCreate("service", invocation); Assert.assertEquals("service", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "test_schema"; operationMeta.getSchemaQualifiedName(); result = "test_schema.test_opr"; } }; qpsStrategy = qpsControllerManager.getOrCreate("test_service", invocation); Assert.assertEquals("test_service", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "test_schema"; operationMeta.getSchemaQualifiedName(); result = "test-schema.test-opr"; } }; qpsStrategy = qpsControllerManager.getOrCreate("test-service", invocation); Assert.assertEquals("test-service", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "schema"; operationMeta.getSchemaQualifiedName(); result = "schema.opr.tail"; } }; qpsStrategy = qpsControllerManager.getOrCreate("svc", invocation); Assert.assertEquals("svc", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "schema.opr2"; operationMeta.getSchemaQualifiedName(); result = "schema.opr2.tail"; } }; qpsStrategy = qpsControllerManager.getOrCreate("svc", invocation); Assert.assertEquals("svc", ((AbstractQpsStrategy) qpsStrategy).getKey()); Assert.assertNull(((AbstractQpsStrategy) qpsStrategy).getQpsLimit()); } |
ConsumerQpsFlowControlHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { if (!Config.INSTANCE.isConsumerEnabled()) { invocation.next(asyncResp); return; } QpsStrategy qpsStrategy = qpsControllerMgr.getOrCreate(invocation.getMicroserviceName(), invocation); if (qpsStrategy.isLimitNewRequest()) { CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol"); asyncResp.consumerFail( new InvocationException(QpsConst.TOO_MANY_REQUESTS_STATUS, errorData)); return; } invocation.next(asyncResp); } @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHandle() throws Exception { String key = "svc.schema.opr"; AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("key"); qpsStrategy.setQpsLimit(12L); Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta); Mockito.when(operationMeta.getSchemaQualifiedName()).thenReturn("schema.opr"); Mockito.when(invocation.getSchemaId()).thenReturn("schema"); Mockito.when(invocation.getMicroserviceName()).thenReturn("svc"); setQpsController(key, qpsStrategy); new MockUp<FixedWindowStrategy>() { @Mock public boolean isLimitNewRequest() { return true; } }; new MockUp<QpsControllerManager>() { @Mock protected QpsStrategy create(String qualifiedNameKey) { return qpsStrategy; } }; handler.handle(invocation, asyncResp); ArgumentCaptor<InvocationException> captor = ArgumentCaptor.forClass(InvocationException.class); Mockito.verify(asyncResp).consumerFail(captor.capture()); InvocationException invocationException = captor.getValue(); assertEquals(QpsConst.TOO_MANY_REQUESTS_STATUS, invocationException.getStatus()); assertEquals("rejected by qps flowcontrol", ((CommonExceptionData) invocationException.getErrorData()).getMessage()); }
@Test public void testHandleIsLimitNewRequestAsFalse() throws Exception { String key = "service.schema.id"; AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("service"); qpsStrategy.setQpsLimit(12L); Mockito.when(invocation.getMicroserviceName()).thenReturn("service"); Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta); Mockito.when(operationMeta.getSchemaQualifiedName()).thenReturn("schema.id"); setQpsController(key, qpsStrategy); new MockUp<QpsStrategy>() { @Mock public boolean isLimitNewRequest() { return false; } }; new MockUp<QpsControllerManager>() { @Mock protected QpsStrategy create(String qualifiedNameKey) { return qpsStrategy; } }; handler.handle(invocation, asyncResp); Mockito.verify(invocation).next(asyncResp); } |
DelayFault extends AbstractFault { @Override public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse) { if (!shouldDelay(invocation, faultParam, asynResponse)) { asynResponse.success(SUCCESS_RESPONSE); return; } LOGGER.debug("Fault injection: delay is added for the request by fault inject handler"); long delay = FaultInjectionUtil.getFaultInjectionConfig(invocation, "delay.fixedDelay"); if (delay == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) { LOGGER.debug("Fault injection: delay is not configured"); asynResponse.success(SUCCESS_RESPONSE); return; } executeDelay(faultParam, asynResponse, delay); } @Override int getOrder(); @Override void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse); } | @Test public void injectFaultVertxDelay() throws InterruptedException { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay", "10"); ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", "100"); assertEquals("10", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay") .getString()); assertEquals("100", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent") .getString()); DelayFault delayFault = new DelayFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); CountDownLatch latch = new CountDownLatch(1); delayFault.injectFault(invocation, faultParam, response -> { resultHolder.value = response.getResult(); latch.countDown(); }); latch.await(10, TimeUnit.SECONDS); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultSystemDelay() throws InterruptedException { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay", "10"); ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", "100"); assertEquals("10", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay") .getString()); assertEquals("100", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent") .getString()); DelayFault delayFault = new DelayFault(); FaultParam faultParam = new FaultParam(1); Holder<String> resultHolder = new Holder<>(); CountDownLatch latch = new CountDownLatch(1); delayFault.injectFault(invocation, faultParam, response -> { resultHolder.value = response.getResult(); latch.countDown(); }); latch.await(10, TimeUnit.SECONDS); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultNotDelay() throws InterruptedException { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay", "10"); ArchaiusUtils.setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", "0"); assertEquals("10", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay") .getString()); assertEquals("0", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent") .getString()); DelayFault delayFault = new DelayFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); CountDownLatch latch = new CountDownLatch(1); delayFault.injectFault(invocation, faultParam, response -> { resultHolder.value = response.getResult(); latch.countDown(); }); latch.await(3, TimeUnit.SECONDS); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultNoPercentageConfig() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", null); assertNull(DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent") .getString()); DelayFault delayFault = new DelayFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); delayFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultNoDelayMsConfig() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", "10"); assertEquals("10", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent") .getString()); DelayFault delayFault = new DelayFault(); FaultParam faultParam = new FaultParam(10); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); delayFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); } |
PerfInfo { @Override public String toString() { return "PerfInfo [tps=" + tps + ", msTotalTime=" + msTotalTime + ", msLatency=" + calcMsLatency() + ", msMaxLatency=" + msMaxLatency + "]"; } double getTps(); void setTps(double tps); double getMsTotalTime(); void setMsTotalTime(double msTotalTime); double getMsMaxLatency(); void setMsMaxLatency(double msMaxLatency); void add(PerfInfo other); double calcMsLatency(); @Override String toString(); } | @Test public void testToString() { PerfInfo perf = new PerfInfo(); perf.setTps(10); perf.setMsTotalTime(10); perf.setMsMaxLatency(100); Assert.assertEquals("PerfInfo [tps=10.0, msTotalTime=10.0, msLatency=1.0, msMaxLatency=100.0]", perf.toString()); } |
AbortFault extends AbstractFault { @Override public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asyncResponse) { if (!shouldAbort(invocation, faultParam)) { asyncResponse.success(SUCCESS_RESPONSE); return; } int errorCode = FaultInjectionUtil.getFaultInjectionConfig(invocation, "abort.httpStatus"); if (errorCode == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) { LOGGER.debug("Fault injection: Abort error code is not configured"); asyncResponse.success(SUCCESS_RESPONSE); return; } CommonExceptionData errorData = new CommonExceptionData(ABORTED_ERROR_MSG); asyncResponse.consumerFail(new InvocationException(errorCode, ABORTED_ERROR_MSG, errorData)); } @Override void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asyncResponse); @Override int getOrder(); static final String ABORTED_ERROR_MSG; } | @Test public void injectFaultError() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.httpStatus", "421"); ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent", "100"); assertEquals("421", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.httpStatus") .getString()); assertEquals("100", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent") .getString()); AbortFault abortFault = new AbortFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<InvocationException> resultHolder = new Holder<>(); abortFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals(421, resultHolder.value.getStatusCode()); assertEquals("aborted by fault inject", resultHolder.value.getReasonPhrase()); assertEquals("CommonExceptionData [message=aborted by fault inject]", resultHolder.value.getErrorData().toString()); }
@Test public void injectFaultNoError() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.httpStatus", "421"); ArchaiusUtils.setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent", "0"); assertEquals("421", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.httpStatus") .getString()); assertEquals("0", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent") .getString()); AbortFault abortFault = new AbortFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); abortFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultNoPercentageConfig() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent", null); assertNull(DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent") .getString()); AbortFault abortFault = new AbortFault(); FaultParam faultParam = new FaultParam(1); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); abortFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); }
@Test public void injectFaultNoErrorCodeConfig() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent", "10"); assertEquals("10", DynamicProperty .getInstance("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent") .getString()); AbortFault abortFault = new AbortFault(); FaultParam faultParam = new FaultParam(10); Vertx vertx = VertxUtils.getOrCreateVertxByName("faultinjectionTest", null); faultParam.setVertx(vertx); Holder<String> resultHolder = new Holder<>(); abortFault.injectFault(invocation, faultParam, response -> resultHolder.value = response.getResult()); AtomicLong count = FaultInjectionUtil.getOperMetTotalReq("restMicroserviceQualifiedName12"); assertEquals(1, count.get()); assertEquals("success", resultHolder.value); } |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected Observable<Response> resumeWithFallback() { Throwable cause = getFailedExecutionException(); Observable<Response> observable = Observable.create(f -> { try { f.onNext(FallbackPolicyManager.getFallbackResponse(type, cause, invocation)); f.onCompleted(); } catch (Exception e) { LOG.warn("fallback failed due to:" + e.getMessage()); throw e; } }); return observable; } protected BizkeeperCommand(String type, Invocation invocation, HystrixObservableCommand.Setter setter); } | @Test public void testResumeWithFallbackProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> observe = bizkeeperCommand.resumeWithFallback(); Assert.assertNotNull(observe); }
@Test public void testResumeWithFallbackConsumer() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ConsumerBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> observe = bizkeeperCommand.resumeWithFallback(); Assert.assertNotNull(observe); } |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected Observable<Response> construct() { Observable<Response> observable = Observable.create(f -> { try { invocation.next(resp -> { if (isFailedResponse(resp)) { LOG.warn("bizkeeper command {} failed due to {}", invocation.getInvocationQualifiedName(), resp.getResult()); f.onError(resp.getResult()); FallbackPolicyManager.record(type, invocation, resp, false); } else { f.onNext(resp); f.onCompleted(); FallbackPolicyManager.record(type, invocation, resp, true); } }); } catch (Exception e) { LOG.warn("bizkeeper command {} execute failed due to {}", invocation.getInvocationQualifiedName(), e.getClass().getName()); f.onError(e); } }); return observable; } protected BizkeeperCommand(String type, Invocation invocation, HystrixObservableCommand.Setter setter); } | @Test public void testConstructProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> response = bizkeeperCommand.construct(); Assert.assertNotNull(response); }
@Test public void testConstructConsumer() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ConsumerBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> response = bizkeeperCommand.construct(); Assert.assertNotNull(response); } |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected String getCacheKey() { if (HystrixRequestContext.isCurrentThreadInitialized()) { StringBuilder sb = new StringBuilder(); sb.append(this.getCommandGroup().name()); sb.append("-"); sb.append(this.getCommandKey().name()); return sb.toString(); } else { return super.getCacheKey(); } } protected BizkeeperCommand(String type, Invocation invocation, HystrixObservableCommand.Setter setter); } | @Test public void testGetCacheKeyWithContextInitializedProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); HystrixRequestContext.initializeContext(); String cacheKey = bizkeeperCommand.getCacheKey(); Assert.assertNotNull(cacheKey); }
@Test public void testGetCacheKeyWithContextInitializedConsumer() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ConsumerBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); HystrixRequestContext.initializeContext(); String cacheKey = bizkeeperCommand.getCacheKey(); Assert.assertNotNull(cacheKey); } |
OperationPerf { public void add(OperationPerf operationPerf) { operationPerf.stages.forEach((key, value) -> { PerfInfo perfInfo = stages.computeIfAbsent(key, n -> new PerfInfo()); perfInfo.add(value); }); if (operationPerf.getLatencyDistribution() == null) { return; } if (latencyDistribution == null) { latencyDistribution = new Integer[operationPerf.getLatencyDistribution().length]; Arrays.fill(latencyDistribution, 0); } for (int idx = 0; idx < operationPerf.getLatencyDistribution().length; idx++) { latencyDistribution[idx] += operationPerf.getLatencyDistribution()[idx]; } } String getOperation(); void setOperation(String operation); Map<String, PerfInfo> getStages(); Integer[] getLatencyDistribution(); void setLatencyDistribution(Integer[] latencyDistribution); void setStages(Map<String, PerfInfo> stages); PerfInfo findStage(String stage); void add(OperationPerf operationPerf); } | @Test public void add() { Assert.assertTrue(opPerf.getStages().isEmpty()); OperationPerf otherOpPerf = Utils.createOperationPerf(op); opPerf.add(otherOpPerf); Assert.assertEquals(op, otherOpPerf.getOperation()); PerfInfo perfInfo = opPerf.findStage(MeterInvocationConst.STAGE_TOTAL); Assert.assertEquals(10, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); perfInfo = opPerf.findStage(MeterInvocationConst.STAGE_EXECUTION); Assert.assertEquals(10, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); } |
CommandKey { public static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation) { return CustomizeCommandGroupKey.asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName(), invocation); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation); static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation); } | @Test public void testToHystrixCommandGroupKey() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); Assert.assertNotNull(invocation); HystrixCommandGroupKey hystrixCommandGroupKey = CommandKey.toHystrixCommandGroupKey("groupname", invocation); Assert.assertNotNull(hystrixCommandGroupKey); } |
CommandKey { public static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation) { return HystrixCommandKey.Factory .asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName()); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation); static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation); } | @Test public void testToHystrixCommandKey() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); Assert.assertNotNull(invocation); HystrixCommandKey hystrixCommandGroupKey = CommandKey.toHystrixCommandKey("groupname", invocation); Assert.assertNotNull(hystrixCommandGroupKey); } |
ConsumerBizkeeperHandler extends BizkeeperHandler { @Override protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) { HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); setCommonProperties(invocation, setter); BizkeeperCommand command = new ConsumerBizkeeperCommand(groupname, invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey(groupname, invocation)) .andCommandKey(CommandKey.toHystrixCommandKey(groupname, invocation)) .andCommandPropertiesDefaults(setter)); return command; } ConsumerBizkeeperHandler(); } | @Test public void testCreateBizkeeperCommand() { HystrixPlugins.reset(); ConsumerBizkeeperHandler consumerBizkeeperHandler = new ConsumerBizkeeperHandler(); Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); CommandKey.toHystrixCommandGroupKey("groupname", invocation); CommandKey.toHystrixCommandKey("groupname", invocation); BizkeeperCommand command = consumerBizkeeperHandler.createBizkeeperCommand(invocation); Assert.assertNotNull(command); } |
BizkeeperRequestContext { public static BizkeeperRequestContext initializeContext() { return new BizkeeperRequestContext(HystrixRequestContext.initializeContext()); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); } | @Test public void testInitializeContext() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); Assert.assertNotNull(bizkeeperRequestContext); } |
BizkeeperRequestContext { public void shutdown() { this.context.shutdown(); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); } | @Test public void testShutdown() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); boolean validAssert; try { bizkeeperRequestContext.shutdown(); validAssert = true; } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); } |
BizkeeperHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) { HystrixObservable<Response> command = delegate.createBizkeeperCommand(invocation); Observable<Response> observable = command.toObservable(); observable.subscribe(asyncResp::complete, error -> { LOG.warn("catch error in bizkeeper:" + error.getMessage()); asyncResp.fail(invocation.getInvocationType(), error); }, () -> { }); } BizkeeperHandler(String groupname); @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHandleWithException() { boolean validAssert; HystrixPlugins.reset(); try { validAssert = true; bizkeeperHandler.handle(invocation, asyncResp); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
@Test public void testHandle() { boolean validAssert; try { Assert.assertNotNull(bizkeeperHandler); Mockito.when(invocation.getMicroserviceName()).thenReturn("test1"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); validAssert = true; bizkeeperHandler.handle(invocation, asyncResp); } catch (Exception exce) { validAssert = false; } Assert.assertTrue(validAssert); }
@Test public void testHandleForceThrowException() throws Exception { Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandleForceThrowException"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()) .thenReturn("testHandleForceThrowException"); System.setProperty("servicecomb.fallback.Group_Name.testHandleForceThrowException.force", "true"); System.setProperty("servicecomb.fallbackpolicy.Group_Name.testHandleForceThrowException.policy", "throwexception"); bizkeeperHandler.handle(invocation, f -> { Assert.assertTrue(f.isFailed()); }); }
@Test public void testHandleForceReturnnull() throws Exception { Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandleForceReturnnull"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()) .thenReturn("testHandleForceReturnnull"); System.setProperty("servicecomb.fallback.Group_Name.testHandleForceReturnnull.force", "true"); System.setProperty("servicecomb.fallbackpolicy.Group_Name.testHandleForceReturnnull.policy", "returnnull"); bizkeeperHandler.handle(invocation, f -> { Assert.assertTrue(f.isSuccessed()); Assert.assertNull(f.getResult()); }); }
@Test public void testHandleInError() throws Exception { Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandleInError"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()) .thenReturn("testHandleInError"); FallbackPolicy policy = Mockito.mock(FallbackPolicy.class); Mockito.when(policy.name()).thenReturn("throwException"); Mockito.when(policy.getFallbackResponse(Mockito.any(Invocation.class), Mockito.any(null))) .thenThrow(new RuntimeException()); FallbackPolicyManager.addPolicy(policy); System.setProperty("servicecomb.fallbackpolicy.groupname.testHandleInError.policy", "throwException"); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { AsyncResponse asyncRsp = invocation.getArgumentAt(0, AsyncResponse.class); asyncRsp.fail(InvocationType.CONSUMER, new Exception("testHandleInError")); return null; } }).when(invocation).next(Mockito.any(AsyncResponse.class)); bizkeeperHandler.handle(invocation, f -> { Assert.assertTrue(f.isFailed()); }); }
@Test public void testHandlNextException() throws Exception { Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandlNextException"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()) .thenReturn("testHandlNextException"); Mockito.doThrow(new Exception("testHandlNextException")).when(invocation).next(Mockito.any(AsyncResponse.class)); bizkeeperHandler.handle(invocation, f -> { Assert.assertTrue(f.isFailed()); }); }
@Test public void testHandleSuccess() throws Exception { Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandleSuccess"); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()) .thenReturn("testHandleSuccess"); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { AsyncResponse asyncRsp = invocation.getArgumentAt(0, AsyncResponse.class); asyncRsp.success(""); return null; } }).when(invocation).next(Mockito.any(AsyncResponse.class)); bizkeeperHandler.handle(invocation, f -> { Assert.assertTrue(f.isSuccessed()); }); } |
BizkeeperHandler implements Handler { protected void setCommonProperties(Invocation invocation, HystrixCommandProperties.Setter setter) { } BizkeeperHandler(String groupname); @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testSetCommonProperties() { boolean validAssert; try { validAssert = true; HystrixPlugins.reset(); HystrixCommandProperties.Setter setter = Mockito.mock(HystrixCommandProperties.Setter.class); bizkeeperHandler.setCommonProperties(invocation, setter); } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); } |
DefaultLogPublisher implements MetricsInitializer { @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { if (!DynamicPropertyFactory.getInstance() .getBooleanProperty(ENABLED, false) .get()) { return; } initLatencyDistribution(); eventBus.register(this); } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Subscribe void onPolledEvent(PolledEvent event); static final String ENABLED; static final String ENDPOINTS_CLIENT_DETAIL_ENABLED; } | @Test public void init_enabled_default() { Holder<Boolean> registered = new Holder<>(false); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertFalse(registered.value); }
@Test public void init_enabled_true() { Holder<Boolean> registered = new Holder<>(); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; ArchaiusUtils.setProperty(DefaultLogPublisher.ENABLED, true); publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertTrue(registered.value); }
@Test public void init_enabled_false() { Holder<Boolean> registered = new Holder<>(); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; ArchaiusUtils.setProperty(DefaultLogPublisher.ENABLED, false); publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertNull(registered.value); } |
Configuration { private Configuration() { } private Configuration(); int getIsolationTimeoutInMilliseconds(String type, String microserviceName,
String qualifiedOperationName); boolean getIsolationTimeoutEnabled(String type, String microserviceName,
String qualifiedOperationName); int getIsolationMaxConcurrentRequests(String type, String microserviceName,
String qualifiedOperationName); boolean isCircuitBreakerEnabled(String type, String microserviceName, String qualifiedOperationName); boolean isCircuitBreakerForceOpen(String type, String microserviceName, String qualifiedOperationName); boolean isCircuitBreakerForceClosed(String type, String microserviceName, String qualifiedOperationName); int getCircuitBreakerSleepWindowInMilliseconds(String type, String microserviceName,
String qualifiedOperationName); int getCircuitBreakerRequestVolumeThreshold(String type, String microserviceName,
String qualifiedOperationName); int getCircuitBreakerErrorThresholdPercentage(String type, String microserviceName,
String qualifiedOperationName); boolean isFallbackEnabled(String type, String microserviceName, String qualifiedOperationName); boolean isFallbackForce(String type, String microserviceName, String qualifiedOperationName); int getFallbackMaxConcurrentRequests(String type, String microserviceName, String qualifiedOperationName); String getFallbackPolicyPolicy(String type, String microserviceName, String qualifiedOperationName); static final String FALLBACKPOLICY_POLICY_THROW; static final String FALLBACKPOLICY_POLICY_RETURN; static final Configuration INSTANCE; } | @Test public void testConfiguration() { assertNotNull(Configuration.INSTANCE); assertEquals("returnnull", Configuration.FALLBACKPOLICY_POLICY_RETURN); assertEquals("throwexception", Configuration.FALLBACKPOLICY_POLICY_THROW); Configuration c = Configuration.INSTANCE; Invocation invocation = Mockito.mock(Invocation.class); String test2 = invocation.getMicroserviceName(); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceName()).thenReturn("testqualify"); int res = c.getIsolationTimeoutInMilliseconds("groupname", test2, "testqualify"); assertEquals(30000, res); boolean b1 = c.getIsolationTimeoutEnabled("groupname", test2, "testqualify"); assertFalse(b1); int res1 = c.getIsolationMaxConcurrentRequests("groupname", test2, "testqualify"); assertEquals(1000, res1); boolean b2 = c.isCircuitBreakerEnabled("groupname", test2, "testqualify"); assertTrue(b2); String str = c.getFallbackPolicyPolicy("groupname", test2, "testqualify"); assertEquals(null, str); assertFalse(c.isCircuitBreakerForceOpen("groupname", test2, "testqualify")); assertFalse(c.isCircuitBreakerForceClosed("groupname", test2, "testqualify")); assertEquals(15000, c.getCircuitBreakerSleepWindowInMilliseconds("groupname", test2, "testqualify")); assertEquals(20, c.getCircuitBreakerRequestVolumeThreshold("groupname", test2, "testqualify")); assertEquals(50, c.getCircuitBreakerErrorThresholdPercentage("groupname", test2, "testqualify")); assertTrue(c.isFallbackEnabled("groupname", test2, "testqualify")); } |
BizkeeperExceptionUtils extends ExceptionUtils { public static CseException createBizkeeperException(String code, Throwable cause, Object... args) { String msg = String.format(ERROR_DESC_MGR.ensureFindValue(code), args); return new CseException(code, msg, cause); } private BizkeeperExceptionUtils(); static CseException createBizkeeperException(String code, Throwable cause, Object... args); static final String SERVICECOMB_BIZKEEPER_FALLBACK; } | @Test public void testCreateBizkeeperException() { Assert.assertEquals("servicecomb.bizkeeper.fallback", BizkeeperExceptionUtils.SERVICECOMB_BIZKEEPER_FALLBACK); CseException cseException = BizkeeperExceptionUtils.createBizkeeperException("servicecomb.bizkeeper.fallback", new Throwable(), "ARGS"); Assert.assertNotNull(cseException); } |
HystrixPropertiesStrategyExt extends HystrixPropertiesStrategy { public static HystrixPropertiesStrategyExt getInstance() { return INSTANCE; } private HystrixPropertiesStrategyExt(); static HystrixPropertiesStrategyExt getInstance(); @Override HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder); } | @Test public void testGetCommandPropertiesCacheKey() { assertNotNull(HystrixPropertiesStrategyExt.getInstance()); HystrixPropertiesStrategyExt hps = HystrixPropertiesStrategyExt.getInstance(); HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class); Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceName()).thenReturn("testqualify"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false) .withFallbackIsolationSemaphoreMaxConcurrentRequests( Configuration.INSTANCE.getFallbackMaxConcurrentRequests("groupname", "testing", invocation.getOperationMeta().getMicroserviceQualifiedName())); String str1 = hps.getCommandPropertiesCacheKey(commandKey, setter); Assert.assertNull(str1); } |
HystrixPropertiesStrategyExt extends HystrixPropertiesStrategy { @Override public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder) { HystrixCommandProperties commandProperties = commandPropertiesMap.get(commandKey.name()); if (commandProperties == null) { commandProperties = new HystrixCommandPropertiesExt(commandKey, builder); commandPropertiesMap.putIfAbsent(commandKey.name(), commandProperties); } return commandProperties; } private HystrixPropertiesStrategyExt(); static HystrixPropertiesStrategyExt getInstance(); @Override HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder); } | @Test public void testgetCommandProperties() { HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class); Mockito.when(commandKey.name()) .thenReturn("provider.HystrixPropertiesStrategyExtTest.testgetCommandProperties"); HystrixCommandProperties commandPro = HystrixPropertiesStrategyExt.getInstance() .getCommandProperties(commandKey, HystrixCommandProperties.Setter()); Assert.assertTrue(commandPro.circuitBreakerEnabled().get()); Assert.assertEquals(Integer.valueOf(50), commandPro.circuitBreakerErrorThresholdPercentage().get()); Assert.assertFalse(commandPro.circuitBreakerForceClosed().get()); Assert.assertFalse(commandPro.circuitBreakerForceOpen().get()); Assert.assertEquals(Integer.valueOf(20), commandPro.circuitBreakerRequestVolumeThreshold().get()); Assert.assertEquals(Integer.valueOf(15000), commandPro.circuitBreakerSleepWindowInMilliseconds().get()); Assert.assertEquals(Integer.valueOf(1000), commandPro.executionIsolationSemaphoreMaxConcurrentRequests().get()); Assert.assertTrue(commandPro.executionIsolationThreadInterruptOnTimeout().get()); Assert.assertEquals(null, commandPro.executionIsolationThreadPoolKeyOverride().get()); Assert.assertEquals(Integer.valueOf(30000), commandPro.executionTimeoutInMilliseconds().get()); Assert.assertFalse(commandPro.executionTimeoutEnabled().get()); Assert.assertEquals(Integer.valueOf(10), commandPro.fallbackIsolationSemaphoreMaxConcurrentRequests().get()); Assert.assertTrue(commandPro.fallbackEnabled().get()); Assert.assertEquals(Integer.valueOf(100), commandPro.metricsRollingPercentileBucketSize().get()); Assert.assertFalse(commandPro.metricsRollingPercentileEnabled().get()); } |
CircutBreakerEventNotifier extends HystrixEventNotifier { @Override public void markEvent(HystrixEventType eventType, HystrixCommandKey key) { String keyName = key.name(); AtomicBoolean flag = circuitFlag.computeIfAbsent(keyName, k -> new AtomicBoolean()); switch (eventType) { case SHORT_CIRCUITED: if (flag.compareAndSet(false, true)) { eventBus.post(new CircutBreakerEvent(key, Type.OPEN)); } break; case SUCCESS: if (flag.compareAndSet(true, false)) { eventBus.post(new CircutBreakerEvent(key, Type.CLOSE)); } break; default: break; } } @Override void markEvent(HystrixEventType eventType, HystrixCommandKey key); } | @Test public void testMarkEvent() { Mockito.when(commandKey.name()).thenReturn("Consumer.springmvc.springmvcHello.sayHi"); new Expectations(HystrixCommandMetrics.class) { { HystrixCommandMetrics.getInstance(commandKey); result = null; } }; circutBreakerEventNotifier.markEvent(HystrixEventType.SHORT_CIRCUITED, commandKey); Assert.assertEquals(1, taskList.size()); circutBreakerEventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey); Assert.assertEquals(2, taskList.size()); } |
RSAAuthenticationToken { public RSAAuthenticationToken(String instanceId, String serviceId, long generateTime, String randomCode, String sign) { this.instanceId = instanceId; this.generateTime = generateTime; this.randomCode = randomCode; this.serviceId = serviceId; this.sign = sign; this.tokenFormat = String.format("%s@%s@%s@%s@%s", instanceId, serviceId, generateTime, randomCode, sign); } RSAAuthenticationToken(String instanceId, String serviceId, long generateTime,
String randomCode, String sign); String plainToken(); String getInstanceId(); long getGenerateTime(); String getSign(); String format(); static RSAAuthenticationToken fromStr(String token); String getServiceId(); void setServiceId(String serviceId); @Override boolean equals(Object obj); int hashCode(); final static long TOKEN_ACTIVE_TIME; } | @Test public void testRSAAuthenticationToken() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException { String tokenstr = "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk="; RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr); String contents = token.plainToken(); Assert.assertEquals( "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ", contents); String sign = token.getSign(); Assert.assertEquals( "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=", sign); String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB"; Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents)); } |
RSAAuthenticationToken { public static RSAAuthenticationToken fromStr(String token) { String[] tokenArr = token.split("@"); if (tokenArr.length != 5) { return null; } return new RSAAuthenticationToken(tokenArr[0], tokenArr[1], Long.valueOf(tokenArr[2]), tokenArr[3], tokenArr[4]); } RSAAuthenticationToken(String instanceId, String serviceId, long generateTime,
String randomCode, String sign); String plainToken(); String getInstanceId(); long getGenerateTime(); String getSign(); String format(); static RSAAuthenticationToken fromStr(String token); String getServiceId(); void setServiceId(String serviceId); @Override boolean equals(Object obj); int hashCode(); final static long TOKEN_ACTIVE_TIME; } | @Test public void testRSAAuthenticationTokenError() { String tokenstr = "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk="; RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr); Assert.assertNull(token); }
@Test public void testEqual() { String tokenstr = "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk="; RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr); Assert.assertNotEquals(token, null); RSAAuthenticationToken token2 = RSAAuthenticationToken.fromStr( "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk"); Assert.assertNotEquals(token2, token); RSAAuthenticationToken token3 = RSAAuthenticationToken.fromStr( "e8a0a4b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk"); Assert.assertNotEquals(token3, token); RSAAuthenticationToken token4 = RSAAuthenticationToken.fromStr( "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk="); Assert.assertEquals(token4, token); } |
DtmProviderHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { try { if (dtmContextImMethod != null) { String traceId = invocation.getContext().get(Const.TRACE_ID_NAME); invocation.getContext().put(DTM_TRACE_ID_KEY, traceId); dtmContextImMethod.invoke(null, invocation.getContext()); } } catch (Throwable e) { LOG.warn("Failed to execute method DTMContext#{}, please check", DtmConfig.DTM_IMPORT_METHOD, e); } invocation.next(asyncResp); } DtmProviderHandler(); @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHandler(@Mocked Invocation invocation) throws Exception { DtmProviderHandler providerHandler = new DtmProviderHandler(); providerHandler.init(null, null); Map<String, String> context = new HashMap<>(); new Expectations() {{ invocation.getContext(); result = context; }}; String expectTxId = "dtm-tx-id"; String expectTraceId = "dtm-trace-id"; context.put(DTMContext.GLOBAL_TX_ID_KEY, expectTxId); context.put(Const.TRACE_ID_NAME, expectTraceId); Assert.assertEquals("", DTMContext.TRACE_ID); Assert.assertEquals("", DTMContext.GLOBAL_TX_ID); providerHandler.handle(invocation, null); Assert.assertEquals(expectTraceId, DTMContext.TRACE_ID); Assert.assertEquals(expectTxId, DTMContext.GLOBAL_TX_ID); } |
CasEnvConfig { public Map<String, String> getNonEmptyProperties() { return properties.entrySet().stream().filter(entry -> StringUtils.isNotEmpty(entry.getValue())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); } private CasEnvConfig(); Map<String, String> getNonEmptyProperties(); static final CasEnvConfig INSTANCE; } | @Test public void testConfig() { CasEnvConfig instance = CasEnvConfig.INSTANCE; assertEquals(2, instance.getNonEmptyProperties().size()); assertEquals("application-id", instance.getNonEmptyProperties().get("CAS_APPLICATION_ID")); assertEquals("env-id", instance.getNonEmptyProperties().get("CAS_ENVIRONMENT_ID")); } |
KieClient { public String putKeyValue(String key, KVBody kvBody) { try { ObjectMapper mapper = new ObjectMapper(); HttpResponse response = httpClient.putHttpRequest("/kie/kv/" + key, null, mapper.writeValueAsString(kvBody)); if (response.getStatusCode() == HttpStatus.SC_OK) { return response.getContent(); } else { LOGGER.error("create keyValue fails, responseStatusCode={}, responseMessage={}, responseContent{}", response.getStatusCode(), response.getMessage(), response.getContent()); } } catch (IOException e) { LOGGER.error("create keyValue fails", e); } return null; } KieClient(); KieClient(String host, int port, String projectName); KieClient(KieRawClient serviceCenterRawClient); String putKeyValue(String key, KVBody kvBody); List<KVResponse> getValueOfKey(String key); List<KVResponse> searchKeyValueByLabels(Map<String, String> labels); void deleteKeyValue(KVDoc kvDoc); } | @Test public void putKeyValue() throws IOException { KieRawClient kieRawClient = Mockito.mock(KieRawClient.class); KVBody kvBody = new KVBody(); kvBody.setValue("test"); kvBody.setValueType("string"); Map<String, String> labels = new HashMap<>(); labels.put("app1", "111"); kvBody.setLabels(labels); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("OK"); String responseContext = "{\n" + " \"_id\": \"5db0213bb927bafaf707e06a\",\n" + " \"label_id\": \"5db0039bb927bafaf707e037\",\n" + " \"key\": \"testKey\",\n" + " \"value\": \"testValue\",\n" + " \"value_type\": \"string\",\n" + " \"labels\": {\n" + " \"app1\": \"111\"\n" + " },\n" + " \"domain\": \"default\",\n" + " \"revision\": 10\n" + "}"; httpResponse.setContent(responseContext); ObjectMapper mapper = new ObjectMapper(); Mockito.when(kieRawClient.putHttpRequest("/kie/kv/test1", null, mapper.writeValueAsString(kvBody))) .thenReturn(httpResponse); KieClient kieClient = new KieClient(kieRawClient); String kvResponses = kieClient.putKeyValue("test1", kvBody); Assert.assertNotNull(kvResponses); } |
KieClient { public void deleteKeyValue(KVDoc kvDoc) { try { HttpResponse response = httpClient.deleteHttpRequest("/kie/kv/?kvID=" + kvDoc.getId(), null, null); if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) { LOGGER.info("Delete keyValue success"); } else { LOGGER.error("delete keyValue fails, responseStatusCode={}, responseMessage={}, responseContent{}", response.getStatusCode(), response.getMessage(), response.getContent()); } } catch (IOException e) { LOGGER.error("delete keyValue fails", e); } } KieClient(); KieClient(String host, int port, String projectName); KieClient(KieRawClient serviceCenterRawClient); String putKeyValue(String key, KVBody kvBody); List<KVResponse> getValueOfKey(String key); List<KVResponse> searchKeyValueByLabels(Map<String, String> labels); void deleteKeyValue(KVDoc kvDoc); } | @Test public void deleteKeyValue() throws IOException { KieRawClient kieRawClient = Mockito.mock(KieRawClient.class); KVDoc kvDoc = new KVDoc(); kvDoc.setId("111"); kvDoc.setKey("test"); kvDoc.setValue("testValue"); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(204); httpResponse.setMessage("OK"); Mockito.when(kieRawClient.deleteHttpRequest("/kie/kv/?kvID=" + kvDoc.getId(), null, null)) .thenReturn(httpResponse); KieClient kieClient = new KieClient(kieRawClient); kieClient.deleteKeyValue(kvDoc); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstancesResponse getServiceCenterInstances() { try { HttpResponse response = httpClient.getHttpRequest("/registry/health", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), MicroserviceInstancesResponse.class); } else { throw new OperationException( "get service-center instances fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service-center instances fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceCenterInstances() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instances\": [\n" + " {\n" + " \"instanceId\": \"111111\",\n" + " \"serviceId\": \"222222\",\n" + " \"version\": \"1.0\",\n" + " \"hostName\": \"Test\",\n" + " \"endpoints\": [\n" + " \"string\"\n" + " ],\n" + " \"status\": \"UP\",\n" + " \"properties\": {\n" + " \"additionalProp1\": \"string\",\n" + " \"additionalProp2\": \"string\",\n" + " \"additionalProp3\": \"string\"\n" + " },\n" + " \"healthCheck\": {\n" + " \"mode\": \"push\",\n" + " \"port\": \"0\",\n" + " \"interval\": \"0\",\n" + " \"times\": \"0\"\n" + " },\n" + " \"dataCenterInfo\": {\n" + " \"name\": \"string\",\n" + " \"region\": \"string\",\n" + " \"availableZone\": \"string\"\n" + " },\n" + " \"timestamp\": \"333333\",\n" + " \"modTimestamp\": \"4444444\"\n" + " }\n" + " ]\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest("/registry/health", null, null)).thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); MicroserviceInstancesResponse serviceCenterInstances = serviceCenterClient.getServiceCenterInstances(); Assert.assertNotNull(serviceCenterInstances); Assert.assertEquals(1, serviceCenterInstances.getInstances().size()); Assert.assertEquals("111111", serviceCenterInstances.getInstances().get(0).getInstanceId()); Assert.assertEquals("222222", serviceCenterInstances.getInstances().get(0).getServiceId()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceResponse registerMicroservice(Microservice microservice) { try { CreateMicroserviceRequest request = new CreateMicroserviceRequest(); request.setService(microservice); HttpResponse response = httpClient .postHttpRequest("/registry/microservices", null, HttpUtils.serialize(request)); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), RegisteredMicroserviceResponse.class); } else { throw new OperationException( "register service fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "register service fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestRegistryService() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"serviceId\": \"111111\"}"); Microservice microservice = new Microservice(); microservice.setServiceName("Test"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); Mockito.when(serviceCenterRawClient .postHttpRequest("/registry/microservices", null, objectMapper.writeValueAsString(microservice))) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); RegisteredMicroserviceResponse actualResponse = serviceCenterClient.registerMicroservice(microservice); Assert.assertNotNull(actualResponse); Assert.assertEquals("111111", actualResponse.getServiceId()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public Microservice getMicroserviceByServiceId(String serviceId) { try { HttpResponse response = httpClient.getHttpRequest("/registry/microservices/" + serviceId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { MicroserviceResponse microserviceResponse = HttpUtils .deserialize(response.getContent(), MicroserviceResponse.class); return microserviceResponse.getService(); } else { throw new OperationException( "get service message fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service message fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceMessage() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"service\": {\n" + " \"serviceId\": \"111111\",\n" + " \"environment\": \"string\",\n" + " \"appId\": \"string\",\n" + " \"serviceName\": \"string\",\n" + " \"version\": \"string\",\n" + " \"description\": \"string\",\n" + " \"level\": \"string\",\n" + " \"registerBy\": \"string\",\n" + " \"schemas\": [\n" + " \"string\"\n" + " ],\n" + " \"status\": \"UP\",\n" + " \"timestamp\": \"string\",\n" + " \"modTimestamp\": \"string\",\n" + " \"framework\": {\n" + " \"name\": \"string\",\n" + " \"version\": \"string\"\n" + " },\n" + " \"paths\": [\n" + " {\n" + " \"Path\": \"string\",\n" + " \"Property\": {\n" + " \"additionalProp1\": \"string\",\n" + " \"additionalProp2\": \"string\",\n" + " \"additionalProp3\": \"string\"\n" + " }\n" + " }\n" + " ],\n" + " \"properties\": {\n" + " \"additionalProp1\": \"string\",\n" + " \"additionalProp2\": \"string\",\n" + " \"additionalProp3\": \"string\"\n" + " }\n" + " }\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest("/registry/microservices/111111", null, null)) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); Microservice microservices = serviceCenterClient.getMicroserviceByServiceId("111111"); Assert.assertNotNull(microservices); Assert.assertEquals("111111", microservices.getServiceId()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroservicesResponse getMicroserviceList() { try { HttpResponse response = httpClient.getHttpRequest("/registry/microservices", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), MicroservicesResponse.class); } else { throw new OperationException( "get service List fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service List fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceList() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); MicroservicesResponse microservicesResponse = new MicroservicesResponse(); List<Microservice> microserviceList = new ArrayList<Microservice>(); microserviceList.add(new Microservice("Test1")); microserviceList.add(new Microservice("Test2")); microserviceList.add(new Microservice("Test3")); microservicesResponse.setServices(microserviceList); ObjectMapper mapper = new ObjectMapper(); httpResponse.setContent(mapper.writeValueAsString(microservicesResponse)); Mockito.when(serviceCenterRawClient.getHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); MicroservicesResponse actualMicroservicesResponse = serviceCenterClient.getMicroserviceList(); Assert.assertNotNull(actualMicroservicesResponse); Assert.assertEquals(3, actualMicroservicesResponse.getServices().size()); Assert.assertEquals("Test1", actualMicroservicesResponse.getServices().get(0).getServiceName()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceResponse queryServiceId(Microservice microservice) { try { URIBuilder uriBuilder = new URIBuilder("/registry/existence"); uriBuilder.setParameter("type", "microservice"); uriBuilder.setParameter("appId", microservice.getAppId()); uriBuilder.setParameter("serviceName", microservice.getServiceName()); uriBuilder.setParameter("version", microservice.getVersion()); uriBuilder.setParameter("env", microservice.getEnvironment()); HttpResponse response = httpClient.getHttpRequest(uriBuilder.build().toString(), null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), RegisteredMicroserviceResponse.class); } else { LOGGER.info("Query serviceId fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); return null; } } catch (IOException e) { throw new OperationException( "query serviceId fails", e); } catch (URISyntaxException e) { throw new OperationException( "build url failed.", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestQueryServiceId() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"serviceId\": \"111111\"}"); Mockito.when(serviceCenterRawClient.getHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); Microservice microservice = new Microservice("Test111"); RegisteredMicroserviceResponse actualServiceId = serviceCenterClient.queryServiceId(microservice); Assert.assertNotNull(actualServiceId); Assert.assertEquals("111111", actualServiceId.getServiceId()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance) { try { CreateMicroserviceInstanceRequest request = new CreateMicroserviceInstanceRequest(); request.setInstance(instance); HttpResponse response = httpClient .postHttpRequest("/registry/microservices/" + instance.getServiceId() + "/instances", null, HttpUtils.serialize(request)); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), RegisteredMicroserviceInstanceResponse.class); } else { throw new OperationException( "register service instance fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "register service instance fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestRegisterServiceInstance() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"instanceId\": \"111111\"}"); MicroserviceInstance instance = new MicroserviceInstance(); instance.setInstanceId("111111"); instance.setServiceId("222222"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); Mockito.when(serviceCenterRawClient.postHttpRequest("/registry/microservices/222222/instances", null, mapper.writeValueAsString(instance))) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); RegisteredMicroserviceInstanceResponse actualResponse = serviceCenterClient.registerMicroserviceInstance(instance); Assert.assertNotNull(actualResponse); Assert.assertEquals("111111", actualResponse.getInstanceId()); } |
ServiceCenterClient implements ServiceCenterOperation { public void deleteMicroserviceInstance(String serviceId, String instanceId) { try { HttpResponse response = httpClient .deleteHttpRequest("/registry/microservices/" + serviceId + "/instances/" + instanceId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("DELETE SERVICE INSTANCE OK"); } else { throw new OperationException( "delete service instance fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "delete service instance fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestDeleteServiceInstance() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.deleteHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); serviceCenterClient.deleteMicroserviceInstance("111", "222"); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/instances", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), MicroserviceInstancesResponse.class); } else { throw new OperationException( "get service instances list fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service instances list fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceInstanceList() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instances\": [\n" + " {\n" + " \"instanceId\": \"111111\",\n" + " \"serviceId\": \"222222\",\n" + " \"version\": \"1.0\",\n" + " \"hostName\": \"Test\",\n" + " \"endpoints\": [\n" + " \"string\"\n" + " ],\n" + " \"status\": \"UP\",\n" + " \"timestamp\": \"333333\",\n" + " \"modTimestamp\": \"4444444\"\n" + " }\n" + " ]\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest("/registry/microservices/222222/instances", null, null)) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); MicroserviceInstancesResponse serviceCenterInstances = serviceCenterClient .getMicroserviceInstanceList("222222"); Assert.assertNotNull(serviceCenterInstances); Assert.assertEquals(1, serviceCenterInstances.getInstances().size()); Assert.assertEquals("111111", serviceCenterInstances.getInstances().get(0).getInstanceId()); Assert.assertEquals("222222", serviceCenterInstances.getInstances().get(0).getServiceId()); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/instances/" + instanceId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { MicroserviceInstanceResponse instanceResponse = HttpUtils .deserialize(response.getContent(), MicroserviceInstanceResponse.class); return instanceResponse.getInstance(); } else { throw new OperationException( "get service instance message fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service instance message fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceInstanceMessage() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instance\": {\n" + " \"instanceId\": \"111\",\n" + " \"serviceId\": \"222\",\n" + " \"version\": \"1.0\",\n" + " \"hostName\": \"Test\",\n" + " \"endpoints\": [\n" + " \"string\"\n" + " ],\n" + " \"status\": \"UP\",\n" + " \"properties\": {\n" + " \"additionalProp1\": \"string\",\n" + " \"additionalProp2\": \"string\",\n" + " \"additionalProp3\": \"string\"\n" + " },\n" + " \"healthCheck\": {\n" + " \"mode\": \"push\",\n" + " \"port\": \"0\",\n" + " \"interval\": \"0\",\n" + " \"times\": \"0\"\n" + " },\n" + " \"dataCenterInfo\": {\n" + " \"name\": \"string\",\n" + " \"region\": \"string\",\n" + " \"availableZone\": \"string\"\n" + " },\n" + " \"timestamp\": \"333333\",\n" + " \"modTimestamp\": \"4444444\"\n" + " }\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); MicroserviceInstance responseInstance = serviceCenterClient .getMicroserviceInstance("111", "222"); Assert.assertNotNull(responseInstance); Assert.assertEquals("111", responseInstance.getInstanceId()); Assert.assertEquals("Test", responseInstance.getHostName()); } |
ServiceCenterClient implements ServiceCenterOperation { public void sendHeartBeats(HeartbeatsRequest heartbeatsRequest) { try { HttpResponse response = httpClient .putHttpRequest("/registry/heartbeats", null, HttpUtils.serialize(heartbeatsRequest)); if (response.getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("HEARTBEATS SUCCESS"); } else { throw new OperationException( "heartbeats fails, statusCode = " + response.getStatusCode() + "; message = " + response.getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "heartbeats fails ", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestSendHeartBeats() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); HeartbeatsRequest heartbeatsRequest = new HeartbeatsRequest("001", "1001"); heartbeatsRequest.addInstances(new InstancesRequest("002", "1002")); ObjectMapper mapper = new ObjectMapper(); Mockito .when(serviceCenterRawClient.putHttpRequest("/registry/microservices/111/instances/222/heartbeat", null, null)) .thenReturn(httpResponse); Mockito.when(serviceCenterRawClient .putHttpRequest("/registry/heartbeats", null, mapper.writeValueAsString(heartbeatsRequest))) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); serviceCenterClient.sendHeartBeats(heartbeatsRequest); } |
ServiceCenterClient implements ServiceCenterOperation { @Override public boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId, MicroserviceInstanceStatus status) { try { HttpResponse response = httpClient.putHttpRequest( "/registry/microservices/" + serviceId + "/instances/" + instanceId + "/status?value=" + status, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("UPDATE STATUS OK"); return true; } else { throw new OperationException( "update service instance status fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "update service instance status fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestUpdateServicesInstanceStatus() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.putHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); Boolean result = serviceCenterClient .updateMicroserviceInstanceStatus("111", "222", MicroserviceInstanceStatus.UP); Assert.assertNotNull(result); Assert.assertEquals(true, result); } |
ServiceCenterClient implements ServiceCenterOperation { public List<SchemaInfo> getServiceSchemasList(String serviceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/schemas", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { GetSchemaListResponse getSchemaResponse = HttpUtils .deserialize(response.getContent(), GetSchemaListResponse.class); return getSchemaResponse.getSchemas(); } else { throw new OperationException( "get service schemas list fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service schemas list fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceSchemas() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"schemas\": [\n" + " {\n" + " \"schemaId\": \"111111\",\n" + " \"schema\": \"test\",\n" + " \"summary\": \"test\"\n" + " }\n" + " ]\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); List<SchemaInfo> schemaResponse = serviceCenterClient .getServiceSchemasList("111"); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(mapper.writeValueAsString(schemaResponse)); Assert.assertNotNull(jsonNode); Assert.assertEquals("111111", jsonNode.get(0).get("schemaId").textValue()); Assert.assertEquals("test", jsonNode.get(0).get("schema").textValue()); } |
ServiceCenterClient implements ServiceCenterOperation { public String getServiceSchemaContext(String serviceId, String schemaId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/schemas/" + schemaId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { GetSchemaResponse getSchemaResponse = HttpUtils.deserialize(response.getContent(), GetSchemaResponse.class); return getSchemaResponse.getSchema(); } else { throw new OperationException( "get service schema context fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "get service schemas context fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestGetServiceSchemasContext() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"schema\": \"test context\"\n" + "}"; httpResponse.setContent(responseString); Mockito.when(serviceCenterRawClient.getHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); String schemaContext = serviceCenterClient .getServiceSchemaContext("111", "222"); Assert.assertNotNull(schemaContext); Assert.assertEquals("test context", schemaContext); } |
DefaultLogPublisher implements MetricsInitializer { @Subscribe public void onPolledEvent(PolledEvent event) { try { printLog(event.getMeters()); } catch (Throwable e) { LOGGER.error("Failed to print perf log.", e); } } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Subscribe void onPolledEvent(PolledEvent event); static final String ENABLED; static final String ENDPOINTS_CLIENT_DETAIL_ENABLED; } | @Test public void onPolledEvent_failed() { publisher.onPolledEvent(null); LoggingEvent event = collector.getEvents().get(0); Assert.assertEquals("Failed to print perf log.", event.getMessage()); Assert.assertEquals(NullPointerException.class, event.getThrowableInformation().getThrowable().getClass()); }
@Test public void onPolledEvent(@Injectable VertxImpl vertxImpl, @Injectable MeasurementTree tree, @Injectable GlobalRegistry globalRegistry, @Injectable EventBus eventBus, @Injectable MetricsBootstrapConfig config) { try { ArchaiusUtils.setProperty("servicecomb.metrics.publisher.defaultLog.enabled", true); ArchaiusUtils.setProperty("servicecomb.metrics.invocation.latencyDistribution", "0,1,100"); publisher.init(globalRegistry, eventBus, config); new Expectations(VertxUtils.class) { { VertxUtils.getVertxMap(); result = Collections.singletonMap("v", vertxImpl); } }; DefaultPublishModel model = new DefaultPublishModel(); PerfInfo perfTotal = new PerfInfo(); perfTotal.setTps(10_0000); perfTotal.setMsTotalTime(30000L * 1_0000); perfTotal.setMsMaxLatency(30000); OperationPerf operationPerf = new OperationPerf(); operationPerf.setOperation("op"); operationPerf.setLatencyDistribution(new Integer[] {12, 120, 1200}); operationPerf.getStages().put(MeterInvocationConst.STAGE_TOTAL, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_EXECUTOR_QUEUE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_EXECUTION, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_PREPARE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_HANDLERS_REQUEST, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_HANDLERS_RESPONSE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CLIENT_FILTERS_REQUEST, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CLIENT_FILTERS_RESPONSE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CONSUMER_SEND_REQUEST, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_PRODUCER_SEND_RESPONSE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CONSUMER_GET_CONNECTION, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CONSUMER_WRITE_TO_BUF, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CONSUMER_WAIT_RESPONSE, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_CONSUMER_WAKE_CONSUMER, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_SERVER_FILTERS_REQUEST, perfTotal); operationPerf.getStages().put(MeterInvocationConst.STAGE_SERVER_FILTERS_RESPONSE, perfTotal); OperationPerfGroup operationPerfGroup = new OperationPerfGroup(Const.RESTFUL, Status.OK.name()); operationPerfGroup.addOperationPerf(operationPerf); OperationPerfGroups operationPerfGroups = new OperationPerfGroups(); operationPerfGroups.getGroups().put(operationPerfGroup.getTransport(), Collections.singletonMap(operationPerfGroup.getStatus(), operationPerfGroup)); model.getConsumer().setOperationPerfGroups(operationPerfGroups); model.getProducer().setOperationPerfGroups(operationPerfGroups); model.getEdge().setOperationPerfGroups(operationPerfGroups); model.getThreadPools().put("test", new ThreadPoolPublishModel()); Measurement measurement = new Measurement(null, 0L, 1.0); MeasurementNode measurementNodeCpuAll = new MeasurementNode("allProcess", new HashMap<>()); MeasurementNode measurementNodeCpuProcess = new MeasurementNode("currentProcess", new HashMap<>()); MeasurementNode measurementNodeSend = new MeasurementNode("send", new HashMap<>()); MeasurementNode measurementNodeSendPacket = new MeasurementNode("sendPackets", new HashMap<>()); MeasurementNode measurementNodeRecv = new MeasurementNode("receive", new HashMap<>()); MeasurementNode measurementNodeRecvPacket = new MeasurementNode("receivePackets", new HashMap<>()); MeasurementNode measurementNodeEth0 = new MeasurementNode("eth0", new HashMap<>()); MeasurementNode measurementNodeNet = new MeasurementNode("net", new HashMap<>()); MeasurementNode measurementNodeOs = new MeasurementNode("os", new HashMap<>()); measurementNodeSend.getMeasurements().add(measurement); measurementNodeRecv.getMeasurements().add(measurement); measurementNodeCpuAll.getMeasurements().add(measurement); measurementNodeCpuProcess.getMeasurements().add(measurement); measurementNodeRecvPacket.getMeasurements().add(measurement); measurementNodeSendPacket.getMeasurements().add(measurement); measurementNodeEth0.getChildren().put("send", measurementNodeSend); measurementNodeEth0.getChildren().put("receive", measurementNodeRecv); measurementNodeEth0.getChildren().put("receivePackets", measurementNodeRecvPacket); measurementNodeEth0.getChildren().put("sendPackets", measurementNodeSendPacket); measurementNodeNet.getChildren().put("eth0", measurementNodeEth0); measurementNodeOs.getChildren().put("cpu", measurementNodeCpuAll); measurementNodeOs.getChildren().put("processCpu", measurementNodeCpuProcess); measurementNodeOs.getChildren().put("net", measurementNodeNet); measurementNodeOs.getMeasurements().add(measurement); measurementNodeNet.getMeasurements().add(measurement); measurementNodeEth0.getMeasurements().add(measurement); new MockUp<PublishModelFactory>() { @Mock DefaultPublishModel createDefaultPublishModel() { return model; } @Mock MeasurementTree getTree() { return tree; } }; new Expectations() { { tree.findChild(OsMeter.OS_NAME); result = measurementNodeOs; } }; publisher.onPolledEvent(new PolledEvent(Collections.emptyList(), Collections.emptyList())); List<LoggingEvent> events = collector.getEvents().stream() .filter(e -> DefaultLogPublisher.class.getName().equals(e.getLoggerName())).collect(Collectors.toList()); LoggingEvent event = events.get(0); Assert.assertEquals("\n" + "os:\n" + " cpu:\n" + " all usage: 100.00% all idle: 0.00% process: 100.00%\n" + " net:\n" + " send(Bps) recv(Bps) send(pps) recv(pps) interface\n" + " 1 1 1 1 eth0\n" + "vertx:\n" + " instances:\n" + " name eventLoopContext-created\n" + " v 0\n" + "threadPool:\n" + " coreSize maxThreads poolSize currentBusy rejected queueSize taskCount taskFinished name\n" + " 0 0 0 0 NaN 0 0.0 0.0 test\n" + "consumer:\n" + " simple:\n" + " status tps latency [0,1) [1,100) [100,) operation\n" + " rest.OK 100000.0 3000.000/30000.000 12 120 1200 op\n" + " 100000.0 3000.000/30000.000 12 120 1200 (summary)\n" + " details:\n" + " rest.OK:\n" + " op:\n" + " prepare : 3000.000/30000.000 handlersReq : 3000.000/30000.000 cFiltersReq: 3000.000/30000.000 sendReq : 3000.000/30000.000\n" + " getConnect : 3000.000/30000.000 writeBuf : 3000.000/30000.000 waitResp : 3000.000/30000.000 wakeConsumer: 3000.000/30000.000\n" + " cFiltersResp: 3000.000/30000.000 handlersResp: 3000.000/30000.000\n" + "producer:\n" + " simple:\n" + " status tps latency [0,1) [1,100) [100,) operation\n" + " rest.OK 100000.0 3000.000/30000.000 12 120 1200 op\n" + " 100000.0 3000.000/30000.000 12 120 1200 (summary)\n" + " details:\n" + " rest.OK:\n" + " op:\n" + " prepare: 3000.000/30000.000 queue : 3000.000/30000.000 filtersReq : 3000.000/30000.000 handlersReq: 3000.000/30000.000\n" + " execute: 3000.000/30000.000 handlersResp: 3000.000/30000.000 filtersResp: 3000.000/30000.000 sendResp : 3000.000/30000.000\n" + "edge:\n" + " simple:\n" + " status tps latency [0,1) [1,100) [100,) operation\n" + " rest.OK 100000.0 3000.000/30000.000 12 120 1200 op\n" + " 100000.0 3000.000/30000.000 12 120 1200 (summary)\n" + " details:\n" + " rest.OK:\n" + " op:\n" + " prepare : 3000.000/30000.000 queue : 3000.000/30000.000 sFiltersReq : 3000.000/30000.000 handlersReq : 3000.000/30000.000\n" + " cFiltersReq : 3000.000/30000.000 sendReq : 3000.000/30000.000 getConnect : 3000.000/30000.000 writeBuf : 3000.000/30000.000\n" + " waitResp : 3000.000/30000.000 wakeConsumer: 3000.000/30000.000 cFiltersResp: 3000.000/30000.000 handlersResp: 3000.000/30000.000\n" + " sFiltersResp: 3000.000/30000.000 sendResp : 3000.000/30000.000\n", event.getMessage()); } catch (Exception e) { e.printStackTrace(); Assert.fail("unexpected error happen. " + e.getMessage()); } } |
ServiceCenterClient implements ServiceCenterOperation { @Override public boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo) { try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaInfo.getSchema()); request.setSummary(schemaInfo.getSummary()); HttpResponse response = httpClient .putHttpRequest("/registry/microservices/" + serviceId + "/schemas/" + schemaInfo.getSchemaId(), null, HttpUtils.serialize(request)); if (response.getStatusCode() == HttpStatus.SC_OK) { return true; } else { throw new OperationException( "update service schema fails, statusCode = " + response.getStatusCode() + "; message = " + response .getMessage() + "; content = " + response.getContent()); } } catch (IOException e) { throw new OperationException( "update service schema fails", e); } } ServiceCenterClient(ServiceCenterRawClient httpClient); ServiceCenterClient(AddressManager addressManager, SSLProperties sslProperties,
AKSKProperties akskProperties,
String tenantName,
Map<String, String> extraGlobalHeaders); @Override MicroserviceInstancesResponse getServiceCenterInstances(); @Override RegisteredMicroserviceResponse registerMicroservice(Microservice microservice); @Override MicroservicesResponse getMicroserviceList(); @Override RegisteredMicroserviceResponse queryServiceId(Microservice microservice); @Override Microservice getMicroserviceByServiceId(String serviceId); @Override RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance); @Override FindMicroserviceInstancesResponse findMicroserviceInstance(String consumerId, String appId, String serviceName,
String versionRule,
String revision); @Override MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId); @Override MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId); void deleteMicroserviceInstance(String serviceId, String instanceId); @Override boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId,
MicroserviceInstanceStatus status); void sendHeartBeats(HeartbeatsRequest heartbeatsRequest); @Override boolean sendHeartBeat(String serviceId, String instanceId); List<SchemaInfo> getServiceSchemasList(String serviceId); String getServiceSchemaContext(String serviceId, String schemaId); @Override boolean registerSchema(String serviceId, String schemaId, CreateSchemaRequest schema); @Override boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo); @Override boolean batchUpdateServiceSchemaContext(String serviceId, ModifySchemasRequest modifySchemasRequest); } | @Test public void TestUpdateServiceSchema() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.putHttpRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(httpResponse); ServiceCenterClient serviceCenterClient = new ServiceCenterClient(serviceCenterRawClient); boolean result = serviceCenterClient .updateServiceSchemaContext("111", new SchemaInfo()); Assert.assertNotNull(result); Assert.assertEquals(true, result); } |
TransportConfigUtils { public static int readVerticleCount(String key, String deprecatedKey) { int count = DynamicPropertyFactory.getInstance().getIntProperty(key, -1).get(); if (count > 0) { return count; } count = DynamicPropertyFactory.getInstance().getIntProperty(deprecatedKey, -1).get(); if (count > 0) { LOGGER.warn("{} is ambiguous, and deprecated, recommended to use {}.", deprecatedKey, key); return count; } count = Runtime.getRuntime().availableProcessors() > 8 ? 8 : Runtime.getRuntime().availableProcessors(); LOGGER.info("{} not defined, set to {}.", key, count); return count; } private TransportConfigUtils(); static int readVerticleCount(String key, String deprecatedKey); } | @Test public void readVerticleCount_new_exist() { ArchaiusUtils.setProperty(key, 10); Assert.assertEquals(10, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); }
@Test public void readVerticleCount_old_exist() { ArchaiusUtils.setProperty(deprecatedKey, 10); LogCollector collector = new LogCollector(); Assert.assertEquals(10, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); Assert.assertEquals("thread-count is ambiguous, and deprecated, recommended to use verticle-count.", collector.getEvents().get(0).getMessage()); collector.teardown(); }
@Test public void readVerticleCount_default_smallCpu() { new MockUp<Runtime>() { @Mock int availableProcessors() { return 7; } }; LogCollector collector = new LogCollector(); Assert.assertEquals(7, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); Assert.assertEquals("verticle-count not defined, set to 7.", collector.getLastEvents().getMessage()); collector.teardown(); }
@Test public void readVerticleCount_default_bigCpu() { AtomicInteger count = new AtomicInteger(8); new MockUp<Runtime>() { @Mock int availableProcessors() { return count.get(); } }; LogCollector collector = new LogCollector(); Assert.assertEquals(8, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); Assert.assertEquals("verticle-count not defined, set to 8.", collector.getLastEvents().getMessage()); count.set(9); collector.clear(); Assert.assertEquals(8, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); Assert.assertEquals("verticle-count not defined, set to 8.", collector.getLastEvents().getMessage()); collector.teardown(); } |
HighwayCodec { public static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer) throws Exception { RequestRootDeserializer<Object> requestDeserializer = operationProtobuf.getRequestRootDeserializer(); Map<String, Object> swaggerArguments = requestDeserializer.deserialize(bodyBuffer.getBytes()); addPrimitiveTypeDefaultValues(invocation, swaggerArguments); invocation.setSwaggerArguments(swaggerArguments); invocation.mergeContext(header.getContext()); } private HighwayCodec(); static TcpOutputStream encodeRequest(long msgId, Invocation invocation,
OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf,
Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema,
Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); } | @Test public void testDecodeRequestTraceId(@Mocked Endpoint endpoint) throws Exception { commonMock(); Invocation invocation = new Invocation(endpoint, operationMeta, null); invocation.addContext("X-B3-traceId", "test1"); Assert.assertEquals("test1", invocation.getContext("X-B3-traceId")); RequestHeader headers = new RequestHeader(); Map<String, String> context = new HashMap<>(); headers.setContext(context); HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer); Assert.assertEquals("test1", invocation.getContext("X-B3-traceId")); context.put("X-B3-traceId", "test2"); HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer); Assert.assertEquals("test2", invocation.getContext("X-B3-traceId")); } |
HighwayCodec { public static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema, Object body) throws Exception { try (HighwayOutputStream os = new HighwayOutputStream(msgId)) { os.write(header, bodySchema, body); return os.getBuffer(); } } private HighwayCodec(); static TcpOutputStream encodeRequest(long msgId, Invocation invocation,
OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf,
Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema,
Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); } | @Test public void testEncodeResponse() { boolean status = true; ResponseRootSerializer bodySchema = Mockito.mock(ResponseRootSerializer.class); try { commonMock(); Object data = new Object(); Mockito.when(bodySchema.serialize(data)).thenReturn(new byte[0]); HighwayCodec.encodeResponse(23432142, null, bodySchema, data); } catch (Exception e) { e.printStackTrace(); status = false; } Assert.assertTrue(status); } |
HighwayCodec { public static TcpOutputStream encodeRequest(long msgId, Invocation invocation, OperationProtobuf operationProtobuf) throws Exception { RequestHeader header = new RequestHeader(); header.setMsgType(MsgType.REQUEST); header.setFlags(0); header.setDestMicroservice(invocation.getMicroserviceName()); header.setSchemaId(invocation.getSchemaId()); header.setOperationName(invocation.getOperationName()); header.setContext(invocation.getContext()); HighwayOutputStream os = new HighwayOutputStream(msgId); os.write(header, operationProtobuf.getRequestRootSerializer(), invocation.getSwaggerArguments()); return os; } private HighwayCodec(); static TcpOutputStream encodeRequest(long msgId, Invocation invocation,
OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf,
Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema,
Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); } | @Test public void testEncodeRequest() { boolean status = true; try { commonMock(); Map<String, Object> args = new HashMap<>(0); Mockito.when(invocation.getInvocationArguments()).thenReturn(args); Mockito.when(requestSerializer.serialize(args)).thenReturn(new byte[0]); TcpOutputStream os = HighwayCodec.encodeRequest(0, invocation, operationProtobuf); Assert.assertNotNull(os); Assert.assertArrayEquals(TcpParser.TCP_MAGIC, os.getBuffer().getBytes(0, 7)); } catch (Exception e) { e.printStackTrace(); status = false; } Assert.assertTrue(status); } |
ResponseHeader { public void setContext(Map<String, String> context) { this.context = context; } static RootSerializer getRootSerializer(); static ResponseHeader readObject(Buffer bodyBuffer); int getFlags(); void setFlags(int flags); int getStatusCode(); void setStatusCode(int statusCode); String getReasonPhrase(); void setReasonPhrase(String reason); Map<String, String> getContext(); void setContext(Map<String, String> context); Headers getHeaders(); void setHeaders(Headers headers); } | @Test public void testSetContext() { context.put("key1", "v1"); responseHeader.setContext(context); Assert.assertNotNull(responseHeader.getContext()); Assert.assertEquals("v1", responseHeader.getContext().get("key1")); } |
HighwayServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); } | @Test public void should_not_invoke_filter_when_decode_request_failed(@Mocked FilterNode nextNode) throws Exception { mockDecodeRequestFail(); codecFilter.onFilter(invocation, nextNode); new Verifications() { { nextNode.onFilter(invocation); times = 0; } }; }
@Test public void should_convert_exception_to_response_when_decode_request_failed() throws Exception { mockDecodeRequestFail(); Response response = codecFilter.onFilter(invocation, nextNode).get(); assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR); assertThat(Json.encode(response.getResult())) .isEqualTo("{\"code\":\"SCB.50000000\",\"message\":\"encode request failed\"}"); } |
HighwayTransport extends AbstractTransport { public boolean init() throws Exception { highwayClient.init(transportVertx); DeploymentOptions deployOptions = new DeploymentOptions().setInstances(HighwayConfig.getServerThreadCount()); setListenAddressWithoutSchema(HighwayConfig.getAddress(), Collections.singletonMap(TcpConst.LOGIN, "true")); SimpleJsonObject json = new SimpleJsonObject(); json.put(ENDPOINT_KEY, getEndpoint()); deployOptions.setConfig(json); deployOptions.setWorkerPoolName("pool-worker-transport-highway"); return VertxUtils.blockDeploy(transportVertx, HighwayServerVerticle.class, deployOptions); } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testInit() { boolean status = true; try { transport.init(); } catch (Exception e) { status = false; } Assert.assertTrue(status); } |
HighwayTransport extends AbstractTransport { @Override public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception { highwayClient.send(invocation, asyncResp); } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testSendException() throws Exception { Invocation invocation = Mockito.mock(Invocation.class); AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class); commonHighwayMock(invocation); Holder<Boolean> sended = new Holder<>(false); new MockUp<HighwayClient>() { @Mock public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception { sended.value = true; } }; transport.send(invocation, asyncResp); Assert.assertTrue(sended.value); } |
HighwayTransport extends AbstractTransport { @Override public String getName() { return Const.HIGHWAY; } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHighway() { Invocation invocation = Mockito.mock(Invocation.class); commonHighwayMock(invocation); Assert.assertEquals("highway", transport.getName()); } |
HighwayConfig { public static int getServerThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.highway.server.verticle-count", "servicecomb.highway.server.thread-count"); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCount(); } | @Test public void getServerThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.server.verticle-count", 1); Assert.assertEquals(HighwayConfig.getServerThreadCount(), 1); } |
HighwayConfig { public static int getClientThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.highway.client.verticle-count", "servicecomb.highway.client.thread-count"); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCount(); } | @Test public void getClientThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.client.verticle-count", 1); Assert.assertEquals(HighwayConfig.getClientThreadCount(), 1); } |
HighwayConfig { public static String getAddress() { DynamicStringProperty address = DynamicPropertyFactory.getInstance().getStringProperty("servicecomb.highway.address", null); return address.get(); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCount(); } | @Test public void getAddress() { Assert.assertEquals(HighwayConfig.getAddress(), null); } |
HighwayClient { public void init(Vertx vertx) throws Exception { TcpClientConfig normalConfig = createTcpClientConfig(); normalConfig.setSsl(false); TcpClientConfig sslConfig = createTcpClientConfig(); sslConfig.setSsl(true); clientMgr = new ClientPoolManager<>(vertx, new HighwayClientPoolFactory(normalConfig, sslConfig)); DeploymentOptions deployOptions = VertxUtils.createClientDeployOptions(clientMgr, HighwayConfig.getClientThreadCount()); VertxUtils.blockDeploy(vertx, ClientVerticle.class, deployOptions); } void init(Vertx vertx); void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHighwayClientSSL(@Mocked Vertx vertx) throws Exception { new MockUp<VertxUtils>() { @Mock <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls, DeploymentOptions options) { return true; } }; client.init(vertx); ClientPoolManager<HighwayClientConnectionPool> clientMgr = Deencapsulation.getField(client, "clientMgr"); Assert.assertSame(vertx, Deencapsulation.getField(clientMgr, "vertx")); } |
RestClientInvocation { public void invoke(Invocation invocation, AsyncResponse asyncResp) throws Exception { this.invocation = invocation; this.asyncResp = asyncResp; OperationMeta operationMeta = invocation.getOperationMeta(); restOperationMeta = operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); String path = this.createRequestPath(restOperationMeta); IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress(); createRequest(ipPort, path); clientRequest.putHeader(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE, invocation.getMicroserviceName()); RestClientRequestImpl restClientRequest = new RestClientRequestImpl(clientRequest, httpClientWithContext.context(), asyncResp, throwableHandler); invocation.getHandlerContext().put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest); Buffer requestBodyBuffer = restClientRequest.getBodyBuffer(); HttpServletRequestEx requestEx = new VertxClientRequestToHttpServletRequest(clientRequest, requestBodyBuffer); invocation.getInvocationStageTrace().startClientFiltersRequest(); for (HttpClientFilter filter : httpClientFilters) { if (filter.enabled()) { filter.beforeSendRequest(invocation, requestEx); } } clientRequest.exceptionHandler(e -> { invocation.getTraceIdLogger().error(LOGGER, "Failed to send request, local:{}, remote:{}, message={}.", getLocalAddress(), ipPort.getSocketAddress(), ExceptionUtils.getExceptionMessageWithoutTrace(e)); throwableHandler.handle(e); }); invocation.getInvocationStageTrace().startSend(); httpClientWithContext.runOnContext(httpClient -> { clientRequest.setTimeout(operationMeta.getConfig().getMsRequestTimeout()); processServiceCombHeaders(invocation, operationMeta); try { restClientRequest.end(); } catch (Throwable e) { invocation.getTraceIdLogger().error(LOGGER, "send http request failed, local:{}, remote: {}, message={}.", getLocalAddress(), ipPort , ExceptionUtils.getExceptionMessageWithoutTrace(e)); fail((ConnectionBase) clientRequest.connection(), e); } }); } RestClientInvocation(HttpClientWithContext httpClientWithContext, List<HttpClientFilter> httpClientFilters); void invoke(Invocation invocation, AsyncResponse asyncResp); } | @Test public void invoke(@Mocked Response resp) throws Exception { doAnswer(a -> { asyncResp.complete(resp); return null; }).when(request).end(); restClientInvocation.invoke(invocation, asyncResp); Assert.assertSame(resp, response); Assert.assertThat(headers.names(), Matchers.containsInAnyOrder(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE, org.apache.servicecomb.core.Const.CSE_CONTEXT)); Assert.assertEquals(TARGET_MICROSERVICE_NAME, headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE)); Assert.assertEquals("{}", headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT)); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartClientFiltersRequest()); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartSend()); }
@Test public void invoke_endThrow() throws Exception { Mockito.doThrow(Error.class).when(request).end(); restClientInvocation.invoke(invocation, asyncResp); Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.instanceOf(Error.class)); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartClientFiltersRequest()); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getFinishClientFiltersResponse()); }
@Test public void invoke_requestThrow() throws Exception { Throwable t = new RuntimeExceptionWithoutStackTrace(); doAnswer(a -> { exceptionHandler.handle(t); return null; }).when(request).end(); restClientInvocation.invoke(invocation, asyncResp); restClientInvocation.invoke(invocation, asyncResp); Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.sameInstance(t)); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartClientFiltersRequest()); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getFinishClientFiltersResponse()); } |
MetricsRestPublisher implements MetricsInitializer { @ApiResponses({ @ApiResponse(code = 400, response = String.class, message = "illegal request content"), }) @GET @Path("/") public Map<String, Double> measure() { Map<String, Double> measurements = new LinkedHashMap<>(); if (globalRegistry == null) { return measurements; } StringBuilder sb = new StringBuilder(); for (Registry registry : globalRegistry.getRegistries()) { for (Meter meter : registry) { meter.measure().forEach(measurement -> { String key = idToString(measurement.id(), sb); measurements.put(key, measurement.value()); }); } } return measurements; } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @ApiResponses({ @ApiResponse(code = 400, response = String.class, message = "illegal request content"), }) @GET @Path("/") Map<String, Double> measure(); } | @Test public void measure_globalRegistryNull() { Map<String, Double> result = publisher.measure(); Assert.assertEquals(0, result.size()); } |
RestClientInvocation { protected void setCseContext() { try { String cseContext = JsonUtils.writeValueAsString(invocation.getContext()); clientRequest.putHeader(org.apache.servicecomb.core.Const.CSE_CONTEXT, cseContext); } catch (Throwable e) { invocation.getTraceIdLogger().error(LOGGER, "Failed to encode and set cseContext, message={}." , ExceptionUtils.getExceptionMessageWithoutTrace(e)); } } RestClientInvocation(HttpClientWithContext httpClientWithContext, List<HttpClientFilter> httpClientFilters); void invoke(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testSetCseContext() { Map<String, String> contextMap = Collections.singletonMap("k", "v"); when(invocation.getContext()).thenReturn(contextMap); restClientInvocation.setCseContext(); Assert.assertEquals("x-cse-context: {\"k\":\"v\"}\n", headers.toString()); }
@Test public void testSetCseContext_failed() throws JsonProcessingException { LogCollector logCollector = new LogCollector(); logCollector.setLogLevel(RestClientInvocation.class.getName(), Level.DEBUG); new Expectations(JsonUtils.class) { { JsonUtils.writeValueAsString(any); result = new RuntimeExceptionWithoutStackTrace(); } }; restClientInvocation.setCseContext(); Assert.assertEquals( "Failed to encode and set cseContext, message=cause:RuntimeExceptionWithoutStackTrace,message:null.", logCollector.getEvents().get(0).getMessage()); logCollector.teardown(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.