Search in sources :

Example 1 with ClusterConfigurationNotAvailableException

use of org.apache.geode.internal.process.ClusterConfigurationNotAvailableException in project geode by apache.

the class ServerLauncher method start.

/**
   * Invokes the 'start' command and operation to startup a GemFire server (a cache server). Note,
   * this method will cause the JVM to block upon server start, providing the calling Thread is a
   * non-daemon Thread.
   *
   * @see #run()
   */
public ServerState start() {
    if (isStartable()) {
        INSTANCE.compareAndSet(null, this);
        try {
            process = new ControllableProcess(this.controlHandler, new File(getWorkingDirectory()), ProcessType.SERVER, isForcing());
            if (!isDisableDefaultServer()) {
                assertPortAvailable(getServerBindAddress(), getServerPort());
            }
            SystemFailure.setExitOK(true);
            ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(), new StartupStatusListener() {

                @Override
                public void setStatus(final String statusMessage) {
                    debug("Callback setStatus(String) called with message (%1$s)...", statusMessage);
                    ServerLauncher.this.statusMessage = statusMessage;
                }
            });
            try {
                final Properties gemfireProperties = getDistributedSystemProperties(getProperties());
                this.cache = createCache(gemfireProperties);
                // Set the resource manager options
                if (this.criticalHeapPercentage != null) {
                    this.cache.getResourceManager().setCriticalHeapPercentage(getCriticalHeapPercentage());
                }
                if (this.evictionHeapPercentage != null) {
                    this.cache.getResourceManager().setEvictionHeapPercentage(getEvictionHeapPercentage());
                }
                if (this.criticalOffHeapPercentage != null) {
                    this.cache.getResourceManager().setCriticalOffHeapPercentage(getCriticalOffHeapPercentage());
                }
                if (this.evictionOffHeapPercentage != null) {
                    this.cache.getResourceManager().setEvictionOffHeapPercentage(getEvictionOffHeapPercentage());
                }
                this.cache.setIsServer(true);
                startCacheServer(this.cache);
                assignBuckets(this.cache);
                rebalance(this.cache);
            } finally {
                ProcessLauncherContext.remove();
            }
            debug("Running Server on (%1$s) in (%2$s) as (%2$s)...", getId(), getWorkingDirectory(), getMember());
            this.running.set(true);
            return new ServerState(this, Status.ONLINE);
        } catch (AuthenticationRequiredException e) {
            failOnStart(e);
            throw new AuthenticationRequiredException("user/password required. Please start your server with --user and --password. " + e.getMessage());
        } catch (GemFireSecurityException e) {
            failOnStart(e);
            throw new GemFireSecurityException(e.getMessage());
        } catch (IOException e) {
            failOnStart(e);
            throw new RuntimeException(LocalizedStrings.Launcher_Command_START_IO_ERROR_MESSAGE.toLocalizedString(getServiceName(), getWorkingDirectory(), getId(), e.getMessage()), e);
        } catch (FileAlreadyExistsException e) {
            failOnStart(e);
            throw new RuntimeException(LocalizedStrings.Launcher_Command_START_PID_FILE_ALREADY_EXISTS_ERROR_MESSAGE.toLocalizedString(getServiceName(), getWorkingDirectory(), getId()), e);
        } catch (PidUnavailableException e) {
            failOnStart(e);
            throw new RuntimeException(LocalizedStrings.Launcher_Command_START_PID_UNAVAILABLE_ERROR_MESSAGE.toLocalizedString(getServiceName(), getId(), getWorkingDirectory(), e.getMessage()), e);
        } catch (ClusterConfigurationNotAvailableException e) {
            failOnStart(e);
            throw e;
        } catch (RuntimeException e) {
            failOnStart(e);
            throw e;
        } catch (Exception e) {
            failOnStart(e);
            throw new RuntimeException(e);
        } catch (Error e) {
            failOnStart(e);
            throw e;
        } finally {
            this.starting.set(false);
        }
    } else {
        throw new IllegalStateException(LocalizedStrings.Launcher_Command_START_SERVICE_ALREADY_RUNNING_ERROR_MESSAGE.toLocalizedString(getServiceName(), getWorkingDirectory(), getId()));
    }
}
Also used : ControllableProcess(org.apache.geode.internal.process.ControllableProcess) FileAlreadyExistsException(org.apache.geode.internal.process.FileAlreadyExistsException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) IOException(java.io.IOException) Properties(java.util.Properties) TimeoutException(java.util.concurrent.TimeoutException) PidUnavailableException(org.apache.geode.internal.process.PidUnavailableException) MBeanInvocationFailedException(org.apache.geode.internal.process.MBeanInvocationFailedException) FileAlreadyExistsException(org.apache.geode.internal.process.FileAlreadyExistsException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) FileNotFoundException(java.io.FileNotFoundException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ConnectionFailedException(org.apache.geode.internal.process.ConnectionFailedException) GfJsonException(org.apache.geode.management.internal.cli.json.GfJsonException) OptionException(joptsimple.OptionException) UnableToControlProcessException(org.apache.geode.internal.process.UnableToControlProcessException) ClusterConfigurationNotAvailableException(org.apache.geode.internal.process.ClusterConfigurationNotAvailableException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) AttachAPINotFoundException(org.apache.geode.lang.AttachAPINotFoundException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) StartupStatusListener(org.apache.geode.internal.process.StartupStatusListener) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) PidUnavailableException(org.apache.geode.internal.process.PidUnavailableException) ClusterConfigurationNotAvailableException(org.apache.geode.internal.process.ClusterConfigurationNotAvailableException) File(java.io.File)

