Search in sources :

Example 6 with TcpClient

use of org.apache.geode.distributed.internal.tcpserver.TcpClient in project geode by apache.

the class ClusterConfigurationLoader method requestConfigurationFromLocators.

/**
   * Request the shared configuration for group(s) from locator(s) this member is bootstrapped with.
   *
   * This will request the group config this server belongs plus the "cluster" config
   * 
   * @param config this member's configuration.
   * @return {@link ConfigurationResponse}
   */
public static ConfigurationResponse requestConfigurationFromLocators(DistributionConfig config, List<String> locatorList) throws ClusterConfigurationNotAvailableException, UnknownHostException {
    List<String> groups = ClusterConfigurationLoader.getGroups(config);
    ConfigurationRequest request = new ConfigurationRequest();
    request.addGroups(ClusterConfigurationService.CLUSTER_CONFIG);
    for (String group : groups) {
        request.addGroups(group);
    }
    request.setNumAttempts(10);
    ConfigurationResponse response = null;
    // Try talking to all the locators in the list
    // to get the shared configuration.
    TcpClient client = new TcpClient();
    for (String locatorInfo : locatorList) {
        DistributionLocatorId dlId = new DistributionLocatorId(locatorInfo);
        String ipaddress = dlId.getBindAddress();
        InetAddress locatorInetAddress = null;
        if (StringUtils.isNotBlank(ipaddress)) {
            locatorInetAddress = InetAddress.getByName(ipaddress);
        } else {
            locatorInetAddress = dlId.getHost();
        }
        int port = dlId.getPort();
        try {
            response = (ConfigurationResponse) client.requestToServer(locatorInetAddress, port, request, 10000);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Log
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    if (response == null || response.failedToGetSharedConfig()) {
        throw new ClusterConfigurationNotAvailableException(LocalizedStrings.Launcher_Command_FAILED_TO_GET_SHARED_CONFIGURATION.toLocalizedString());
    }
    return response;
}
Also used : ConfigurationResponse(org.apache.geode.management.internal.configuration.messages.ConfigurationResponse) UnknownHostException(java.net.UnknownHostException) DistributionLocatorId(org.apache.geode.internal.admin.remote.DistributionLocatorId) ConfigurationRequest(org.apache.geode.management.internal.configuration.messages.ConfigurationRequest) TcpClient(org.apache.geode.distributed.internal.tcpserver.TcpClient) IOException(java.io.IOException) ClusterConfigurationNotAvailableException(org.apache.geode.internal.process.ClusterConfigurationNotAvailableException) InetAddress(java.net.InetAddress)

Example 7 with TcpClient

use of org.apache.geode.distributed.internal.tcpserver.TcpClient in project geode by apache.

the class ClusterConfigurationStatusRetriever method fromLocator.

public static String fromLocator(String locatorHostName, int locatorPort) throws ClassNotFoundException, IOException {
    final StringBuilder buffer = new StringBuilder();
    try {
        final InetAddress networkAddress = InetAddress.getByName(locatorHostName);
        InetSocketAddress inetSockAddr = new InetSocketAddress(networkAddress, locatorPort);
        TcpClient client = new TcpClient();
        SharedConfigurationStatusResponse statusResponse = (SharedConfigurationStatusResponse) client.requestToServer(inetSockAddr, new SharedConfigurationStatusRequest(), 10000, true);
        for (int i = 0; i < NUM_ATTEMPTS_FOR_SHARED_CONFIGURATION_STATUS; i++) {
            if (statusResponse.getStatus().equals(org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus.STARTED) || statusResponse.getStatus().equals(org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus.NOT_STARTED)) {
                statusResponse = (SharedConfigurationStatusResponse) client.requestToServer(inetSockAddr, new SharedConfigurationStatusRequest(), 10000, true);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                // Swallow the exception
                }
            } else {
                break;
            }
        }
        switch(statusResponse.getStatus()) {
            case RUNNING:
                buffer.append("\nCluster configuration service is up and running.");
                break;
            case STOPPED:
                buffer.append("\nCluster configuration service failed to start , please check the log file for errors.");
                break;
            case WAITING:
                buffer.append("\nCluster configuration service is waiting for other locators with newer shared configuration data.");
                Set<PersistentMemberPattern> pmpSet = statusResponse.getOtherLocatorInformation();
                if (!pmpSet.isEmpty()) {
                    buffer.append("\nThis locator might have stale cluster configuration data.");
                    buffer.append("\nFollowing locators contain potentially newer cluster configuration data");
                    for (PersistentMemberPattern pmp : pmpSet) {
                        buffer.append("\nHost : ").append(pmp.getHost());
                        buffer.append("\nDirectory : ").append(pmp.getDirectory());
                    }
                } else {
                    buffer.append("\nPlease check the log file for errors");
                }
                break;
            case UNDETERMINED:
                buffer.append("\nUnable to determine the status of shared configuration service, please check the log file");
                break;
            case NOT_STARTED:
                buffer.append("\nCluster configuration service has not been started yet");
                break;
            case STARTED:
                buffer.append("\nCluster configuration service has been started, but its not running yet");
                break;
        }
    } catch (Exception e) {
        // TODO fix this once Trac Bug #50513 gets fixed
        // NOTE this ClassCastException occurs if the a plain text TCP/IP connection is used to
        // connect to a Locator
        // configured with SSL.
        Gfsh.getCurrentInstance().logToFile(String.format("Failed to get the status of the Shared Configuration Service running on Locator (%1$s[%2$d])!", locatorHostName, locatorPort), e);
    }
    return buffer.toString();
}
Also used : SharedConfigurationStatusResponse(org.apache.geode.management.internal.configuration.messages.SharedConfigurationStatusResponse) PersistentMemberPattern(org.apache.geode.internal.cache.persistence.PersistentMemberPattern) InetSocketAddress(java.net.InetSocketAddress) TcpClient(org.apache.geode.distributed.internal.tcpserver.TcpClient) SharedConfigurationStatusRequest(org.apache.geode.management.internal.configuration.messages.SharedConfigurationStatusRequest) InetAddress(java.net.InetAddress) IOException(java.io.IOException)

Example 8 with TcpClient

use of org.apache.geode.distributed.internal.tcpserver.TcpClient in project geode by apache.

the class LocatorLoadBalancingDUnitTest method testEstimation.

/**
   * Test that the locator will properly estimate the load for servers when it receives connection
   * requests.
   */
@Test
public void testEstimation() throws IOException, ClassNotFoundException {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    String hostName = NetworkUtils.getServerHostName(vm0.getHost());
    vm0.invoke("Start Locator", () -> startLocator(hostName, locatorPort, ""));
    String locators = getLocatorString(host, locatorPort);
    int serverPort = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
    ServerLoad expectedLoad = new ServerLoad(2 / 800f, 1 / 800.0f, 0f, 1f);
    ServerLocation expectedLocation = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort);
    Map expected = new HashMap();
    expected.put(expectedLocation, expectedLoad);
    SocketCreatorFactory.setDistributionConfig(new DistributionConfigImpl(new Properties()));
    ClientConnectionResponse response;
    response = (ClientConnectionResponse) new TcpClient().requestToServer(InetAddress.getByName(NetworkUtils.getServerHostName(host)), locatorPort, new ClientConnectionRequest(Collections.EMPTY_SET, null), 10000);
    Assert.assertEquals(expectedLocation, response.getServer());
    response = (ClientConnectionResponse) new TcpClient().requestToServer(InetAddress.getByName(NetworkUtils.getServerHostName(host)), locatorPort, new ClientConnectionRequest(Collections.EMPTY_SET, null), 10000, true);
    Assert.assertEquals(expectedLocation, response.getServer());
    // we expect that the connection load load will be 2 * the loadPerConnection
    vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
    QueueConnectionResponse response2;
    response2 = (QueueConnectionResponse) new TcpClient().requestToServer(InetAddress.getByName(NetworkUtils.getServerHostName(host)), locatorPort, new QueueConnectionRequest(null, 2, Collections.EMPTY_SET, null, false), 10000, true);
    Assert.assertEquals(Collections.singletonList(expectedLocation), response2.getServers());
    response2 = (QueueConnectionResponse) new TcpClient().requestToServer(InetAddress.getByName(NetworkUtils.getServerHostName(host)), locatorPort, new QueueConnectionRequest(null, 5, Collections.EMPTY_SET, null, false), 10000, true);
    Assert.assertEquals(Collections.singletonList(expectedLocation), response2.getServers());
    // we expect that the queue load will increase by 2
    expectedLoad.setSubscriptionConnectionLoad(2f);
    vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
}
Also used : QueueConnectionRequest(org.apache.geode.cache.client.internal.locator.QueueConnectionRequest) ServerLocation(org.apache.geode.distributed.internal.ServerLocation) HashMap(java.util.HashMap) ClientConnectionRequest(org.apache.geode.cache.client.internal.locator.ClientConnectionRequest) Host(org.apache.geode.test.dunit.Host) Properties(java.util.Properties) ServerLoad(org.apache.geode.cache.server.ServerLoad) ClientConnectionResponse(org.apache.geode.cache.client.internal.locator.ClientConnectionResponse) DistributionConfigImpl(org.apache.geode.distributed.internal.DistributionConfigImpl) TcpClient(org.apache.geode.distributed.internal.tcpserver.TcpClient) VM(org.apache.geode.test.dunit.VM) QueueConnectionResponse(org.apache.geode.cache.client.internal.locator.QueueConnectionResponse) HashMap(java.util.HashMap) Map(java.util.Map) ClientServerTest(org.apache.geode.test.junit.categories.ClientServerTest) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 9 with TcpClient

