changeset 1257:264f429d2019

Improve messages when agent is already running Reviewed-by: jerboaa Review-thread: http://icedtea.classpath.org/pipermail/thermostat/2013-September/008281.html PR1068
author Omair Majid <omajid@redhat.com>
date Fri, 20 Sep 2013 12:21:31 -0400
parents 9f8cb76cec1d
children 01f01fb9f63d
files agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/AgentApplication.java agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/MongoProcessRunner.java agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/StorageCommand.java agent/cli/src/test/java/com/redhat/thermostat/agent/cli/impl/AgentApplicationTest.java agent/command/src/main/java/com/redhat/thermostat/agent/command/ConfigurationServer.java agent/command/src/main/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImpl.java agent/command/src/test/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImplTest.java
diffstat 7 files changed, 85 insertions(+), 61 deletions(-) [+]
line wrap: on
line diff
--- a/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/AgentApplication.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/AgentApplication.java	Fri Sep 20 12:21:31 2013 -0400
@@ -36,6 +36,7 @@
 
 package com.redhat.thermostat.agent.cli.impl;
 
+import java.io.IOException;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.logging.Level;
@@ -127,38 +128,46 @@
             public Object addingService(ServiceReference reference) {
                 final ConfigurationServer configServer = (ConfigurationServer) super.addingService(reference);
                 String [] host = configuration.getConfigListenAddress().split(":");
-                configServer.startListening(host[0], Integer.valueOf(host[1]));
+
+                try {
+                    configServer.startListening(host[0], Integer.valueOf(host[1]));
+
+                    ConnectionListener connectionListener = new ConnectionListener() {
+                        @Override
+                        public void changed(ConnectionStatus newStatus) {
+                            switch (newStatus) {
+                            case DISCONNECTED:
+                                logger.warning("Unexpected disconnect event.");
+                                break;
+                            case CONNECTING:
+                                logger.fine("Connecting to storage.");
+                                break;
+                            case CONNECTED:
+                                logger.fine("Connected to storage");
+                                handleConnected(configServer);
+                                break;
+                            case FAILED_TO_CONNECT:
+                                // ConnectionException will be thrown
+                                break;
+                            default:
+                                logger.warning("Unfamiliar ConnectionStatus value: " + newStatus.toString());
+                            }
+                        }
+                    };
+
+                    dbService.addConnectionListener(connectionListener);
+                    logger.fine("Connecting to storage...");
                 
-                ConnectionListener connectionListener = new ConnectionListener() {
-                    @Override
-                    public void changed(ConnectionStatus newStatus) {
-                        switch (newStatus) {
-                        case DISCONNECTED:
-                            logger.warning("Unexpected disconnect event.");
-                            break;
-                        case CONNECTING:
-                            logger.fine("Connecting to storage.");
-                            break;
-                        case CONNECTED:
-                            logger.fine("Connected to storage");
-                            handleConnected(configServer);
-                            break;
-                        case FAILED_TO_CONNECT:
-                            // ConnectionException will be thrown
-                            break;
-                        default:
-                            logger.warning("Unfamiliar ConnectionStatus value: " + newStatus.toString());
-                        }
-                    }
-                };
-
-                dbService.addConnectionListener(connectionListener);
-                logger.fine("Connecting to storage...");
-                
-                try {
                     dbService.connect();
+                } catch (IOException e) {
+                    logger.log(Level.SEVERE, e.getMessage());
+                    // log stack trace as info only
+                    logger.log(Level.INFO, e.getMessage(), e);
+                    shutdown();
                 } catch (ConnectionException e) {
-                    logger.log(Level.SEVERE, "Could not connect to storage.", e);
+                    logger.log(Level.SEVERE, "Could not connect to storage (" + e.getMessage() + ")");
+                    // log stack trace as info only
+                    logger.log(Level.INFO, "Could nto connect to storage", e);
                     shutdown();
                 }
                 
--- a/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/MongoProcessRunner.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/MongoProcessRunner.java	Fri Sep 20 12:21:31 2013 -0400
@@ -143,16 +143,28 @@
         return processIsRunning;
     }
     
+    /**
+     * Start the mongod process.
+     *
+     * @throws ApplicationException to signal an error starting the process. Callers should catch this and handle appropriately.
+     */
     public void startService() throws IOException, InterruptedException,
             ApplicationException, InvalidConfigurationException {
 
         if (isStorageRunning()) {
             LocalizedString message = translator.localize(LocaleResources.STORAGE_ALREADY_RUNNING_WITH_PID, String.valueOf(pid));
-            display(message);
             throw new StorageAlreadyRunningException(pid, message.getContents());
         }
         
-        String dbVersion = getDBVersion();
+        String dbVersion;
+        try {
+            dbVersion = getDBVersion();
+        } catch (IOException e) {
+            LocalizedString message = translator.localize(
+                    LocaleResources.CANNOT_EXECUTE_PROCESS, MONGO_PROCESS);
+            throw new ApplicationException(message.getContents(), e);
+
+        }
         List<String> commands = null;
         commands = getStartupCommand(dbVersion);
         
@@ -164,7 +176,6 @@
             status = process.runAndReturnResult();
         } catch (ApplicationException ae) {
             LocalizedString message = translator.localize(LocaleResources.CANNOT_EXECUTE_PROCESS, MONGO_PROCESS);
-            display(message);
             throw ae;
         }
 
@@ -182,20 +193,23 @@
             display(translator.localize(LocaleResources.PID_IS, String.valueOf(pid)));
             
         } else {
-            
+            // don't display anything when throwing an exception; whatever catches the exception will do so.
             LocalizedString message = translator.localize(LocaleResources.CANNOT_START_SERVER,
                              configuration.getDBPath().toString(),
                              String.valueOf(status));
-            display(message);
             throw new StorageStartException(configuration.getDBPath(), status, message.getContents());
         }
     }
     