Example 2 with ClusterConfigurationNotAvailableException

use of org.apache.geode.internal.process.ClusterConfigurationNotAvailableException in project geode by apache.

the class LauncherLifecycleCommands method startServer.

@CliCommand(value = CliStrings.START_SERVER, help = CliStrings.START_SERVER__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEODE_SERVER, CliStrings.TOPIC_GEODE_LIFECYCLE })
public Result startServer(@CliOption(key = CliStrings.START_SERVER__NAME, help = CliStrings.START_SERVER__NAME__HELP) String memberName, @CliOption(key = CliStrings.START_SERVER__ASSIGN_BUCKETS, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__ASSIGN_BUCKETS__HELP) final Boolean assignBuckets, @CliOption(key = CliStrings.START_SERVER__BIND_ADDRESS, help = CliStrings.START_SERVER__BIND_ADDRESS__HELP) final String bindAddress, @CliOption(key = CliStrings.START_SERVER__CACHE_XML_FILE, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_SERVER__CACHE_XML_FILE__HELP) String cacheXmlPathname, @CliOption(key = CliStrings.START_SERVER__CLASSPATH, /* optionContext = ConverterHint.FILE_PATH, // there's an issue with TAB here */
help = CliStrings.START_SERVER__CLASSPATH__HELP) final String classpath, @CliOption(key = CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE, help = CliStrings.START_SERVER__CRITICAL__HEAP__HELP) final Float criticalHeapPercentage, @CliOption(key = CliStrings.START_SERVER__CRITICAL_OFF_HEAP_PERCENTAGE, help = CliStrings.START_SERVER__CRITICAL_OFF_HEAP__HELP) final Float criticalOffHeapPercentage, @CliOption(key = CliStrings.START_SERVER__DIR, help = CliStrings.START_SERVER__DIR__HELP) String workingDirectory, @CliOption(key = CliStrings.START_SERVER__DISABLE_DEFAULT_SERVER, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__DISABLE_DEFAULT_SERVER__HELP) final Boolean disableDefaultServer, @CliOption(key = CliStrings.START_SERVER__DISABLE_EXIT_WHEN_OUT_OF_MEMORY, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__DISABLE_EXIT_WHEN_OUT_OF_MEMORY_HELP) final Boolean disableExitWhenOutOfMemory, @CliOption(key = CliStrings.START_SERVER__ENABLE_TIME_STATISTICS, specifiedDefaultValue = "true", help = CliStrings.START_SERVER__ENABLE_TIME_STATISTICS__HELP) final Boolean enableTimeStatistics, @CliOption(key = CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE, help = CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE__HELP) final Float evictionHeapPercentage, @CliOption(key = CliStrings.START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE, help = CliStrings.START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE__HELP) final Float evictionOffHeapPercentage, @CliOption(key = CliStrings.START_SERVER__FORCE, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__FORCE__HELP) final Boolean force, @CliOption(key = CliStrings.START_SERVER__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.START_SERVER__GROUP__HELP) final String group, @CliOption(key = CliStrings.START_SERVER__HOSTNAME__FOR__CLIENTS, help = CliStrings.START_SERVER__HOSTNAME__FOR__CLIENTS__HELP) final String hostNameForClients, @CliOption(key = CliStrings.START_SERVER__INCLUDE_SYSTEM_CLASSPATH, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = CliStrings.START_SERVER__INCLUDE_SYSTEM_CLASSPATH__HELP) final Boolean includeSystemClasspath, @CliOption(key = CliStrings.START_SERVER__INITIAL_HEAP, help = CliStrings.START_SERVER__INITIAL_HEAP__HELP) final String initialHeap, @CliOption(key = CliStrings.START_SERVER__J, optionContext = GfshParser.J_OPTION_CONTEXT, help = CliStrings.START_SERVER__J__HELP) final String[] jvmArgsOpts, @CliOption(key = CliStrings.START_SERVER__LOCATORS, optionContext = ConverterHint.LOCATOR_DISCOVERY_CONFIG, help = CliStrings.START_SERVER__LOCATORS__HELP) final String locators, @CliOption(key = CliStrings.START_SERVER__LOCATOR_WAIT_TIME, help = CliStrings.START_SERVER__LOCATOR_WAIT_TIME_HELP) final Integer locatorWaitTime, @CliOption(key = CliStrings.START_SERVER__LOCK_MEMORY, specifiedDefaultValue = "true", help = CliStrings.START_SERVER__LOCK_MEMORY__HELP) final Boolean lockMemory, @CliOption(key = CliStrings.START_SERVER__LOG_LEVEL, optionContext = ConverterHint.LOG_LEVEL, help = CliStrings.START_SERVER__LOG_LEVEL__HELP) final String logLevel, @CliOption(key = CliStrings.START_SERVER__MAX__CONNECTIONS, help = CliStrings.START_SERVER__MAX__CONNECTIONS__HELP) final Integer maxConnections, @CliOption(key = CliStrings.START_SERVER__MAXHEAP, help = CliStrings.START_SERVER__MAXHEAP__HELP) final String maxHeap, @CliOption(key = CliStrings.START_SERVER__MAX__MESSAGE__COUNT, help = CliStrings.START_SERVER__MAX__MESSAGE__COUNT__HELP) final Integer maxMessageCount, @CliOption(key = CliStrings.START_SERVER__MAX__THREADS, help = CliStrings.START_SERVER__MAX__THREADS__HELP) final Integer maxThreads, @CliOption(key = CliStrings.START_SERVER__MCAST_ADDRESS, help = CliStrings.START_SERVER__MCAST_ADDRESS__HELP) final String mcastBindAddress, @CliOption(key = CliStrings.START_SERVER__MCAST_PORT, help = CliStrings.START_SERVER__MCAST_PORT__HELP) final Integer mcastPort, @CliOption(key = CliStrings.START_SERVER__MEMCACHED_PORT, help = CliStrings.START_SERVER__MEMCACHED_PORT__HELP) final Integer memcachedPort, @CliOption(key = CliStrings.START_SERVER__MEMCACHED_PROTOCOL, help = CliStrings.START_SERVER__MEMCACHED_PROTOCOL__HELP) final String memcachedProtocol, @CliOption(key = CliStrings.START_SERVER__MEMCACHED_BIND_ADDRESS, help = CliStrings.START_SERVER__MEMCACHED_BIND_ADDRESS__HELP) final String memcachedBindAddress, @CliOption(key = CliStrings.START_SERVER__REDIS_PORT, help = CliStrings.START_SERVER__REDIS_PORT__HELP) final Integer redisPort, @CliOption(key = CliStrings.START_SERVER__REDIS_BIND_ADDRESS, help = CliStrings.START_SERVER__REDIS_BIND_ADDRESS__HELP) final String redisBindAddress, @CliOption(key = CliStrings.START_SERVER__REDIS_PASSWORD, help = CliStrings.START_SERVER__REDIS_PASSWORD__HELP) final String redisPassword, @CliOption(key = CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE, help = CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE__HELP) final Integer messageTimeToLive, @CliOption(key = CliStrings.START_SERVER__OFF_HEAP_MEMORY_SIZE, help = CliStrings.START_SERVER__OFF_HEAP_MEMORY_SIZE__HELP) final String offHeapMemorySize, @CliOption(key = CliStrings.START_SERVER__PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_SERVER__PROPERTIES__HELP) String gemfirePropertiesPathname, @CliOption(key = CliStrings.START_SERVER__REBALANCE, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__REBALANCE__HELP) final Boolean rebalance, @CliOption(key = CliStrings.START_SERVER__SECURITY_PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_SERVER__SECURITY_PROPERTIES__HELP) String gemfireSecurityPropertiesPathname, @CliOption(key = CliStrings.START_SERVER__SERVER_BIND_ADDRESS, unspecifiedDefaultValue = CacheServer.DEFAULT_BIND_ADDRESS, help = CliStrings.START_SERVER__SERVER_BIND_ADDRESS__HELP) final String serverBindAddress, @CliOption(key = CliStrings.START_SERVER__SERVER_PORT, unspecifiedDefaultValue = ("" + CacheServer.DEFAULT_PORT), help = CliStrings.START_SERVER__SERVER_PORT__HELP) final Integer serverPort, @CliOption(key = CliStrings.START_SERVER__SOCKET__BUFFER__SIZE, help = CliStrings.START_SERVER__SOCKET__BUFFER__SIZE__HELP) final Integer socketBufferSize, @CliOption(key = CliStrings.START_SERVER__SPRING_XML_LOCATION, help = CliStrings.START_SERVER__SPRING_XML_LOCATION_HELP) final String springXmlLocation, @CliOption(key = CliStrings.START_SERVER__STATISTIC_ARCHIVE_FILE, help = CliStrings.START_SERVER__STATISTIC_ARCHIVE_FILE__HELP) final String statisticsArchivePathname, @CliOption(key = CliStrings.START_SERVER__USE_CLUSTER_CONFIGURATION, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__USE_CLUSTER_CONFIGURATION__HELP) final Boolean requestSharedConfiguration, @CliOption(key = CliStrings.START_SERVER__REST_API, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_SERVER__REST_API__HELP) final Boolean startRestApi, @CliOption(key = CliStrings.START_SERVER__HTTP_SERVICE_PORT, unspecifiedDefaultValue = "", help = CliStrings.START_SERVER__HTTP_SERVICE_PORT__HELP) final String httpServicePort, @CliOption(key = CliStrings.START_SERVER__HTTP_SERVICE_BIND_ADDRESS, unspecifiedDefaultValue = "", help = CliStrings.START_SERVER__HTTP_SERVICE_BIND_ADDRESS__HELP) final String httpServiceBindAddress, @CliOption(key = CliStrings.START_SERVER__USERNAME, unspecifiedDefaultValue = "", help = CliStrings.START_SERVER__USERNAME__HELP) final String userName, @CliOption(key = START_SERVER__PASSWORD, unspecifiedDefaultValue = "", help = CliStrings.START_SERVER__PASSWORD__HELP) String passwordToUse) // NOTICE: keep the parameters in alphabetical order based on their CliStrings.START_SERVER_* text
{
    try {
        if (StringUtils.isBlank(memberName)) {
            // when the user doesn't give us a name, we make one up!
            memberName = nameGenerator.generate('-');
        }
        // prompt for password is username is specified in the command
        if (StringUtils.isNotBlank(userName)) {
            if (StringUtils.isBlank(passwordToUse)) {
                passwordToUse = getGfsh().readPassword(START_SERVER__PASSWORD + ": ");
            }
            if (StringUtils.isBlank(passwordToUse)) {
                return ResultBuilder.createConnectionErrorResult(CliStrings.START_SERVER__MSG__PASSWORD_MUST_BE_SPECIFIED);
            }
        }
        workingDirectory = resolveWorkingDir(workingDirectory, memberName);
        cacheXmlPathname = CliUtil.resolvePathname(cacheXmlPathname);
        if (StringUtils.isNotBlank(cacheXmlPathname) && !IOUtils.isExistingPathname(cacheXmlPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.CACHE_XML_NOT_FOUND_MESSAGE, cacheXmlPathname));
        }
        gemfirePropertiesPathname = CliUtil.resolvePathname(gemfirePropertiesPathname);
        if (StringUtils.isNotBlank(gemfirePropertiesPathname) && !IOUtils.isExistingPathname(gemfirePropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY, gemfirePropertiesPathname));
        }
        gemfireSecurityPropertiesPathname = CliUtil.resolvePathname(gemfireSecurityPropertiesPathname);
        if (StringUtils.isNotBlank(gemfireSecurityPropertiesPathname) && !IOUtils.isExistingPathname(gemfireSecurityPropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gemfireSecurityPropertiesPathname));
        }
        File serverPidFile = new File(workingDirectory, ProcessType.SERVER.getPidFileName());
        final int oldPid = readPid(serverPidFile);
        Properties gemfireProperties = new Properties();
        gemfireProperties.setProperty(BIND_ADDRESS, StringUtils.defaultString(bindAddress));
        gemfireProperties.setProperty(CACHE_XML_FILE, StringUtils.defaultString(cacheXmlPathname));
        gemfireProperties.setProperty(ENABLE_TIME_STATISTICS, StringUtils.defaultString(enableTimeStatistics));
        gemfireProperties.setProperty(GROUPS, StringUtils.defaultString(group));
        gemfireProperties.setProperty(LOCATORS, StringUtils.defaultString(locators));
        gemfireProperties.setProperty(LOCATOR_WAIT_TIME, StringUtils.defaultString(locatorWaitTime));
        gemfireProperties.setProperty(LOG_LEVEL, StringUtils.defaultString(logLevel));
        gemfireProperties.setProperty(MCAST_ADDRESS, StringUtils.defaultString(mcastBindAddress));
        gemfireProperties.setProperty(MCAST_PORT, StringUtils.defaultString(mcastPort));
        gemfireProperties.setProperty(MEMCACHED_PORT, StringUtils.defaultString(memcachedPort));
        gemfireProperties.setProperty(MEMCACHED_PROTOCOL, StringUtils.defaultString(memcachedProtocol));
        gemfireProperties.setProperty(MEMCACHED_BIND_ADDRESS, StringUtils.defaultString(memcachedBindAddress));
        gemfireProperties.setProperty(REDIS_PORT, StringUtils.defaultString(redisPort));
        gemfireProperties.setProperty(REDIS_BIND_ADDRESS, StringUtils.defaultString(redisBindAddress));
        gemfireProperties.setProperty(REDIS_PASSWORD, StringUtils.defaultString(redisPassword));
        gemfireProperties.setProperty(STATISTIC_ARCHIVE_FILE, StringUtils.defaultString(statisticsArchivePathname));
        gemfireProperties.setProperty(USE_CLUSTER_CONFIGURATION, StringUtils.defaultString(requestSharedConfiguration, Boolean.TRUE.toString()));
        gemfireProperties.setProperty(LOCK_MEMORY, StringUtils.defaultString(lockMemory));
        gemfireProperties.setProperty(OFF_HEAP_MEMORY_SIZE, StringUtils.defaultString(offHeapMemorySize));
        gemfireProperties.setProperty(START_DEV_REST_API, StringUtils.defaultString(startRestApi));
        gemfireProperties.setProperty(HTTP_SERVICE_PORT, StringUtils.defaultString(httpServicePort));
        gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, StringUtils.defaultString(httpServiceBindAddress));
        // properties file
        if (StringUtils.isNotBlank(userName)) {
            gemfireProperties.setProperty(ResourceConstants.USER_NAME, userName);
            gemfireProperties.setProperty(ResourceConstants.PASSWORD, passwordToUse);
        }
        // read the OSProcess enable redirect system property here -- TODO: replace with new GFSH
        // argument
        final boolean redirectOutput = Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
        ServerLauncher.Builder serverLauncherBuilder = new ServerLauncher.Builder().setAssignBuckets(assignBuckets).setDisableDefaultServer(disableDefaultServer).setForce(force).setRebalance(rebalance).setRedirectOutput(redirectOutput).setServerBindAddress(serverBindAddress).setServerPort(serverPort).setSpringXmlLocation(springXmlLocation).setWorkingDirectory(workingDirectory).setCriticalHeapPercentage(criticalHeapPercentage).setEvictionHeapPercentage(evictionHeapPercentage).setCriticalOffHeapPercentage(criticalOffHeapPercentage).setEvictionOffHeapPercentage(evictionOffHeapPercentage).setMaxConnections(maxConnections).setMaxMessageCount(maxMessageCount).setMaxThreads(maxThreads).setMessageTimeToLive(messageTimeToLive).setSocketBufferSize(socketBufferSize);
        if (hostNameForClients != null) {
            serverLauncherBuilder.setHostNameForClients(hostNameForClients);
        }
        if (memberName != null) {
            serverLauncherBuilder.setMemberName(memberName);
        }
        ServerLauncher serverLauncher = serverLauncherBuilder.build();
        String[] serverCommandLine = createStartServerCommandLine(serverLauncher, gemfirePropertiesPathname, gemfireSecurityPropertiesPathname, gemfireProperties, classpath, includeSystemClasspath, jvmArgsOpts, disableExitWhenOutOfMemory, initialHeap, maxHeap);
        if (getGfsh().getDebug()) {
            getGfsh().logInfo(StringUtils.join(serverCommandLine, StringUtils.SPACE), null);
        }
        Process serverProcess = new ProcessBuilder(serverCommandLine).directory(new File(serverLauncher.getWorkingDirectory())).start();
        serverProcess.getInputStream().close();
        serverProcess.getOutputStream().close();
        // fix TRAC bug #51967 by using NON_BLOCKING on Windows
        final ReadingMode readingMode = SystemUtils.isWindows() ? ReadingMode.NON_BLOCKING : ReadingMode.BLOCKING;
        // need thread-safe StringBuffer
        final StringBuffer message = new StringBuffer();
        InputListener inputListener = new InputListener() {

            @Override
            public void notifyInputLine(String line) {
                message.append(line);
                if (readingMode == ReadingMode.BLOCKING) {
                    message.append(StringUtils.LINE_SEPARATOR);
                }
            }
        };
        ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(serverProcess).inputStream(serverProcess.getErrorStream()).inputListener(inputListener).readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
        ServerState serverState;
        String previousServerStatusMessage = null;
        LauncherSignalListener serverSignalListener = new LauncherSignalListener();
        final boolean registeredServerSignalListener = getGfsh().getSignalHandler().registerListener(serverSignalListener);
        try {
            getGfsh().logInfo(String.format(CliStrings.START_SERVER__RUN_MESSAGE, IOUtils.tryGetCanonicalPathElseGetAbsolutePath(new File(serverLauncher.getWorkingDirectory()))), null);
            serverState = ServerState.fromDirectory(workingDirectory, memberName);
            do {
                if (serverProcess.isAlive()) {
                    Gfsh.print(".");
                    synchronized (this) {
                        TimeUnit.MILLISECONDS.timedWait(this, 500);
                    }
                    serverState = ServerState.fromDirectory(workingDirectory, memberName);
                    String currentServerStatusMessage = serverState.getStatusMessage();
                    if (serverState.isStartingOrNotResponding() && !(StringUtils.isBlank(currentServerStatusMessage) || currentServerStatusMessage.equalsIgnoreCase(previousServerStatusMessage) || currentServerStatusMessage.trim().toLowerCase().equals("null"))) {
                        Gfsh.println();
                        Gfsh.println(currentServerStatusMessage);
                        previousServerStatusMessage = currentServerStatusMessage;
                    }
                } else {
                    final int exitValue = serverProcess.exitValue();
                    return ResultBuilder.createShellClientErrorResult(String.format(CliStrings.START_SERVER__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE, exitValue, serverLauncher.getWorkingDirectory(), message.toString()));
                }
            } while (!(registeredServerSignalListener && serverSignalListener.isSignaled()) && serverState.isStartingOrNotResponding());
        } finally {
            // stop will close
            stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
            // ErrorStream
            getGfsh().getSignalHandler().unregisterListener(serverSignalListener);
        }
        Gfsh.println();
        final boolean asyncStart = ServerState.isStartingNotRespondingOrNull(serverState);
        if (asyncStart) {
            // async start
            Gfsh.print(String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, SERVER_TERM_NAME));
            return ResultBuilder.createInfoResult("");
        } else {
            return ResultBuilder.createInfoResult(serverState.toString());
        }
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        if (message != null && message.matches(LocalizedStrings.Launcher_Builder_UNKNOWN_HOST_ERROR_MESSAGE.toLocalizedString(".+"))) {
            message = CliStrings.format(CliStrings.LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1, SERVER_TERM_NAME, message);
        }
        return ResultBuilder.createUserErrorResult(message);
    } catch (IllegalStateException e) {
        return ResultBuilder.createUserErrorResult(e.getMessage());
    } catch (ClusterConfigurationNotAvailableException e) {
        return ResultBuilder.createShellClientErrorResult(e.getMessage());
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable t) {
        SystemFailure.checkFailure();
        return ResultBuilder.createShellClientErrorResult(String.format(CliStrings.START_SERVER__GENERAL_ERROR_MESSAGE, toString(t, getGfsh().getDebug())));
    }
}
Also used : CommandStringBuilder(org.apache.geode.management.internal.cli.util.CommandStringBuilder) ResultBuilder(org.apache.geode.management.internal.cli.result.ResultBuilder) ServerState(org.apache.geode.distributed.ServerLauncher.ServerState) OSProcess(org.apache.geode.internal.OSProcess) Properties(java.util.Properties) ConnectionEndpoint(org.apache.geode.management.internal.cli.util.ConnectionEndpoint) ConverterHint(org.apache.geode.management.cli.ConverterHint) ServerLauncher(org.apache.geode.distributed.ServerLauncher) InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) ProcessStreamReader(org.apache.geode.internal.process.ProcessStreamReader) ClusterConfigurationNotAvailableException(org.apache.geode.internal.process.ClusterConfigurationNotAvailableException) File(java.io.File) ReadingMode(org.apache.geode.internal.process.ProcessStreamReader.ReadingMode) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Example 3 with ClusterConfigurationNotAvailableException

