Search in sources :

Example 16 with GemFireConfigException

use of org.apache.geode.GemFireConfigException in project geode by apache.

the class SocketCreator method readSSLProperties.

/**
   * Used to read the properties from console. AgentLauncher calls this method directly & ignores
   * gemfire.properties. CacheServerLauncher and SystemAdmin call this through
   * {@link #readSSLProperties(Map)} and do NOT ignore gemfire.properties.
   * 
   * @param env Map in which the properties are to be read from console.
   * @param ignoreGemFirePropsFile if <code>false</code> existing gemfire.properties file is read,
   *        if <code>true</code>, properties from gemfire.properties file are ignored.
   */
public static void readSSLProperties(Map<String, String> env, boolean ignoreGemFirePropsFile) {
    Properties props = new Properties();
    DistributionConfigImpl.loadGemFireProperties(props, ignoreGemFirePropsFile);
    for (Object entry : props.entrySet()) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) entry;
        // if the value of ssl props is empty, read them from console
        if (ent.getKey().startsWith(DistributionConfig.SSL_SYSTEM_PROPS_NAME) || ent.getKey().startsWith(DistributionConfig.SYS_PROP_NAME)) {
            String key = ent.getKey();
            if (key.startsWith(DistributionConfig.SYS_PROP_NAME)) {
                key = key.substring(DistributionConfig.SYS_PROP_NAME.length());
            }
            if (ent.getValue() == null || ent.getValue().trim().equals("")) {
                GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();
                if (!consoleReader.isSupported()) {
                    throw new GemFireConfigException("SSL properties are empty, but a console is not available");
                }
                if (key.toLowerCase().contains("password")) {
                    char[] password = consoleReader.readPassword("Please enter " + key + ": ");
                    env.put(key, PasswordUtil.encrypt(new String(password), false));
                } else {
                    String val = consoleReader.readLine("Please enter " + key + ": ");
                    env.put(key, val);
                }
            }
        }
    }
}
Also used : GfeConsoleReader(org.apache.geode.internal.GfeConsoleReaderFactory.GfeConsoleReader) GemFireConfigException(org.apache.geode.GemFireConfigException) Properties(java.util.Properties) Map(java.util.Map) HashMap(java.util.HashMap)

Example 17 with GemFireConfigException

use of org.apache.geode.GemFireConfigException in project geode by apache.

the class InternalDistributedSystem method initialize.

/**
   * Initializes this connection to a distributed system with the current configuration state.
   */