use of org.apache.geode.distributed.internal.tcpserver.TcpClient in project geode by apache.

the class GMSLocator method recover.

private boolean recover(InetSocketAddress other) {
    try {
        logger.info("Peer locator attempting to recover from " + other);
        TcpClient client = new TcpClient();
        Object response = client.requestToServer(other.getAddress(), other.getPort(), new GetViewRequest(), 20000, true);
        if (response != null && (response instanceof GetViewResponse)) {
            this.view = ((GetViewResponse) response).getView();
            logger.info("Peer locator recovered initial membership of {}", view);
            return true;
        }
    } catch (IOException | ClassNotFoundException ignore) {
        logger.debug("Peer locator could not recover membership view from {}: {}", other, ignore.getMessage());
    }
    logger.info("Peer locator was unable to recover state from this locator");
    return false;
}
Also used : TcpClient(org.apache.geode.distributed.internal.tcpserver.TcpClient) IOException(java.io.IOException)

Example 10 with TcpClient

use of org.apache.geode.distributed.internal.tcpserver.TcpClient in project geode by apache.

the class ClusterConfigurationServiceDUnitTest method testSharedConfigurationService.

@Test
public void testSharedConfigurationService() throws Exception {
    // Start the Locator and wait for shared configuration to be available
    final String testGroup = "G1";
    final String clusterLogLevel = "error";
    final String groupLogLevel = "fine";
    final String testName = getName();
    final VM locator1Vm = getHost(0).getVM(1);
    final VM dataMemberVm = getHost(0).getVM(2);
    final VM locator2Vm = getHost(0).getVM(3);
    final int[] ports = getRandomAvailableTCPPorts(3);
    final int locator1Port = ports[0];
    locator1Vm.invoke(() -> {
        final File locatorLogFile = new File(testName + "-locator-" + locator1Port + ".log");
        final Properties locatorProps = new Properties();
        locatorProps.setProperty(NAME, "Locator1");
        locatorProps.setProperty(MCAST_PORT, "0");
        locatorProps.setProperty(LOG_LEVEL, "info");
        locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
        try {
            final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator1Port, locatorLogFile, null, locatorProps);
            WaitCriterion wc = new WaitCriterion() {

                @Override
                public boolean done() {
                    return locator.isSharedConfigurationRunning();
                }

                @Override
                public String description() {
                    return "Waiting for shared configuration to be started";
                }
            };
            waitForCriterion(wc, TIMEOUT, INTERVAL, true);
        } catch (IOException e) {
            fail("Unable to create a locator with a shared configuration", e);
        }
    });
    XmlEntity xmlEntity = dataMemberVm.invoke(() -> {
        Properties localProps = new Properties();
        localProps.setProperty(MCAST_PORT, "0");
        localProps.setProperty(LOCATORS, "localhost[" + locator1Port + "]");
        localProps.setProperty(GROUPS, testGroup);
        getSystem(localProps);
        Cache cache = getCache();
        assertNotNull(cache);
        DiskStoreFactory dsFactory = cache.createDiskStoreFactory();
        File dsDir = new File("dsDir");
        if (!dsDir.exists()) {
            dsDir.mkdir();
        }
        dsFactory.setDiskDirs(new File[] { dsDir });
        dsFactory.create(DISKSTORENAME);
        RegionFactory regionFactory = getCache().createRegionFactory(RegionShortcut.REPLICATE);
        regionFactory.create(REGION1);
        return new XmlEntity(CacheXml.REGION, "name", REGION1);
    });
    locator1Vm.invoke(() -> {
        ClusterConfigurationService sc = InternalLocator.getLocator().getSharedConfiguration();
        sc.addXmlEntity(xmlEntity, new String[] { testGroup });
        // Modify property and cache attributes
        Properties clusterProperties = new Properties();
        clusterProperties.setProperty(LOG_LEVEL, clusterLogLevel);
        XmlEntity cacheEntity = XmlEntity.builder().withType(CacheXml.CACHE).build();
        Map<String, String> cacheAttributes = new HashMap<String, String>();
        cacheAttributes.put(CacheXml.COPY_ON_READ, "true");
        sc.modifyXmlAndProperties(clusterProperties, cacheEntity, null);
        clusterProperties.setProperty(LOG_LEVEL, groupLogLevel);
        sc.modifyXmlAndProperties(clusterProperties, cacheEntity, new String[] { testGroup });
        // Add a jar
        byte[][] jarBytes = new byte[1][];
        jarBytes[0] = "Hello".getBytes();
        assertTrue(sc.addJarsToThisLocator(new String[] { "foo.jar" }, jarBytes, null));
        // Add a jar for the group
        jarBytes = new byte[1][];
        jarBytes[0] = "Hello".getBytes();
        assertTrue(sc.addJarsToThisLocator(new String[] { "bar.jar" }, jarBytes, new String[] { testGroup }));
    });
    final int locator2Port = ports[1];
    // Create another locator in VM2
    locator2Vm.invoke(() -> {
        final File locatorLogFile = new File(testName + "-locator-" + locator2Port + ".log");
        final Properties locatorProps = new Properties();
        locatorProps.setProperty(NAME, "Locator2");
        locatorProps.setProperty(MCAST_PORT, "0");
        locatorProps.setProperty(LOG_LEVEL, "info");
        locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
        locatorProps.setProperty(LOCATORS, "localhost[" + locator1Port + "]");
        try {
            final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator2Port, locatorLogFile, null, locatorProps);
            WaitCriterion wc = new WaitCriterion() {

                @Override
                public boolean done() {
                    return locator.isSharedConfigurationRunning();
                }

                @Override
                public String description() {
                    return "Waiting for shared configuration to be started";
                }
            };
            waitForCriterion(wc, TIMEOUT, INTERVAL, true);
        } catch (IOException e) {
            fail("Unable to create a locator with a shared configuration", e);
        }
        InternalLocator locator = (InternalLocator) Locator.getLocator();
        ClusterConfigurationService sharedConfig = locator.getSharedConfiguration();
        Map<String, Configuration> entireConfiguration = sharedConfig.getEntireConfiguration();
        Configuration clusterConfig = entireConfiguration.get(ClusterConfigurationService.CLUSTER_CONFIG);
        assertNotNull(clusterConfig);
        assertNotNull(clusterConfig.getJarNames());
        assertTrue(clusterConfig.getJarNames().contains("foo.jar"));
        assertTrue(clusterConfig.getGemfireProperties().getProperty(LOG_LEVEL).equals(clusterLogLevel));
        assertNotNull(clusterConfig.getCacheXmlContent());
        Configuration testGroupConfiguration = entireConfiguration.get(testGroup);
        assertNotNull(testGroupConfiguration);
        assertNotNull(testGroupConfiguration.getJarNames());
        assertTrue(testGroupConfiguration.getJarNames().contains("bar.jar"));
        assertTrue(testGroupConfiguration.getGemfireProperties().getProperty(LOG_LEVEL).equals(groupLogLevel));
        assertNotNull(testGroupConfiguration.getCacheXmlContent());
        assertTrue(testGroupConfiguration.getCacheXmlContent().contains(REGION1));
        Map<String, byte[]> jarData = sharedConfig.getAllJarsFromThisLocator(entireConfiguration.keySet());
        String[] jarNames = jarData.keySet().stream().toArray(String[]::new);
        byte[][] jarBytes = jarData.values().toArray(new byte[jarNames.length][]);
        assertNotNull(jarNames);
        assertNotNull(jarBytes);
        sharedConfig.deleteXmlEntity(new XmlEntity(CacheXml.REGION, "name", REGION1), new String[] { testGroup });
        sharedConfig.removeJars(new String[] { "foo.jar" }, null);
        sharedConfig.removeJars(null, null);
    });
    dataMemberVm.invoke(() -> {
        Set<String> groups = new HashSet<String>();
        groups.add(testGroup);
        ConfigurationRequest configRequest = new ConfigurationRequest(groups);
        ConfigurationResponse configResponse = (ConfigurationResponse) new TcpClient().requestToServer(InetAddress.getByName("localhost"), locator2Port, configRequest, 1000);
        assertNotNull(configResponse);
        Map<String, Configuration> requestedConfiguration = configResponse.getRequestedConfiguration();
        Configuration clusterConfiguration = requestedConfiguration.get(ClusterConfigurationService.CLUSTER_CONFIG);
        assertNotNull(clusterConfiguration);
        assertTrue(configResponse.getJarNames().length == 0);
        assertTrue(configResponse.getJars().length == 0);
        assertTrue(clusterConfiguration.getJarNames().isEmpty());
        assertTrue(clusterConfiguration.getGemfireProperties().getProperty(LOG_LEVEL).equals(clusterLogLevel));
        Configuration testGroupConfiguration = requestedConfiguration.get(testGroup);
        assertNotNull(testGroupConfiguration);
        assertFalse(testGroupConfiguration.getCacheXmlContent().contains(REGION1));
        assertTrue(testGroupConfiguration.getJarNames().isEmpty());
        assertTrue(testGroupConfiguration.getGemfireProperties().getProperty(LOG_LEVEL).equals(groupLogLevel));
        GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
        Map<InternalDistributedMember, Collection<String>> locatorsWithSharedConfiguration = cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration();
        assertFalse(locatorsWithSharedConfiguration.isEmpty());
        assertTrue(locatorsWithSharedConfiguration.size() == 2);
        Set<InternalDistributedMember> locatorMembers = locatorsWithSharedConfiguration.keySet();
        for (InternalDistributedMember locatorMember : locatorMembers) {
            System.out.println(locatorMember);
        }
        return null;
    });
}
Also used : ConfigurationResponse(org.apache.geode.management.internal.configuration.messages.ConfigurationResponse) Configuration(org.apache.geode.management.internal.configuration.domain.Configuration) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) RegionFactory(org.apache.geode.cache.RegionFactory) TcpClient(org.apache.geode.distributed.internal.tcpserver.TcpClient) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) IOException(java.io.IOException) DiskStoreFactory(org.apache.geode.cache.DiskStoreFactory) XmlEntity(org.apache.geode.management.internal.configuration.domain.XmlEntity) InternalLocator(org.apache.geode.distributed.internal.InternalLocator) WaitCriterion(org.apache.geode.test.dunit.WaitCriterion) ClusterConfigurationService(org.apache.geode.distributed.internal.ClusterConfigurationService) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) ConfigurationRequest(org.apache.geode.management.internal.configuration.messages.ConfigurationRequest) VM(org.apache.geode.test.dunit.VM) File(java.io.File) Cache(org.apache.geode.cache.Cache) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

TcpClient (org.apache.geode.distributed.internal.tcpserver.TcpClient)10 IOException (java.io.IOException)5 Test (org.junit.Test)4 ConnectException (java.net.ConnectException)3 InetAddress (java.net.InetAddress)3 InetSocketAddress (java.net.InetSocketAddress)2 Properties (java.util.Properties)2 ClientConnectionResponse (org.apache.geode.cache.client.internal.locator.ClientConnectionResponse)2 DistributionConfigImpl (org.apache.geode.distributed.internal.DistributionConfigImpl)2 ServerLocation (org.apache.geode.distributed.internal.ServerLocation)2 DistributionLocatorId (org.apache.geode.internal.admin.remote.DistributionLocatorId)2 ConfigurationRequest (org.apache.geode.management.internal.configuration.messages.ConfigurationRequest)2 ConfigurationResponse (org.apache.geode.management.internal.configuration.messages.ConfigurationResponse)2 VM (org.apache.geode.test.dunit.VM)2 ClientServerTest (org.apache.geode.test.junit.categories.ClientServerTest)2 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)2 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)2 File (java.io.File)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1