use of org.apache.geode.internal.process.ClusterConfigurationNotAvailableException 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 4 with ClusterConfigurationNotAvailableException

use of org.apache.geode.internal.process.ClusterConfigurationNotAvailableException in project geode by apache.

the class GemFireCacheImpl method requestSharedConfiguration.

/**
   * Request the shared configuration from the locator(s) which have the Cluster config service
   * running
   */
private ConfigurationResponse requestSharedConfiguration() {
    final DistributionConfig config = this.system.getConfig();
    if (!(this.dm instanceof DistributionManager)) {
        return null;
    }
    // do nothing if this vm is/has locator or this is a client
    if (this.dm.getDMType() == DistributionManager.LOCATOR_DM_TYPE || this.isClient || Locator.getLocator() != null) {
        return null;
    }
    // can't simply return null if server is not using shared configuration, since we need to find
    // out
    // if the locator is running in secure mode or not, if yes, then we need to throw an exception
    // if server is not using cluster config
    Map<InternalDistributedMember, Collection<String>> scl = getDistributionManager().getAllHostedLocatorsWithSharedConfiguration();
    // then do not make requests to the locators
    if (scl.isEmpty()) {
        logger.info(LocalizedMessage.create(LocalizedStrings.GemFireCache_NO_LOCATORS_FOUND_WITH_SHARED_CONFIGURATION));
        return null;
    }
    List<String> locatorConnectionStrings = getSharedConfigLocatorConnectionStringList();
    try {
        ConfigurationResponse response = ClusterConfigurationLoader.requestConfigurationFromLocators(this.system.getConfig(), locatorConnectionStrings);
        // log the configuration received from the locator
        logger.info(LocalizedMessage.create(LocalizedStrings.GemFireCache_RECEIVED_SHARED_CONFIGURATION_FROM_LOCATORS));
        logger.info(response.describeConfig());
        Configuration clusterConfig = response.getRequestedConfiguration().get(ClusterConfigurationService.CLUSTER_CONFIG);
        Properties clusterSecProperties = clusterConfig == null ? new Properties() : clusterConfig.getGemfireProperties();
        // If not using shared configuration, return null or throw an exception is locator is secured
        if (!config.getUseSharedConfiguration()) {
            if (clusterSecProperties.containsKey(ConfigurationProperties.SECURITY_MANAGER)) {
                throw new GemFireConfigException(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION_2.toLocalizedString());
            } else {
                logger.info(LocalizedMessage.create(LocalizedStrings.GemFireCache_NOT_USING_SHARED_CONFIGURATION));
                return null;
            }
        }
        Properties serverSecProperties = config.getSecurityProps();
        // check for possible mis-configuration
        if (isMisConfigured(clusterSecProperties, serverSecProperties, ConfigurationProperties.SECURITY_MANAGER) || isMisConfigured(clusterSecProperties, serverSecProperties, ConfigurationProperties.SECURITY_POST_PROCESSOR)) {
            throw new GemFireConfigException(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION.toLocalizedString());
        }
        return response;
    } catch (ClusterConfigurationNotAvailableException e) {
        throw new GemFireConfigException(LocalizedStrings.GemFireCache_SHARED_CONFIGURATION_NOT_AVAILABLE.toLocalizedString(), e);
    } catch (UnknownHostException e) {
        throw new GemFireConfigException(e.getLocalizedMessage(), e);
    }
}
Also used : ConfigurationResponse(org.apache.geode.management.internal.configuration.messages.ConfigurationResponse) Configuration(org.apache.geode.management.internal.configuration.domain.Configuration) UnknownHostException(java.net.UnknownHostException) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) GemFireConfigException(org.apache.geode.GemFireConfigException) Collection(java.util.Collection) ClusterConfigurationNotAvailableException(org.apache.geode.internal.process.ClusterConfigurationNotAvailableException) DistributionManager(org.apache.geode.distributed.internal.DistributionManager)

Aggregations

ClusterConfigurationNotAvailableException (org.apache.geode.internal.process.ClusterConfigurationNotAvailableException)4 UnknownHostException (java.net.UnknownHostException)3 Properties (java.util.Properties)3 File (java.io.File)2 IOException (java.io.IOException)2 ConfigurationResponse (org.apache.geode.management.internal.configuration.messages.ConfigurationResponse)2 FileNotFoundException (java.io.FileNotFoundException)1 InetAddress (java.net.InetAddress)1 Collection (java.util.Collection)1 TimeoutException (java.util.concurrent.TimeoutException)1 MalformedObjectNameException (javax.management.MalformedObjectNameException)1 OptionException (joptsimple.OptionException)1 GemFireConfigException (org.apache.geode.GemFireConfigException)1 ConfigurationProperties (org.apache.geode.distributed.ConfigurationProperties)1 ServerLauncher (org.apache.geode.distributed.ServerLauncher)1 ServerState (org.apache.geode.distributed.ServerLauncher.ServerState)1 DistributionConfig (org.apache.geode.distributed.internal.DistributionConfig)1 DistributionManager (org.apache.geode.distributed.internal.DistributionManager)1 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)1 TcpClient (org.apache.geode.distributed.internal.tcpserver.TcpClient)1