+    /**
+     * Stop the mongod process.
+     *
+     * @throws ApplicationException to signal an error stopping the storage. Callers should catch this and handle appropriately.
+     */
     public void stopService() throws IOException, InterruptedException, InvalidConfigurationException, ApplicationException {
  
         if (!isStorageRunning()) {
             LocalizedString message = translator.localize(LocaleResources.STORAGE_NOT_RUNNING);
-            display(message);
             throw new StorageNotRunningException(message.getContents());
         }
         List<String> commands = new ArrayList<>(Arrays.asList(MONGO_SHUTDOWN_ARGS));
@@ -213,11 +227,10 @@
                 // ignore
             }
         } else {
-            
+            // don't display anything when throwing an exception; whatever catches the exception will do so.
             LocalizedString message = translator.localize(LocaleResources.CANNOT_SHUTDOWN_SERVER,
                     configuration.getDBPath().toString(),
                     String.valueOf(status));
-            display(message);
             throw new StorageStopException(configuration.getDBPath(), status, message.getContents());
         }
     }
@@ -260,16 +273,7 @@
     }
  
     private String getDBVersion() throws IOException {
-        Process process;
-        try {
-            process = new ProcessBuilder(Arrays.asList("mongod", "--version"))
-                    .start();
-        } catch (IOException e) {
-            LocalizedString message = translator.localize(
-                    LocaleResources.CANNOT_EXECUTE_PROCESS, MONGO_PROCESS);
-            display(message);
-            throw e;
-        }
+        Process process = new ProcessBuilder(Arrays.asList("mongod", "--version")).start();
         InputStream out = process.getInputStream();
         return doGetDBVersion(out);
     }