private void initialize() {
    if (this.originalConfig.getLocators().equals("")) {
        if (this.originalConfig.getMcastPort() != 0) {
            throw new GemFireConfigException("The " + LOCATORS + " attribute can not be empty when the " + MCAST_PORT + " attribute is non-zero.");
        } else {
            // no distribution
            this.isLoner = true;
        }
    }
    this.config = new RuntimeDistributionConfigImpl(this);
    if (!this.isLoner) {
        this.attemptingToReconnect = (reconnectAttemptCounter > 0);
    }
    try {
        SocketCreatorFactory.setDistributionConfig(config);
        AlertAppender.getInstance().onConnect(this);
        // LOG: create LogWriterAppender(s) if log-file or security-log-file is specified
        final boolean hasLogFile = this.config.getLogFile() != null && !this.config.getLogFile().equals(new File(""));
        final boolean hasSecurityLogFile = this.config.getSecurityLogFile() != null && !this.config.getSecurityLogFile().equals(new File(""));
        LogService.configureLoggers(hasLogFile, hasSecurityLogFile);
        if (hasLogFile || hasSecurityLogFile) {
            // main log file
            if (hasLogFile) {
                // if log-file then create logWriterAppender
                this.logWriterAppender = LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.MAIN, this.isLoner, this.config, true);
            }
            // security log file
            if (hasSecurityLogFile) {
                // if security-log-file then create securityLogWriterAppender
                this.securityLogWriterAppender = LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.SECURITY, this.isLoner, this.config, false);
            } else {
            // let security route to regular log-file or stdout
            }
        }
        // getSecurityLogWriter
        if (this.logWriter == null) {
            this.logWriter = LogWriterFactory.createLogWriterLogger(this.isLoner, false, this.config, true);
            this.logWriter.fine("LogWriter is created.");
        }
        if (this.securityLogWriter == null) {
            // LOG: whole new LogWriterLogger instance for security
            this.securityLogWriter = LogWriterFactory.createLogWriterLogger(this.isLoner, true, this.config, false);
            this.securityLogWriter.fine("SecurityLogWriter is created.");
        }
        Services.setLogWriter(this.logWriter);
        Services.setSecurityLogWriter(this.securityLogWriter);
        this.clock = new DSClock(this.isLoner);
        if (this.attemptingToReconnect && logger.isDebugEnabled()) {
            logger.debug("This thread is initializing a new DistributedSystem in order to reconnect to other members");
        }
        // bridge server and will need to enforce the member limit
        if (Boolean.getBoolean(InternalLocator.FORCE_LOCATOR_DM_TYPE)) {
            this.locatorDMTypeForced = true;
        }
        // Initialize the Diffie-Hellman and public/private keys
        try {
            HandShake.initCertsMap(this.config.getSecurityProps());
            HandShake.initPrivateKey(this.config.getSecurityProps());
            HandShake.initDHKeys(this.config);
        } catch (Exception ex) {
            throw new GemFireSecurityException(LocalizedStrings.InternalDistributedSystem_PROBLEM_IN_INITIALIZING_KEYS_FOR_CLIENT_AUTHENTICATION.toLocalizedString(), ex);
        }
        final long offHeapMemorySize = OffHeapStorage.parseOffHeapMemorySize(getConfig().getOffHeapMemorySize());
        this.offHeapStore = OffHeapStorage.createOffHeapStorage(this, offHeapMemorySize, this);
        // Note: this can only happen on a linux system
        if (getConfig().getLockMemory()) {
            // This calculation is not exact, but seems fairly close. So far we have
            // not loaded much into the heap and the current RSS usage is already
            // included the available memory calculation.
            long avail = LinuxProcFsStatistics.getAvailableMemory(logger);
            long size = offHeapMemorySize + Runtime.getRuntime().totalMemory();
            if (avail < size) {
                if (ALLOW_MEMORY_LOCK_WHEN_OVERCOMMITTED) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.InternalDistributedSystem_MEMORY_OVERCOMMIT_WARN, size - avail));
                } else {
                    throw new IllegalStateException(LocalizedStrings.InternalDistributedSystem_MEMORY_OVERCOMMIT.toLocalizedString(avail, size));
                }
            }
            logger.info("Locking memory. This may take a while...");
            GemFireCacheImpl.lockMemory();
            logger.info("Finished locking memory.");
        }
        try {
            startInitLocator();
        } catch (InterruptedException e) {
            throw new SystemConnectException("Startup has been interrupted", e);
        }
        synchronized (this.isConnectedMutex) {
            this.isConnected = true;
        }
        if (!this.isLoner) {
            try {
                if (this.quorumChecker != null) {
                    this.quorumChecker.suspend();
                }
                this.dm = DistributionManager.create(this);
                // fix bug #46324
                if (InternalLocator.hasLocator()) {
                    InternalLocator locator = InternalLocator.getLocator();
                    getDistributionManager().addHostedLocators(getDistributedMember(), InternalLocator.getLocatorStrings(), locator.isSharedConfigurationEnabled());
                }
            } finally {
                if (this.dm == null && this.quorumChecker != null) {
                    this.quorumChecker.resume();
                }
                setDisconnected();
            }
        } else {
            this.dm = new LonerDistributionManager(this, this.logWriter);
        }
        Assert.assertTrue(this.dm != null);
        Assert.assertTrue(this.dm.getSystem() == this);
        try {
            this.id = this.dm.getChannelId();
        } catch (DistributedSystemDisconnectedException e) {
            // but during startup we should instead throw a SystemConnectException
            throw new SystemConnectException(LocalizedStrings.InternalDistributedSystem_DISTRIBUTED_SYSTEM_HAS_DISCONNECTED.toLocalizedString(), e);
        }
        synchronized (this.isConnectedMutex) {
            this.isConnected = true;
        }
        if (attemptingToReconnect && (this.startedLocator == null)) {
            try {
                startInitLocator();
            } catch (InterruptedException e) {
                throw new SystemConnectException("Startup has been interrupted", e);
            }
        }
        try {
            endInitLocator();
        } catch (IOException e) {
            throw new GemFireIOException("Problem finishing a locator service start", e);
        }
        if (!statsDisabled) {
            // to fix bug 42527 we need a sampler
            // even if sampling is not enabled.
            this.sampler = new GemFireStatSampler(this);
            this.sampler.start();
        }
        if (this.logWriterAppender != null) {
            LogWriterAppenders.startupComplete(LogWriterAppenders.Identifier.MAIN);
        }
        if (this.securityLogWriterAppender != null) {
            LogWriterAppenders.startupComplete(LogWriterAppenders.Identifier.SECURITY);
        }
        // this.logger.info("ds created", new RuntimeException("DEBUG: STACK"));
        // Log any instantiators that were registered before the log writer
        // was created
        InternalInstantiator.logInstantiators();
    } catch (RuntimeException ex) {
        this.config.close();
        throw ex;
    }
    resourceListeners = new CopyOnWriteArrayList<ResourceEventsListener>();
    this.reconnected = this.attemptingToReconnect;
    this.attemptingToReconnect = false;
}
Also used : DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) GemFireIOException(org.apache.geode.GemFireIOException) IOException(java.io.IOException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CacheXmlException(org.apache.geode.cache.CacheXmlException) CancelException(org.apache.geode.CancelException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) ManagementException(org.apache.geode.management.ManagementException) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GemFireIOException(org.apache.geode.GemFireIOException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SystemConnectException(org.apache.geode.SystemConnectException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) GemFireStatSampler(org.apache.geode.internal.statistics.GemFireStatSampler) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) GemFireConfigException(org.apache.geode.GemFireConfigException) GemFireIOException(org.apache.geode.GemFireIOException) File(java.io.File) SystemConnectException(org.apache.geode.SystemConnectException)

Example 18 with GemFireConfigException

use of org.apache.geode.GemFireConfigException in project geode by apache.

the class InternalDistributedSystem method reconnect.

/**
   * A reconnect is tried when gemfire is configured to reconnect in case of a required role loss.
   * The reconnect will try reconnecting to the distributed system every max-time-out millseconds
   * for max-number-of-tries configured in gemfire.properties file. It uses the cache.xml file to
   * intialize the cache and create regions.
   */
private void reconnect(boolean forcedDisconnect, String reason) {
    // Collect all the state for cache
    // Collect all the state for Regions
    // Close the cache,
    // loop trying to connect, waiting before each attempt
    //
    // If reconnecting for lost-roles the reconnected system's cache will decide
    // whether the reconnected system should stay up. After max-tries we will
    // give up.
    //
    // If reconnecting for forced-disconnect we ignore max-tries and keep attempting
    // to join the distributed system until successful
    this.attemptingToReconnect = true;
    InternalDistributedSystem ids = InternalDistributedSystem.getAnyInstance();
    if (ids == null) {
        ids = this;
    }
    // first save the current cache description. This is created by
    // the membership manager when forced-disconnect starts. If we're
    // reconnecting for lost roles then this will be null
    String cacheXML = null;
    List<CacheServerCreation> cacheServerCreation = null;
    InternalCache cache = GemFireCacheImpl.getInstance();
    if (cache != null) {
        cacheXML = cache.getCacheConfig().getCacheXMLDescription();
        cacheServerCreation = cache.getCacheConfig().getCacheServerCreation();
    }
    DistributionConfig oldConfig = ids.getConfig();
    Properties configProps = getProperties();
    int timeOut = oldConfig.getMaxWaitTimeForReconnect();
    int maxTries = oldConfig.getMaxNumReconnectTries();
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (Thread.currentThread().getName().equals("DisconnectThread")) {
        if (isDebugEnabled) {
            logger.debug("changing thread name to ReconnectThread");
        }
        Thread.currentThread().setName("ReconnectThread");
    }
    // get the membership manager for quorum checks
    MembershipManager mbrMgr = this.dm.getMembershipManager();
    this.quorumChecker = mbrMgr.getQuorumChecker();
    if (logger.isDebugEnabled()) {
        if (quorumChecker == null) {
            logger.debug("No quorum checks will be performed during reconnect attempts");
        } else {
            logger.debug("Initialized quorum checking service: {}", quorumChecker);
        }
    }
    // LOG:CLEANUP: deal with reconnect and INHIBIT_DM_BANNER -- this should be ok now
    String appendToLogFile = System.getProperty(APPEND_TO_LOG_FILE);
    if (appendToLogFile == null) {
        System.setProperty(APPEND_TO_LOG_FILE, "true");
    }
    String inhibitBanner = System.getProperty(InternalLocator.INHIBIT_DM_BANNER);
    if (inhibitBanner == null) {
        System.setProperty(InternalLocator.INHIBIT_DM_BANNER, "true");
    }
    if (forcedDisconnect) {
        systemAttemptingReconnect = this;
    }
    try {
        while (this.reconnectDS == null || !this.reconnectDS.isConnected()) {
            if (isReconnectCancelled()) {
                break;
            }
            if (!forcedDisconnect) {
                if (isDebugEnabled) {
                    logger.debug("Max number of tries : {} and max time out : {}", maxTries, timeOut);
                }
                if (reconnectAttemptCounter >= maxTries) {
                    if (isDebugEnabled) {
                        logger.debug("Stopping the checkrequiredrole thread because reconnect : {} reached the max number of reconnect tries : {}", reconnectAttemptCounter, maxTries);
                    }
                    throw new CacheClosedException(LocalizedStrings.InternalDistributedSystem_SOME_REQUIRED_ROLES_MISSING.toLocalizedString());
                }
            }
            if (reconnectAttemptCounter == 0) {
                reconnectAttemptTime = System.currentTimeMillis();
            }
            reconnectAttemptCounter++;
            if (isReconnectCancelled()) {
                return;
            }
            logger.info("Disconnecting old DistributedSystem to prepare for a reconnect attempt");
            try {
                disconnect(true, reason, false);
            } catch (Exception ee) {
                logger.warn("Exception disconnecting for reconnect", ee);
            }
            try {
                reconnectLock.wait(timeOut);
            } catch (InterruptedException e) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.InternalDistributedSystem_WAITING_THREAD_FOR_RECONNECT_GOT_INTERRUPTED));
                Thread.currentThread().interrupt();
                return;
            }
            if (isReconnectCancelled()) {
                return;
            }
            logger.info(LocalizedMessage.create(LocalizedStrings.DISTRIBUTED_SYSTEM_RECONNECTING, new Object[] { reconnectAttemptCounter }));
            int savNumOfTries = reconnectAttemptCounter;
            try {
                // notify listeners of each attempt and then again after successful
                notifyReconnectListeners(this, this.reconnectDS, true);
                if (this.locatorDMTypeForced) {
                    System.setProperty(InternalLocator.FORCE_LOCATOR_DM_TYPE, "true");
                }
                configProps.put(DistributionConfig.DS_RECONNECTING_NAME, Boolean.TRUE);
                if (quorumChecker != null) {
                    configProps.put(DistributionConfig.DS_QUORUM_CHECKER_NAME, quorumChecker);
                }
                InternalDistributedSystem newDS = null;
                if (isReconnectCancelled()) {
                    return;
                }
                try {
                    newDS = (InternalDistributedSystem) connect(configProps);
                } catch (CancelException e) {
                    if (isReconnectCancelled()) {
                        return;
                    } else {
                        throw e;
                    }
                } finally {
                    if (newDS == null && quorumChecker != null) {
                        // make sure the quorum checker is listening for messages from former members
                        quorumChecker.resume();
                    }
                }
                if (this.reconnectCancelled) {
                    newDS.disconnect();
                    continue;
                }
                this.reconnectDS = newDS;
            } catch (SystemConnectException e) {
                logger.debug("Attempt to reconnect failed with SystemConnectException");
                if (e.getMessage().contains("Rejecting the attempt of a member using an older version")) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.InternalDistributedSystem_EXCEPTION_OCCURRED_WHILE_TRYING_TO_CONNECT_THE_SYSTEM_DURING_RECONNECT), e);
                    attemptingToReconnect = false;
                    return;
                }
                continue;
            } catch (GemFireConfigException e) {
                if (isDebugEnabled) {
                    logger.debug("Attempt to reconnect failed with GemFireConfigException");
                }
                continue;
            } catch (Exception ee) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.InternalDistributedSystem_EXCEPTION_OCCURRED_WHILE_TRYING_TO_CONNECT_THE_SYSTEM_DURING_RECONNECT), ee);
                attemptingToReconnect = false;
                return;
            } finally {
                if (this.locatorDMTypeForced) {
                    System.getProperties().remove(InternalLocator.FORCE_LOCATOR_DM_TYPE);
                }
                reconnectAttemptCounter = savNumOfTries;
            }
            DM newDM = this.reconnectDS.getDistributionManager();
            if (newDM instanceof DistributionManager) {
                // a cache
                if (((DistributionManager) newDM).getDMType() != DistributionManager.ADMIN_ONLY_DM_TYPE) {
                    try {
                        CacheConfig config = new CacheConfig();
                        if (cacheXML != null) {
                            config.setCacheXMLDescription(cacheXML);
                        }
                        cache = GemFireCacheImpl.create(this.reconnectDS, config);
                        createAndStartCacheServers(cacheServerCreation, cache);
                        if (cache.getCachePerfStats().getReliableRegionsMissing() == 0) {
                            reconnectAttemptCounter = 0;
                        } else {
                        // this try failed. The new cache will call reconnect again
                        }
                    } catch (CacheXmlException e) {
                        logger.warn("Exception occurred while trying to create the cache during reconnect", e);
                        reconnectDS.disconnect();
                        reconnectDS = null;
                        reconnectCancelled = true;
                        break;
                    } catch (CancelException ignor) {
                        logger.warn("Exception occurred while trying to create the cache during reconnect", ignor);
                        reconnectDS.disconnect();
                        reconnectDS = null;
                    } catch (Exception e) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.InternalDistributedSystem_EXCEPTION_OCCURRED_WHILE_TRYING_TO_CREATE_THE_CACHE_DURING_RECONNECT), e);
                    }
                }
            }
            if (reconnectDS != null && reconnectDS.isConnected()) {
                // make sure the new DS and cache are stable before exiting this loop
                try {
                    Thread.sleep(config.getMemberTimeout() * 3);
                } catch (InterruptedException e) {
                    logger.info("Reconnect thread has been interrupted - exiting");
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        }
        if (isReconnectCancelled()) {
            reconnectDS.disconnect();
        } else {
            reconnectDS.isReconnectingDS = false;
            notifyReconnectListeners(this, this.reconnectDS, false);
        }
    } finally {
        systemAttemptingReconnect = null;
        attemptingToReconnect = false;
        if (appendToLogFile == null) {
            System.getProperties().remove(APPEND_TO_LOG_FILE);
        } else {
            System.setProperty(APPEND_TO_LOG_FILE, appendToLogFile);
        }
        if (inhibitBanner == null) {
            System.getProperties().remove(InternalLocator.INHIBIT_DM_BANNER);
        } else {
            System.setProperty(InternalLocator.INHIBIT_DM_BANNER, inhibitBanner);
        }
        if (quorumChecker != null) {
            mbrMgr.releaseQuorumChecker(quorumChecker);
        }
    }
    if (isReconnectCancelled()) {
        logger.debug("reconnect can no longer be done because of an explicit disconnect");
        if (reconnectDS != null) {
            reconnectDS.disconnect();
        }
        attemptingToReconnect = false;
        return;
    } else {
        logger.info("Reconnect completed.\nNew DistributedSystem is {}\nNew Cache is {}", reconnectDS, cache);
    }
}
Also used : InternalCache(org.apache.geode.internal.cache.InternalCache) CacheClosedException(org.apache.geode.cache.CacheClosedException) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CacheXmlException(org.apache.geode.cache.CacheXmlException) CancelException(org.apache.geode.CancelException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) ManagementException(org.apache.geode.management.ManagementException) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GemFireIOException(org.apache.geode.GemFireIOException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SystemConnectException(org.apache.geode.SystemConnectException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) CacheXmlException(org.apache.geode.cache.CacheXmlException) CacheServerCreation(org.apache.geode.internal.cache.xmlcache.CacheServerCreation) GemFireConfigException(org.apache.geode.GemFireConfigException) MembershipManager(org.apache.geode.distributed.internal.membership.MembershipManager) GMSMembershipManager(org.apache.geode.distributed.internal.membership.gms.mgr.GMSMembershipManager) CancelException(org.apache.geode.CancelException) CacheConfig(org.apache.geode.internal.cache.CacheConfig) SystemConnectException(org.apache.geode.SystemConnectException)

Example 19 with GemFireConfigException

use of org.apache.geode.GemFireConfigException in project geode by apache.

the class JGroupsMessenger method readJGMessage.

/**
   * deserialize a jgroups payload. If it's a DistributionMessage find the ID of the sender and
   * establish it as the message's sender
   */
Object readJGMessage(Message jgmsg) {
    Object result = null;
    int messageLength = jgmsg.getLength();
    if (logger.isTraceEnabled()) {
        logger.trace("deserializing a message of length " + messageLength);
    }
    if (messageLength == 0) {
        // jgroups messages with no payload are used for protocol interchange, such
        // as STABLE_GOSSIP
        logger.trace("message length is zero - ignoring");
        return null;
    }
    Exception problem = null;
    byte[] buf = jgmsg.getRawBuffer();
    try {
        long start = services.getStatistics().startMsgDeserialization();
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buf, jgmsg.getOffset(), jgmsg.getLength()));
        short ordinal = Version.readOrdinal(dis);
        if (ordinal < Version.CURRENT_ORDINAL) {
            dis = new VersionedDataInputStream(dis, Version.fromOrdinalNoThrow(ordinal, true));
        }
        // read
        boolean isEncrypted = dis.readBoolean();
        if (isEncrypted && encrypt == null) {
            throw new GemFireConfigException("Got remote message as encrypted");
        }
        if (isEncrypted) {
            result = readEncryptedMessage(dis, ordinal, encrypt);
        } else {
            result = deserializeMessage(dis, ordinal);
        }
        services.getStatistics().endMsgDeserialization(start);
    } catch (ClassNotFoundException | IOException | RuntimeException e) {
        problem = e;
    } catch (Exception e) {
        problem = e;
    }
    if (problem != null) {
        logger.error(LocalizedMessage.create(LocalizedStrings.GroupMembershipService_EXCEPTION_DESERIALIZING_MESSAGE_PAYLOAD_0, jgmsg), problem);
        return null;
    }
    return result;
}
Also used : GemFireIOException(org.apache.geode.GemFireIOException) IOException(java.io.IOException) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) DataInputStream(java.io.DataInputStream) MemberShunnedException(org.apache.geode.internal.tcp.MemberShunnedException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GemFireIOException(org.apache.geode.GemFireIOException) SystemConnectException(org.apache.geode.SystemConnectException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ByteArrayInputStream(java.io.ByteArrayInputStream) GemFireConfigException(org.apache.geode.GemFireConfigException) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream)

Example 20 with GemFireConfigException

use of org.apache.geode.GemFireConfigException in project geode by apache.

the class JGroupsMessenger method init.

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void init(Services s) {
    this.services = s;
    RemoteTransportConfig transport = services.getConfig().getTransport();
    DistributionConfig dc = services.getConfig().getDistributionConfig();
    boolean b = dc.getEnableNetworkPartitionDetection();
    System.setProperty("jgroups.resolve_dns", String.valueOf(!b));
    InputStream is;
    String r;
    if (transport.isMcastEnabled()) {
        r = JGROUPS_MCAST_CONFIG_FILE_NAME;
    } else {
        r = DEFAULT_JGROUPS_TCP_CONFIG;
    }
    is = ClassPathLoader.getLatest().getResourceAsStream(getClass(), r);
    if (is == null) {
        throw new GemFireConfigException(LocalizedStrings.GroupMembershipService_CANNOT_FIND_0.toLocalizedString(r));
    }
    String properties;
    try {
        // PlainConfigurator config = PlainConfigurator.getInstance(is);
        // properties = config.getProtocolStackString();
        StringBuilder sb = new StringBuilder(3000);
        BufferedReader br;
        br = new BufferedReader(new InputStreamReader(is, "US-ASCII"));
        String input;
        while ((input = br.readLine()) != null) {
            sb.append(input);
        }
        br.close();
        properties = sb.toString();
    } catch (Exception ex) {
        throw new GemFireConfigException(LocalizedStrings.GroupMembershipService_AN_EXCEPTION_WAS_THROWN_WHILE_READING_JGROUPS_CONFIG.toLocalizedString(), ex);
    }
    if (properties.startsWith("<!--")) {
        int commentEnd = properties.indexOf("-->");
        properties = properties.substring(commentEnd + 3);
    }
    if (transport.isMcastEnabled()) {
        properties = replaceStrings(properties, "MCAST_PORT", String.valueOf(transport.getMcastId().getPort()));
        properties = replaceStrings(properties, "MCAST_ADDRESS", dc.getMcastAddress().getHostAddress());
        properties = replaceStrings(properties, "MCAST_TTL", String.valueOf(dc.getMcastTtl()));
        properties = replaceStrings(properties, "MCAST_SEND_BUFFER_SIZE", String.valueOf(dc.getMcastSendBufferSize()));
        properties = replaceStrings(properties, "MCAST_RECV_BUFFER_SIZE", String.valueOf(dc.getMcastRecvBufferSize()));
        properties = replaceStrings(properties, "MCAST_RETRANSMIT_INTERVAL", "" + Integer.getInteger(DistributionConfig.GEMFIRE_PREFIX + "mcast-retransmit-interval", 500));
        properties = replaceStrings(properties, "RETRANSMIT_LIMIT", String.valueOf(dc.getUdpFragmentSize() - 256));
    }
    if (transport.isMcastEnabled() || transport.isTcpDisabled() || (dc.getUdpRecvBufferSize() != DistributionConfig.DEFAULT_UDP_RECV_BUFFER_SIZE)) {
        properties = replaceStrings(properties, "UDP_RECV_BUFFER_SIZE", "" + dc.getUdpRecvBufferSize());
    } else {
        properties = replaceStrings(properties, "UDP_RECV_BUFFER_SIZE", "" + DistributionConfig.DEFAULT_UDP_RECV_BUFFER_SIZE_REDUCED);
    }
    properties = replaceStrings(properties, "UDP_SEND_BUFFER_SIZE", "" + dc.getUdpSendBufferSize());
    String str = transport.getBindAddress();
    // JGroups UDP protocol requires a bind address
    if (str == null || str.length() == 0) {
        try {
            str = SocketCreator.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new GemFireConfigException(e.getMessage(), e);
        }
    }
    properties = replaceStrings(properties, "BIND_ADDR_SETTING", "bind_addr=\"" + str + "\"");
    int port = Integer.getInteger(DistributionConfig.GEMFIRE_PREFIX + "jg-bind-port", 0);
    if (port != 0) {
        properties = replaceStrings(properties, "MEMBERSHIP_PORT_RANGE_START", "" + port);
        properties = replaceStrings(properties, "MEMBERSHIP_PORT_RANGE", "" + 0);
    } else {
        int[] ports = dc.getMembershipPortRange();
        properties = replaceStrings(properties, "MEMBERSHIP_PORT_RANGE_START", "" + ports[0]);
        properties = replaceStrings(properties, "MEMBERSHIP_PORT_RANGE", "" + (ports[1] - ports[0]));
    }
    properties = replaceStrings(properties, "UDP_FRAGMENT_SIZE", "" + dc.getUdpFragmentSize());
    properties = replaceStrings(properties, "FC_MAX_CREDITS", "" + dc.getMcastFlowControl().getByteAllowance());
    properties = replaceStrings(properties, "FC_THRESHOLD", "" + dc.getMcastFlowControl().getRechargeThreshold());
    properties = replaceStrings(properties, "FC_MAX_BLOCK", "" + dc.getMcastFlowControl().getRechargeBlockMs());
    this.jgStackConfig = properties;
    if (!dc.getSecurityUDPDHAlgo().isEmpty()) {
        try {
            this.encrypt = new GMSEncrypt(services);
            logger.info("Initializing GMSEncrypt ");
        } catch (Exception e) {
            throw new GemFireConfigException("problem initializing encryption protocol", e);
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) ByteArrayInputStream(java.io.ByteArrayInputStream) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) RemoteTransportConfig(org.apache.geode.internal.admin.remote.RemoteTransportConfig) MemberShunnedException(org.apache.geode.internal.tcp.MemberShunnedException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GemFireIOException(org.apache.geode.GemFireIOException) SystemConnectException(org.apache.geode.SystemConnectException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) GemFireConfigException(org.apache.geode.GemFireConfigException) BufferedReader(java.io.BufferedReader)

Aggregations

GemFireConfigException (org.apache.geode.GemFireConfigException)28 IOException (java.io.IOException)11 SystemConnectException (org.apache.geode.SystemConnectException)10 Properties (java.util.Properties)7 ForcedDisconnectException (org.apache.geode.ForcedDisconnectException)7 DistributedSystemDisconnectedException (org.apache.geode.distributed.DistributedSystemDisconnectedException)6 Test (org.junit.Test)6 UnknownHostException (java.net.UnknownHostException)5 CancelException (org.apache.geode.CancelException)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 DataInputStream (java.io.DataInputStream)4 InetSocketAddress (java.net.InetSocketAddress)4 GemFireIOException (org.apache.geode.GemFireIOException)4 VersionedDataInputStream (org.apache.geode.internal.VersionedDataInputStream)4 MemberShunnedException (org.apache.geode.internal.tcp.MemberShunnedException)4 GemFireSecurityException (org.apache.geode.security.GemFireSecurityException)4 InputStream (java.io.InputStream)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ServerSocket (java.net.ServerSocket)3 NetView (org.apache.geode.distributed.internal.membership.NetView)3