--- a/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/StorageCommand.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/cli/src/main/java/com/redhat/thermostat/agent/cli/impl/db/StorageCommand.java	Fri Sep 20 12:21:31 2013 -0400
@@ -117,6 +117,9 @@
         } catch (InvalidConfigurationException e) {
             // rethrow
             throw e;
+        } catch (ApplicationException e) {
+            logger.log(Level.WARNING, e.getMessage());
+            getNotifier().fireAction(ApplicationState.FAIL, e);
         } catch (Exception e) {
             logger.log(Level.WARNING, e.getMessage(), e);
             getNotifier().fireAction(ApplicationState.FAIL, e);
--- a/agent/cli/src/test/java/com/redhat/thermostat/agent/cli/impl/AgentApplicationTest.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/cli/src/test/java/com/redhat/thermostat/agent/cli/impl/AgentApplicationTest.java	Fri Sep 20 12:21:31 2013 -0400
@@ -48,6 +48,7 @@
 import static org.mockito.Mockito.when;
 import static org.powermock.api.mockito.PowerMockito.whenNew;
 
+import java.io.IOException;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -236,14 +237,18 @@
             @Override
             public void run() {
                 // Finish when config server starts listening
-                doAnswer(new Answer<Void>() {
+                try {
+                    doAnswer(new Answer<Void>() {
 
-                    @Override
-                    public Void answer(InvocationOnMock invocation) throws Throwable {
-                        latch.countDown();
-                        return null;
-                    }
-                }).when(configServer).startListening(COMMAND_CHANNLE_BIND_HOST, COMMAND_CHANNEL_BIND_PORT);
+                        @Override
+                        public Void answer(InvocationOnMock invocation) throws Throwable {
+                            latch.countDown();
+                            return null;
+                        }
+                    }).when(configServer).startListening(COMMAND_CHANNLE_BIND_HOST, COMMAND_CHANNEL_BIND_PORT);
+                } catch (IOException e1) {
+                    fail("a mock should not throw an exception");
+                }
                 
                 try {
                     agent.run(commandContext);
--- a/agent/command/src/main/java/com/redhat/thermostat/agent/command/ConfigurationServer.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/command/src/main/java/com/redhat/thermostat/agent/command/ConfigurationServer.java	Fri Sep 20 12:21:31 2013 -0400
@@ -36,6 +36,8 @@
 
 package com.redhat.thermostat.agent.command;
 
+import java.io.IOException;
+
 import com.redhat.thermostat.annotations.Service;
 import com.redhat.thermostat.common.command.Request;
 
@@ -52,8 +54,9 @@
     /**
      * Starts the configuration server so it listens at the interface specified
      * by the {@code host} and {@code port}.
+     * @throws IOException if it fails to listen
      */
-    void startListening(String host, int port);
+    void startListening(String host, int port) throws IOException;
 
     /**
      * Shuts down the configuration server. No additional {@link Request}s will
--- a/agent/command/src/main/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImpl.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/command/src/main/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImpl.java	Fri Sep 20 12:21:31 2013 -0400
@@ -36,6 +36,7 @@
 
 package com.redhat.thermostat.agent.command.internal;
 
+import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -56,7 +57,7 @@
     }
 
     @Override
-    public void startListening(String hostname, int port) {
+    public void startListening(String hostname, int port) throws IOException {
         ServerBootstrap bootstrap = (ServerBootstrap) ctx.getBootstrap();
 
         InetSocketAddress addr = new InetSocketAddress(hostname, port);
@@ -66,9 +67,7 @@
             // Bind and start to accept incoming connections.
             bootstrap.bind(addr);
         } catch (ChannelException e) {
-            logger.log(Level.SEVERE, "Failed to bind command channel server!", e);
-            // rethrow, in order to stop agent from continuing
-            throw e;
+            throw new IOException("Failed to bind command channel server (" + e.getMessage() + ")", e);
         }
         logger.log(Level.FINEST, "Bound command channel server to " + addr.toString());
     }
--- a/agent/command/src/test/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImplTest.java	Thu Sep 19 16:18:08 2013 -0400
+++ b/agent/command/src/test/java/com/redhat/thermostat/agent/command/internal/ConfigurationServerImplTest.java	Fri Sep 20 12:21:31 2013 -0400
@@ -43,6 +43,7 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import java.io.IOException;
 import java.net.InetSocketAddress;
 
 import org.jboss.netty.bootstrap.ServerBootstrap;
@@ -71,7 +72,7 @@
     }
 
     @Test
-    public void testStartListening() {
+    public void testStartListening() throws IOException {
         ConfigurationServerImpl server = new ConfigurationServerImpl(ctx);
         server.startListening("127.0.0.1", 123);
 
@@ -92,7 +93,7 @@
         try {
             server.startListening("does-not-resolve.example.com", 123);
             fail("Should have thrown exception");
-        } catch (ChannelException e) {
+        } catch (IOException e) {
             // pass
         }
     }